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