xref: /linux-6.15/rust/kernel/workqueue.rs (revision 47f0dbe8)
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 
31*47f0dbe8SAlice Ryhl use crate::{bindings, prelude::*, sync::Arc, sync::LockClassKey, types::Opaque};
32*47f0dbe8SAlice Ryhl use alloc::boxed::Box;
337324b889SAlice Ryhl use core::marker::PhantomData;
34*47f0dbe8SAlice Ryhl use core::pin::Pin;
357324b889SAlice Ryhl 
367324b889SAlice Ryhl /// Creates a [`Work`] initialiser with the given name and a newly-created lock class.
377324b889SAlice Ryhl #[macro_export]
387324b889SAlice Ryhl macro_rules! new_work {
397324b889SAlice Ryhl     ($($name:literal)?) => {
407324b889SAlice Ryhl         $crate::workqueue::Work::new($crate::optional_name!($($name)?), $crate::static_lock_class!())
417324b889SAlice Ryhl     };
427324b889SAlice Ryhl }
43d4d791d4SAlice Ryhl 
44d4d791d4SAlice Ryhl /// A kernel work queue.
45d4d791d4SAlice Ryhl ///
46d4d791d4SAlice Ryhl /// Wraps the kernel's C `struct workqueue_struct`.
47d4d791d4SAlice Ryhl ///
48d4d791d4SAlice Ryhl /// It allows work items to be queued to run on thread pools managed by the kernel. Several are
49d4d791d4SAlice Ryhl /// always available, for example, `system`, `system_highpri`, `system_long`, etc.
50d4d791d4SAlice Ryhl #[repr(transparent)]
51d4d791d4SAlice Ryhl pub struct Queue(Opaque<bindings::workqueue_struct>);
52d4d791d4SAlice Ryhl 
53d4d791d4SAlice Ryhl // SAFETY: Accesses to workqueues used by [`Queue`] are thread-safe.
54d4d791d4SAlice Ryhl unsafe impl Send for Queue {}
55d4d791d4SAlice Ryhl // SAFETY: Accesses to workqueues used by [`Queue`] are thread-safe.
56d4d791d4SAlice Ryhl unsafe impl Sync for Queue {}
57d4d791d4SAlice Ryhl 
58d4d791d4SAlice Ryhl impl Queue {
59d4d791d4SAlice Ryhl     /// Use the provided `struct workqueue_struct` with Rust.
60d4d791d4SAlice Ryhl     ///
61d4d791d4SAlice Ryhl     /// # Safety
62d4d791d4SAlice Ryhl     ///
63d4d791d4SAlice Ryhl     /// The caller must ensure that the provided raw pointer is not dangling, that it points at a
64d4d791d4SAlice Ryhl     /// valid workqueue, and that it remains valid until the end of 'a.
65d4d791d4SAlice Ryhl     pub unsafe fn from_raw<'a>(ptr: *const bindings::workqueue_struct) -> &'a Queue {
66d4d791d4SAlice Ryhl         // SAFETY: The `Queue` type is `#[repr(transparent)]`, so the pointer cast is valid. The
67d4d791d4SAlice Ryhl         // caller promises that the pointer is not dangling.
68d4d791d4SAlice Ryhl         unsafe { &*(ptr as *const Queue) }
69d4d791d4SAlice Ryhl     }
70d4d791d4SAlice Ryhl 
71d4d791d4SAlice Ryhl     /// Enqueues a work item.
72d4d791d4SAlice Ryhl     ///
73d4d791d4SAlice Ryhl     /// This may fail if the work item is already enqueued in a workqueue.
74d4d791d4SAlice Ryhl     ///
75d4d791d4SAlice Ryhl     /// The work item will be submitted using `WORK_CPU_UNBOUND`.
76d4d791d4SAlice Ryhl     pub fn enqueue<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput
77d4d791d4SAlice Ryhl     where
78d4d791d4SAlice Ryhl         W: RawWorkItem<ID> + Send + 'static,
79d4d791d4SAlice Ryhl     {
80d4d791d4SAlice Ryhl         let queue_ptr = self.0.get();
81d4d791d4SAlice Ryhl 
82d4d791d4SAlice Ryhl         // SAFETY: We only return `false` if the `work_struct` is already in a workqueue. The other
83d4d791d4SAlice Ryhl         // `__enqueue` requirements are not relevant since `W` is `Send` and static.
84d4d791d4SAlice Ryhl         //
85d4d791d4SAlice Ryhl         // The call to `bindings::queue_work_on` will dereference the provided raw pointer, which
86d4d791d4SAlice Ryhl         // is ok because `__enqueue` guarantees that the pointer is valid for the duration of this
87d4d791d4SAlice Ryhl         // closure.
88d4d791d4SAlice Ryhl         //
89d4d791d4SAlice Ryhl         // Furthermore, if the C workqueue code accesses the pointer after this call to
90d4d791d4SAlice Ryhl         // `__enqueue`, then the work item was successfully enqueued, and `bindings::queue_work_on`
91d4d791d4SAlice Ryhl         // will have returned true. In this case, `__enqueue` promises that the raw pointer will
92d4d791d4SAlice Ryhl         // stay valid until we call the function pointer in the `work_struct`, so the access is ok.
93d4d791d4SAlice Ryhl         unsafe {
94d4d791d4SAlice Ryhl             w.__enqueue(move |work_ptr| {
95d4d791d4SAlice Ryhl                 bindings::queue_work_on(bindings::WORK_CPU_UNBOUND as _, queue_ptr, work_ptr)
96d4d791d4SAlice Ryhl             })
97d4d791d4SAlice Ryhl         }
98d4d791d4SAlice Ryhl     }
99d4d791d4SAlice Ryhl }
100d4d791d4SAlice Ryhl 
101d4d791d4SAlice Ryhl /// A raw work item.
102d4d791d4SAlice Ryhl ///
103d4d791d4SAlice Ryhl /// This is the low-level trait that is designed for being as general as possible.
104d4d791d4SAlice Ryhl ///
105d4d791d4SAlice Ryhl /// The `ID` parameter to this trait exists so that a single type can provide multiple
106d4d791d4SAlice Ryhl /// implementations of this trait. For example, if a struct has multiple `work_struct` fields, then
107d4d791d4SAlice Ryhl /// you will implement this trait once for each field, using a different id for each field. The
108d4d791d4SAlice Ryhl /// actual value of the id is not important as long as you use different ids for different fields
109d4d791d4SAlice Ryhl /// of the same struct. (Fields of different structs need not use different ids.)
110d4d791d4SAlice Ryhl ///
111d4d791d4SAlice Ryhl /// Note that the id is used only to select the right method to call during compilation. It wont be
112d4d791d4SAlice Ryhl /// part of the final executable.
113d4d791d4SAlice Ryhl ///
114d4d791d4SAlice Ryhl /// # Safety
115d4d791d4SAlice Ryhl ///
116d4d791d4SAlice Ryhl /// Implementers must ensure that any pointers passed to a `queue_work_on` closure by `__enqueue`
117d4d791d4SAlice Ryhl /// remain valid for the duration specified in the guarantees section of the documentation for
118d4d791d4SAlice Ryhl /// `__enqueue`.
119d4d791d4SAlice Ryhl pub unsafe trait RawWorkItem<const ID: u64> {
120d4d791d4SAlice Ryhl     /// The return type of [`Queue::enqueue`].
121d4d791d4SAlice Ryhl     type EnqueueOutput;
122d4d791d4SAlice Ryhl 
123d4d791d4SAlice Ryhl     /// Enqueues this work item on a queue using the provided `queue_work_on` method.
124d4d791d4SAlice Ryhl     ///
125d4d791d4SAlice Ryhl     /// # Guarantees
126d4d791d4SAlice Ryhl     ///
127d4d791d4SAlice Ryhl     /// If this method calls the provided closure, then the raw pointer is guaranteed to point at a
128d4d791d4SAlice Ryhl     /// valid `work_struct` for the duration of the call to the closure. If the closure returns
129d4d791d4SAlice Ryhl     /// true, then it is further guaranteed that the pointer remains valid until someone calls the
130d4d791d4SAlice Ryhl     /// function pointer stored in the `work_struct`.
131d4d791d4SAlice Ryhl     ///
132d4d791d4SAlice Ryhl     /// # Safety
133d4d791d4SAlice Ryhl     ///
134d4d791d4SAlice Ryhl     /// The provided closure may only return `false` if the `work_struct` is already in a workqueue.
135d4d791d4SAlice Ryhl     ///
136d4d791d4SAlice Ryhl     /// If the work item type is annotated with any lifetimes, then you must not call the function
137d4d791d4SAlice Ryhl     /// pointer after any such lifetime expires. (Never calling the function pointer is okay.)
138d4d791d4SAlice Ryhl     ///
139d4d791d4SAlice Ryhl     /// If the work item type is not [`Send`], then the function pointer must be called on the same
140d4d791d4SAlice Ryhl     /// thread as the call to `__enqueue`.
141d4d791d4SAlice Ryhl     unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
142d4d791d4SAlice Ryhl     where
143d4d791d4SAlice Ryhl         F: FnOnce(*mut bindings::work_struct) -> bool;
144d4d791d4SAlice Ryhl }
14503394130SWedson Almeida Filho 
1467324b889SAlice Ryhl /// Defines the method that should be called directly when a work item is executed.
1477324b889SAlice Ryhl ///
1487324b889SAlice Ryhl /// This trait is implemented by `Pin<Box<T>>` and `Arc<T>`, and is mainly intended to be
1497324b889SAlice Ryhl /// implemented for smart pointer types. For your own structs, you would implement [`WorkItem`]
1507324b889SAlice Ryhl /// instead. The `run` method on this trait will usually just perform the appropriate
1517324b889SAlice Ryhl /// `container_of` translation and then call into the `run` method from the [`WorkItem`] trait.
1527324b889SAlice Ryhl ///
1537324b889SAlice Ryhl /// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
1547324b889SAlice Ryhl ///
1557324b889SAlice Ryhl /// # Safety
1567324b889SAlice Ryhl ///
1577324b889SAlice Ryhl /// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with the [`run`]
1587324b889SAlice Ryhl /// method of this trait as the function pointer.
1597324b889SAlice Ryhl ///
1607324b889SAlice Ryhl /// [`__enqueue`]: RawWorkItem::__enqueue
1617324b889SAlice Ryhl /// [`run`]: WorkItemPointer::run
1627324b889SAlice Ryhl pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
1637324b889SAlice Ryhl     /// Run this work item.
1647324b889SAlice Ryhl     ///
1657324b889SAlice Ryhl     /// # Safety
1667324b889SAlice Ryhl     ///
1677324b889SAlice Ryhl     /// The provided `work_struct` pointer must originate from a previous call to `__enqueue` where
1687324b889SAlice Ryhl     /// the `queue_work_on` closure returned true, and the pointer must still be valid.
1697324b889SAlice Ryhl     unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
1707324b889SAlice Ryhl }
1717324b889SAlice Ryhl 
1727324b889SAlice Ryhl /// Defines the method that should be called when this work item is executed.
1737324b889SAlice Ryhl ///
1747324b889SAlice Ryhl /// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
1757324b889SAlice Ryhl pub trait WorkItem<const ID: u64 = 0> {
1767324b889SAlice Ryhl     /// The pointer type that this struct is wrapped in. This will typically be `Arc<Self>` or
1777324b889SAlice Ryhl     /// `Pin<Box<Self>>`.
1787324b889SAlice Ryhl     type Pointer: WorkItemPointer<ID>;
1797324b889SAlice Ryhl 
1807324b889SAlice Ryhl     /// The method that should be called when this work item is executed.
1817324b889SAlice Ryhl     fn run(this: Self::Pointer);
1827324b889SAlice Ryhl }
1837324b889SAlice Ryhl 
1847324b889SAlice Ryhl /// Links for a work item.
1857324b889SAlice Ryhl ///
1867324b889SAlice Ryhl /// This struct contains a function pointer to the `run` function from the [`WorkItemPointer`]
1877324b889SAlice Ryhl /// trait, and defines the linked list pointers necessary to enqueue a work item in a workqueue.
1887324b889SAlice Ryhl ///
1897324b889SAlice Ryhl /// Wraps the kernel's C `struct work_struct`.
1907324b889SAlice Ryhl ///
1917324b889SAlice Ryhl /// This is a helper type used to associate a `work_struct` with the [`WorkItem`] that uses it.
1927324b889SAlice Ryhl #[repr(transparent)]
1937324b889SAlice Ryhl pub struct Work<T: ?Sized, const ID: u64 = 0> {
1947324b889SAlice Ryhl     work: Opaque<bindings::work_struct>,
1957324b889SAlice Ryhl     _inner: PhantomData<T>,
1967324b889SAlice Ryhl }
1977324b889SAlice Ryhl 
1987324b889SAlice Ryhl // SAFETY: Kernel work items are usable from any thread.
1997324b889SAlice Ryhl //
2007324b889SAlice Ryhl // We do not need to constrain `T` since the work item does not actually contain a `T`.
2017324b889SAlice Ryhl unsafe impl<T: ?Sized, const ID: u64> Send for Work<T, ID> {}
2027324b889SAlice Ryhl // SAFETY: Kernel work items are usable from any thread.
2037324b889SAlice Ryhl //
2047324b889SAlice Ryhl // We do not need to constrain `T` since the work item does not actually contain a `T`.
2057324b889SAlice Ryhl unsafe impl<T: ?Sized, const ID: u64> Sync for Work<T, ID> {}
2067324b889SAlice Ryhl 
2077324b889SAlice Ryhl impl<T: ?Sized, const ID: u64> Work<T, ID> {
2087324b889SAlice Ryhl     /// Creates a new instance of [`Work`].
2097324b889SAlice Ryhl     #[inline]
2107324b889SAlice Ryhl     #[allow(clippy::new_ret_no_self)]
2117324b889SAlice Ryhl     pub fn new(name: &'static CStr, key: &'static LockClassKey) -> impl PinInit<Self>
2127324b889SAlice Ryhl     where
2137324b889SAlice Ryhl         T: WorkItem<ID>,
2147324b889SAlice Ryhl     {
2157324b889SAlice Ryhl         // SAFETY: The `WorkItemPointer` implementation promises that `run` can be used as the work
2167324b889SAlice Ryhl         // item function.
2177324b889SAlice Ryhl         unsafe {
2187324b889SAlice Ryhl             kernel::init::pin_init_from_closure(move |slot| {
2197324b889SAlice Ryhl                 let slot = Self::raw_get(slot);
2207324b889SAlice Ryhl                 bindings::init_work_with_key(
2217324b889SAlice Ryhl                     slot,
2227324b889SAlice Ryhl                     Some(T::Pointer::run),
2237324b889SAlice Ryhl                     false,
2247324b889SAlice Ryhl                     name.as_char_ptr(),
2257324b889SAlice Ryhl                     key.as_ptr(),
2267324b889SAlice Ryhl                 );
2277324b889SAlice Ryhl                 Ok(())
2287324b889SAlice Ryhl             })
2297324b889SAlice Ryhl         }
2307324b889SAlice Ryhl     }
2317324b889SAlice Ryhl 
2327324b889SAlice Ryhl     /// Get a pointer to the inner `work_struct`.
2337324b889SAlice Ryhl     ///
2347324b889SAlice Ryhl     /// # Safety
2357324b889SAlice Ryhl     ///
2367324b889SAlice Ryhl     /// The provided pointer must not be dangling and must be properly aligned. (But the memory
2377324b889SAlice Ryhl     /// need not be initialized.)
2387324b889SAlice Ryhl     #[inline]
2397324b889SAlice Ryhl     pub unsafe fn raw_get(ptr: *const Self) -> *mut bindings::work_struct {
2407324b889SAlice Ryhl         // SAFETY: The caller promises that the pointer is aligned and not dangling.
2417324b889SAlice Ryhl         //
2427324b889SAlice Ryhl         // A pointer cast would also be ok due to `#[repr(transparent)]`. We use `addr_of!` so that
2437324b889SAlice Ryhl         // the compiler does not complain that the `work` field is unused.
2447324b889SAlice Ryhl         unsafe { Opaque::raw_get(core::ptr::addr_of!((*ptr).work)) }
2457324b889SAlice Ryhl     }
2467324b889SAlice Ryhl }
2477324b889SAlice Ryhl 
2487324b889SAlice Ryhl /// Declares that a type has a [`Work<T, ID>`] field.
2497324b889SAlice Ryhl ///
2507324b889SAlice Ryhl /// The intended way of using this trait is via the [`impl_has_work!`] macro. You can use the macro
2517324b889SAlice Ryhl /// like this:
2527324b889SAlice Ryhl ///
2537324b889SAlice Ryhl /// ```no_run
2547324b889SAlice Ryhl /// use kernel::impl_has_work;
2557324b889SAlice Ryhl /// use kernel::prelude::*;
2567324b889SAlice Ryhl /// use kernel::workqueue::Work;
2577324b889SAlice Ryhl ///
2587324b889SAlice Ryhl /// struct MyWorkItem {
2597324b889SAlice Ryhl ///     work_field: Work<MyWorkItem, 1>,
2607324b889SAlice Ryhl /// }
2617324b889SAlice Ryhl ///
2627324b889SAlice Ryhl /// impl_has_work! {
2637324b889SAlice Ryhl ///     impl HasWork<MyWorkItem, 1> for MyWorkItem { self.work_field }
2647324b889SAlice Ryhl /// }
2657324b889SAlice Ryhl /// ```
2667324b889SAlice Ryhl ///
2677324b889SAlice Ryhl /// Note that since the `Work` type is annotated with an id, you can have several `work_struct`
2687324b889SAlice Ryhl /// fields by using a different id for each one.
2697324b889SAlice Ryhl ///
2707324b889SAlice Ryhl /// # Safety
2717324b889SAlice Ryhl ///
2727324b889SAlice Ryhl /// The [`OFFSET`] constant must be the offset of a field in Self of type [`Work<T, ID>`]. The methods on
2737324b889SAlice Ryhl /// this trait must have exactly the behavior that the definitions given below have.
2747324b889SAlice Ryhl ///
2757324b889SAlice Ryhl /// [`Work<T, ID>`]: Work
2767324b889SAlice Ryhl /// [`impl_has_work!`]: crate::impl_has_work
2777324b889SAlice Ryhl /// [`OFFSET`]: HasWork::OFFSET
2787324b889SAlice Ryhl pub unsafe trait HasWork<T, const ID: u64 = 0> {
2797324b889SAlice Ryhl     /// The offset of the [`Work<T, ID>`] field.
2807324b889SAlice Ryhl     ///
2817324b889SAlice Ryhl     /// [`Work<T, ID>`]: Work
2827324b889SAlice Ryhl     const OFFSET: usize;
2837324b889SAlice Ryhl 
2847324b889SAlice Ryhl     /// Returns the offset of the [`Work<T, ID>`] field.
2857324b889SAlice Ryhl     ///
2867324b889SAlice Ryhl     /// This method exists because the [`OFFSET`] constant cannot be accessed if the type is not Sized.
2877324b889SAlice Ryhl     ///
2887324b889SAlice Ryhl     /// [`Work<T, ID>`]: Work
2897324b889SAlice Ryhl     /// [`OFFSET`]: HasWork::OFFSET
2907324b889SAlice Ryhl     #[inline]
2917324b889SAlice Ryhl     fn get_work_offset(&self) -> usize {
2927324b889SAlice Ryhl         Self::OFFSET
2937324b889SAlice Ryhl     }
2947324b889SAlice Ryhl 
2957324b889SAlice Ryhl     /// Returns a pointer to the [`Work<T, ID>`] field.
2967324b889SAlice Ryhl     ///
2977324b889SAlice Ryhl     /// # Safety
2987324b889SAlice Ryhl     ///
2997324b889SAlice Ryhl     /// The provided pointer must point at a valid struct of type `Self`.
3007324b889SAlice Ryhl     ///
3017324b889SAlice Ryhl     /// [`Work<T, ID>`]: Work
3027324b889SAlice Ryhl     #[inline]
3037324b889SAlice Ryhl     unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<T, ID> {
3047324b889SAlice Ryhl         // SAFETY: The caller promises that the pointer is valid.
3057324b889SAlice Ryhl         unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut Work<T, ID> }
3067324b889SAlice Ryhl     }
3077324b889SAlice Ryhl 
3087324b889SAlice Ryhl     /// Returns a pointer to the struct containing the [`Work<T, ID>`] field.
3097324b889SAlice Ryhl     ///
3107324b889SAlice Ryhl     /// # Safety
3117324b889SAlice Ryhl     ///
3127324b889SAlice Ryhl     /// The pointer must point at a [`Work<T, ID>`] field in a struct of type `Self`.
3137324b889SAlice Ryhl     ///
3147324b889SAlice Ryhl     /// [`Work<T, ID>`]: Work
3157324b889SAlice Ryhl     #[inline]
3167324b889SAlice Ryhl     unsafe fn work_container_of(ptr: *mut Work<T, ID>) -> *mut Self
3177324b889SAlice Ryhl     where
3187324b889SAlice Ryhl         Self: Sized,
3197324b889SAlice Ryhl     {
3207324b889SAlice Ryhl         // SAFETY: The caller promises that the pointer points at a field of the right type in the
3217324b889SAlice Ryhl         // right kind of struct.
3227324b889SAlice Ryhl         unsafe { (ptr as *mut u8).sub(Self::OFFSET) as *mut Self }
3237324b889SAlice Ryhl     }
3247324b889SAlice Ryhl }
3257324b889SAlice Ryhl 
3267324b889SAlice Ryhl /// Used to safely implement the [`HasWork<T, ID>`] trait.
3277324b889SAlice Ryhl ///
3287324b889SAlice Ryhl /// # Examples
3297324b889SAlice Ryhl ///
3307324b889SAlice Ryhl /// ```
3317324b889SAlice Ryhl /// use kernel::impl_has_work;
3327324b889SAlice Ryhl /// use kernel::sync::Arc;
3337324b889SAlice Ryhl /// use kernel::workqueue::{self, Work};
3347324b889SAlice Ryhl ///
3357324b889SAlice Ryhl /// struct MyStruct {
3367324b889SAlice Ryhl ///     work_field: Work<MyStruct, 17>,
3377324b889SAlice Ryhl /// }
3387324b889SAlice Ryhl ///
3397324b889SAlice Ryhl /// impl_has_work! {
3407324b889SAlice Ryhl ///     impl HasWork<MyStruct, 17> for MyStruct { self.work_field }
3417324b889SAlice Ryhl /// }
3427324b889SAlice Ryhl /// ```
3437324b889SAlice Ryhl ///
3447324b889SAlice Ryhl /// [`HasWork<T, ID>`]: HasWork
3457324b889SAlice Ryhl #[macro_export]
3467324b889SAlice Ryhl macro_rules! impl_has_work {
3477324b889SAlice Ryhl     ($(impl$(<$($implarg:ident),*>)?
3487324b889SAlice Ryhl        HasWork<$work_type:ty $(, $id:tt)?>
3497324b889SAlice Ryhl        for $self:ident $(<$($selfarg:ident),*>)?
3507324b889SAlice Ryhl        { self.$field:ident }
3517324b889SAlice Ryhl     )*) => {$(
3527324b889SAlice Ryhl         // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right
3537324b889SAlice Ryhl         // type.
3547324b889SAlice Ryhl         unsafe impl$(<$($implarg),*>)? $crate::workqueue::HasWork<$work_type $(, $id)?> for $self $(<$($selfarg),*>)? {
3557324b889SAlice Ryhl             const OFFSET: usize = ::core::mem::offset_of!(Self, $field) as usize;
3567324b889SAlice Ryhl 
3577324b889SAlice Ryhl             #[inline]
3587324b889SAlice Ryhl             unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_type $(, $id)?> {
3597324b889SAlice Ryhl                 // SAFETY: The caller promises that the pointer is not dangling.
3607324b889SAlice Ryhl                 unsafe {
3617324b889SAlice Ryhl                     ::core::ptr::addr_of_mut!((*ptr).$field)
3627324b889SAlice Ryhl                 }
3637324b889SAlice Ryhl             }
3647324b889SAlice Ryhl         }
3657324b889SAlice Ryhl     )*};
3667324b889SAlice Ryhl }
3677324b889SAlice Ryhl 
368*47f0dbe8SAlice Ryhl unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
369*47f0dbe8SAlice Ryhl where
370*47f0dbe8SAlice Ryhl     T: WorkItem<ID, Pointer = Self>,
371*47f0dbe8SAlice Ryhl     T: HasWork<T, ID>,
372*47f0dbe8SAlice Ryhl {
373*47f0dbe8SAlice Ryhl     unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
374*47f0dbe8SAlice Ryhl         // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
375*47f0dbe8SAlice Ryhl         let ptr = ptr as *mut Work<T, ID>;
376*47f0dbe8SAlice Ryhl         // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
377*47f0dbe8SAlice Ryhl         let ptr = unsafe { T::work_container_of(ptr) };
378*47f0dbe8SAlice Ryhl         // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
379*47f0dbe8SAlice Ryhl         let arc = unsafe { Arc::from_raw(ptr) };
380*47f0dbe8SAlice Ryhl 
381*47f0dbe8SAlice Ryhl         T::run(arc)
382*47f0dbe8SAlice Ryhl     }
383*47f0dbe8SAlice Ryhl }
384*47f0dbe8SAlice Ryhl 
385*47f0dbe8SAlice Ryhl unsafe impl<T, const ID: u64> RawWorkItem<ID> for Arc<T>
386*47f0dbe8SAlice Ryhl where
387*47f0dbe8SAlice Ryhl     T: WorkItem<ID, Pointer = Self>,
388*47f0dbe8SAlice Ryhl     T: HasWork<T, ID>,
389*47f0dbe8SAlice Ryhl {
390*47f0dbe8SAlice Ryhl     type EnqueueOutput = Result<(), Self>;
391*47f0dbe8SAlice Ryhl 
392*47f0dbe8SAlice Ryhl     unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
393*47f0dbe8SAlice Ryhl     where
394*47f0dbe8SAlice Ryhl         F: FnOnce(*mut bindings::work_struct) -> bool,
395*47f0dbe8SAlice Ryhl     {
396*47f0dbe8SAlice Ryhl         // Casting between const and mut is not a problem as long as the pointer is a raw pointer.
397*47f0dbe8SAlice Ryhl         let ptr = Arc::into_raw(self).cast_mut();
398*47f0dbe8SAlice Ryhl 
399*47f0dbe8SAlice Ryhl         // SAFETY: Pointers into an `Arc` point at a valid value.
400*47f0dbe8SAlice Ryhl         let work_ptr = unsafe { T::raw_get_work(ptr) };
401*47f0dbe8SAlice Ryhl         // SAFETY: `raw_get_work` returns a pointer to a valid value.
402*47f0dbe8SAlice Ryhl         let work_ptr = unsafe { Work::raw_get(work_ptr) };
403*47f0dbe8SAlice Ryhl 
404*47f0dbe8SAlice Ryhl         if queue_work_on(work_ptr) {
405*47f0dbe8SAlice Ryhl             Ok(())
406*47f0dbe8SAlice Ryhl         } else {
407*47f0dbe8SAlice Ryhl             // SAFETY: The work queue has not taken ownership of the pointer.
408*47f0dbe8SAlice Ryhl             Err(unsafe { Arc::from_raw(ptr) })
409*47f0dbe8SAlice Ryhl         }
410*47f0dbe8SAlice Ryhl     }
411*47f0dbe8SAlice Ryhl }
412*47f0dbe8SAlice Ryhl 
413*47f0dbe8SAlice Ryhl unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<Box<T>>
414*47f0dbe8SAlice Ryhl where
415*47f0dbe8SAlice Ryhl     T: WorkItem<ID, Pointer = Self>,
416*47f0dbe8SAlice Ryhl     T: HasWork<T, ID>,
417*47f0dbe8SAlice Ryhl {
418*47f0dbe8SAlice Ryhl     unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
419*47f0dbe8SAlice Ryhl         // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
420*47f0dbe8SAlice Ryhl         let ptr = ptr as *mut Work<T, ID>;
421*47f0dbe8SAlice Ryhl         // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
422*47f0dbe8SAlice Ryhl         let ptr = unsafe { T::work_container_of(ptr) };
423*47f0dbe8SAlice Ryhl         // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
424*47f0dbe8SAlice Ryhl         let boxed = unsafe { Box::from_raw(ptr) };
425*47f0dbe8SAlice Ryhl         // SAFETY: The box was already pinned when it was enqueued.
426*47f0dbe8SAlice Ryhl         let pinned = unsafe { Pin::new_unchecked(boxed) };
427*47f0dbe8SAlice Ryhl 
428*47f0dbe8SAlice Ryhl         T::run(pinned)
429*47f0dbe8SAlice Ryhl     }
430*47f0dbe8SAlice Ryhl }
431*47f0dbe8SAlice Ryhl 
432*47f0dbe8SAlice Ryhl unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<Box<T>>
433*47f0dbe8SAlice Ryhl where
434*47f0dbe8SAlice Ryhl     T: WorkItem<ID, Pointer = Self>,
435*47f0dbe8SAlice Ryhl     T: HasWork<T, ID>,
436*47f0dbe8SAlice Ryhl {
437*47f0dbe8SAlice Ryhl     type EnqueueOutput = ();
438*47f0dbe8SAlice Ryhl 
439*47f0dbe8SAlice Ryhl     unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
440*47f0dbe8SAlice Ryhl     where
441*47f0dbe8SAlice Ryhl         F: FnOnce(*mut bindings::work_struct) -> bool,
442*47f0dbe8SAlice Ryhl     {
443*47f0dbe8SAlice Ryhl         // SAFETY: We're not going to move `self` or any of its fields, so its okay to temporarily
444*47f0dbe8SAlice Ryhl         // remove the `Pin` wrapper.
445*47f0dbe8SAlice Ryhl         let boxed = unsafe { Pin::into_inner_unchecked(self) };
446*47f0dbe8SAlice Ryhl         let ptr = Box::into_raw(boxed);
447*47f0dbe8SAlice Ryhl 
448*47f0dbe8SAlice Ryhl         // SAFETY: Pointers into a `Box` point at a valid value.
449*47f0dbe8SAlice Ryhl         let work_ptr = unsafe { T::raw_get_work(ptr) };
450*47f0dbe8SAlice Ryhl         // SAFETY: `raw_get_work` returns a pointer to a valid value.
451*47f0dbe8SAlice Ryhl         let work_ptr = unsafe { Work::raw_get(work_ptr) };
452*47f0dbe8SAlice Ryhl 
453*47f0dbe8SAlice Ryhl         if !queue_work_on(work_ptr) {
454*47f0dbe8SAlice Ryhl             // SAFETY: This method requires exclusive ownership of the box, so it cannot be in a
455*47f0dbe8SAlice Ryhl             // workqueue.
456*47f0dbe8SAlice Ryhl             unsafe { ::core::hint::unreachable_unchecked() }
457*47f0dbe8SAlice Ryhl         }
458*47f0dbe8SAlice Ryhl     }
459*47f0dbe8SAlice Ryhl }
460*47f0dbe8SAlice Ryhl 
46103394130SWedson Almeida Filho /// Returns the system work queue (`system_wq`).
46203394130SWedson Almeida Filho ///
46303394130SWedson Almeida Filho /// It is the one used by `schedule[_delayed]_work[_on]()`. Multi-CPU multi-threaded. There are
46403394130SWedson Almeida Filho /// users which expect relatively short queue flush time.
46503394130SWedson Almeida Filho ///
46603394130SWedson Almeida Filho /// Callers shouldn't queue work items which can run for too long.
46703394130SWedson Almeida Filho pub fn system() -> &'static Queue {
46803394130SWedson Almeida Filho     // SAFETY: `system_wq` is a C global, always available.
46903394130SWedson Almeida Filho     unsafe { Queue::from_raw(bindings::system_wq) }
47003394130SWedson Almeida Filho }
47103394130SWedson Almeida Filho 
47203394130SWedson Almeida Filho /// Returns the system high-priority work queue (`system_highpri_wq`).
47303394130SWedson Almeida Filho ///
47403394130SWedson Almeida Filho /// It is similar to the one returned by [`system`] but for work items which require higher
47503394130SWedson Almeida Filho /// scheduling priority.
47603394130SWedson Almeida Filho pub fn system_highpri() -> &'static Queue {
47703394130SWedson Almeida Filho     // SAFETY: `system_highpri_wq` is a C global, always available.
47803394130SWedson Almeida Filho     unsafe { Queue::from_raw(bindings::system_highpri_wq) }
47903394130SWedson Almeida Filho }
48003394130SWedson Almeida Filho 
48103394130SWedson Almeida Filho /// Returns the system work queue for potentially long-running work items (`system_long_wq`).
48203394130SWedson Almeida Filho ///
48303394130SWedson Almeida Filho /// It is similar to the one returned by [`system`] but may host long running work items. Queue
48403394130SWedson Almeida Filho /// flushing might take relatively long.
48503394130SWedson Almeida Filho pub fn system_long() -> &'static Queue {
48603394130SWedson Almeida Filho     // SAFETY: `system_long_wq` is a C global, always available.
48703394130SWedson Almeida Filho     unsafe { Queue::from_raw(bindings::system_long_wq) }
48803394130SWedson Almeida Filho }
48903394130SWedson Almeida Filho 
49003394130SWedson Almeida Filho /// Returns the system unbound work queue (`system_unbound_wq`).
49103394130SWedson Almeida Filho ///
49203394130SWedson Almeida Filho /// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items
49303394130SWedson Almeida Filho /// are executed immediately as long as `max_active` limit is not reached and resources are
49403394130SWedson Almeida Filho /// available.
49503394130SWedson Almeida Filho pub fn system_unbound() -> &'static Queue {
49603394130SWedson Almeida Filho     // SAFETY: `system_unbound_wq` is a C global, always available.
49703394130SWedson Almeida Filho     unsafe { Queue::from_raw(bindings::system_unbound_wq) }
49803394130SWedson Almeida Filho }
49903394130SWedson Almeida Filho 
50003394130SWedson Almeida Filho /// Returns the system freezable work queue (`system_freezable_wq`).
50103394130SWedson Almeida Filho ///
50203394130SWedson Almeida Filho /// It is equivalent to the one returned by [`system`] except that it's freezable.
50303394130SWedson Almeida Filho ///
50403394130SWedson Almeida Filho /// A freezable workqueue participates in the freeze phase of the system suspend operations. Work
50503394130SWedson Almeida Filho /// items on the workqueue are drained and no new work item starts execution until thawed.
50603394130SWedson Almeida Filho pub fn system_freezable() -> &'static Queue {
50703394130SWedson Almeida Filho     // SAFETY: `system_freezable_wq` is a C global, always available.
50803394130SWedson Almeida Filho     unsafe { Queue::from_raw(bindings::system_freezable_wq) }
50903394130SWedson Almeida Filho }
51003394130SWedson Almeida Filho 
51103394130SWedson Almeida Filho /// Returns the system power-efficient work queue (`system_power_efficient_wq`).
51203394130SWedson Almeida Filho ///
51303394130SWedson Almeida Filho /// It is inclined towards saving power and is converted to "unbound" variants if the
51403394130SWedson Almeida Filho /// `workqueue.power_efficient` kernel parameter is specified; otherwise, it is similar to the one
51503394130SWedson Almeida Filho /// returned by [`system`].
51603394130SWedson Almeida Filho pub fn system_power_efficient() -> &'static Queue {
51703394130SWedson Almeida Filho     // SAFETY: `system_power_efficient_wq` is a C global, always available.
51803394130SWedson Almeida Filho     unsafe { Queue::from_raw(bindings::system_power_efficient_wq) }
51903394130SWedson Almeida Filho }
52003394130SWedson Almeida Filho 
52103394130SWedson Almeida Filho /// Returns the system freezable power-efficient work queue (`system_freezable_power_efficient_wq`).
52203394130SWedson Almeida Filho ///
52303394130SWedson Almeida Filho /// It is similar to the one returned by [`system_power_efficient`] except that is freezable.
52403394130SWedson Almeida Filho ///
52503394130SWedson Almeida Filho /// A freezable workqueue participates in the freeze phase of the system suspend operations. Work
52603394130SWedson Almeida Filho /// items on the workqueue are drained and no new work item starts execution until thawed.
52703394130SWedson Almeida Filho pub fn system_freezable_power_efficient() -> &'static Queue {
52803394130SWedson Almeida Filho     // SAFETY: `system_freezable_power_efficient_wq` is a C global, always available.
52903394130SWedson Almeida Filho     unsafe { Queue::from_raw(bindings::system_freezable_power_efficient_wq) }
53003394130SWedson Almeida Filho }
531