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