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::{
193 aref::{
194 ARef,
195 AlwaysRefCounted, //
196 },
197 Arc,
198 LockClassKey, //
199 },
200 time::Jiffies,
201 types::Opaque,
202};
203use core::{marker::PhantomData, ptr::NonNull};
204
205/// Creates a [`Work`] initialiser with the given name and a newly-created lock class.
206#[macro_export]
207macro_rules! new_work {
208 ($($name:literal)?) => {
209 $crate::workqueue::Work::new($crate::optional_name!($($name)?), $crate::static_lock_class!())
210 };
211}
212pub use new_work;
213
214/// Creates a [`DelayedWork`] initialiser with the given name and a newly-created lock class.
215#[macro_export]
216macro_rules! new_delayed_work {
217 () => {
218 $crate::workqueue::DelayedWork::new(
219 $crate::optional_name!(),
220 $crate::static_lock_class!(),
221 $crate::c_str!(::core::concat!(
222 ::core::file!(),
223 ":",
224 ::core::line!(),
225 "_timer"
226 )),
227 $crate::static_lock_class!(),
228 )
229 };
230 ($name:literal) => {
231 $crate::workqueue::DelayedWork::new(
232 $crate::c_str!($name),
233 $crate::static_lock_class!(),
234 $crate::c_str!(::core::concat!($name, "_timer")),
235 $crate::static_lock_class!(),
236 )
237 };
238}
239pub use new_delayed_work;
240
241/// A kernel work queue.
242///
243/// Wraps the kernel's C `struct workqueue_struct`.
244///
245/// It allows work items to be queued to run on thread pools managed by the kernel. Several are
246/// always available, for example, `system`, `system_highpri`, `system_long`, etc.
247#[repr(transparent)]
248pub struct Queue(Opaque<bindings::workqueue_struct>);
249
250// SAFETY: Accesses to workqueues used by [`Queue`] are thread-safe.
251unsafe impl Send for Queue {}
252// SAFETY: Accesses to workqueues used by [`Queue`] are thread-safe.
253unsafe impl Sync for Queue {}
254
255impl Queue {
256 /// Use the provided `struct workqueue_struct` with Rust.
257 ///
258 /// # Safety
259 ///
260 /// The caller must ensure that the provided raw pointer is not dangling, that it points at a
261 /// valid workqueue, and that it remains valid until the end of `'a`.
262 pub unsafe fn from_raw<'a>(ptr: *const bindings::workqueue_struct) -> &'a Queue {
263 // SAFETY: The `Queue` type is `#[repr(transparent)]`, so the pointer cast is valid. The
264 // caller promises that the pointer is not dangling.
265 unsafe { &*ptr.cast::<Queue>() }
266 }
267
268 /// Enqueues a work item.
269 ///
270 /// This may fail if the work item is already enqueued in a workqueue.
271 ///
272 /// The work item will be submitted using `WORK_CPU_UNBOUND`.
273 pub fn enqueue<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput
274 where
275 W: RawWorkItem<ID> + Send + 'static,
276 {
277 let queue_ptr = self.0.get();
278
279 // SAFETY: We only return `false` if the `work_struct` is already in a workqueue. The other
280 // `__enqueue` requirements are not relevant since `W` is `Send` and static.
281 //
282 // The call to `bindings::queue_work_on` will dereference the provided raw pointer, which
283 // is ok because `__enqueue` guarantees that the pointer is valid for the duration of this
284 // closure.
285 //
286 // Furthermore, if the C workqueue code accesses the pointer after this call to
287 // `__enqueue`, then the work item was successfully enqueued, and `bindings::queue_work_on`
288 // will have returned true. In this case, `__enqueue` promises that the raw pointer will
289 // stay valid until we call the function pointer in the `work_struct`, so the access is ok.
290 unsafe {
291 w.__enqueue(move |work_ptr| {
292 bindings::queue_work_on(
293 bindings::wq_misc_consts_WORK_CPU_UNBOUND as ffi::c_int,
294 queue_ptr,
295 work_ptr,
296 )
297 })
298 }
299 }
300
301 /// Enqueues a delayed work item.
302 ///
303 /// This may fail if the work item is already enqueued in a workqueue.
304 ///
305 /// The work item will be submitted using `WORK_CPU_UNBOUND`.
306 pub fn enqueue_delayed<W, const ID: u64>(&self, w: W, delay: Jiffies) -> W::EnqueueOutput
307 where
308 W: RawDelayedWorkItem<ID> + Send + 'static,
309 {
310 let queue_ptr = self.0.get();
311
312 // SAFETY: We only return `false` if the `work_struct` is already in a workqueue. The other
313 // `__enqueue` requirements are not relevant since `W` is `Send` and static.
314 //
315 // The call to `bindings::queue_delayed_work_on` will dereference the provided raw pointer,
316 // which is ok because `__enqueue` guarantees that the pointer is valid for the duration of
317 // this closure, and the safety requirements of `RawDelayedWorkItem` expands this
318 // requirement to apply to the entire `delayed_work`.
319 //
320 // Furthermore, if the C workqueue code accesses the pointer after this call to
321 // `__enqueue`, then the work item was successfully enqueued, and
322 // `bindings::queue_delayed_work_on` will have returned true. In this case, `__enqueue`
323 // promises that the raw pointer will stay valid until we call the function pointer in the
324 // `work_struct`, so the access is ok.
325 unsafe {
326 w.__enqueue(move |work_ptr| {
327 bindings::queue_delayed_work_on(
328 bindings::wq_misc_consts_WORK_CPU_UNBOUND as ffi::c_int,
329 queue_ptr,
330 container_of!(work_ptr, bindings::delayed_work, work),
331 delay,
332 )
333 })
334 }
335 }
336
337 /// Tries to spawn the given function or closure as a work item.
338 ///
339 /// This method can fail because it allocates memory to store the work item.
340 pub fn try_spawn<T: 'static + Send + FnOnce()>(
341 &self,
342 flags: Flags,
343 func: T,
344 ) -> Result<(), AllocError> {
345 let init = pin_init!(ClosureWork {
346 work <- new_work!("Queue::try_spawn"),
347 func: Some(func),
348 });
349
350 self.enqueue(KBox::pin_init(init, flags).map_err(|_| AllocError)?);
351 Ok(())
352 }
353}
354
355/// A helper type used in [`try_spawn`].
356///
357/// [`try_spawn`]: Queue::try_spawn
358#[pin_data]
359struct ClosureWork<T> {
360 #[pin]
361 work: Work<ClosureWork<T>>,
362 func: Option<T>,
363}
364
365impl<T: FnOnce()> WorkItem for ClosureWork<T> {
366 type Pointer = Pin<KBox<Self>>;
367
368 fn run(mut this: Pin<KBox<Self>>) {
369 if let Some(func) = this.as_mut().project().func.take() {
370 (func)()
371 }
372 }
373}
374
375/// A raw work item.
376///
377/// This is the low-level trait that is designed for being as general as possible.
378///
379/// The `ID` parameter to this trait exists so that a single type can provide multiple
380/// implementations of this trait. For example, if a struct has multiple `work_struct` fields, then
381/// you will implement this trait once for each field, using a different id for each field. The
382/// actual value of the id is not important as long as you use different ids for different fields
383/// of the same struct. (Fields of different structs need not use different ids.)
384///
385/// Note that the id is used only to select the right method to call during compilation. It won't be
386/// part of the final executable.
387///
388/// # Safety
389///
390/// Implementers must ensure that any pointers passed to a `queue_work_on` closure by [`__enqueue`]
391/// remain valid for the duration specified in the guarantees section of the documentation for
392/// [`__enqueue`].
393///
394/// [`__enqueue`]: RawWorkItem::__enqueue
395pub unsafe trait RawWorkItem<const ID: u64> {
396 /// The return type of [`Queue::enqueue`].
397 type EnqueueOutput;
398
399 /// Enqueues this work item on a queue using the provided `queue_work_on` method.
400 ///
401 /// # Guarantees
402 ///
403 /// If this method calls the provided closure, then the raw pointer is guaranteed to point at a
404 /// valid `work_struct` for the duration of the call to the closure. If the closure returns
405 /// true, then it is further guaranteed that the pointer remains valid until someone calls the
406 /// function pointer stored in the `work_struct`.
407 ///
408 /// # Safety
409 ///
410 /// The provided closure may only return `false` if the `work_struct` is already in a workqueue.
411 ///
412 /// If the work item type is annotated with any lifetimes, then you must not call the function
413 /// pointer after any such lifetime expires. (Never calling the function pointer is okay.)
414 ///
415 /// If the work item type is not [`Send`], then the function pointer must be called on the same
416 /// thread as the call to `__enqueue`.
417 unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
418 where
419 F: FnOnce(*mut bindings::work_struct) -> bool;
420}
421
422/// A raw delayed work item.
423///
424/// # Safety
425///
426/// If the `__enqueue` method in the `RawWorkItem` implementation calls the closure, then the
427/// provided pointer must point at the `work` field of a valid `delayed_work`, and the guarantees
428/// that `__enqueue` provides about accessing the `work_struct` must also apply to the rest of the
429/// `delayed_work` struct.
430pub unsafe trait RawDelayedWorkItem<const ID: u64>: RawWorkItem<ID> {}
431
432/// Defines the method that should be called directly when a work item is executed.
433///
434/// This trait is implemented by `Pin<KBox<T>>`, [`Arc<T>`] and [`ARef<T>`], and
435/// is mainly intended to be implemented for smart pointer types. For your own
436/// structs, you would implement [`WorkItem`] instead. The [`run`] method on
437/// this trait will usually just perform the appropriate `container_of`
438/// 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// SAFETY: Like the `Arc<T>` implementation, the `__enqueue` implementation for
945// `ARef<T>` obtains a `work_struct` from the `Work` field using
946// `T::raw_get_work`, so the same safety reasoning applies:
947//
948// - `__enqueue` gets the `work_struct` from the `Work` field, using `T::raw_get_work`.
949// - The only safe way to create a `Work` object is through `Work::new`.
950// - `Work::new` makes sure that `T::Pointer::run` is passed to `init_work_with_key`.
951// - Finally `Work` and `RawWorkItem` guarantee that the correct `Work` field
952// will be used because of the ID const generic bound. This makes sure that `T::raw_get_work`
953// uses the correct offset for the `Work` field, and `Work::new` picks the correct
954// implementation of `WorkItemPointer` for `ARef<T>`.
955unsafe impl<T, const ID: u64> WorkItemPointer<ID> for ARef<T>
956where
957 T: AlwaysRefCounted,
958 T: WorkItem<ID, Pointer = Self>,
959 T: HasWork<T, ID>,
960{
961 unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
962 // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
963 let ptr = ptr.cast::<Work<T, ID>>();
964
965 // SAFETY: This computes the pointer that `__enqueue` got from
966 // `ARef::into_raw`.
967 let ptr = unsafe { T::work_container_of(ptr) };
968
969 // SAFETY: The safety contract of `work_container_of` ensures that it
970 // returns a valid non-null pointer.
971 let ptr = unsafe { NonNull::new_unchecked(ptr) };
972
973 // SAFETY: This pointer comes from `ARef::into_raw` and we've been given
974 // back ownership.
975 let aref = unsafe { ARef::from_raw(ptr) };
976
977 T::run(aref)
978 }
979}
980
981// SAFETY: The `work_struct` raw pointer is guaranteed to be valid for the duration of the call to
982// the closure because we get it from an `ARef`, which means that the ref count will be at least 1,
983// and we don't drop the `ARef` ourselves. If `queue_work_on` returns true, it is further guaranteed
984// to be valid until a call to the function pointer in `work_struct` because we leak the memory it
985// points to, and only reclaim it if the closure returns false, or in `WorkItemPointer::run`, which
986// is what the function pointer in the `work_struct` must be pointing to, according to the safety
987// requirements of `WorkItemPointer`.
988unsafe impl<T, const ID: u64> RawWorkItem<ID> for ARef<T>
989where
990 T: AlwaysRefCounted,
991 T: WorkItem<ID, Pointer = Self>,
992 T: HasWork<T, ID>,
993{
994 type EnqueueOutput = Result<(), Self>;
995
996 unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
997 where
998 F: FnOnce(*mut bindings::work_struct) -> bool,
999 {
1000 let ptr = ARef::into_raw(self);
1001
1002 // SAFETY: Pointers from ARef::into_raw are valid and non-null.
1003 let work_ptr = unsafe { T::raw_get_work(ptr.as_ptr()) };
1004 // SAFETY: `raw_get_work` returns a pointer to a valid value.
1005 let work_ptr = unsafe { Work::raw_get(work_ptr) };
1006
1007 if queue_work_on(work_ptr) {
1008 Ok(())
1009 } else {
1010 // SAFETY: The work queue has not taken ownership of the pointer.
1011 Err(unsafe { ARef::from_raw(ptr) })
1012 }
1013 }
1014}
1015
1016// SAFETY: By the safety requirements of `HasDelayedWork`, the `work_struct` returned by methods in
1017// `HasWork` provides a `work_struct` that is the `work` field of a `delayed_work`, and the rest of
1018// the `delayed_work` has the same access rules as its `work` field.
1019unsafe impl<T, const ID: u64> RawDelayedWorkItem<ID> for ARef<T>
1020where
1021 T: WorkItem<ID, Pointer = Self>,
1022 T: HasDelayedWork<T, ID>,
1023 T: AlwaysRefCounted,
1024{
1025}
1026
1027/// Returns the system work queue (`system_wq`).
1028///
1029/// It is the one used by `schedule[_delayed]_work[_on]()`. Multi-CPU multi-threaded. There are
1030/// users which expect relatively short queue flush time.
1031///
1032/// Callers shouldn't queue work items which can run for too long.
1033pub fn system() -> &'static Queue {
1034 // SAFETY: `system_wq` is a C global, always available.
1035 unsafe { Queue::from_raw(bindings::system_wq) }
1036}
1037
1038/// Returns the system high-priority work queue (`system_highpri_wq`).
1039///
1040/// It is similar to the one returned by [`system`] but for work items which require higher
1041/// scheduling priority.
1042pub fn system_highpri() -> &'static Queue {
1043 // SAFETY: `system_highpri_wq` is a C global, always available.
1044 unsafe { Queue::from_raw(bindings::system_highpri_wq) }
1045}
1046
1047/// Returns the system work queue for potentially long-running work items (`system_long_wq`).
1048///
1049/// It is similar to the one returned by [`system`] but may host long running work items. Queue
1050/// flushing might take relatively long.
1051pub fn system_long() -> &'static Queue {
1052 // SAFETY: `system_long_wq` is a C global, always available.
1053 unsafe { Queue::from_raw(bindings::system_long_wq) }
1054}
1055
1056/// Returns the system unbound work queue (`system_unbound_wq`).
1057///
1058/// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items
1059/// are executed immediately as long as `max_active` limit is not reached and resources are
1060/// available.
1061pub fn system_unbound() -> &'static Queue {
1062 // SAFETY: `system_unbound_wq` is a C global, always available.
1063 unsafe { Queue::from_raw(bindings::system_unbound_wq) }
1064}
1065
1066/// Returns the system freezable work queue (`system_freezable_wq`).
1067///
1068/// It is equivalent to the one returned by [`system`] except that it's freezable.
1069///
1070/// A freezable workqueue participates in the freeze phase of the system suspend operations. Work
1071/// items on the workqueue are drained and no new work item starts execution until thawed.
1072pub fn system_freezable() -> &'static Queue {
1073 // SAFETY: `system_freezable_wq` is a C global, always available.
1074 unsafe { Queue::from_raw(bindings::system_freezable_wq) }
1075}
1076
1077/// Returns the system power-efficient work queue (`system_power_efficient_wq`).
1078///
1079/// It is inclined towards saving power and is converted to "unbound" variants if the
1080/// `workqueue.power_efficient` kernel parameter is specified; otherwise, it is similar to the one
1081/// returned by [`system`].
1082pub fn system_power_efficient() -> &'static Queue {
1083 // SAFETY: `system_power_efficient_wq` is a C global, always available.
1084 unsafe { Queue::from_raw(bindings::system_power_efficient_wq) }
1085}
1086
1087/// Returns the system freezable power-efficient work queue (`system_freezable_power_efficient_wq`).
1088///
1089/// It is similar to the one returned by [`system_power_efficient`] except that is freezable.
1090///
1091/// A freezable workqueue participates in the freeze phase of the system suspend operations. Work
1092/// items on the workqueue are drained and no new work item starts execution until thawed.
1093pub fn system_freezable_power_efficient() -> &'static Queue {
1094 // SAFETY: `system_freezable_power_efficient_wq` is a C global, always available.
1095 unsafe { Queue::from_raw(bindings::system_freezable_power_efficient_wq) }
1096}
1097
1098/// Returns the system bottom halves work queue (`system_bh_wq`).
1099///
1100/// It is similar to the one returned by [`system`] but for work items which
1101/// need to run from a softirq context.
1102pub fn system_bh() -> &'static Queue {
1103 // SAFETY: `system_bh_wq` is a C global, always available.
1104 unsafe { Queue::from_raw(bindings::system_bh_wq) }
1105}
1106
1107/// Returns the system bottom halves high-priority work queue (`system_bh_highpri_wq`).
1108///
1109/// It is similar to the one returned by [`system_bh`] but for work items which
1110/// require higher scheduling priority.
1111pub fn system_bh_highpri() -> &'static Queue {
1112 // SAFETY: `system_bh_highpri_wq` is a C global, always available.
1113 unsafe { Queue::from_raw(bindings::system_bh_highpri_wq) }
1114}