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;
198
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 pub unsafe fn from_raw<'a>(ptr: *const bindings::workqueue_struct) -> &'a Queue {
257 // SAFETY: The `Queue` type is `#[repr(transparent)]`, so the pointer cast is valid. The
258 // caller promises that the pointer is not dangling.
259 unsafe { &*ptr.cast::<Queue>() }
260 }
261
262 /// Enqueues a work item.
263 ///
264 /// This may fail if the work item is already enqueued in a workqueue.
265 ///
266 /// The work item will be submitted using `WORK_CPU_UNBOUND`.
267 pub fn enqueue<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput
268 where
269 W: RawWorkItem<ID> + Send + 'static,
270 {
271 let queue_ptr = self.0.get();
272
273 // SAFETY: We only return `false` if the `work_struct` is already in a workqueue. The other
274 // `__enqueue` requirements are not relevant since `W` is `Send` and static.
275 //
276 // The call to `bindings::queue_work_on` will dereference the provided raw pointer, which
277 // is ok because `__enqueue` guarantees that the pointer is valid for the duration of this
278 // closure.
279 //
280 // Furthermore, if the C workqueue code accesses the pointer after this call to
281 // `__enqueue`, then the work item was successfully enqueued, and `bindings::queue_work_on`
282 // will have returned true. In this case, `__enqueue` promises that the raw pointer will
283 // stay valid until we call the function pointer in the `work_struct`, so the access is ok.
284 unsafe {
285 w.__enqueue(move |work_ptr| {
286 bindings::queue_work_on(
287 bindings::wq_misc_consts_WORK_CPU_UNBOUND as ffi::c_int,
288 queue_ptr,
289 work_ptr,
290 )
291 })
292 }
293 }
294
295 /// Enqueues a delayed work item.
296 ///
297 /// This may fail if the work item is already enqueued in a workqueue.
298 ///
299 /// The work item will be submitted using `WORK_CPU_UNBOUND`.
300 pub fn enqueue_delayed<W, const ID: u64>(&self, w: W, delay: Jiffies) -> W::EnqueueOutput
301 where
302 W: RawDelayedWorkItem<ID> + Send + 'static,
303 {
304 let queue_ptr = self.0.get();
305
306 // SAFETY: We only return `false` if the `work_struct` is already in a workqueue. The other
307 // `__enqueue` requirements are not relevant since `W` is `Send` and static.
308 //
309 // The call to `bindings::queue_delayed_work_on` will dereference the provided raw pointer,
310 // which is ok because `__enqueue` guarantees that the pointer is valid for the duration of
311 // this closure, and the safety requirements of `RawDelayedWorkItem` expands this
312 // requirement to apply to the entire `delayed_work`.
313 //
314 // Furthermore, if the C workqueue code accesses the pointer after this call to
315 // `__enqueue`, then the work item was successfully enqueued, and
316 // `bindings::queue_delayed_work_on` will have returned true. In this case, `__enqueue`
317 // promises that the raw pointer will stay valid until we call the function pointer in the
318 // `work_struct`, so the access is ok.
319 unsafe {
320 w.__enqueue(move |work_ptr| {
321 bindings::queue_delayed_work_on(
322 bindings::wq_misc_consts_WORK_CPU_UNBOUND as ffi::c_int,
323 queue_ptr,
324 container_of!(work_ptr, bindings::delayed_work, work),
325 delay,
326 )
327 })
328 }
329 }
330
331 /// Tries to spawn the given function or closure as a work item.
332 ///
333 /// This method can fail because it allocates memory to store the work item.
334 pub fn try_spawn<T: 'static + Send + FnOnce()>(
335 &self,
336 flags: Flags,
337 func: T,
338 ) -> Result<(), AllocError> {
339 let init = pin_init!(ClosureWork {
340 work <- new_work!("Queue::try_spawn"),
341 func: Some(func),
342 });
343
344 self.enqueue(KBox::pin_init(init, flags).map_err(|_| AllocError)?);
345 Ok(())
346 }
347}
348
349/// A helper type used in [`try_spawn`].
350///
351/// [`try_spawn`]: Queue::try_spawn
352#[pin_data]
353struct ClosureWork<T> {
354 #[pin]
355 work: Work<ClosureWork<T>>,
356 func: Option<T>,
357}
358
359impl<T> ClosureWork<T> {
360 fn project(self: Pin<&mut Self>) -> &mut Option<T> {
361 // SAFETY: The `func` field is not structurally pinned.
362 unsafe { &mut self.get_unchecked_mut().func }
363 }
364}
365
366impl<T: FnOnce()> WorkItem for ClosureWork<T> {
367 type Pointer = Pin<KBox<Self>>;
368
369 fn run(mut this: Pin<KBox<Self>>) {
370 if let Some(func) = this.as_mut().project().take() {
371 (func)()
372 }
373 }
374}
375
376/// A raw work item.
377///
378/// This is the low-level trait that is designed for being as general as possible.
379///
380/// The `ID` parameter to this trait exists so that a single type can provide multiple
381/// implementations of this trait. For example, if a struct has multiple `work_struct` fields, then
382/// you will implement this trait once for each field, using a different id for each field. The
383/// actual value of the id is not important as long as you use different ids for different fields
384/// of the same struct. (Fields of different structs need not use different ids.)
385///
386/// Note that the id is used only to select the right method to call during compilation. It won't be
387/// part of the final executable.
388///
389/// # Safety
390///
391/// Implementers must ensure that any pointers passed to a `queue_work_on` closure by [`__enqueue`]
392/// remain valid for the duration specified in the guarantees section of the documentation for
393/// [`__enqueue`].
394///
395/// [`__enqueue`]: RawWorkItem::__enqueue
396pub unsafe trait RawWorkItem<const ID: u64> {
397 /// The return type of [`Queue::enqueue`].
398 type EnqueueOutput;
399
400 /// Enqueues this work item on a queue using the provided `queue_work_on` method.
401 ///
402 /// # Guarantees
403 ///
404 /// If this method calls the provided closure, then the raw pointer is guaranteed to point at a
405 /// valid `work_struct` for the duration of the call to the closure. If the closure returns
406 /// true, then it is further guaranteed that the pointer remains valid until someone calls the
407 /// function pointer stored in the `work_struct`.
408 ///
409 /// # Safety
410 ///
411 /// The provided closure may only return `false` if the `work_struct` is already in a workqueue.
412 ///
413 /// If the work item type is annotated with any lifetimes, then you must not call the function
414 /// pointer after any such lifetime expires. (Never calling the function pointer is okay.)
415 ///
416 /// If the work item type is not [`Send`], then the function pointer must be called on the same
417 /// thread as the call to `__enqueue`.
418 unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
419 where
420 F: FnOnce(*mut bindings::work_struct) -> bool;
421}
422
423/// A raw delayed work item.
424///
425/// # Safety
426///
427/// If the `__enqueue` method in the `RawWorkItem` implementation calls the closure, then the
428/// provided pointer must point at the `work` field of a valid `delayed_work`, and the guarantees
429/// that `__enqueue` provides about accessing the `work_struct` must also apply to the rest of the
430/// `delayed_work` struct.
431pub unsafe trait RawDelayedWorkItem<const ID: u64>: RawWorkItem<ID> {}
432
433/// Defines the method that should be called directly when a work item is executed.
434///
435/// This trait is implemented by `Pin<KBox<T>>` and [`Arc<T>`], and is mainly intended to be
436/// implemented for smart pointer types. For your own structs, you would implement [`WorkItem`]
437/// instead. The [`run`] method on this trait will usually just perform the appropriate
438/// `container_of` translation and then call into the [`run`][WorkItem::run] method from the
439/// [`WorkItem`] trait.
440///
441/// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
442///
443/// # Safety
444///
445/// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with the [`run`]
446/// method of this trait as the function pointer.
447///
448/// [`__enqueue`]: RawWorkItem::__enqueue
449/// [`run`]: WorkItemPointer::run
450pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
451 /// Run this work item.
452 ///
453 /// # Safety
454 ///
455 /// The provided `work_struct` pointer must originate from a previous call to [`__enqueue`]
456 /// where the `queue_work_on` closure returned true, and the pointer must still be valid.
457 ///
458 /// [`__enqueue`]: RawWorkItem::__enqueue
459 unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
460}
461
462/// Defines the method that should be called when this work item is executed.
463///
464/// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
465pub trait WorkItem<const ID: u64 = 0> {
466 /// The pointer type that this struct is wrapped in. This will typically be `Arc<Self>` or
467 /// `Pin<KBox<Self>>`.
468 type Pointer: WorkItemPointer<ID>;
469
470 /// The method that should be called when this work item is executed.
471 fn run(this: Self::Pointer);
472}
473
474/// Links for a work item.
475///
476/// This struct contains a function pointer to the [`run`] function from the [`WorkItemPointer`]
477/// trait, and defines the linked list pointers necessary to enqueue a work item in a workqueue.
478///
479/// Wraps the kernel's C `struct work_struct`.
480///
481/// This is a helper type used to associate a `work_struct` with the [`WorkItem`] that uses it.
482///
483/// [`run`]: WorkItemPointer::run
484#[pin_data]
485#[repr(transparent)]
486pub struct Work<T: ?Sized, const ID: u64 = 0> {
487 #[pin]
488 work: Opaque<bindings::work_struct>,
489 _inner: PhantomData<T>,
490}
491
492// SAFETY: Kernel work items are usable from any thread.
493//
494// We do not need to constrain `T` since the work item does not actually contain a `T`.
495unsafe impl<T: ?Sized, const ID: u64> Send for Work<T, ID> {}
496// SAFETY: Kernel work items are usable from any thread.
497//
498// We do not need to constrain `T` since the work item does not actually contain a `T`.
499unsafe impl<T: ?Sized, const ID: u64> Sync for Work<T, ID> {}
500
501impl<T: ?Sized, const ID: u64> Work<T, ID> {
502 /// Creates a new instance of [`Work`].
503 #[inline]
504 pub fn new(name: &'static CStr, key: Pin<&'static LockClassKey>) -> impl PinInit<Self>
505 where
506 T: WorkItem<ID>,
507 {
508 pin_init!(Self {
509 work <- Opaque::ffi_init(|slot| {
510 // SAFETY: The `WorkItemPointer` implementation promises that `run` can be used as
511 // the work item function.
512 unsafe {
513 bindings::init_work_with_key(
514 slot,
515 Some(T::Pointer::run),
516 false,
517 name.as_char_ptr(),
518 key.as_ptr(),
519 )
520 }
521 }),
522 _inner: PhantomData,
523 })
524 }
525
526 /// Get a pointer to the inner `work_struct`.
527 ///
528 /// # Safety
529 ///
530 /// The provided pointer must not be dangling and must be properly aligned. (But the memory
531 /// need not be initialized.)
532 #[inline]
533 pub unsafe fn raw_get(ptr: *const Self) -> *mut bindings::work_struct {
534 // SAFETY: The caller promises that the pointer is aligned and not dangling.
535 //
536 // A pointer cast would also be ok due to `#[repr(transparent)]`. We use `addr_of!` so that
537 // the compiler does not complain that the `work` field is unused.
538 unsafe { Opaque::cast_into(core::ptr::addr_of!((*ptr).work)) }
539 }
540}
541
542/// Declares that a type contains a [`Work<T, ID>`].
543///
544/// The intended way of using this trait is via the [`impl_has_work!`] macro. You can use the macro
545/// like this:
546///
547/// ```no_run
548/// use kernel::workqueue::{impl_has_work, Work};
549///
550/// struct MyWorkItem {
551/// work_field: Work<MyWorkItem, 1>,
552/// }
553///
554/// impl_has_work! {
555/// impl HasWork<MyWorkItem, 1> for MyWorkItem { self.work_field }
556/// }
557/// ```
558///
559/// Note that since the [`Work`] type is annotated with an id, you can have several `work_struct`
560/// fields by using a different id for each one.
561///
562/// # Safety
563///
564/// The methods [`raw_get_work`] and [`work_container_of`] must return valid pointers and must be
565/// true inverses of each other; that is, they must satisfy the following invariants:
566/// - `work_container_of(raw_get_work(ptr)) == ptr` for any `ptr: *mut Self`.
567/// - `raw_get_work(work_container_of(ptr)) == ptr` for any `ptr: *mut Work<T, ID>`.
568///
569/// [`impl_has_work!`]: crate::impl_has_work
570/// [`raw_get_work`]: HasWork::raw_get_work
571/// [`work_container_of`]: HasWork::work_container_of
572pub unsafe trait HasWork<T, const ID: u64 = 0> {
573 /// Returns a pointer to the [`Work<T, ID>`] field.
574 ///
575 /// # Safety
576 ///
577 /// The provided pointer must point at a valid struct of type `Self`.
578 unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<T, ID>;
579
580 /// Returns a pointer to the struct containing the [`Work<T, ID>`] field.
581 ///
582 /// # Safety
583 ///
584 /// The pointer must point at a [`Work<T, ID>`] field in a struct of type `Self`.
585 unsafe fn work_container_of(ptr: *mut Work<T, ID>) -> *mut Self;
586}
587
588/// Used to safely implement the [`HasWork<T, ID>`] trait.
589///
590/// # Examples
591///
592/// ```
593/// use kernel::sync::Arc;
594/// use kernel::workqueue::{self, impl_has_work, Work};
595///
596/// struct MyStruct<'a, T, const N: usize> {
597/// work_field: Work<MyStruct<'a, T, N>, 17>,
598/// f: fn(&'a [T; N]),
599/// }
600///
601/// impl_has_work! {
602/// impl{'a, T, const N: usize} HasWork<MyStruct<'a, T, N>, 17>
603/// for MyStruct<'a, T, N> { self.work_field }
604/// }
605/// ```
606#[macro_export]
607macro_rules! impl_has_work {
608 ($(impl$({$($generics:tt)*})?
609 HasWork<$work_type:ty $(, $id:tt)?>
610 for $self:ty
611 { self.$field:ident }
612 )*) => {$(
613 // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right
614 // type.
615 unsafe impl$(<$($generics)+>)? $crate::workqueue::HasWork<$work_type $(, $id)?> for $self {
616 #[inline]
617 unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_type $(, $id)?> {
618 // SAFETY: The caller promises that the pointer is not dangling.
619 unsafe {
620 ::core::ptr::addr_of_mut!((*ptr).$field)
621 }
622 }
623
624 #[inline]
625 unsafe fn work_container_of(
626 ptr: *mut $crate::workqueue::Work<$work_type $(, $id)?>,
627 ) -> *mut Self {
628 // SAFETY: The caller promises that the pointer points at a field of the right type
629 // in the right kind of struct.
630 unsafe { $crate::container_of!(ptr, Self, $field) }
631 }
632 }
633 )*};
634}
635pub use impl_has_work;
636
637impl_has_work! {
638 impl{T} HasWork<Self> for ClosureWork<T> { self.work }
639}
640
641/// Links for a delayed work item.
642///
643/// This struct contains a function pointer to the [`run`] function from the [`WorkItemPointer`]
644/// trait, and defines the linked list pointers necessary to enqueue a work item in a workqueue in
645/// a delayed manner.
646///
647/// Wraps the kernel's C `struct delayed_work`.
648///
649/// This is a helper type used to associate a `delayed_work` with the [`WorkItem`] that uses it.
650///
651/// [`run`]: WorkItemPointer::run
652#[pin_data]
653#[repr(transparent)]
654pub struct DelayedWork<T: ?Sized, const ID: u64 = 0> {
655 #[pin]
656 dwork: Opaque<bindings::delayed_work>,
657 _inner: PhantomData<T>,
658}
659
660// SAFETY: Kernel work items are usable from any thread.
661//
662// We do not need to constrain `T` since the work item does not actually contain a `T`.
663unsafe impl<T: ?Sized, const ID: u64> Send for DelayedWork<T, ID> {}
664// SAFETY: Kernel work items are usable from any thread.
665//
666// We do not need to constrain `T` since the work item does not actually contain a `T`.
667unsafe impl<T: ?Sized, const ID: u64> Sync for DelayedWork<T, ID> {}
668
669impl<T: ?Sized, const ID: u64> DelayedWork<T, ID> {
670 /// Creates a new instance of [`DelayedWork`].
671 #[inline]
672 pub fn new(
673 work_name: &'static CStr,
674 work_key: Pin<&'static LockClassKey>,
675 timer_name: &'static CStr,
676 timer_key: Pin<&'static LockClassKey>,
677 ) -> impl PinInit<Self>
678 where
679 T: WorkItem<ID>,
680 {
681 pin_init!(Self {
682 dwork <- Opaque::ffi_init(|slot: *mut bindings::delayed_work| {
683 // SAFETY: The `WorkItemPointer` implementation promises that `run` can be used as
684 // the work item function.
685 unsafe {
686 bindings::init_work_with_key(
687 core::ptr::addr_of_mut!((*slot).work),
688 Some(T::Pointer::run),
689 false,
690 work_name.as_char_ptr(),
691 work_key.as_ptr(),
692 )
693 }
694
695 // SAFETY: The `delayed_work_timer_fn` function pointer can be used here because
696 // the timer is embedded in a `struct delayed_work`, and only ever scheduled via
697 // the core workqueue code, and configured to run in irqsafe context.
698 unsafe {
699 bindings::timer_init_key(
700 core::ptr::addr_of_mut!((*slot).timer),
701 Some(bindings::delayed_work_timer_fn),
702 bindings::TIMER_IRQSAFE,
703 timer_name.as_char_ptr(),
704 timer_key.as_ptr(),
705 )
706 }
707 }),
708 _inner: PhantomData,
709 })
710 }
711
712 /// Get a pointer to the inner `delayed_work`.
713 ///
714 /// # Safety
715 ///
716 /// The provided pointer must not be dangling and must be properly aligned. (But the memory
717 /// need not be initialized.)
718 #[inline]
719 pub unsafe fn raw_as_work(ptr: *const Self) -> *mut Work<T, ID> {
720 // SAFETY: The caller promises that the pointer is aligned and not dangling.
721 let dw: *mut bindings::delayed_work =
722 unsafe { Opaque::cast_into(core::ptr::addr_of!((*ptr).dwork)) };
723 // SAFETY: The caller promises that the pointer is aligned and not dangling.
724 let wrk: *mut bindings::work_struct = unsafe { core::ptr::addr_of_mut!((*dw).work) };
725 // CAST: Work and work_struct have compatible layouts.
726 wrk.cast()
727 }
728}
729
730/// Declares that a type contains a [`DelayedWork<T, ID>`].
731///
732/// # Safety
733///
734/// The `HasWork<T, ID>` implementation must return a `work_struct` that is stored in the `work`
735/// field of a `delayed_work` with the same access rules as the `work_struct`.
736pub unsafe trait HasDelayedWork<T, const ID: u64 = 0>: HasWork<T, ID> {}
737
738/// Used to safely implement the [`HasDelayedWork<T, ID>`] trait.
739///
740/// This macro also implements the [`HasWork`] trait, so you do not need to use [`impl_has_work!`]
741/// when using this macro.
742///
743/// # Examples
744///
745/// ```
746/// use kernel::sync::Arc;
747/// use kernel::workqueue::{self, impl_has_delayed_work, DelayedWork};
748///
749/// struct MyStruct<'a, T, const N: usize> {
750/// work_field: DelayedWork<MyStruct<'a, T, N>, 17>,
751/// f: fn(&'a [T; N]),
752/// }
753///
754/// impl_has_delayed_work! {
755/// impl{'a, T, const N: usize} HasDelayedWork<MyStruct<'a, T, N>, 17>
756/// for MyStruct<'a, T, N> { self.work_field }
757/// }
758/// ```
759#[macro_export]
760macro_rules! impl_has_delayed_work {
761 ($(impl$({$($generics:tt)*})?
762 HasDelayedWork<$work_type:ty $(, $id:tt)?>
763 for $self:ty
764 { self.$field:ident }
765 )*) => {$(
766 // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right
767 // type.
768 unsafe impl$(<$($generics)+>)?
769 $crate::workqueue::HasDelayedWork<$work_type $(, $id)?> for $self {}
770
771 // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right
772 // type.
773 unsafe impl$(<$($generics)+>)? $crate::workqueue::HasWork<$work_type $(, $id)?> for $self {
774 #[inline]
775 unsafe fn raw_get_work(
776 ptr: *mut Self
777 ) -> *mut $crate::workqueue::Work<$work_type $(, $id)?> {
778 // SAFETY: The caller promises that the pointer is not dangling.
779 let ptr: *mut $crate::workqueue::DelayedWork<$work_type $(, $id)?> = unsafe {
780 ::core::ptr::addr_of_mut!((*ptr).$field)
781 };
782
783 // SAFETY: The caller promises that the pointer is not dangling.
784 unsafe { $crate::workqueue::DelayedWork::raw_as_work(ptr) }
785 }
786
787 #[inline]
788 unsafe fn work_container_of(
789 ptr: *mut $crate::workqueue::Work<$work_type $(, $id)?>,
790 ) -> *mut Self {
791 // SAFETY: The caller promises that the pointer points at a field of the right type
792 // in the right kind of struct.
793 let ptr = unsafe { $crate::workqueue::Work::raw_get(ptr) };
794
795 // SAFETY: The caller promises that the pointer points at a field of the right type
796 // in the right kind of struct.
797 let delayed_work = unsafe {
798 $crate::container_of!(ptr, $crate::bindings::delayed_work, work)
799 };
800
801 let delayed_work: *mut $crate::workqueue::DelayedWork<$work_type $(, $id)?> =
802 delayed_work.cast();
803
804 // SAFETY: The caller promises that the pointer points at a field of the right type
805 // in the right kind of struct.
806 unsafe { $crate::container_of!(delayed_work, Self, $field) }
807 }
808 }
809 )*};
810}
811pub use impl_has_delayed_work;
812
813// SAFETY: The `__enqueue` implementation in RawWorkItem uses a `work_struct` initialized with the
814// `run` method of this trait as the function pointer because:
815// - `__enqueue` gets the `work_struct` from the `Work` field, using `T::raw_get_work`.
816// - The only safe way to create a `Work` object is through `Work::new`.
817// - `Work::new` makes sure that `T::Pointer::run` is passed to `init_work_with_key`.
818// - Finally `Work` and `RawWorkItem` guarantee that the correct `Work` field
819// will be used because of the ID const generic bound. This makes sure that `T::raw_get_work`
820// uses the correct offset for the `Work` field, and `Work::new` picks the correct
821// implementation of `WorkItemPointer` for `Arc<T>`.
822unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
823where
824 T: WorkItem<ID, Pointer = Self>,
825 T: HasWork<T, ID>,
826{
827 unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
828 // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
829 let ptr = ptr.cast::<Work<T, ID>>();
830 // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
831 let ptr = unsafe { T::work_container_of(ptr) };
832 // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
833 let arc = unsafe { Arc::from_raw(ptr) };
834
835 T::run(arc)
836 }
837}
838
839// SAFETY: The `work_struct` raw pointer is guaranteed to be valid for the duration of the call to
840// the closure because we get it from an `Arc`, which means that the ref count will be at least 1,
841// and we don't drop the `Arc` ourselves. If `queue_work_on` returns true, it is further guaranteed
842// to be valid until a call to the function pointer in `work_struct` because we leak the memory it
843// points to, and only reclaim it if the closure returns false, or in `WorkItemPointer::run`, which
844// is what the function pointer in the `work_struct` must be pointing to, according to the safety
845// requirements of `WorkItemPointer`.
846unsafe impl<T, const ID: u64> RawWorkItem<ID> for Arc<T>
847where
848 T: WorkItem<ID, Pointer = Self>,
849 T: HasWork<T, ID>,
850{
851 type EnqueueOutput = Result<(), Self>;
852
853 unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
854 where
855 F: FnOnce(*mut bindings::work_struct) -> bool,
856 {
857 // Casting between const and mut is not a problem as long as the pointer is a raw pointer.
858 let ptr = Arc::into_raw(self).cast_mut();
859
860 // SAFETY: Pointers into an `Arc` point at a valid value.
861 let work_ptr = unsafe { T::raw_get_work(ptr) };
862 // SAFETY: `raw_get_work` returns a pointer to a valid value.
863 let work_ptr = unsafe { Work::raw_get(work_ptr) };
864
865 if queue_work_on(work_ptr) {
866 Ok(())
867 } else {
868 // SAFETY: The work queue has not taken ownership of the pointer.
869 Err(unsafe { Arc::from_raw(ptr) })
870 }
871 }
872}
873
874// SAFETY: By the safety requirements of `HasDelayedWork`, the `work_struct` returned by methods in
875// `HasWork` provides a `work_struct` that is the `work` field of a `delayed_work`, and the rest of
876// the `delayed_work` has the same access rules as its `work` field.
877unsafe impl<T, const ID: u64> RawDelayedWorkItem<ID> for Arc<T>
878where
879 T: WorkItem<ID, Pointer = Self>,
880 T: HasDelayedWork<T, ID>,
881{
882}
883
884// SAFETY: TODO.
885unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<KBox<T>>
886where
887 T: WorkItem<ID, Pointer = Self>,
888 T: HasWork<T, ID>,
889{
890 unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
891 // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
892 let ptr = ptr.cast::<Work<T, ID>>();
893 // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
894 let ptr = unsafe { T::work_container_of(ptr) };
895 // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
896 let boxed = unsafe { KBox::from_raw(ptr) };
897 // SAFETY: The box was already pinned when it was enqueued.
898 let pinned = unsafe { Pin::new_unchecked(boxed) };
899
900 T::run(pinned)
901 }
902}
903
904// SAFETY: TODO.
905unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<KBox<T>>
906where
907 T: WorkItem<ID, Pointer = Self>,
908 T: HasWork<T, ID>,
909{
910 type EnqueueOutput = ();
911
912 unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
913 where
914 F: FnOnce(*mut bindings::work_struct) -> bool,
915 {
916 // SAFETY: We're not going to move `self` or any of its fields, so its okay to temporarily
917 // remove the `Pin` wrapper.
918 let boxed = unsafe { Pin::into_inner_unchecked(self) };
919 let ptr = KBox::into_raw(boxed);
920
921 // SAFETY: Pointers into a `KBox` point at a valid value.
922 let work_ptr = unsafe { T::raw_get_work(ptr) };
923 // SAFETY: `raw_get_work` returns a pointer to a valid value.
924 let work_ptr = unsafe { Work::raw_get(work_ptr) };
925
926 if !queue_work_on(work_ptr) {
927 // SAFETY: This method requires exclusive ownership of the box, so it cannot be in a
928 // workqueue.
929 unsafe { ::core::hint::unreachable_unchecked() }
930 }
931 }
932}
933
934// SAFETY: By the safety requirements of `HasDelayedWork`, the `work_struct` returned by methods in
935// `HasWork` provides a `work_struct` that is the `work` field of a `delayed_work`, and the rest of
936// the `delayed_work` has the same access rules as its `work` field.
937unsafe impl<T, const ID: u64> RawDelayedWorkItem<ID> for Pin<KBox<T>>
938where
939 T: WorkItem<ID, Pointer = Self>,
940 T: HasDelayedWork<T, ID>,
941{
942}
943
944/// Returns the system work queue (`system_wq`).
945///
946/// It is the one used by `schedule[_delayed]_work[_on]()`. Multi-CPU multi-threaded. There are
947/// users which expect relatively short queue flush time.
948///
949/// Callers shouldn't queue work items which can run for too long.
950pub fn system() -> &'static Queue {
951 // SAFETY: `system_wq` is a C global, always available.
952 unsafe { Queue::from_raw(bindings::system_wq) }
953}
954
955/// Returns the system high-priority work queue (`system_highpri_wq`).
956///
957/// It is similar to the one returned by [`system`] but for work items which require higher
958/// scheduling priority.
959pub fn system_highpri() -> &'static Queue {
960 // SAFETY: `system_highpri_wq` is a C global, always available.
961 unsafe { Queue::from_raw(bindings::system_highpri_wq) }
962}
963
964/// Returns the system work queue for potentially long-running work items (`system_long_wq`).
965///
966/// It is similar to the one returned by [`system`] but may host long running work items. Queue
967/// flushing might take relatively long.
968pub fn system_long() -> &'static Queue {
969 // SAFETY: `system_long_wq` is a C global, always available.
970 unsafe { Queue::from_raw(bindings::system_long_wq) }
971}
972
973/// Returns the system unbound work queue (`system_unbound_wq`).
974///
975/// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items
976/// are executed immediately as long as `max_active` limit is not reached and resources are
977/// available.
978pub fn system_unbound() -> &'static Queue {
979 // SAFETY: `system_unbound_wq` is a C global, always available.
980 unsafe { Queue::from_raw(bindings::system_unbound_wq) }
981}
982
983/// Returns the system freezable work queue (`system_freezable_wq`).
984///
985/// It is equivalent to the one returned by [`system`] except that it's freezable.
986///
987/// A freezable workqueue participates in the freeze phase of the system suspend operations. Work
988/// items on the workqueue are drained and no new work item starts execution until thawed.
989pub fn system_freezable() -> &'static Queue {
990 // SAFETY: `system_freezable_wq` is a C global, always available.
991 unsafe { Queue::from_raw(bindings::system_freezable_wq) }
992}
993
994/// Returns the system power-efficient work queue (`system_power_efficient_wq`).
995///
996/// It is inclined towards saving power and is converted to "unbound" variants if the
997/// `workqueue.power_efficient` kernel parameter is specified; otherwise, it is similar to the one
998/// returned by [`system`].
999pub fn system_power_efficient() -> &'static Queue {
1000 // SAFETY: `system_power_efficient_wq` is a C global, always available.
1001 unsafe { Queue::from_raw(bindings::system_power_efficient_wq) }
1002}
1003
1004/// Returns the system freezable power-efficient work queue (`system_freezable_power_efficient_wq`).
1005///
1006/// It is similar to the one returned by [`system_power_efficient`] except that is freezable.
1007///
1008/// A freezable workqueue participates in the freeze phase of the system suspend operations. Work
1009/// items on the workqueue are drained and no new work item starts execution until thawed.
1010pub fn system_freezable_power_efficient() -> &'static Queue {
1011 // SAFETY: `system_freezable_power_efficient_wq` is a C global, always available.
1012 unsafe { Queue::from_raw(bindings::system_freezable_power_efficient_wq) }
1013}
1014
1015/// Returns the system bottom halves work queue (`system_bh_wq`).
1016///
1017/// It is similar to the one returned by [`system`] but for work items which
1018/// need to run from a softirq context.
1019pub fn system_bh() -> &'static Queue {
1020 // SAFETY: `system_bh_wq` is a C global, always available.
1021 unsafe { Queue::from_raw(bindings::system_bh_wq) }
1022}
1023
1024/// Returns the system bottom halves high-priority work queue (`system_bh_highpri_wq`).
1025///
1026/// It is similar to the one returned by [`system_bh`] but for work items which
1027/// require higher scheduling priority.
1028pub fn system_bh_highpri() -> &'static Queue {
1029 // SAFETY: `system_bh_highpri_wq` is a C global, always available.
1030 unsafe { Queue::from_raw(bindings::system_bh_highpri_wq) }
1031}