kernel/
workqueue.rs

1// SPDX-License-Identifier: GPL-2.0
2
3//! Work queues.
4//!
5//! This file has two components: The raw work item API, and the safe work item API.
6//!
7//! One pattern that is used in both APIs is the `ID` const generic, which exists to allow a single
8//! type to define multiple `work_struct` fields. This is done by choosing an id for each field,
9//! and using that id to specify which field you wish to use. (The actual value doesn't matter, as
10//! long as you use different values for different fields of the same struct.) Since these IDs are
11//! generic, they are used only at compile-time, so they shouldn't exist in the final binary.
12//!
13//! # The raw API
14//!
15//! The raw API consists of the [`RawWorkItem`] trait, where the work item needs to provide an
16//! arbitrary function that knows how to enqueue the work item. It should usually not be used
17//! directly, but if you want to, you can use it without using the pieces from the safe API.
18//!
19//! # The safe API
20//!
21//! The safe API is used via the [`Work`] struct and [`WorkItem`] traits. Furthermore, it also
22//! includes a trait called [`WorkItemPointer`], which is usually not used directly by the user.
23//!
24//!  * The [`Work`] struct is the Rust wrapper for the C `work_struct` type.
25//!  * The [`WorkItem`] trait is implemented for structs that can be enqueued to a workqueue.
26//!  * The [`WorkItemPointer`] trait is implemented for the pointer type that points at a something
27//!    that implements [`WorkItem`].
28//!
29//! ## Example
30//!
31//! This example defines a struct that holds an integer and can be scheduled on the workqueue. When
32//! the struct is executed, it will print the integer. Since there is only one `work_struct` field,
33//! we do not need to specify ids for the fields.
34//!
35//! ```
36//! use kernel::sync::Arc;
37//! use kernel::workqueue::{self, impl_has_work, new_work, Work, WorkItem};
38//!
39//! #[pin_data]
40//! struct MyStruct {
41//!     value: i32,
42//!     #[pin]
43//!     work: Work<MyStruct>,
44//! }
45//!
46//! impl_has_work! {
47//!     impl HasWork<Self> for MyStruct { self.work }
48//! }
49//!
50//! impl MyStruct {
51//!     fn new(value: i32) -> Result<Arc<Self>> {
52//!         Arc::pin_init(pin_init!(MyStruct {
53//!             value,
54//!             work <- new_work!("MyStruct::work"),
55//!         }), GFP_KERNEL)
56//!     }
57//! }
58//!
59//! impl WorkItem for MyStruct {
60//!     type Pointer = Arc<MyStruct>;
61//!
62//!     fn run(this: Arc<MyStruct>) {
63//!         pr_info!("The value is: {}\n", this.value);
64//!     }
65//! }
66//!
67//! /// This method will enqueue the struct for execution on the system workqueue, where its value
68//! /// will be printed.
69//! fn print_later(val: Arc<MyStruct>) {
70//!     let _ = workqueue::system().enqueue(val);
71//! }
72//! # print_later(MyStruct::new(42).unwrap());
73//! ```
74//!
75//! The following example shows how multiple `work_struct` fields can be used:
76//!
77//! ```
78//! use kernel::sync::Arc;
79//! use kernel::workqueue::{self, impl_has_work, new_work, Work, WorkItem};
80//!
81//! #[pin_data]
82//! struct MyStruct {
83//!     value_1: i32,
84//!     value_2: i32,
85//!     #[pin]
86//!     work_1: Work<MyStruct, 1>,
87//!     #[pin]
88//!     work_2: Work<MyStruct, 2>,
89//! }
90//!
91//! impl_has_work! {
92//!     impl HasWork<Self, 1> for MyStruct { self.work_1 }
93//!     impl HasWork<Self, 2> for MyStruct { self.work_2 }
94//! }
95//!
96//! impl MyStruct {
97//!     fn new(value_1: i32, value_2: i32) -> Result<Arc<Self>> {
98//!         Arc::pin_init(pin_init!(MyStruct {
99//!             value_1,
100//!             value_2,
101//!             work_1 <- new_work!("MyStruct::work_1"),
102//!             work_2 <- new_work!("MyStruct::work_2"),
103//!         }), GFP_KERNEL)
104//!     }
105//! }
106//!
107//! impl WorkItem<1> for MyStruct {
108//!     type Pointer = Arc<MyStruct>;
109//!
110//!     fn run(this: Arc<MyStruct>) {
111//!         pr_info!("The value is: {}\n", this.value_1);
112//!     }
113//! }
114//!
115//! impl WorkItem<2> for MyStruct {
116//!     type Pointer = Arc<MyStruct>;
117//!
118//!     fn run(this: Arc<MyStruct>) {
119//!         pr_info!("The second value is: {}\n", this.value_2);
120//!     }
121//! }
122//!
123//! fn print_1_later(val: Arc<MyStruct>) {
124//!     let _ = workqueue::system().enqueue::<Arc<MyStruct>, 1>(val);
125//! }
126//!
127//! fn print_2_later(val: Arc<MyStruct>) {
128//!     let _ = workqueue::system().enqueue::<Arc<MyStruct>, 2>(val);
129//! }
130//! # print_1_later(MyStruct::new(24, 25).unwrap());
131//! # print_2_later(MyStruct::new(41, 42).unwrap());
132//! ```
133//!
134//! C header: [`include/linux/workqueue.h`](srctree/include/linux/workqueue.h)
135
136use crate::alloc::{AllocError, Flags};
137use crate::{prelude::*, sync::Arc, sync::LockClassKey, types::Opaque};
138use core::marker::PhantomData;
139
140/// Creates a [`Work`] initialiser with the given name and a newly-created lock class.
141#[macro_export]
142macro_rules! new_work {
143    ($($name:literal)?) => {
144        $crate::workqueue::Work::new($crate::optional_name!($($name)?), $crate::static_lock_class!())
145    };
146}
147pub use new_work;
148
149/// A kernel work queue.
150///
151/// Wraps the kernel's C `struct workqueue_struct`.
152///
153/// It allows work items to be queued to run on thread pools managed by the kernel. Several are
154/// always available, for example, `system`, `system_highpri`, `system_long`, etc.
155#[repr(transparent)]
156pub struct Queue(Opaque<bindings::workqueue_struct>);
157
158// SAFETY: Accesses to workqueues used by [`Queue`] are thread-safe.
159unsafe impl Send for Queue {}
160// SAFETY: Accesses to workqueues used by [`Queue`] are thread-safe.
161unsafe impl Sync for Queue {}
162
163impl Queue {
164    /// Use the provided `struct workqueue_struct` with Rust.
165    ///
166    /// # Safety
167    ///
168    /// The caller must ensure that the provided raw pointer is not dangling, that it points at a
169    /// valid workqueue, and that it remains valid until the end of `'a`.
170    pub unsafe fn from_raw<'a>(ptr: *const bindings::workqueue_struct) -> &'a Queue {
171        // SAFETY: The `Queue` type is `#[repr(transparent)]`, so the pointer cast is valid. The
172        // caller promises that the pointer is not dangling.
173        unsafe { &*(ptr as *const Queue) }
174    }
175
176    /// Enqueues a work item.
177    ///
178    /// This may fail if the work item is already enqueued in a workqueue.
179    ///
180    /// The work item will be submitted using `WORK_CPU_UNBOUND`.
181    pub fn enqueue<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput
182    where
183        W: RawWorkItem<ID> + Send + 'static,
184    {
185        let queue_ptr = self.0.get();
186
187        // SAFETY: We only return `false` if the `work_struct` is already in a workqueue. The other
188        // `__enqueue` requirements are not relevant since `W` is `Send` and static.
189        //
190        // The call to `bindings::queue_work_on` will dereference the provided raw pointer, which
191        // is ok because `__enqueue` guarantees that the pointer is valid for the duration of this
192        // closure.
193        //
194        // Furthermore, if the C workqueue code accesses the pointer after this call to
195        // `__enqueue`, then the work item was successfully enqueued, and `bindings::queue_work_on`
196        // will have returned true. In this case, `__enqueue` promises that the raw pointer will
197        // stay valid until we call the function pointer in the `work_struct`, so the access is ok.
198        unsafe {
199            w.__enqueue(move |work_ptr| {
200                bindings::queue_work_on(
201                    bindings::wq_misc_consts_WORK_CPU_UNBOUND as _,
202                    queue_ptr,
203                    work_ptr,
204                )
205            })
206        }
207    }
208
209    /// Tries to spawn the given function or closure as a work item.
210    ///
211    /// This method can fail because it allocates memory to store the work item.
212    pub fn try_spawn<T: 'static + Send + FnOnce()>(
213        &self,
214        flags: Flags,
215        func: T,
216    ) -> Result<(), AllocError> {
217        let init = pin_init!(ClosureWork {
218            work <- new_work!("Queue::try_spawn"),
219            func: Some(func),
220        });
221
222        self.enqueue(KBox::pin_init(init, flags).map_err(|_| AllocError)?);
223        Ok(())
224    }
225}
226
227/// A helper type used in [`try_spawn`].
228///
229/// [`try_spawn`]: Queue::try_spawn
230#[pin_data]
231struct ClosureWork<T> {
232    #[pin]
233    work: Work<ClosureWork<T>>,
234    func: Option<T>,
235}
236
237impl<T> ClosureWork<T> {
238    fn project(self: Pin<&mut Self>) -> &mut Option<T> {
239        // SAFETY: The `func` field is not structurally pinned.
240        unsafe { &mut self.get_unchecked_mut().func }
241    }
242}
243
244impl<T: FnOnce()> WorkItem for ClosureWork<T> {
245    type Pointer = Pin<KBox<Self>>;
246
247    fn run(mut this: Pin<KBox<Self>>) {
248        if let Some(func) = this.as_mut().project().take() {
249            (func)()
250        }
251    }
252}
253
254/// A raw work item.
255///
256/// This is the low-level trait that is designed for being as general as possible.
257///
258/// The `ID` parameter to this trait exists so that a single type can provide multiple
259/// implementations of this trait. For example, if a struct has multiple `work_struct` fields, then
260/// you will implement this trait once for each field, using a different id for each field. The
261/// actual value of the id is not important as long as you use different ids for different fields
262/// of the same struct. (Fields of different structs need not use different ids.)
263///
264/// Note that the id is used only to select the right method to call during compilation. It won't be
265/// part of the final executable.
266///
267/// # Safety
268///
269/// Implementers must ensure that any pointers passed to a `queue_work_on` closure by [`__enqueue`]
270/// remain valid for the duration specified in the guarantees section of the documentation for
271/// [`__enqueue`].
272///
273/// [`__enqueue`]: RawWorkItem::__enqueue
274pub unsafe trait RawWorkItem<const ID: u64> {
275    /// The return type of [`Queue::enqueue`].
276    type EnqueueOutput;
277
278    /// Enqueues this work item on a queue using the provided `queue_work_on` method.
279    ///
280    /// # Guarantees
281    ///
282    /// If this method calls the provided closure, then the raw pointer is guaranteed to point at a
283    /// valid `work_struct` for the duration of the call to the closure. If the closure returns
284    /// true, then it is further guaranteed that the pointer remains valid until someone calls the
285    /// function pointer stored in the `work_struct`.
286    ///
287    /// # Safety
288    ///
289    /// The provided closure may only return `false` if the `work_struct` is already in a workqueue.
290    ///
291    /// If the work item type is annotated with any lifetimes, then you must not call the function
292    /// pointer after any such lifetime expires. (Never calling the function pointer is okay.)
293    ///
294    /// If the work item type is not [`Send`], then the function pointer must be called on the same
295    /// thread as the call to `__enqueue`.
296    unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
297    where
298        F: FnOnce(*mut bindings::work_struct) -> bool;
299}
300
301/// Defines the method that should be called directly when a work item is executed.
302///
303/// This trait is implemented by `Pin<KBox<T>>` and [`Arc<T>`], and is mainly intended to be
304/// implemented for smart pointer types. For your own structs, you would implement [`WorkItem`]
305/// instead. The [`run`] method on this trait will usually just perform the appropriate
306/// `container_of` translation and then call into the [`run`][WorkItem::run] method from the
307/// [`WorkItem`] trait.
308///
309/// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
310///
311/// # Safety
312///
313/// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with the [`run`]
314/// method of this trait as the function pointer.
315///
316/// [`__enqueue`]: RawWorkItem::__enqueue
317/// [`run`]: WorkItemPointer::run
318pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
319    /// Run this work item.
320    ///
321    /// # Safety
322    ///
323    /// The provided `work_struct` pointer must originate from a previous call to [`__enqueue`]
324    /// where the `queue_work_on` closure returned true, and the pointer must still be valid.
325    ///
326    /// [`__enqueue`]: RawWorkItem::__enqueue
327    unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
328}
329
330/// Defines the method that should be called when this work item is executed.
331///
332/// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
333pub trait WorkItem<const ID: u64 = 0> {
334    /// The pointer type that this struct is wrapped in. This will typically be `Arc<Self>` or
335    /// `Pin<KBox<Self>>`.
336    type Pointer: WorkItemPointer<ID>;
337
338    /// The method that should be called when this work item is executed.
339    fn run(this: Self::Pointer);
340}
341
342/// Links for a work item.
343///
344/// This struct contains a function pointer to the [`run`] function from the [`WorkItemPointer`]
345/// trait, and defines the linked list pointers necessary to enqueue a work item in a workqueue.
346///
347/// Wraps the kernel's C `struct work_struct`.
348///
349/// This is a helper type used to associate a `work_struct` with the [`WorkItem`] that uses it.
350///
351/// [`run`]: WorkItemPointer::run
352#[pin_data]
353#[repr(transparent)]
354pub struct Work<T: ?Sized, const ID: u64 = 0> {
355    #[pin]
356    work: Opaque<bindings::work_struct>,
357    _inner: PhantomData<T>,
358}
359
360// SAFETY: Kernel work items are usable from any thread.
361//
362// We do not need to constrain `T` since the work item does not actually contain a `T`.
363unsafe impl<T: ?Sized, const ID: u64> Send for Work<T, ID> {}
364// SAFETY: Kernel work items are usable from any thread.
365//
366// We do not need to constrain `T` since the work item does not actually contain a `T`.
367unsafe impl<T: ?Sized, const ID: u64> Sync for Work<T, ID> {}
368
369impl<T: ?Sized, const ID: u64> Work<T, ID> {
370    /// Creates a new instance of [`Work`].
371    #[inline]
372    pub fn new(name: &'static CStr, key: Pin<&'static LockClassKey>) -> impl PinInit<Self>
373    where
374        T: WorkItem<ID>,
375    {
376        pin_init!(Self {
377            work <- Opaque::ffi_init(|slot| {
378                // SAFETY: The `WorkItemPointer` implementation promises that `run` can be used as
379                // the work item function.
380                unsafe {
381                    bindings::init_work_with_key(
382                        slot,
383                        Some(T::Pointer::run),
384                        false,
385                        name.as_char_ptr(),
386                        key.as_ptr(),
387                    )
388                }
389            }),
390            _inner: PhantomData,
391        })
392    }
393
394    /// Get a pointer to the inner `work_struct`.
395    ///
396    /// # Safety
397    ///
398    /// The provided pointer must not be dangling and must be properly aligned. (But the memory
399    /// need not be initialized.)
400    #[inline]
401    pub unsafe fn raw_get(ptr: *const Self) -> *mut bindings::work_struct {
402        // SAFETY: The caller promises that the pointer is aligned and not dangling.
403        //
404        // A pointer cast would also be ok due to `#[repr(transparent)]`. We use `addr_of!` so that
405        // the compiler does not complain that the `work` field is unused.
406        unsafe { Opaque::raw_get(core::ptr::addr_of!((*ptr).work)) }
407    }
408}
409
410/// Declares that a type has a [`Work<T, ID>`] field.
411///
412/// The intended way of using this trait is via the [`impl_has_work!`] macro. You can use the macro
413/// like this:
414///
415/// ```no_run
416/// use kernel::workqueue::{impl_has_work, Work};
417///
418/// struct MyWorkItem {
419///     work_field: Work<MyWorkItem, 1>,
420/// }
421///
422/// impl_has_work! {
423///     impl HasWork<MyWorkItem, 1> for MyWorkItem { self.work_field }
424/// }
425/// ```
426///
427/// Note that since the [`Work`] type is annotated with an id, you can have several `work_struct`
428/// fields by using a different id for each one.
429///
430/// # Safety
431///
432/// The [`OFFSET`] constant must be the offset of a field in `Self` of type [`Work<T, ID>`]. The
433/// methods on this trait must have exactly the behavior that the definitions given below have.
434///
435/// [`impl_has_work!`]: crate::impl_has_work
436/// [`OFFSET`]: HasWork::OFFSET
437pub unsafe trait HasWork<T, const ID: u64 = 0> {
438    /// The offset of the [`Work<T, ID>`] field.
439    const OFFSET: usize;
440
441    /// Returns the offset of the [`Work<T, ID>`] field.
442    ///
443    /// This method exists because the [`OFFSET`] constant cannot be accessed if the type is not
444    /// [`Sized`].
445    ///
446    /// [`OFFSET`]: HasWork::OFFSET
447    #[inline]
448    fn get_work_offset(&self) -> usize {
449        Self::OFFSET
450    }
451
452    /// Returns a pointer to the [`Work<T, ID>`] field.
453    ///
454    /// # Safety
455    ///
456    /// The provided pointer must point at a valid struct of type `Self`.
457    #[inline]
458    unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<T, ID> {
459        // SAFETY: The caller promises that the pointer is valid.
460        unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut Work<T, ID> }
461    }
462
463    /// Returns a pointer to the struct containing the [`Work<T, ID>`] field.
464    ///
465    /// # Safety
466    ///
467    /// The pointer must point at a [`Work<T, ID>`] field in a struct of type `Self`.
468    #[inline]
469    unsafe fn work_container_of(ptr: *mut Work<T, ID>) -> *mut Self
470    where
471        Self: Sized,
472    {
473        // SAFETY: The caller promises that the pointer points at a field of the right type in the
474        // right kind of struct.
475        unsafe { (ptr as *mut u8).sub(Self::OFFSET) as *mut Self }
476    }
477}
478
479/// Used to safely implement the [`HasWork<T, ID>`] trait.
480///
481/// # Examples
482///
483/// ```
484/// use kernel::sync::Arc;
485/// use kernel::workqueue::{self, impl_has_work, Work};
486///
487/// struct MyStruct<'a, T, const N: usize> {
488///     work_field: Work<MyStruct<'a, T, N>, 17>,
489///     f: fn(&'a [T; N]),
490/// }
491///
492/// impl_has_work! {
493///     impl{'a, T, const N: usize} HasWork<MyStruct<'a, T, N>, 17>
494///     for MyStruct<'a, T, N> { self.work_field }
495/// }
496/// ```
497#[macro_export]
498macro_rules! impl_has_work {
499    ($(impl$({$($generics:tt)*})?
500       HasWork<$work_type:ty $(, $id:tt)?>
501       for $self:ty
502       { self.$field:ident }
503    )*) => {$(
504        // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right
505        // type.
506        unsafe impl$(<$($generics)+>)? $crate::workqueue::HasWork<$work_type $(, $id)?> for $self {
507            const OFFSET: usize = ::core::mem::offset_of!(Self, $field) as usize;
508
509            #[inline]
510            unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_type $(, $id)?> {
511                // SAFETY: The caller promises that the pointer is not dangling.
512                unsafe {
513                    ::core::ptr::addr_of_mut!((*ptr).$field)
514                }
515            }
516        }
517    )*};
518}
519pub use impl_has_work;
520
521impl_has_work! {
522    impl{T} HasWork<Self> for ClosureWork<T> { self.work }
523}
524
525// SAFETY: The `__enqueue` implementation in RawWorkItem uses a `work_struct` initialized with the
526// `run` method of this trait as the function pointer because:
527//   - `__enqueue` gets the `work_struct` from the `Work` field, using `T::raw_get_work`.
528//   - The only safe way to create a `Work` object is through `Work::new`.
529//   - `Work::new` makes sure that `T::Pointer::run` is passed to `init_work_with_key`.
530//   - Finally `Work` and `RawWorkItem` guarantee that the correct `Work` field
531//     will be used because of the ID const generic bound. This makes sure that `T::raw_get_work`
532//     uses the correct offset for the `Work` field, and `Work::new` picks the correct
533//     implementation of `WorkItemPointer` for `Arc<T>`.
534unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
535where
536    T: WorkItem<ID, Pointer = Self>,
537    T: HasWork<T, ID>,
538{
539    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
540        // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
541        let ptr = ptr as *mut Work<T, ID>;
542        // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
543        let ptr = unsafe { T::work_container_of(ptr) };
544        // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
545        let arc = unsafe { Arc::from_raw(ptr) };
546
547        T::run(arc)
548    }
549}
550
551// SAFETY: The `work_struct` raw pointer is guaranteed to be valid for the duration of the call to
552// the closure because we get it from an `Arc`, which means that the ref count will be at least 1,
553// and we don't drop the `Arc` ourselves. If `queue_work_on` returns true, it is further guaranteed
554// to be valid until a call to the function pointer in `work_struct` because we leak the memory it
555// points to, and only reclaim it if the closure returns false, or in `WorkItemPointer::run`, which
556// is what the function pointer in the `work_struct` must be pointing to, according to the safety
557// requirements of `WorkItemPointer`.
558unsafe impl<T, const ID: u64> RawWorkItem<ID> for Arc<T>
559where
560    T: WorkItem<ID, Pointer = Self>,
561    T: HasWork<T, ID>,
562{
563    type EnqueueOutput = Result<(), Self>;
564
565    unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
566    where
567        F: FnOnce(*mut bindings::work_struct) -> bool,
568    {
569        // Casting between const and mut is not a problem as long as the pointer is a raw pointer.
570        let ptr = Arc::into_raw(self).cast_mut();
571
572        // SAFETY: Pointers into an `Arc` point at a valid value.
573        let work_ptr = unsafe { T::raw_get_work(ptr) };
574        // SAFETY: `raw_get_work` returns a pointer to a valid value.
575        let work_ptr = unsafe { Work::raw_get(work_ptr) };
576
577        if queue_work_on(work_ptr) {
578            Ok(())
579        } else {
580            // SAFETY: The work queue has not taken ownership of the pointer.
581            Err(unsafe { Arc::from_raw(ptr) })
582        }
583    }
584}
585
586// SAFETY: TODO.
587unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<KBox<T>>
588where
589    T: WorkItem<ID, Pointer = Self>,
590    T: HasWork<T, ID>,
591{
592    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
593        // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
594        let ptr = ptr as *mut Work<T, ID>;
595        // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
596        let ptr = unsafe { T::work_container_of(ptr) };
597        // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
598        let boxed = unsafe { KBox::from_raw(ptr) };
599        // SAFETY: The box was already pinned when it was enqueued.
600        let pinned = unsafe { Pin::new_unchecked(boxed) };
601
602        T::run(pinned)
603    }
604}
605
606// SAFETY: TODO.
607unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<KBox<T>>
608where
609    T: WorkItem<ID, Pointer = Self>,
610    T: HasWork<T, ID>,
611{
612    type EnqueueOutput = ();
613
614    unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
615    where
616        F: FnOnce(*mut bindings::work_struct) -> bool,
617    {
618        // SAFETY: We're not going to move `self` or any of its fields, so its okay to temporarily
619        // remove the `Pin` wrapper.
620        let boxed = unsafe { Pin::into_inner_unchecked(self) };
621        let ptr = KBox::into_raw(boxed);
622
623        // SAFETY: Pointers into a `KBox` point at a valid value.
624        let work_ptr = unsafe { T::raw_get_work(ptr) };
625        // SAFETY: `raw_get_work` returns a pointer to a valid value.
626        let work_ptr = unsafe { Work::raw_get(work_ptr) };
627
628        if !queue_work_on(work_ptr) {
629            // SAFETY: This method requires exclusive ownership of the box, so it cannot be in a
630            // workqueue.
631            unsafe { ::core::hint::unreachable_unchecked() }
632        }
633    }
634}
635
636/// Returns the system work queue (`system_wq`).
637///
638/// It is the one used by `schedule[_delayed]_work[_on]()`. Multi-CPU multi-threaded. There are
639/// users which expect relatively short queue flush time.
640///
641/// Callers shouldn't queue work items which can run for too long.
642pub fn system() -> &'static Queue {
643    // SAFETY: `system_wq` is a C global, always available.
644    unsafe { Queue::from_raw(bindings::system_wq) }
645}
646
647/// Returns the system high-priority work queue (`system_highpri_wq`).
648///
649/// It is similar to the one returned by [`system`] but for work items which require higher
650/// scheduling priority.
651pub fn system_highpri() -> &'static Queue {
652    // SAFETY: `system_highpri_wq` is a C global, always available.
653    unsafe { Queue::from_raw(bindings::system_highpri_wq) }
654}
655
656/// Returns the system work queue for potentially long-running work items (`system_long_wq`).
657///
658/// It is similar to the one returned by [`system`] but may host long running work items. Queue
659/// flushing might take relatively long.
660pub fn system_long() -> &'static Queue {
661    // SAFETY: `system_long_wq` is a C global, always available.
662    unsafe { Queue::from_raw(bindings::system_long_wq) }
663}
664
665/// Returns the system unbound work queue (`system_unbound_wq`).
666///
667/// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items
668/// are executed immediately as long as `max_active` limit is not reached and resources are
669/// available.
670pub fn system_unbound() -> &'static Queue {
671    // SAFETY: `system_unbound_wq` is a C global, always available.
672    unsafe { Queue::from_raw(bindings::system_unbound_wq) }
673}
674
675/// Returns the system freezable work queue (`system_freezable_wq`).
676///
677/// It is equivalent to the one returned by [`system`] except that it's freezable.
678///
679/// A freezable workqueue participates in the freeze phase of the system suspend operations. Work
680/// items on the workqueue are drained and no new work item starts execution until thawed.
681pub fn system_freezable() -> &'static Queue {
682    // SAFETY: `system_freezable_wq` is a C global, always available.
683    unsafe { Queue::from_raw(bindings::system_freezable_wq) }
684}
685
686/// Returns the system power-efficient work queue (`system_power_efficient_wq`).
687///
688/// It is inclined towards saving power and is converted to "unbound" variants if the
689/// `workqueue.power_efficient` kernel parameter is specified; otherwise, it is similar to the one
690/// returned by [`system`].
691pub fn system_power_efficient() -> &'static Queue {
692    // SAFETY: `system_power_efficient_wq` is a C global, always available.
693    unsafe { Queue::from_raw(bindings::system_power_efficient_wq) }
694}
695
696/// Returns the system freezable power-efficient work queue (`system_freezable_power_efficient_wq`).
697///
698/// It is similar to the one returned by [`system_power_efficient`] except that is freezable.
699///
700/// A freezable workqueue participates in the freeze phase of the system suspend operations. Work
701/// items on the workqueue are drained and no new work item starts execution until thawed.
702pub fn system_freezable_power_efficient() -> &'static Queue {
703    // SAFETY: `system_freezable_power_efficient_wq` is a C global, always available.
704    unsafe { Queue::from_raw(bindings::system_freezable_power_efficient_wq) }
705}
706
707/// Returns the system bottom halves work queue (`system_bh_wq`).
708///
709/// It is similar to the one returned by [`system`] but for work items which
710/// need to run from a softirq context.
711pub fn system_bh() -> &'static Queue {
712    // SAFETY: `system_bh_wq` is a C global, always available.
713    unsafe { Queue::from_raw(bindings::system_bh_wq) }
714}
715
716/// Returns the system bottom halves high-priority work queue (`system_bh_highpri_wq`).
717///
718/// It is similar to the one returned by [`system_bh`] but for work items which
719/// require higher scheduling priority.
720pub fn system_bh_highpri() -> &'static Queue {
721    // SAFETY: `system_bh_highpri_wq` is a C global, always available.
722    unsafe { Queue::from_raw(bindings::system_bh_highpri_wq) }
723}