File Index
Files and directories
Sign in
FILE

workqueue.rs

File preview with syntax highlighting.

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