kernel/workqueue.rs
1// SPDX-License-Identifier: GPL-2.0
2
3//! Work queues.
4//!
5//! This file has two components: The raw work item API, and the safe work item API.
6//!
7//! One pattern that is used in both APIs is the `ID` const generic, which exists to allow a single
8//! type to define multiple `work_struct` fields. This is done by choosing an id for each field,
9//! and using that id to specify which field you wish to use. (The actual value doesn't matter, as
10//! long as you use different values for different fields of the same struct.) Since these IDs are
11//! generic, they are used only at compile-time, so they shouldn't exist in the final binary.
12//!
13//! # The raw API
14//!
15//! The raw API consists of the [`RawWorkItem`] trait, where the work item needs to provide an
16//! arbitrary function that knows how to enqueue the work item. It should usually not be used
17//! directly, but if you want to, you can use it without using the pieces from the safe API.
18//!
19//! # The safe API
20//!
21//! The safe API is used via the [`Work`] struct and [`WorkItem`] traits. Furthermore, it also
22//! includes a trait called [`WorkItemPointer`], which is usually not used directly by the user.
23//!
24//! * The [`Work`] struct is the Rust wrapper for the C `work_struct` type.
25//! * The [`WorkItem`] trait is implemented for structs that can be enqueued to a workqueue.
26//! * The [`WorkItemPointer`] trait is implemented for the pointer type that points at a something
27//! that implements [`WorkItem`].
28//!
29//! ## Examples
30//!
31//! This example defines a struct that holds an integer and can be scheduled on the workqueue. When
32//! the struct is executed, it will print the integer. Since there is only one `work_struct` field,
33//! we do not need to specify ids for the fields.
34//!
35//! ```
36//! use kernel::sync::Arc;
37//! use kernel::workqueue::{self, impl_has_work, new_work, Work, WorkItem};
38//!
39//! #[pin_data]
40//! struct MyStruct {
41//! value: i32,
42//! #[pin]
43//! work: Work<MyStruct>,
44//! }
45//!
46//! impl_has_work! {
47//! impl HasWork<Self> for MyStruct { self.work }
48//! }
49//!
50//! impl MyStruct {
51//! fn new(value: i32) -> Result<Arc<Self>> {
52//! Arc::pin_init(pin_init!(MyStruct {
53//! value,
54//! work <- new_work!("MyStruct::work"),
55//! }), GFP_KERNEL)
56//! }
57//! }
58//!
59//! impl WorkItem for MyStruct {
60//! type Pointer = Arc<MyStruct>;
61//!
62//! fn run(this: Arc<MyStruct>) {
63//! pr_info!("The value is: {}\n", this.value);
64//! }
65//! }
66//!
67//! /// This method will enqueue the struct for execution on the system workqueue, where its value
68//! /// will be printed.
69//! fn print_later(val: Arc<MyStruct>) {
70//! let _ = workqueue::system().enqueue(val);
71//! }
72//! # print_later(MyStruct::new(42).unwrap());
73//! ```
74//!
75//! The following example shows how multiple `work_struct` fields can be used:
76//!
77//! ```
78//! use kernel::sync::Arc;
79//! use kernel::workqueue::{self, impl_has_work, new_work, Work, WorkItem};
80//!
81//! #[pin_data]
82//! struct MyStruct {
83//! value_1: i32,
84//! value_2: i32,
85//! #[pin]
86//! work_1: Work<MyStruct, 1>,
87//! #[pin]
88//! work_2: Work<MyStruct, 2>,
89//! }
90//!
91//! impl_has_work! {
92//! impl HasWork<Self, 1> for MyStruct { self.work_1 }
93//! impl HasWork<Self, 2> for MyStruct { self.work_2 }
94//! }
95//!
96//! impl MyStruct {
97//! fn new(value_1: i32, value_2: i32) -> Result<Arc<Self>> {
98//! Arc::pin_init(pin_init!(MyStruct {
99//! value_1,
100//! value_2,
101//! work_1 <- new_work!("MyStruct::work_1"),
102//! work_2 <- new_work!("MyStruct::work_2"),
103//! }), GFP_KERNEL)
104//! }
105//! }
106//!
107//! impl WorkItem<1> for MyStruct {
108//! type Pointer = Arc<MyStruct>;
109//!
110//! fn run(this: Arc<MyStruct>) {
111//! pr_info!("The value is: {}\n", this.value_1);
112//! }
113//! }
114//!
115//! impl WorkItem<2> for MyStruct {
116//! type Pointer = Arc<MyStruct>;
117//!
118//! fn run(this: Arc<MyStruct>) {
119//! pr_info!("The second value is: {}\n", this.value_2);
120//! }
121//! }
122//!
123//! fn print_1_later(val: Arc<MyStruct>) {
124//! let _ = workqueue::system().enqueue::<Arc<MyStruct>, 1>(val);
125//! }
126//!
127//! fn print_2_later(val: Arc<MyStruct>) {
128//! let _ = workqueue::system().enqueue::<Arc<MyStruct>, 2>(val);
129//! }
130//! # print_1_later(MyStruct::new(24, 25).unwrap());
131//! # print_2_later(MyStruct::new(41, 42).unwrap());
132//! ```
133//!
134//! This example shows how you can schedule delayed work items:
135//!
136//! ```
137//! use kernel::sync::Arc;
138//! use kernel::workqueue::{self, impl_has_delayed_work, new_delayed_work, DelayedWork, WorkItem};
139//!
140//! #[pin_data]
141//! struct MyStruct {
142//! value: i32,
143//! #[pin]
144//! work: DelayedWork<MyStruct>,
145//! }
146//!
147//! impl_has_delayed_work! {
148//! impl HasDelayedWork<Self> for MyStruct { self.work }
149//! }
150//!
151//! impl MyStruct {
152//! fn new(value: i32) -> Result<Arc<Self>> {
153//! Arc::pin_init(
154//! pin_init!(MyStruct {
155//! value,
156//! work <- new_delayed_work!("MyStruct::work"),
157//! }),
158//! GFP_KERNEL,
159//! )
160//! }
161//! }
162//!
163//! impl WorkItem for MyStruct {
164//! type Pointer = Arc<MyStruct>;
165//!
166//! fn run(this: Arc<MyStruct>) {
167//! pr_info!("The value is: {}\n", this.value);
168//! }
169//! }
170//!
171//! /// This method will enqueue the struct for execution on the system workqueue, where its value
172//! /// will be printed 12 jiffies later.
173//! fn print_later(val: Arc<MyStruct>) {
174//! let _ = workqueue::system().enqueue_delayed(val, 12);
175//! }
176//!
177//! /// It is also possible to use the ordinary `enqueue` method together with `DelayedWork`. This
178//! /// is equivalent to calling `enqueue_delayed` with a delay of zero.
179//! fn print_now(val: Arc<MyStruct>) {
180//! let _ = workqueue::system().enqueue(val);
181//! }
182//! # print_later(MyStruct::new(42).unwrap());
183//! # print_now(MyStruct::new(42).unwrap());
184//! ```
185//!
186//! C header: [`include/linux/workqueue.h`](srctree/include/linux/workqueue.h)
187
188use crate::{
189 alloc::{AllocError, Flags},
190 container_of,
191 prelude::*,
192 sync::Arc,
193 sync::LockClassKey,
194 time::Jiffies,
195 types::Opaque,
196};
197use core::marker::PhantomData;
198use safety_macro::safety;
199/// Creates a [`Work`] initialiser with the given name and a newly-created lock class.
200#[macro_export]
201macro_rules! new_work {
202 ($($name:literal)?) => {
203 $crate::workqueue::Work::new($crate::optional_name!($($name)?), $crate::static_lock_class!())
204 };
205}
206pub use new_work;
207
208/// Creates a [`DelayedWork`] initialiser with the given name and a newly-created lock class.
209#[macro_export]
210macro_rules! new_delayed_work {
211 () => {
212 $crate::workqueue::DelayedWork::new(
213 $crate::optional_name!(),
214 $crate::static_lock_class!(),
215 $crate::c_str!(::core::concat!(
216 ::core::file!(),
217 ":",
218 ::core::line!(),
219 "_timer"
220 )),
221 $crate::static_lock_class!(),
222 )
223 };
224 ($name:literal) => {
225 $crate::workqueue::DelayedWork::new(
226 $crate::c_str!($name),
227 $crate::static_lock_class!(),
228 $crate::c_str!(::core::concat!($name, "_timer")),
229 $crate::static_lock_class!(),
230 )
231 };
232}
233pub use new_delayed_work;
234
235/// A kernel work queue.
236///
237/// Wraps the kernel's C `struct workqueue_struct`.
238///
239/// It allows work items to be queued to run on thread pools managed by the kernel. Several are
240/// always available, for example, `system`, `system_highpri`, `system_long`, etc.
241#[repr(transparent)]
242pub struct Queue(Opaque<bindings::workqueue_struct>);
243
244// SAFETY: Accesses to workqueues used by [`Queue`] are thread-safe.
245unsafe impl Send for Queue {}
246// SAFETY: Accesses to workqueues used by [`Queue`] are thread-safe.
247unsafe impl Sync for Queue {}
248
249impl Queue {
250 /// Use the provided `struct workqueue_struct` with Rust.
251 ///
252 /// # Safety
253 ///
254 /// The caller must ensure that the provided raw pointer is not dangling, that it points at a
255 /// valid workqueue, and that it remains valid until the end of `'a`.
256 #[safety{Typed(ptr, bindings::workqueue_struct)}]
257 pub unsafe fn from_raw<'a>(ptr: *const bindings::workqueue_struct) -> &'a Queue {
258 // SAFETY: The `Queue` type is `#[repr(transparent)]`, so the pointer cast is valid. The
259 // caller promises that the pointer is not dangling.
260 unsafe { &*ptr.cast::<Queue>() }
261 }
262
263 /// Enqueues a work item.
264 ///
265 /// This may fail if the work item is already enqueued in a workqueue.
266 ///
267 /// The work item will be submitted using `WORK_CPU_UNBOUND`.
268 pub fn enqueue<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput
269 where
270 W: RawWorkItem<ID> + Send + 'static,
271 {
272 let queue_ptr = self.0.get();
273
274 // SAFETY: We only return `false` if the `work_struct` is already in a workqueue. The other
275 // `__enqueue` requirements are not relevant since `W` is `Send` and static.
276 //
277 // The call to `bindings::queue_work_on` will dereference the provided raw pointer, which
278 // is ok because `__enqueue` guarantees that the pointer is valid for the duration of this
279 // closure.
280 //
281 // Furthermore, if the C workqueue code accesses the pointer after this call to
282 // `__enqueue`, then the work item was successfully enqueued, and `bindings::queue_work_on`
283 // will have returned true. In this case, `__enqueue` promises that the raw pointer will
284 // stay valid until we call the function pointer in the `work_struct`, so the access is ok.
285 unsafe {
286 w.__enqueue(move |work_ptr| {
287 bindings::queue_work_on(
288 bindings::wq_misc_consts_WORK_CPU_UNBOUND as ffi::c_int,
289 queue_ptr,
290 work_ptr,
291 )
292 })
293 }
294 }
295
296 /// Enqueues a delayed work item.
297 ///
298 /// This may fail if the work item is already enqueued in a workqueue.
299 ///
300 /// The work item will be submitted using `WORK_CPU_UNBOUND`.
301 pub fn enqueue_delayed<W, const ID: u64>(&self, w: W, delay: Jiffies) -> W::EnqueueOutput
302 where
303 W: RawDelayedWorkItem<ID> + Send + 'static,
304 {
305 let queue_ptr = self.0.get();
306
307 // SAFETY: We only return `false` if the `work_struct` is already in a workqueue. The other
308 // `__enqueue` requirements are not relevant since `W` is `Send` and static.
309 //
310 // The call to `bindings::queue_delayed_work_on` will dereference the provided raw pointer,
311 // which is ok because `__enqueue` guarantees that the pointer is valid for the duration of
312 // this closure, and the safety requirements of `RawDelayedWorkItem` expands this
313 // requirement to apply to the entire `delayed_work`.
314 //
315 // Furthermore, if the C workqueue code accesses the pointer after this call to
316 // `__enqueue`, then the work item was successfully enqueued, and
317 // `bindings::queue_delayed_work_on` will have returned true. In this case, `__enqueue`
318 // promises that the raw pointer will stay valid until we call the function pointer in the
319 // `work_struct`, so the access is ok.
320 unsafe {
321 w.__enqueue(move |work_ptr| {
322 bindings::queue_delayed_work_on(
323 bindings::wq_misc_consts_WORK_CPU_UNBOUND as ffi::c_int,
324 queue_ptr,
325 container_of!(work_ptr, bindings::delayed_work, work),
326 delay,
327 )
328 })
329 }
330 }
331
332 /// Tries to spawn the given function or closure as a work item.
333 ///
334 /// This method can fail because it allocates memory to store the work item.
335 pub fn try_spawn<T: 'static + Send + FnOnce()>(
336 &self,
337 flags: Flags,
338 func: T,
339 ) -> Result<(), AllocError> {
340 let init = pin_init!(ClosureWork {
341 work <- new_work!("Queue::try_spawn"),
342 func: Some(func),
343 });
344
345 self.enqueue(KBox::pin_init(init, flags).map_err(|_| AllocError)?);
346 Ok(())
347 }
348}
349
350/// A helper type used in [`try_spawn`].
351///
352/// [`try_spawn`]: Queue::try_spawn
353#[pin_data]
354struct ClosureWork<T> {
355 #[pin]
356 work: Work<ClosureWork<T>>,
357 func: Option<T>,
358}
359
360impl<T: FnOnce()> WorkItem for ClosureWork<T> {
361 type Pointer = Pin<KBox<Self>>;
362
363 fn run(mut this: Pin<KBox<Self>>) {
364 if let Some(func) = this.as_mut().project().func.take() {
365 (func)()
366 }
367 }
368}
369
370/// A raw work item.
371///
372/// This is the low-level trait that is designed for being as general as possible.
373///
374/// The `ID` parameter to this trait exists so that a single type can provide multiple
375/// implementations of this trait. For example, if a struct has multiple `work_struct` fields, then
376/// you will implement this trait once for each field, using a different id for each field. The
377/// actual value of the id is not important as long as you use different ids for different fields
378/// of the same struct. (Fields of different structs need not use different ids.)
379///
380/// Note that the id is used only to select the right method to call during compilation. It won't be
381/// part of the final executable.
382///
383/// # Safety
384///
385/// Implementers must ensure that any pointers passed to a `queue_work_on` closure by [`__enqueue`]
386/// remain valid for the duration specified in the guarantees section of the documentation for
387/// [`__enqueue`].
388///
389/// [`__enqueue`]: RawWorkItem::__enqueue
390pub unsafe trait RawWorkItem<const ID: u64> {
391 /// The return type of [`Queue::enqueue`].
392 type EnqueueOutput;
393
394 /// Enqueues this work item on a queue using the provided `queue_work_on` method.
395 ///
396 /// # Guarantees
397 ///
398 /// If this method calls the provided closure, then the raw pointer is guaranteed to point at a
399 /// valid `work_struct` for the duration of the call to the closure. If the closure returns
400 /// true, then it is further guaranteed that the pointer remains valid until someone calls the
401 /// function pointer stored in the `work_struct`.
402 ///
403 /// # Safety
404 ///
405 /// The provided closure may only return `false` if the `work_struct` is already in a workqueue.
406 ///
407 /// If the work item type is annotated with any lifetimes, then you must not call the function
408 /// pointer after any such lifetime expires. (Never calling the function pointer is okay.)
409 ///
410 /// If the work item type is not [`Send`], then the function pointer must be called on the same
411 /// thread as the call to `__enqueue`.
412 unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
413 where
414 F: FnOnce(*mut bindings::work_struct) -> bool;
415}
416
417/// A raw delayed work item.
418///
419/// # Safety
420///
421/// If the `__enqueue` method in the `RawWorkItem` implementation calls the closure, then the
422/// provided pointer must point at the `work` field of a valid `delayed_work`, and the guarantees
423/// that `__enqueue` provides about accessing the `work_struct` must also apply to the rest of the
424/// `delayed_work` struct.
425pub unsafe trait RawDelayedWorkItem<const ID: u64>: RawWorkItem<ID> {}
426
427/// Defines the method that should be called directly when a work item is executed.
428///
429/// This trait is implemented by `Pin<KBox<T>>` and [`Arc<T>`], and is mainly intended to be
430/// implemented for smart pointer types. For your own structs, you would implement [`WorkItem`]
431/// instead. The [`run`] method on this trait will usually just perform the appropriate
432/// `container_of` translation and then call into the [`run`][WorkItem::run] method from the
433/// [`WorkItem`] trait.
434///
435/// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
436///
437/// # Safety
438///
439/// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with the [`run`]
440/// method of this trait as the function pointer.
441///
442/// [`__enqueue`]: RawWorkItem::__enqueue
443/// [`run`]: WorkItemPointer::run
444pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
445 /// Run this work item.
446 ///
447 /// # Safety
448 ///
449 /// The provided `work_struct` pointer must originate from a previous call to [`__enqueue`]
450 /// where the `queue_work_on` closure returned true, and the pointer must still be valid.
451 ///
452 /// [`__enqueue`]: RawWorkItem::__enqueue
453 unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
454}
455
456/// Defines the method that should be called when this work item is executed.
457///
458/// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
459pub trait WorkItem<const ID: u64 = 0> {
460 /// The pointer type that this struct is wrapped in. This will typically be `Arc<Self>` or
461 /// `Pin<KBox<Self>>`.
462 type Pointer: WorkItemPointer<ID>;
463
464 /// The method that should be called when this work item is executed.
465 fn run(this: Self::Pointer);
466}
467
468/// Links for a work item.
469///
470/// This struct contains a function pointer to the [`run`] function from the [`WorkItemPointer`]
471/// trait, and defines the linked list pointers necessary to enqueue a work item in a workqueue.
472///
473/// Wraps the kernel's C `struct work_struct`.
474///
475/// This is a helper type used to associate a `work_struct` with the [`WorkItem`] that uses it.
476///
477/// [`run`]: WorkItemPointer::run
478#[pin_data]
479#[repr(transparent)]
480pub struct Work<T: ?Sized, const ID: u64 = 0> {
481 #[pin]
482 work: Opaque<bindings::work_struct>,
483 _inner: PhantomData<T>,
484}
485
486// SAFETY: Kernel work items are usable from any thread.
487//
488// We do not need to constrain `T` since the work item does not actually contain a `T`.
489unsafe impl<T: ?Sized, const ID: u64> Send for Work<T, ID> {}
490// SAFETY: Kernel work items are usable from any thread.
491//
492// We do not need to constrain `T` since the work item does not actually contain a `T`.
493unsafe impl<T: ?Sized, const ID: u64> Sync for Work<T, ID> {}
494
495impl<T: ?Sized, const ID: u64> Work<T, ID> {
496 /// Creates a new instance of [`Work`].
497 #[inline]
498 pub fn new(name: &'static CStr, key: Pin<&'static LockClassKey>) -> impl PinInit<Self>
499 where
500 T: WorkItem<ID>,
501 {
502 pin_init!(Self {
503 work <- Opaque::ffi_init(|slot| {
504 // SAFETY: The `WorkItemPointer` implementation promises that `run` can be used as
505 // the work item function.
506 unsafe {
507 bindings::init_work_with_key(
508 slot,
509 Some(T::Pointer::run),
510 false,
511 name.as_char_ptr(),
512 key.as_ptr(),
513 )
514 }
515 }),
516 _inner: PhantomData,
517 })
518 }
519
520 /// Get a pointer to the inner `work_struct`.
521 ///
522 /// # Safety
523 ///
524 /// The provided pointer must not be dangling and must be properly aligned. (But the memory
525 /// need not be initialized.)
526 #[inline]
527 #[safety{ValidPtr, Align}]
528 pub unsafe fn raw_get(ptr: *const Self) -> *mut bindings::work_struct {
529 // SAFETY: The caller promises that the pointer is aligned and not dangling.
530 //
531 // A pointer cast would also be ok due to `#[repr(transparent)]`. We use `addr_of!` so that
532 // the compiler does not complain that the `work` field is unused.
533 unsafe { Opaque::cast_into(core::ptr::addr_of!((*ptr).work)) }
534 }
535}
536
537/// Declares that a type contains a [`Work<T, ID>`].
538///
539/// The intended way of using this trait is via the [`impl_has_work!`] macro. You can use the macro
540/// like this:
541///
542/// ```no_run
543/// use kernel::workqueue::{impl_has_work, Work};
544///
545/// struct MyWorkItem {
546/// work_field: Work<MyWorkItem, 1>,
547/// }
548///
549/// impl_has_work! {
550/// impl HasWork<MyWorkItem, 1> for MyWorkItem { self.work_field }
551/// }
552/// ```
553///
554/// Note that since the [`Work`] type is annotated with an id, you can have several `work_struct`
555/// fields by using a different id for each one.
556///
557/// # Safety
558///
559/// The methods [`raw_get_work`] and [`work_container_of`] must return valid pointers and must be
560/// true inverses of each other; that is, they must satisfy the following invariants:
561/// - `work_container_of(raw_get_work(ptr)) == ptr` for any `ptr: *mut Self`.
562/// - `raw_get_work(work_container_of(ptr)) == ptr` for any `ptr: *mut Work<T, ID>`.
563///
564/// [`impl_has_work!`]: crate::impl_has_work
565/// [`raw_get_work`]: HasWork::raw_get_work
566/// [`work_container_of`]: HasWork::work_container_of
567pub unsafe trait HasWork<T, const ID: u64 = 0> {
568 /// Returns a pointer to the [`Work<T, ID>`] field.
569 ///
570 /// # Safety
571 ///
572 /// The provided pointer must point at a valid struct of type `Self`.
573 unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<T, ID>;
574
575 /// Returns a pointer to the struct containing the [`Work<T, ID>`] field.
576 ///
577 /// # Safety
578 ///
579 /// The pointer must point at a [`Work<T, ID>`] field in a struct of type `Self`.
580 unsafe fn work_container_of(ptr: *mut Work<T, ID>) -> *mut Self;
581}
582
583/// Used to safely implement the [`HasWork<T, ID>`] trait.
584///
585/// # Examples
586///
587/// ```
588/// use kernel::sync::Arc;
589/// use kernel::workqueue::{self, impl_has_work, Work};
590///
591/// struct MyStruct<'a, T, const N: usize> {
592/// work_field: Work<MyStruct<'a, T, N>, 17>,
593/// f: fn(&'a [T; N]),
594/// }
595///
596/// impl_has_work! {
597/// impl{'a, T, const N: usize} HasWork<MyStruct<'a, T, N>, 17>
598/// for MyStruct<'a, T, N> { self.work_field }
599/// }
600/// ```
601#[macro_export]
602macro_rules! impl_has_work {
603 ($(impl$({$($generics:tt)*})?
604 HasWork<$work_type:ty $(, $id:tt)?>
605 for $self:ty
606 { self.$field:ident }
607 )*) => {$(
608 // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right
609 // type.
610 unsafe impl$(<$($generics)+>)? $crate::workqueue::HasWork<$work_type $(, $id)?> for $self {
611 #[inline]
612 unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_type $(, $id)?> {
613 // SAFETY: The caller promises that the pointer is not dangling.
614 unsafe {
615 ::core::ptr::addr_of_mut!((*ptr).$field)
616 }
617 }
618
619 #[inline]
620 unsafe fn work_container_of(
621 ptr: *mut $crate::workqueue::Work<$work_type $(, $id)?>,
622 ) -> *mut Self {
623 // SAFETY: The caller promises that the pointer points at a field of the right type
624 // in the right kind of struct.
625 unsafe { $crate::container_of!(ptr, Self, $field) }
626 }
627 }
628 )*};
629}
630pub use impl_has_work;
631
632impl_has_work! {
633 impl{T} HasWork<Self> for ClosureWork<T> { self.work }
634}
635
636/// Links for a delayed work item.
637///
638/// This struct contains a function pointer to the [`run`] function from the [`WorkItemPointer`]
639/// trait, and defines the linked list pointers necessary to enqueue a work item in a workqueue in
640/// a delayed manner.
641///
642/// Wraps the kernel's C `struct delayed_work`.
643///
644/// This is a helper type used to associate a `delayed_work` with the [`WorkItem`] that uses it.
645///
646/// [`run`]: WorkItemPointer::run
647#[pin_data]
648#[repr(transparent)]
649pub struct DelayedWork<T: ?Sized, const ID: u64 = 0> {
650 #[pin]
651 dwork: Opaque<bindings::delayed_work>,
652 _inner: PhantomData<T>,
653}
654
655// SAFETY: Kernel work items are usable from any thread.
656//
657// We do not need to constrain `T` since the work item does not actually contain a `T`.
658unsafe impl<T: ?Sized, const ID: u64> Send for DelayedWork<T, ID> {}
659// SAFETY: Kernel work items are usable from any thread.
660//
661// We do not need to constrain `T` since the work item does not actually contain a `T`.
662unsafe impl<T: ?Sized, const ID: u64> Sync for DelayedWork<T, ID> {}
663
664impl<T: ?Sized, const ID: u64> DelayedWork<T, ID> {
665 /// Creates a new instance of [`DelayedWork`].
666 #[inline]
667 pub fn new(
668 work_name: &'static CStr,
669 work_key: Pin<&'static LockClassKey>,
670 timer_name: &'static CStr,
671 timer_key: Pin<&'static LockClassKey>,
672 ) -> impl PinInit<Self>
673 where
674 T: WorkItem<ID>,
675 {
676 pin_init!(Self {
677 dwork <- Opaque::ffi_init(|slot: *mut bindings::delayed_work| {
678 // SAFETY: The `WorkItemPointer` implementation promises that `run` can be used as
679 // the work item function.
680 unsafe {
681 bindings::init_work_with_key(
682 core::ptr::addr_of_mut!((*slot).work),
683 Some(T::Pointer::run),
684 false,
685 work_name.as_char_ptr(),
686 work_key.as_ptr(),
687 )
688 }
689
690 // SAFETY: The `delayed_work_timer_fn` function pointer can be used here because
691 // the timer is embedded in a `struct delayed_work`, and only ever scheduled via
692 // the core workqueue code, and configured to run in irqsafe context.
693 unsafe {
694 bindings::timer_init_key(
695 core::ptr::addr_of_mut!((*slot).timer),
696 Some(bindings::delayed_work_timer_fn),
697 bindings::TIMER_IRQSAFE,
698 timer_name.as_char_ptr(),
699 timer_key.as_ptr(),
700 )
701 }
702 }),
703 _inner: PhantomData,
704 })
705 }
706
707 /// Get a pointer to the inner `delayed_work`.
708 ///
709 /// # Safety
710 ///
711 /// The provided pointer must not be dangling and must be properly aligned. (But the memory
712 /// need not be initialized.)
713 #[inline]
714 pub unsafe fn raw_as_work(ptr: *const Self) -> *mut Work<T, ID> {
715 // SAFETY: The caller promises that the pointer is aligned and not dangling.
716 let dw: *mut bindings::delayed_work =
717 unsafe { Opaque::cast_into(core::ptr::addr_of!((*ptr).dwork)) };
718 // SAFETY: The caller promises that the pointer is aligned and not dangling.
719 let wrk: *mut bindings::work_struct = unsafe { core::ptr::addr_of_mut!((*dw).work) };
720 // CAST: Work and work_struct have compatible layouts.
721 wrk.cast()
722 }
723}
724
725/// Declares that a type contains a [`DelayedWork<T, ID>`].
726///
727/// # Safety
728///
729/// The `HasWork<T, ID>` implementation must return a `work_struct` that is stored in the `work`
730/// field of a `delayed_work` with the same access rules as the `work_struct`.
731pub unsafe trait HasDelayedWork<T, const ID: u64 = 0>: HasWork<T, ID> {}
732
733/// Used to safely implement the [`HasDelayedWork<T, ID>`] trait.
734///
735/// This macro also implements the [`HasWork`] trait, so you do not need to use [`impl_has_work!`]
736/// when using this macro.
737///
738/// # Examples
739///
740/// ```
741/// use kernel::sync::Arc;
742/// use kernel::workqueue::{self, impl_has_delayed_work, DelayedWork};
743///
744/// struct MyStruct<'a, T, const N: usize> {
745/// work_field: DelayedWork<MyStruct<'a, T, N>, 17>,
746/// f: fn(&'a [T; N]),
747/// }
748///
749/// impl_has_delayed_work! {
750/// impl{'a, T, const N: usize} HasDelayedWork<MyStruct<'a, T, N>, 17>
751/// for MyStruct<'a, T, N> { self.work_field }
752/// }
753/// ```
754#[macro_export]
755macro_rules! impl_has_delayed_work {
756 ($(impl$({$($generics:tt)*})?
757 HasDelayedWork<$work_type:ty $(, $id:tt)?>
758 for $self:ty
759 { self.$field:ident }
760 )*) => {$(
761 // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right
762 // type.
763 unsafe impl$(<$($generics)+>)?
764 $crate::workqueue::HasDelayedWork<$work_type $(, $id)?> for $self {}
765
766 // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right
767 // type.
768 unsafe impl$(<$($generics)+>)? $crate::workqueue::HasWork<$work_type $(, $id)?> for $self {
769 #[inline]
770 unsafe fn raw_get_work(
771 ptr: *mut Self
772 ) -> *mut $crate::workqueue::Work<$work_type $(, $id)?> {
773 // SAFETY: The caller promises that the pointer is not dangling.
774 let ptr: *mut $crate::workqueue::DelayedWork<$work_type $(, $id)?> = unsafe {
775 ::core::ptr::addr_of_mut!((*ptr).$field)
776 };
777
778 // SAFETY: The caller promises that the pointer is not dangling.
779 unsafe { $crate::workqueue::DelayedWork::raw_as_work(ptr) }
780 }
781
782 #[inline]
783 unsafe fn work_container_of(
784 ptr: *mut $crate::workqueue::Work<$work_type $(, $id)?>,
785 ) -> *mut Self {
786 // SAFETY: The caller promises that the pointer points at a field of the right type
787 // in the right kind of struct.
788 let ptr = unsafe { $crate::workqueue::Work::raw_get(ptr) };
789
790 // SAFETY: The caller promises that the pointer points at a field of the right type
791 // in the right kind of struct.
792 let delayed_work = unsafe {
793 $crate::container_of!(ptr, $crate::bindings::delayed_work, work)
794 };
795
796 let delayed_work: *mut $crate::workqueue::DelayedWork<$work_type $(, $id)?> =
797 delayed_work.cast();
798
799 // SAFETY: The caller promises that the pointer points at a field of the right type
800 // in the right kind of struct.
801 unsafe { $crate::container_of!(delayed_work, Self, $field) }
802 }
803 }
804 )*};
805}
806pub use impl_has_delayed_work;
807
808// SAFETY: The `__enqueue` implementation in RawWorkItem uses a `work_struct` initialized with the
809// `run` method of this trait as the function pointer because:
810// - `__enqueue` gets the `work_struct` from the `Work` field, using `T::raw_get_work`.
811// - The only safe way to create a `Work` object is through `Work::new`.
812// - `Work::new` makes sure that `T::Pointer::run` is passed to `init_work_with_key`.
813// - Finally `Work` and `RawWorkItem` guarantee that the correct `Work` field
814// will be used because of the ID const generic bound. This makes sure that `T::raw_get_work`
815// uses the correct offset for the `Work` field, and `Work::new` picks the correct
816// implementation of `WorkItemPointer` for `Arc<T>`.
817unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
818where
819 T: WorkItem<ID, Pointer = Self>,
820 T: HasWork<T, ID>,
821{
822 unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
823 // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
824 let ptr = ptr.cast::<Work<T, ID>>();
825 // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
826 let ptr = unsafe { T::work_container_of(ptr) };
827 // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
828 let arc = unsafe { Arc::from_raw(ptr) };
829
830 T::run(arc)
831 }
832}
833
834// SAFETY: The `work_struct` raw pointer is guaranteed to be valid for the duration of the call to
835// the closure because we get it from an `Arc`, which means that the ref count will be at least 1,
836// and we don't drop the `Arc` ourselves. If `queue_work_on` returns true, it is further guaranteed
837// to be valid until a call to the function pointer in `work_struct` because we leak the memory it
838// points to, and only reclaim it if the closure returns false, or in `WorkItemPointer::run`, which
839// is what the function pointer in the `work_struct` must be pointing to, according to the safety
840// requirements of `WorkItemPointer`.
841unsafe impl<T, const ID: u64> RawWorkItem<ID> for Arc<T>
842where
843 T: WorkItem<ID, Pointer = Self>,
844 T: HasWork<T, ID>,
845{
846 type EnqueueOutput = Result<(), Self>;
847
848 unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
849 where
850 F: FnOnce(*mut bindings::work_struct) -> bool,
851 {
852 // Casting between const and mut is not a problem as long as the pointer is a raw pointer.
853 let ptr = Arc::into_raw(self).cast_mut();
854
855 // SAFETY: Pointers into an `Arc` point at a valid value.
856 let work_ptr = unsafe { T::raw_get_work(ptr) };
857 // SAFETY: `raw_get_work` returns a pointer to a valid value.
858 let work_ptr = unsafe { Work::raw_get(work_ptr) };
859
860 if queue_work_on(work_ptr) {
861 Ok(())
862 } else {
863 // SAFETY: The work queue has not taken ownership of the pointer.
864 Err(unsafe { Arc::from_raw(ptr) })
865 }
866 }
867}
868
869// SAFETY: By the safety requirements of `HasDelayedWork`, the `work_struct` returned by methods in
870// `HasWork` provides a `work_struct` that is the `work` field of a `delayed_work`, and the rest of
871// the `delayed_work` has the same access rules as its `work` field.
872unsafe impl<T, const ID: u64> RawDelayedWorkItem<ID> for Arc<T>
873where
874 T: WorkItem<ID, Pointer = Self>,
875 T: HasDelayedWork<T, ID>,
876{
877}
878
879// SAFETY: TODO.
880unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<KBox<T>>
881where
882 T: WorkItem<ID, Pointer = Self>,
883 T: HasWork<T, ID>,
884{
885 unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
886 // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
887 let ptr = ptr.cast::<Work<T, ID>>();
888 // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
889 let ptr = unsafe { T::work_container_of(ptr) };
890 // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
891 let boxed = unsafe { KBox::from_raw(ptr) };
892 // SAFETY: The box was already pinned when it was enqueued.
893 let pinned = unsafe { Pin::new_unchecked(boxed) };
894
895 T::run(pinned)
896 }
897}
898
899// SAFETY: TODO.
900unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<KBox<T>>
901where
902 T: WorkItem<ID, Pointer = Self>,
903 T: HasWork<T, ID>,
904{
905 type EnqueueOutput = ();
906
907 unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
908 where
909 F: FnOnce(*mut bindings::work_struct) -> bool,
910 {
911 // SAFETY: We're not going to move `self` or any of its fields, so its okay to temporarily
912 // remove the `Pin` wrapper.
913 let boxed = unsafe { Pin::into_inner_unchecked(self) };
914 let ptr = KBox::into_raw(boxed);
915
916 // SAFETY: Pointers into a `KBox` point at a valid value.
917 let work_ptr = unsafe { T::raw_get_work(ptr) };
918 // SAFETY: `raw_get_work` returns a pointer to a valid value.
919 let work_ptr = unsafe { Work::raw_get(work_ptr) };
920
921 if !queue_work_on(work_ptr) {
922 // SAFETY: This method requires exclusive ownership of the box, so it cannot be in a
923 // workqueue.
924 unsafe { ::core::hint::unreachable_unchecked() }
925 }
926 }
927}
928
929// SAFETY: By the safety requirements of `HasDelayedWork`, the `work_struct` returned by methods in
930// `HasWork` provides a `work_struct` that is the `work` field of a `delayed_work`, and the rest of
931// the `delayed_work` has the same access rules as its `work` field.
932unsafe impl<T, const ID: u64> RawDelayedWorkItem<ID> for Pin<KBox<T>>
933where
934 T: WorkItem<ID, Pointer = Self>,
935 T: HasDelayedWork<T, ID>,
936{
937}
938
939/// Returns the system work queue (`system_wq`).
940///
941/// It is the one used by `schedule[_delayed]_work[_on]()`. Multi-CPU multi-threaded. There are
942/// users which expect relatively short queue flush time.
943///
944/// Callers shouldn't queue work items which can run for too long.
945pub fn system() -> &'static Queue {
946 // SAFETY: `system_wq` is a C global, always available.
947 unsafe { Queue::from_raw(bindings::system_wq) }
948}
949
950/// Returns the system high-priority work queue (`system_highpri_wq`).
951///
952/// It is similar to the one returned by [`system`] but for work items which require higher
953/// scheduling priority.
954pub fn system_highpri() -> &'static Queue {
955 // SAFETY: `system_highpri_wq` is a C global, always available.
956 unsafe { Queue::from_raw(bindings::system_highpri_wq) }
957}
958
959/// Returns the system work queue for potentially long-running work items (`system_long_wq`).
960///
961/// It is similar to the one returned by [`system`] but may host long running work items. Queue
962/// flushing might take relatively long.
963pub fn system_long() -> &'static Queue {
964 // SAFETY: `system_long_wq` is a C global, always available.
965 unsafe { Queue::from_raw(bindings::system_long_wq) }
966}
967
968/// Returns the system unbound work queue (`system_unbound_wq`).
969///
970/// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items
971/// are executed immediately as long as `max_active` limit is not reached and resources are
972/// available.
973pub fn system_unbound() -> &'static Queue {
974 // SAFETY: `system_unbound_wq` is a C global, always available.
975 unsafe { Queue::from_raw(bindings::system_unbound_wq) }
976}
977
978/// Returns the system freezable work queue (`system_freezable_wq`).
979///
980/// It is equivalent to the one returned by [`system`] except that it's freezable.
981///
982/// A freezable workqueue participates in the freeze phase of the system suspend operations. Work
983/// items on the workqueue are drained and no new work item starts execution until thawed.
984pub fn system_freezable() -> &'static Queue {
985 // SAFETY: `system_freezable_wq` is a C global, always available.
986 unsafe { Queue::from_raw(bindings::system_freezable_wq) }
987}
988
989/// Returns the system power-efficient work queue (`system_power_efficient_wq`).
990///
991/// It is inclined towards saving power and is converted to "unbound" variants if the
992/// `workqueue.power_efficient` kernel parameter is specified; otherwise, it is similar to the one
993/// returned by [`system`].
994pub fn system_power_efficient() -> &'static Queue {
995 // SAFETY: `system_power_efficient_wq` is a C global, always available.
996 unsafe { Queue::from_raw(bindings::system_power_efficient_wq) }
997}
998
999/// Returns the system freezable power-efficient work queue (`system_freezable_power_efficient_wq`).
1000///
1001/// It is similar to the one returned by [`system_power_efficient`] except that is freezable.
1002///
1003/// A freezable workqueue participates in the freeze phase of the system suspend operations. Work
1004/// items on the workqueue are drained and no new work item starts execution until thawed.
1005pub fn system_freezable_power_efficient() -> &'static Queue {
1006 // SAFETY: `system_freezable_power_efficient_wq` is a C global, always available.
1007 unsafe { Queue::from_raw(bindings::system_freezable_power_efficient_wq) }
1008}
1009
1010/// Returns the system bottom halves work queue (`system_bh_wq`).
1011///
1012/// It is similar to the one returned by [`system`] but for work items which
1013/// need to run from a softirq context.
1014pub fn system_bh() -> &'static Queue {
1015 // SAFETY: `system_bh_wq` is a C global, always available.
1016 unsafe { Queue::from_raw(bindings::system_bh_wq) }
1017}
1018
1019/// Returns the system bottom halves high-priority work queue (`system_bh_highpri_wq`).
1020///
1021/// It is similar to the one returned by [`system_bh`] but for work items which
1022/// require higher scheduling priority.
1023pub fn system_bh_highpri() -> &'static Queue {
1024 // SAFETY: `system_bh_highpri_wq` is a C global, always available.
1025 unsafe { Queue::from_raw(bindings::system_bh_highpri_wq) }
1026}