Linux Audio

Check our new training course

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