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