xref: /linux-6.15/rust/kernel/workqueue.rs (revision 115c95e9)
1d4d791d4SAlice Ryhl // SPDX-License-Identifier: GPL-2.0
2d4d791d4SAlice Ryhl 
3d4d791d4SAlice Ryhl //! Work queues.
4d4d791d4SAlice Ryhl //!
57324b889SAlice Ryhl //! This file has two components: The raw work item API, and the safe work item API.
67324b889SAlice Ryhl //!
77324b889SAlice Ryhl //! One pattern that is used in both APIs is the `ID` const generic, which exists to allow a single
87324b889SAlice Ryhl //! type to define multiple `work_struct` fields. This is done by choosing an id for each field,
97324b889SAlice Ryhl //! and using that id to specify which field you wish to use. (The actual value doesn't matter, as
107324b889SAlice Ryhl //! long as you use different values for different fields of the same struct.) Since these IDs are
117324b889SAlice Ryhl //! generic, they are used only at compile-time, so they shouldn't exist in the final binary.
127324b889SAlice Ryhl //!
137324b889SAlice Ryhl //! # The raw API
147324b889SAlice Ryhl //!
157324b889SAlice Ryhl //! The raw API consists of the `RawWorkItem` trait, where the work item needs to provide an
167324b889SAlice Ryhl //! arbitrary function that knows how to enqueue the work item. It should usually not be used
177324b889SAlice Ryhl //! directly, but if you want to, you can use it without using the pieces from the safe API.
187324b889SAlice Ryhl //!
197324b889SAlice Ryhl //! # The safe API
207324b889SAlice Ryhl //!
217324b889SAlice Ryhl //! The safe API is used via the `Work` struct and `WorkItem` traits. Furthermore, it also includes
227324b889SAlice Ryhl //! a trait called `WorkItemPointer`, which is usually not used directly by the user.
237324b889SAlice Ryhl //!
247324b889SAlice Ryhl //!  * The `Work` struct is the Rust wrapper for the C `work_struct` type.
257324b889SAlice Ryhl //!  * The `WorkItem` trait is implemented for structs that can be enqueued to a workqueue.
267324b889SAlice Ryhl //!  * The `WorkItemPointer` trait is implemented for the pointer type that points at a something
277324b889SAlice Ryhl //!    that implements `WorkItem`.
287324b889SAlice Ryhl //!
29d4d791d4SAlice Ryhl //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
30d4d791d4SAlice Ryhl 
3147f0dbe8SAlice Ryhl use crate::{bindings, prelude::*, sync::Arc, sync::LockClassKey, types::Opaque};
32*115c95e9SAlice Ryhl use alloc::alloc::AllocError;
3347f0dbe8SAlice Ryhl use alloc::boxed::Box;
347324b889SAlice Ryhl use core::marker::PhantomData;
3547f0dbe8SAlice Ryhl use core::pin::Pin;
367324b889SAlice Ryhl 
377324b889SAlice Ryhl /// Creates a [`Work`] initialiser with the given name and a newly-created lock class.
387324b889SAlice Ryhl #[macro_export]
397324b889SAlice Ryhl macro_rules! new_work {
407324b889SAlice Ryhl     ($($name:literal)?) => {
417324b889SAlice Ryhl         $crate::workqueue::Work::new($crate::optional_name!($($name)?), $crate::static_lock_class!())
427324b889SAlice Ryhl     };
437324b889SAlice Ryhl }
44d4d791d4SAlice Ryhl 
45d4d791d4SAlice Ryhl /// A kernel work queue.
46d4d791d4SAlice Ryhl ///
47d4d791d4SAlice Ryhl /// Wraps the kernel's C `struct workqueue_struct`.
48d4d791d4SAlice Ryhl ///
49d4d791d4SAlice Ryhl /// It allows work items to be queued to run on thread pools managed by the kernel. Several are
50d4d791d4SAlice Ryhl /// always available, for example, `system`, `system_highpri`, `system_long`, etc.
51d4d791d4SAlice Ryhl #[repr(transparent)]
52d4d791d4SAlice Ryhl pub struct Queue(Opaque<bindings::workqueue_struct>);
53d4d791d4SAlice Ryhl 
54d4d791d4SAlice Ryhl // SAFETY: Accesses to workqueues used by [`Queue`] are thread-safe.
55d4d791d4SAlice Ryhl unsafe impl Send for Queue {}
56d4d791d4SAlice Ryhl // SAFETY: Accesses to workqueues used by [`Queue`] are thread-safe.
57d4d791d4SAlice Ryhl unsafe impl Sync for Queue {}
58d4d791d4SAlice Ryhl 
59d4d791d4SAlice Ryhl impl Queue {
60d4d791d4SAlice Ryhl     /// Use the provided `struct workqueue_struct` with Rust.
61d4d791d4SAlice Ryhl     ///
62d4d791d4SAlice Ryhl     /// # Safety
63d4d791d4SAlice Ryhl     ///
64d4d791d4SAlice Ryhl     /// The caller must ensure that the provided raw pointer is not dangling, that it points at a
65d4d791d4SAlice Ryhl     /// valid workqueue, and that it remains valid until the end of 'a.
66d4d791d4SAlice Ryhl     pub unsafe fn from_raw<'a>(ptr: *const bindings::workqueue_struct) -> &'a Queue {
67d4d791d4SAlice Ryhl         // SAFETY: The `Queue` type is `#[repr(transparent)]`, so the pointer cast is valid. The
68d4d791d4SAlice Ryhl         // caller promises that the pointer is not dangling.
69d4d791d4SAlice Ryhl         unsafe { &*(ptr as *const Queue) }
70d4d791d4SAlice Ryhl     }
71d4d791d4SAlice Ryhl 
72d4d791d4SAlice Ryhl     /// Enqueues a work item.
73d4d791d4SAlice Ryhl     ///
74d4d791d4SAlice Ryhl     /// This may fail if the work item is already enqueued in a workqueue.
75d4d791d4SAlice Ryhl     ///
76d4d791d4SAlice Ryhl     /// The work item will be submitted using `WORK_CPU_UNBOUND`.
77d4d791d4SAlice Ryhl     pub fn enqueue<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput
78d4d791d4SAlice Ryhl     where
79d4d791d4SAlice Ryhl         W: RawWorkItem<ID> + Send + 'static,
80d4d791d4SAlice Ryhl     {
81d4d791d4SAlice Ryhl         let queue_ptr = self.0.get();
82d4d791d4SAlice Ryhl 
83d4d791d4SAlice Ryhl         // SAFETY: We only return `false` if the `work_struct` is already in a workqueue. The other
84d4d791d4SAlice Ryhl         // `__enqueue` requirements are not relevant since `W` is `Send` and static.
85d4d791d4SAlice Ryhl         //
86d4d791d4SAlice Ryhl         // The call to `bindings::queue_work_on` will dereference the provided raw pointer, which
87d4d791d4SAlice Ryhl         // is ok because `__enqueue` guarantees that the pointer is valid for the duration of this
88d4d791d4SAlice Ryhl         // closure.
89d4d791d4SAlice Ryhl         //
90d4d791d4SAlice Ryhl         // Furthermore, if the C workqueue code accesses the pointer after this call to
91d4d791d4SAlice Ryhl         // `__enqueue`, then the work item was successfully enqueued, and `bindings::queue_work_on`
92d4d791d4SAlice Ryhl         // will have returned true. In this case, `__enqueue` promises that the raw pointer will
93d4d791d4SAlice Ryhl         // stay valid until we call the function pointer in the `work_struct`, so the access is ok.
94d4d791d4SAlice Ryhl         unsafe {
95d4d791d4SAlice Ryhl             w.__enqueue(move |work_ptr| {
96d4d791d4SAlice Ryhl                 bindings::queue_work_on(bindings::WORK_CPU_UNBOUND as _, queue_ptr, work_ptr)
97d4d791d4SAlice Ryhl             })
98d4d791d4SAlice Ryhl         }
99d4d791d4SAlice Ryhl     }
100*115c95e9SAlice Ryhl 
101*115c95e9SAlice Ryhl     /// Tries to spawn the given function or closure as a work item.
102*115c95e9SAlice Ryhl     ///
103*115c95e9SAlice Ryhl     /// This method can fail because it allocates memory to store the work item.
104*115c95e9SAlice Ryhl     pub fn try_spawn<T: 'static + Send + FnOnce()>(&self, func: T) -> Result<(), AllocError> {
105*115c95e9SAlice Ryhl         let init = pin_init!(ClosureWork {
106*115c95e9SAlice Ryhl             work <- new_work!("Queue::try_spawn"),
107*115c95e9SAlice Ryhl             func: Some(func),
108*115c95e9SAlice Ryhl         });
109*115c95e9SAlice Ryhl 
110*115c95e9SAlice Ryhl         self.enqueue(Box::pin_init(init).map_err(|_| AllocError)?);
111*115c95e9SAlice Ryhl         Ok(())
112*115c95e9SAlice Ryhl     }
113*115c95e9SAlice Ryhl }
114*115c95e9SAlice Ryhl 
115*115c95e9SAlice Ryhl /// A helper type used in `try_spawn`.
116*115c95e9SAlice Ryhl #[pin_data]
117*115c95e9SAlice Ryhl struct ClosureWork<T> {
118*115c95e9SAlice Ryhl     #[pin]
119*115c95e9SAlice Ryhl     work: Work<ClosureWork<T>>,
120*115c95e9SAlice Ryhl     func: Option<T>,
121*115c95e9SAlice Ryhl }
122*115c95e9SAlice Ryhl 
123*115c95e9SAlice Ryhl impl<T> ClosureWork<T> {
124*115c95e9SAlice Ryhl     fn project(self: Pin<&mut Self>) -> &mut Option<T> {
125*115c95e9SAlice Ryhl         // SAFETY: The `func` field is not structurally pinned.
126*115c95e9SAlice Ryhl         unsafe { &mut self.get_unchecked_mut().func }
127*115c95e9SAlice Ryhl     }
128*115c95e9SAlice Ryhl }
129*115c95e9SAlice Ryhl 
130*115c95e9SAlice Ryhl impl<T: FnOnce()> WorkItem for ClosureWork<T> {
131*115c95e9SAlice Ryhl     type Pointer = Pin<Box<Self>>;
132*115c95e9SAlice Ryhl 
133*115c95e9SAlice Ryhl     fn run(mut this: Pin<Box<Self>>) {
134*115c95e9SAlice Ryhl         if let Some(func) = this.as_mut().project().take() {
135*115c95e9SAlice Ryhl             (func)()
136*115c95e9SAlice Ryhl         }
137*115c95e9SAlice Ryhl     }
138d4d791d4SAlice Ryhl }
139d4d791d4SAlice Ryhl 
140d4d791d4SAlice Ryhl /// A raw work item.
141d4d791d4SAlice Ryhl ///
142d4d791d4SAlice Ryhl /// This is the low-level trait that is designed for being as general as possible.
143d4d791d4SAlice Ryhl ///
144d4d791d4SAlice Ryhl /// The `ID` parameter to this trait exists so that a single type can provide multiple
145d4d791d4SAlice Ryhl /// implementations of this trait. For example, if a struct has multiple `work_struct` fields, then
146d4d791d4SAlice Ryhl /// you will implement this trait once for each field, using a different id for each field. The
147d4d791d4SAlice Ryhl /// actual value of the id is not important as long as you use different ids for different fields
148d4d791d4SAlice Ryhl /// of the same struct. (Fields of different structs need not use different ids.)
149d4d791d4SAlice Ryhl ///
150d4d791d4SAlice Ryhl /// Note that the id is used only to select the right method to call during compilation. It wont be
151d4d791d4SAlice Ryhl /// part of the final executable.
152d4d791d4SAlice Ryhl ///
153d4d791d4SAlice Ryhl /// # Safety
154d4d791d4SAlice Ryhl ///
155d4d791d4SAlice Ryhl /// Implementers must ensure that any pointers passed to a `queue_work_on` closure by `__enqueue`
156d4d791d4SAlice Ryhl /// remain valid for the duration specified in the guarantees section of the documentation for
157d4d791d4SAlice Ryhl /// `__enqueue`.
158d4d791d4SAlice Ryhl pub unsafe trait RawWorkItem<const ID: u64> {
159d4d791d4SAlice Ryhl     /// The return type of [`Queue::enqueue`].
160d4d791d4SAlice Ryhl     type EnqueueOutput;
161d4d791d4SAlice Ryhl 
162d4d791d4SAlice Ryhl     /// Enqueues this work item on a queue using the provided `queue_work_on` method.
163d4d791d4SAlice Ryhl     ///
164d4d791d4SAlice Ryhl     /// # Guarantees
165d4d791d4SAlice Ryhl     ///
166d4d791d4SAlice Ryhl     /// If this method calls the provided closure, then the raw pointer is guaranteed to point at a
167d4d791d4SAlice Ryhl     /// valid `work_struct` for the duration of the call to the closure. If the closure returns
168d4d791d4SAlice Ryhl     /// true, then it is further guaranteed that the pointer remains valid until someone calls the
169d4d791d4SAlice Ryhl     /// function pointer stored in the `work_struct`.
170d4d791d4SAlice Ryhl     ///
171d4d791d4SAlice Ryhl     /// # Safety
172d4d791d4SAlice Ryhl     ///
173d4d791d4SAlice Ryhl     /// The provided closure may only return `false` if the `work_struct` is already in a workqueue.
174d4d791d4SAlice Ryhl     ///
175d4d791d4SAlice Ryhl     /// If the work item type is annotated with any lifetimes, then you must not call the function
176d4d791d4SAlice Ryhl     /// pointer after any such lifetime expires. (Never calling the function pointer is okay.)
177d4d791d4SAlice Ryhl     ///
178d4d791d4SAlice Ryhl     /// If the work item type is not [`Send`], then the function pointer must be called on the same
179d4d791d4SAlice Ryhl     /// thread as the call to `__enqueue`.
180d4d791d4SAlice Ryhl     unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
181d4d791d4SAlice Ryhl     where
182d4d791d4SAlice Ryhl         F: FnOnce(*mut bindings::work_struct) -> bool;
183d4d791d4SAlice Ryhl }
18403394130SWedson Almeida Filho 
1857324b889SAlice Ryhl /// Defines the method that should be called directly when a work item is executed.
1867324b889SAlice Ryhl ///
1877324b889SAlice Ryhl /// This trait is implemented by `Pin<Box<T>>` and `Arc<T>`, and is mainly intended to be
1887324b889SAlice Ryhl /// implemented for smart pointer types. For your own structs, you would implement [`WorkItem`]
1897324b889SAlice Ryhl /// instead. The `run` method on this trait will usually just perform the appropriate
1907324b889SAlice Ryhl /// `container_of` translation and then call into the `run` method from the [`WorkItem`] trait.
1917324b889SAlice Ryhl ///
1927324b889SAlice Ryhl /// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
1937324b889SAlice Ryhl ///
1947324b889SAlice Ryhl /// # Safety
1957324b889SAlice Ryhl ///
1967324b889SAlice Ryhl /// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with the [`run`]
1977324b889SAlice Ryhl /// method of this trait as the function pointer.
1987324b889SAlice Ryhl ///
1997324b889SAlice Ryhl /// [`__enqueue`]: RawWorkItem::__enqueue
2007324b889SAlice Ryhl /// [`run`]: WorkItemPointer::run
2017324b889SAlice Ryhl pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
2027324b889SAlice Ryhl     /// Run this work item.
2037324b889SAlice Ryhl     ///
2047324b889SAlice Ryhl     /// # Safety
2057324b889SAlice Ryhl     ///
2067324b889SAlice Ryhl     /// The provided `work_struct` pointer must originate from a previous call to `__enqueue` where
2077324b889SAlice Ryhl     /// the `queue_work_on` closure returned true, and the pointer must still be valid.
2087324b889SAlice Ryhl     unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
2097324b889SAlice Ryhl }
2107324b889SAlice Ryhl 
2117324b889SAlice Ryhl /// Defines the method that should be called when this work item is executed.
2127324b889SAlice Ryhl ///
2137324b889SAlice Ryhl /// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
2147324b889SAlice Ryhl pub trait WorkItem<const ID: u64 = 0> {
2157324b889SAlice Ryhl     /// The pointer type that this struct is wrapped in. This will typically be `Arc<Self>` or
2167324b889SAlice Ryhl     /// `Pin<Box<Self>>`.
2177324b889SAlice Ryhl     type Pointer: WorkItemPointer<ID>;
2187324b889SAlice Ryhl 
2197324b889SAlice Ryhl     /// The method that should be called when this work item is executed.
2207324b889SAlice Ryhl     fn run(this: Self::Pointer);
2217324b889SAlice Ryhl }
2227324b889SAlice Ryhl 
2237324b889SAlice Ryhl /// Links for a work item.
2247324b889SAlice Ryhl ///
2257324b889SAlice Ryhl /// This struct contains a function pointer to the `run` function from the [`WorkItemPointer`]
2267324b889SAlice Ryhl /// trait, and defines the linked list pointers necessary to enqueue a work item in a workqueue.
2277324b889SAlice Ryhl ///
2287324b889SAlice Ryhl /// Wraps the kernel's C `struct work_struct`.
2297324b889SAlice Ryhl ///
2307324b889SAlice Ryhl /// This is a helper type used to associate a `work_struct` with the [`WorkItem`] that uses it.
2317324b889SAlice Ryhl #[repr(transparent)]
2327324b889SAlice Ryhl pub struct Work<T: ?Sized, const ID: u64 = 0> {
2337324b889SAlice Ryhl     work: Opaque<bindings::work_struct>,
2347324b889SAlice Ryhl     _inner: PhantomData<T>,
2357324b889SAlice Ryhl }
2367324b889SAlice Ryhl 
2377324b889SAlice Ryhl // SAFETY: Kernel work items are usable from any thread.
2387324b889SAlice Ryhl //
2397324b889SAlice Ryhl // We do not need to constrain `T` since the work item does not actually contain a `T`.
2407324b889SAlice Ryhl unsafe impl<T: ?Sized, const ID: u64> Send for Work<T, ID> {}
2417324b889SAlice Ryhl // SAFETY: Kernel work items are usable from any thread.
2427324b889SAlice Ryhl //
2437324b889SAlice Ryhl // We do not need to constrain `T` since the work item does not actually contain a `T`.
2447324b889SAlice Ryhl unsafe impl<T: ?Sized, const ID: u64> Sync for Work<T, ID> {}
2457324b889SAlice Ryhl 
2467324b889SAlice Ryhl impl<T: ?Sized, const ID: u64> Work<T, ID> {
2477324b889SAlice Ryhl     /// Creates a new instance of [`Work`].
2487324b889SAlice Ryhl     #[inline]
2497324b889SAlice Ryhl     #[allow(clippy::new_ret_no_self)]
2507324b889SAlice Ryhl     pub fn new(name: &'static CStr, key: &'static LockClassKey) -> impl PinInit<Self>
2517324b889SAlice Ryhl     where
2527324b889SAlice Ryhl         T: WorkItem<ID>,
2537324b889SAlice Ryhl     {
2547324b889SAlice Ryhl         // SAFETY: The `WorkItemPointer` implementation promises that `run` can be used as the work
2557324b889SAlice Ryhl         // item function.
2567324b889SAlice Ryhl         unsafe {
2577324b889SAlice Ryhl             kernel::init::pin_init_from_closure(move |slot| {
2587324b889SAlice Ryhl                 let slot = Self::raw_get(slot);
2597324b889SAlice Ryhl                 bindings::init_work_with_key(
2607324b889SAlice Ryhl                     slot,
2617324b889SAlice Ryhl                     Some(T::Pointer::run),
2627324b889SAlice Ryhl                     false,
2637324b889SAlice Ryhl                     name.as_char_ptr(),
2647324b889SAlice Ryhl                     key.as_ptr(),
2657324b889SAlice Ryhl                 );
2667324b889SAlice Ryhl                 Ok(())
2677324b889SAlice Ryhl             })
2687324b889SAlice Ryhl         }
2697324b889SAlice Ryhl     }
2707324b889SAlice Ryhl 
2717324b889SAlice Ryhl     /// Get a pointer to the inner `work_struct`.
2727324b889SAlice Ryhl     ///
2737324b889SAlice Ryhl     /// # Safety
2747324b889SAlice Ryhl     ///
2757324b889SAlice Ryhl     /// The provided pointer must not be dangling and must be properly aligned. (But the memory
2767324b889SAlice Ryhl     /// need not be initialized.)
2777324b889SAlice Ryhl     #[inline]
2787324b889SAlice Ryhl     pub unsafe fn raw_get(ptr: *const Self) -> *mut bindings::work_struct {
2797324b889SAlice Ryhl         // SAFETY: The caller promises that the pointer is aligned and not dangling.
2807324b889SAlice Ryhl         //
2817324b889SAlice Ryhl         // A pointer cast would also be ok due to `#[repr(transparent)]`. We use `addr_of!` so that
2827324b889SAlice Ryhl         // the compiler does not complain that the `work` field is unused.
2837324b889SAlice Ryhl         unsafe { Opaque::raw_get(core::ptr::addr_of!((*ptr).work)) }
2847324b889SAlice Ryhl     }
2857324b889SAlice Ryhl }
2867324b889SAlice Ryhl 
2877324b889SAlice Ryhl /// Declares that a type has a [`Work<T, ID>`] field.
2887324b889SAlice Ryhl ///
2897324b889SAlice Ryhl /// The intended way of using this trait is via the [`impl_has_work!`] macro. You can use the macro
2907324b889SAlice Ryhl /// like this:
2917324b889SAlice Ryhl ///
2927324b889SAlice Ryhl /// ```no_run
2937324b889SAlice Ryhl /// use kernel::impl_has_work;
2947324b889SAlice Ryhl /// use kernel::prelude::*;
2957324b889SAlice Ryhl /// use kernel::workqueue::Work;
2967324b889SAlice Ryhl ///
2977324b889SAlice Ryhl /// struct MyWorkItem {
2987324b889SAlice Ryhl ///     work_field: Work<MyWorkItem, 1>,
2997324b889SAlice Ryhl /// }
3007324b889SAlice Ryhl ///
3017324b889SAlice Ryhl /// impl_has_work! {
3027324b889SAlice Ryhl ///     impl HasWork<MyWorkItem, 1> for MyWorkItem { self.work_field }
3037324b889SAlice Ryhl /// }
3047324b889SAlice Ryhl /// ```
3057324b889SAlice Ryhl ///
3067324b889SAlice Ryhl /// Note that since the `Work` type is annotated with an id, you can have several `work_struct`
3077324b889SAlice Ryhl /// fields by using a different id for each one.
3087324b889SAlice Ryhl ///
3097324b889SAlice Ryhl /// # Safety
3107324b889SAlice Ryhl ///
3117324b889SAlice Ryhl /// The [`OFFSET`] constant must be the offset of a field in Self of type [`Work<T, ID>`]. The methods on
3127324b889SAlice Ryhl /// this trait must have exactly the behavior that the definitions given below have.
3137324b889SAlice Ryhl ///
3147324b889SAlice Ryhl /// [`Work<T, ID>`]: Work
3157324b889SAlice Ryhl /// [`impl_has_work!`]: crate::impl_has_work
3167324b889SAlice Ryhl /// [`OFFSET`]: HasWork::OFFSET
3177324b889SAlice Ryhl pub unsafe trait HasWork<T, const ID: u64 = 0> {
3187324b889SAlice Ryhl     /// The offset of the [`Work<T, ID>`] field.
3197324b889SAlice Ryhl     ///
3207324b889SAlice Ryhl     /// [`Work<T, ID>`]: Work
3217324b889SAlice Ryhl     const OFFSET: usize;
3227324b889SAlice Ryhl 
3237324b889SAlice Ryhl     /// Returns the offset of the [`Work<T, ID>`] field.
3247324b889SAlice Ryhl     ///
3257324b889SAlice Ryhl     /// This method exists because the [`OFFSET`] constant cannot be accessed if the type is not Sized.
3267324b889SAlice Ryhl     ///
3277324b889SAlice Ryhl     /// [`Work<T, ID>`]: Work
3287324b889SAlice Ryhl     /// [`OFFSET`]: HasWork::OFFSET
3297324b889SAlice Ryhl     #[inline]
3307324b889SAlice Ryhl     fn get_work_offset(&self) -> usize {
3317324b889SAlice Ryhl         Self::OFFSET
3327324b889SAlice Ryhl     }
3337324b889SAlice Ryhl 
3347324b889SAlice Ryhl     /// Returns a pointer to the [`Work<T, ID>`] field.
3357324b889SAlice Ryhl     ///
3367324b889SAlice Ryhl     /// # Safety
3377324b889SAlice Ryhl     ///
3387324b889SAlice Ryhl     /// The provided pointer must point at a valid struct of type `Self`.
3397324b889SAlice Ryhl     ///
3407324b889SAlice Ryhl     /// [`Work<T, ID>`]: Work
3417324b889SAlice Ryhl     #[inline]
3427324b889SAlice Ryhl     unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<T, ID> {
3437324b889SAlice Ryhl         // SAFETY: The caller promises that the pointer is valid.
3447324b889SAlice Ryhl         unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut Work<T, ID> }
3457324b889SAlice Ryhl     }
3467324b889SAlice Ryhl 
3477324b889SAlice Ryhl     /// Returns a pointer to the struct containing the [`Work<T, ID>`] field.
3487324b889SAlice Ryhl     ///
3497324b889SAlice Ryhl     /// # Safety
3507324b889SAlice Ryhl     ///
3517324b889SAlice Ryhl     /// The pointer must point at a [`Work<T, ID>`] field in a struct of type `Self`.
3527324b889SAlice Ryhl     ///
3537324b889SAlice Ryhl     /// [`Work<T, ID>`]: Work
3547324b889SAlice Ryhl     #[inline]
3557324b889SAlice Ryhl     unsafe fn work_container_of(ptr: *mut Work<T, ID>) -> *mut Self
3567324b889SAlice Ryhl     where
3577324b889SAlice Ryhl         Self: Sized,
3587324b889SAlice Ryhl     {
3597324b889SAlice Ryhl         // SAFETY: The caller promises that the pointer points at a field of the right type in the
3607324b889SAlice Ryhl         // right kind of struct.
3617324b889SAlice Ryhl         unsafe { (ptr as *mut u8).sub(Self::OFFSET) as *mut Self }
3627324b889SAlice Ryhl     }
3637324b889SAlice Ryhl }
3647324b889SAlice Ryhl 
3657324b889SAlice Ryhl /// Used to safely implement the [`HasWork<T, ID>`] trait.
3667324b889SAlice Ryhl ///
3677324b889SAlice Ryhl /// # Examples
3687324b889SAlice Ryhl ///
3697324b889SAlice Ryhl /// ```
3707324b889SAlice Ryhl /// use kernel::impl_has_work;
3717324b889SAlice Ryhl /// use kernel::sync::Arc;
3727324b889SAlice Ryhl /// use kernel::workqueue::{self, Work};
3737324b889SAlice Ryhl ///
3747324b889SAlice Ryhl /// struct MyStruct {
3757324b889SAlice Ryhl ///     work_field: Work<MyStruct, 17>,
3767324b889SAlice Ryhl /// }
3777324b889SAlice Ryhl ///
3787324b889SAlice Ryhl /// impl_has_work! {
3797324b889SAlice Ryhl ///     impl HasWork<MyStruct, 17> for MyStruct { self.work_field }
3807324b889SAlice Ryhl /// }
3817324b889SAlice Ryhl /// ```
3827324b889SAlice Ryhl ///
3837324b889SAlice Ryhl /// [`HasWork<T, ID>`]: HasWork
3847324b889SAlice Ryhl #[macro_export]
3857324b889SAlice Ryhl macro_rules! impl_has_work {
3867324b889SAlice Ryhl     ($(impl$(<$($implarg:ident),*>)?
3877324b889SAlice Ryhl        HasWork<$work_type:ty $(, $id:tt)?>
3887324b889SAlice Ryhl        for $self:ident $(<$($selfarg:ident),*>)?
3897324b889SAlice Ryhl        { self.$field:ident }
3907324b889SAlice Ryhl     )*) => {$(
3917324b889SAlice Ryhl         // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right
3927324b889SAlice Ryhl         // type.
3937324b889SAlice Ryhl         unsafe impl$(<$($implarg),*>)? $crate::workqueue::HasWork<$work_type $(, $id)?> for $self $(<$($selfarg),*>)? {
3947324b889SAlice Ryhl             const OFFSET: usize = ::core::mem::offset_of!(Self, $field) as usize;
3957324b889SAlice Ryhl 
3967324b889SAlice Ryhl             #[inline]
3977324b889SAlice Ryhl             unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_type $(, $id)?> {
3987324b889SAlice Ryhl                 // SAFETY: The caller promises that the pointer is not dangling.
3997324b889SAlice Ryhl                 unsafe {
4007324b889SAlice Ryhl                     ::core::ptr::addr_of_mut!((*ptr).$field)
4017324b889SAlice Ryhl                 }
4027324b889SAlice Ryhl             }
4037324b889SAlice Ryhl         }
4047324b889SAlice Ryhl     )*};
4057324b889SAlice Ryhl }
4067324b889SAlice Ryhl 
407*115c95e9SAlice Ryhl impl_has_work! {
408*115c95e9SAlice Ryhl     impl<T> HasWork<Self> for ClosureWork<T> { self.work }
409*115c95e9SAlice Ryhl }
410*115c95e9SAlice Ryhl 
41147f0dbe8SAlice Ryhl unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
41247f0dbe8SAlice Ryhl where
41347f0dbe8SAlice Ryhl     T: WorkItem<ID, Pointer = Self>,
41447f0dbe8SAlice Ryhl     T: HasWork<T, ID>,
41547f0dbe8SAlice Ryhl {
41647f0dbe8SAlice Ryhl     unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
41747f0dbe8SAlice Ryhl         // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
41847f0dbe8SAlice Ryhl         let ptr = ptr as *mut Work<T, ID>;
41947f0dbe8SAlice Ryhl         // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
42047f0dbe8SAlice Ryhl         let ptr = unsafe { T::work_container_of(ptr) };
42147f0dbe8SAlice Ryhl         // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
42247f0dbe8SAlice Ryhl         let arc = unsafe { Arc::from_raw(ptr) };
42347f0dbe8SAlice Ryhl 
42447f0dbe8SAlice Ryhl         T::run(arc)
42547f0dbe8SAlice Ryhl     }
42647f0dbe8SAlice Ryhl }
42747f0dbe8SAlice Ryhl 
42847f0dbe8SAlice Ryhl unsafe impl<T, const ID: u64> RawWorkItem<ID> for Arc<T>
42947f0dbe8SAlice Ryhl where
43047f0dbe8SAlice Ryhl     T: WorkItem<ID, Pointer = Self>,
43147f0dbe8SAlice Ryhl     T: HasWork<T, ID>,
43247f0dbe8SAlice Ryhl {
43347f0dbe8SAlice Ryhl     type EnqueueOutput = Result<(), Self>;
43447f0dbe8SAlice Ryhl 
43547f0dbe8SAlice Ryhl     unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
43647f0dbe8SAlice Ryhl     where
43747f0dbe8SAlice Ryhl         F: FnOnce(*mut bindings::work_struct) -> bool,
43847f0dbe8SAlice Ryhl     {
43947f0dbe8SAlice Ryhl         // Casting between const and mut is not a problem as long as the pointer is a raw pointer.
44047f0dbe8SAlice Ryhl         let ptr = Arc::into_raw(self).cast_mut();
44147f0dbe8SAlice Ryhl 
44247f0dbe8SAlice Ryhl         // SAFETY: Pointers into an `Arc` point at a valid value.
44347f0dbe8SAlice Ryhl         let work_ptr = unsafe { T::raw_get_work(ptr) };
44447f0dbe8SAlice Ryhl         // SAFETY: `raw_get_work` returns a pointer to a valid value.
44547f0dbe8SAlice Ryhl         let work_ptr = unsafe { Work::raw_get(work_ptr) };
44647f0dbe8SAlice Ryhl 
44747f0dbe8SAlice Ryhl         if queue_work_on(work_ptr) {
44847f0dbe8SAlice Ryhl             Ok(())
44947f0dbe8SAlice Ryhl         } else {
45047f0dbe8SAlice Ryhl             // SAFETY: The work queue has not taken ownership of the pointer.
45147f0dbe8SAlice Ryhl             Err(unsafe { Arc::from_raw(ptr) })
45247f0dbe8SAlice Ryhl         }
45347f0dbe8SAlice Ryhl     }
45447f0dbe8SAlice Ryhl }
45547f0dbe8SAlice Ryhl 
45647f0dbe8SAlice Ryhl unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<Box<T>>
45747f0dbe8SAlice Ryhl where
45847f0dbe8SAlice Ryhl     T: WorkItem<ID, Pointer = Self>,
45947f0dbe8SAlice Ryhl     T: HasWork<T, ID>,
46047f0dbe8SAlice Ryhl {
46147f0dbe8SAlice Ryhl     unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
46247f0dbe8SAlice Ryhl         // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
46347f0dbe8SAlice Ryhl         let ptr = ptr as *mut Work<T, ID>;
46447f0dbe8SAlice Ryhl         // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
46547f0dbe8SAlice Ryhl         let ptr = unsafe { T::work_container_of(ptr) };
46647f0dbe8SAlice Ryhl         // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
46747f0dbe8SAlice Ryhl         let boxed = unsafe { Box::from_raw(ptr) };
46847f0dbe8SAlice Ryhl         // SAFETY: The box was already pinned when it was enqueued.
46947f0dbe8SAlice Ryhl         let pinned = unsafe { Pin::new_unchecked(boxed) };
47047f0dbe8SAlice Ryhl 
47147f0dbe8SAlice Ryhl         T::run(pinned)
47247f0dbe8SAlice Ryhl     }
47347f0dbe8SAlice Ryhl }
47447f0dbe8SAlice Ryhl 
47547f0dbe8SAlice Ryhl unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<Box<T>>
47647f0dbe8SAlice Ryhl where
47747f0dbe8SAlice Ryhl     T: WorkItem<ID, Pointer = Self>,
47847f0dbe8SAlice Ryhl     T: HasWork<T, ID>,
47947f0dbe8SAlice Ryhl {
48047f0dbe8SAlice Ryhl     type EnqueueOutput = ();
48147f0dbe8SAlice Ryhl 
48247f0dbe8SAlice Ryhl     unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
48347f0dbe8SAlice Ryhl     where
48447f0dbe8SAlice Ryhl         F: FnOnce(*mut bindings::work_struct) -> bool,
48547f0dbe8SAlice Ryhl     {
48647f0dbe8SAlice Ryhl         // SAFETY: We're not going to move `self` or any of its fields, so its okay to temporarily
48747f0dbe8SAlice Ryhl         // remove the `Pin` wrapper.
48847f0dbe8SAlice Ryhl         let boxed = unsafe { Pin::into_inner_unchecked(self) };
48947f0dbe8SAlice Ryhl         let ptr = Box::into_raw(boxed);
49047f0dbe8SAlice Ryhl 
49147f0dbe8SAlice Ryhl         // SAFETY: Pointers into a `Box` point at a valid value.
49247f0dbe8SAlice Ryhl         let work_ptr = unsafe { T::raw_get_work(ptr) };
49347f0dbe8SAlice Ryhl         // SAFETY: `raw_get_work` returns a pointer to a valid value.
49447f0dbe8SAlice Ryhl         let work_ptr = unsafe { Work::raw_get(work_ptr) };
49547f0dbe8SAlice Ryhl 
49647f0dbe8SAlice Ryhl         if !queue_work_on(work_ptr) {
49747f0dbe8SAlice Ryhl             // SAFETY: This method requires exclusive ownership of the box, so it cannot be in a
49847f0dbe8SAlice Ryhl             // workqueue.
49947f0dbe8SAlice Ryhl             unsafe { ::core::hint::unreachable_unchecked() }
50047f0dbe8SAlice Ryhl         }
50147f0dbe8SAlice Ryhl     }
50247f0dbe8SAlice Ryhl }
50347f0dbe8SAlice Ryhl 
50403394130SWedson Almeida Filho /// Returns the system work queue (`system_wq`).
50503394130SWedson Almeida Filho ///
50603394130SWedson Almeida Filho /// It is the one used by `schedule[_delayed]_work[_on]()`. Multi-CPU multi-threaded. There are
50703394130SWedson Almeida Filho /// users which expect relatively short queue flush time.
50803394130SWedson Almeida Filho ///
50903394130SWedson Almeida Filho /// Callers shouldn't queue work items which can run for too long.
51003394130SWedson Almeida Filho pub fn system() -> &'static Queue {
51103394130SWedson Almeida Filho     // SAFETY: `system_wq` is a C global, always available.
51203394130SWedson Almeida Filho     unsafe { Queue::from_raw(bindings::system_wq) }
51303394130SWedson Almeida Filho }
51403394130SWedson Almeida Filho 
51503394130SWedson Almeida Filho /// Returns the system high-priority work queue (`system_highpri_wq`).
51603394130SWedson Almeida Filho ///
51703394130SWedson Almeida Filho /// It is similar to the one returned by [`system`] but for work items which require higher
51803394130SWedson Almeida Filho /// scheduling priority.
51903394130SWedson Almeida Filho pub fn system_highpri() -> &'static Queue {
52003394130SWedson Almeida Filho     // SAFETY: `system_highpri_wq` is a C global, always available.
52103394130SWedson Almeida Filho     unsafe { Queue::from_raw(bindings::system_highpri_wq) }
52203394130SWedson Almeida Filho }
52303394130SWedson Almeida Filho 
52403394130SWedson Almeida Filho /// Returns the system work queue for potentially long-running work items (`system_long_wq`).
52503394130SWedson Almeida Filho ///
52603394130SWedson Almeida Filho /// It is similar to the one returned by [`system`] but may host long running work items. Queue
52703394130SWedson Almeida Filho /// flushing might take relatively long.
52803394130SWedson Almeida Filho pub fn system_long() -> &'static Queue {
52903394130SWedson Almeida Filho     // SAFETY: `system_long_wq` is a C global, always available.
53003394130SWedson Almeida Filho     unsafe { Queue::from_raw(bindings::system_long_wq) }
53103394130SWedson Almeida Filho }
53203394130SWedson Almeida Filho 
53303394130SWedson Almeida Filho /// Returns the system unbound work queue (`system_unbound_wq`).
53403394130SWedson Almeida Filho ///
53503394130SWedson Almeida Filho /// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items
53603394130SWedson Almeida Filho /// are executed immediately as long as `max_active` limit is not reached and resources are
53703394130SWedson Almeida Filho /// available.
53803394130SWedson Almeida Filho pub fn system_unbound() -> &'static Queue {
53903394130SWedson Almeida Filho     // SAFETY: `system_unbound_wq` is a C global, always available.
54003394130SWedson Almeida Filho     unsafe { Queue::from_raw(bindings::system_unbound_wq) }
54103394130SWedson Almeida Filho }
54203394130SWedson Almeida Filho 
54303394130SWedson Almeida Filho /// Returns the system freezable work queue (`system_freezable_wq`).
54403394130SWedson Almeida Filho ///
54503394130SWedson Almeida Filho /// It is equivalent to the one returned by [`system`] except that it's freezable.
54603394130SWedson Almeida Filho ///
54703394130SWedson Almeida Filho /// A freezable workqueue participates in the freeze phase of the system suspend operations. Work
54803394130SWedson Almeida Filho /// items on the workqueue are drained and no new work item starts execution until thawed.
54903394130SWedson Almeida Filho pub fn system_freezable() -> &'static Queue {
55003394130SWedson Almeida Filho     // SAFETY: `system_freezable_wq` is a C global, always available.
55103394130SWedson Almeida Filho     unsafe { Queue::from_raw(bindings::system_freezable_wq) }
55203394130SWedson Almeida Filho }
55303394130SWedson Almeida Filho 
55403394130SWedson Almeida Filho /// Returns the system power-efficient work queue (`system_power_efficient_wq`).
55503394130SWedson Almeida Filho ///
55603394130SWedson Almeida Filho /// It is inclined towards saving power and is converted to "unbound" variants if the
55703394130SWedson Almeida Filho /// `workqueue.power_efficient` kernel parameter is specified; otherwise, it is similar to the one
55803394130SWedson Almeida Filho /// returned by [`system`].
55903394130SWedson Almeida Filho pub fn system_power_efficient() -> &'static Queue {
56003394130SWedson Almeida Filho     // SAFETY: `system_power_efficient_wq` is a C global, always available.
56103394130SWedson Almeida Filho     unsafe { Queue::from_raw(bindings::system_power_efficient_wq) }
56203394130SWedson Almeida Filho }
56303394130SWedson Almeida Filho 
56403394130SWedson Almeida Filho /// Returns the system freezable power-efficient work queue (`system_freezable_power_efficient_wq`).
56503394130SWedson Almeida Filho ///
56603394130SWedson Almeida Filho /// It is similar to the one returned by [`system_power_efficient`] except that is freezable.
56703394130SWedson Almeida Filho ///
56803394130SWedson Almeida Filho /// A freezable workqueue participates in the freeze phase of the system suspend operations. Work
56903394130SWedson Almeida Filho /// items on the workqueue are drained and no new work item starts execution until thawed.
57003394130SWedson Almeida Filho pub fn system_freezable_power_efficient() -> &'static Queue {
57103394130SWedson Almeida Filho     // SAFETY: `system_freezable_power_efficient_wq` is a C global, always available.
57203394130SWedson Almeida Filho     unsafe { Queue::from_raw(bindings::system_freezable_power_efficient_wq) }
57303394130SWedson Almeida Filho }
574