| 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 | //! ## Example |
| 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 | //! C header: [`include/linux/workqueue.h`](srctree/include/linux/workqueue.h) |
| 135 | |
| 136 | use crate::alloc::{AllocError, Flags}; |
| 137 | use crate::{prelude::*, sync::Arc, sync::LockClassKey, types::Opaque}; |
| 138 | use core::marker::PhantomData; |
| 139 | |
| 140 | /// Creates a [`Work`] initialiser with the given name and a newly-created lock class. |
| 141 | #[macro_export] |
| 142 | macro_rules! new_work { |
| 143 | ($($name:literal)?) => { |
| 144 | $crate::workqueue::Work::new($crate::optional_name!($($name)?), $crate::static_lock_class!()) |
| 145 | }; |
| 146 | } |
| 147 | pub use new_work; |
| 148 | |
| 149 | /// A kernel work queue. |
| 150 | /// |
| 151 | /// Wraps the kernel's C `struct workqueue_struct`. |
| 152 | /// |
| 153 | /// It allows work items to be queued to run on thread pools managed by the kernel. Several are |
| 154 | /// always available, for example, `system`, `system_highpri`, `system_long`, etc. |
| 155 | #[repr(transparent)] |
| 156 | pub struct Queue(Opaque<bindings::workqueue_struct>); |
| 157 | |
| 158 | // SAFETY: Accesses to workqueues used by [`Queue`] are thread-safe. |
| 159 | unsafe impl Send for Queue {} |
| 160 | // SAFETY: Accesses to workqueues used by [`Queue`] are thread-safe. |
| 161 | unsafe impl Sync for Queue {} |
| 162 | |
| 163 | impl Queue { |
| 164 | /// Use the provided `struct workqueue_struct` with Rust. |
| 165 | /// |
| 166 | /// # Safety |
| 167 | /// |
| 168 | /// The caller must ensure that the provided raw pointer is not dangling, that it points at a |
| 169 | /// valid workqueue, and that it remains valid until the end of `'a`. |
| 170 | pub unsafe fn from_raw<'a>(ptr: *const bindings::workqueue_struct) -> &'a Queue { |
| 171 | // SAFETY: The `Queue` type is `#[repr(transparent)]`, so the pointer cast is valid. The |
| 172 | // caller promises that the pointer is not dangling. |
| 173 | unsafe { &*(ptr as *const Queue) } |
| 174 | } |
| 175 | |
| 176 | /// Enqueues a work item. |
| 177 | /// |
| 178 | /// This may fail if the work item is already enqueued in a workqueue. |
| 179 | /// |
| 180 | /// The work item will be submitted using `WORK_CPU_UNBOUND`. |
| 181 | pub fn enqueue<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput |
| 182 | where |
| 183 | W: RawWorkItem<ID> + Send + 'static, |
| 184 | { |
| 185 | let queue_ptr = self.0.get(); |
| 186 | |
| 187 | // SAFETY: We only return `false` if the `work_struct` is already in a workqueue. The other |
| 188 | // `__enqueue` requirements are not relevant since `W` is `Send` and static. |
| 189 | // |
| 190 | // The call to `bindings::queue_work_on` will dereference the provided raw pointer, which |
| 191 | // is ok because `__enqueue` guarantees that the pointer is valid for the duration of this |
| 192 | // closure. |
| 193 | // |
| 194 | // Furthermore, if the C workqueue code accesses the pointer after this call to |
| 195 | // `__enqueue`, then the work item was successfully enqueued, and `bindings::queue_work_on` |
| 196 | // will have returned true. In this case, `__enqueue` promises that the raw pointer will |
| 197 | // stay valid until we call the function pointer in the `work_struct`, so the access is ok. |
| 198 | unsafe { |
| 199 | w.__enqueue(move |work_ptr| { |
| 200 | bindings::queue_work_on( |
| 201 | bindings::wq_misc_consts_WORK_CPU_UNBOUND as _, |
| 202 | queue_ptr, |
| 203 | work_ptr, |
| 204 | ) |
| 205 | }) |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | /// Tries to spawn the given function or closure as a work item. |
| 210 | /// |
| 211 | /// This method can fail because it allocates memory to store the work item. |
| 212 | pub fn try_spawn<T: 'static + Send + FnOnce()>( |
| 213 | &self, |
| 214 | flags: Flags, |
| 215 | func: T, |
| 216 | ) -> Result<(), AllocError> { |
| 217 | let init = pin_init!(ClosureWork { |
| 218 | work <- new_work!("Queue::try_spawn" ), |
| 219 | func: Some(func), |
| 220 | }); |
| 221 | |
| 222 | self.enqueue(KBox::pin_init(init, flags).map_err(|_| AllocError)?); |
| 223 | Ok(()) |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | /// A helper type used in [`try_spawn`]. |
| 228 | /// |
| 229 | /// [`try_spawn`]: Queue::try_spawn |
| 230 | #[pin_data] |
| 231 | struct ClosureWork<T> { |
| 232 | #[pin] |
| 233 | work: Work<ClosureWork<T>>, |
| 234 | func: Option<T>, |
| 235 | } |
| 236 | |
| 237 | impl<T> ClosureWork<T> { |
| 238 | fn project(self: Pin<&mut Self>) -> &mut Option<T> { |
| 239 | // SAFETY: The `func` field is not structurally pinned. |
| 240 | unsafe { &mut self.get_unchecked_mut().func } |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | impl<T: FnOnce()> WorkItem for ClosureWork<T> { |
| 245 | type Pointer = Pin<KBox<Self>>; |
| 246 | |
| 247 | fn run(mut this: Pin<KBox<Self>>) { |
| 248 | if let Some(func) = this.as_mut().project().take() { |
| 249 | (func)() |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | /// A raw work item. |
| 255 | /// |
| 256 | /// This is the low-level trait that is designed for being as general as possible. |
| 257 | /// |
| 258 | /// The `ID` parameter to this trait exists so that a single type can provide multiple |
| 259 | /// implementations of this trait. For example, if a struct has multiple `work_struct` fields, then |
| 260 | /// you will implement this trait once for each field, using a different id for each field. The |
| 261 | /// actual value of the id is not important as long as you use different ids for different fields |
| 262 | /// of the same struct. (Fields of different structs need not use different ids.) |
| 263 | /// |
| 264 | /// Note that the id is used only to select the right method to call during compilation. It won't be |
| 265 | /// part of the final executable. |
| 266 | /// |
| 267 | /// # Safety |
| 268 | /// |
| 269 | /// Implementers must ensure that any pointers passed to a `queue_work_on` closure by [`__enqueue`] |
| 270 | /// remain valid for the duration specified in the guarantees section of the documentation for |
| 271 | /// [`__enqueue`]. |
| 272 | /// |
| 273 | /// [`__enqueue`]: RawWorkItem::__enqueue |
| 274 | pub unsafe trait RawWorkItem<const ID: u64> { |
| 275 | /// The return type of [`Queue::enqueue`]. |
| 276 | type EnqueueOutput; |
| 277 | |
| 278 | /// Enqueues this work item on a queue using the provided `queue_work_on` method. |
| 279 | /// |
| 280 | /// # Guarantees |
| 281 | /// |
| 282 | /// If this method calls the provided closure, then the raw pointer is guaranteed to point at a |
| 283 | /// valid `work_struct` for the duration of the call to the closure. If the closure returns |
| 284 | /// true, then it is further guaranteed that the pointer remains valid until someone calls the |
| 285 | /// function pointer stored in the `work_struct`. |
| 286 | /// |
| 287 | /// # Safety |
| 288 | /// |
| 289 | /// The provided closure may only return `false` if the `work_struct` is already in a workqueue. |
| 290 | /// |
| 291 | /// If the work item type is annotated with any lifetimes, then you must not call the function |
| 292 | /// pointer after any such lifetime expires. (Never calling the function pointer is okay.) |
| 293 | /// |
| 294 | /// If the work item type is not [`Send`], then the function pointer must be called on the same |
| 295 | /// thread as the call to `__enqueue`. |
| 296 | unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput |
| 297 | where |
| 298 | F: FnOnce(*mut bindings::work_struct) -> bool; |
| 299 | } |
| 300 | |
| 301 | /// Defines the method that should be called directly when a work item is executed. |
| 302 | /// |
| 303 | /// This trait is implemented by `Pin<KBox<T>>` and [`Arc<T>`], and is mainly intended to be |
| 304 | /// implemented for smart pointer types. For your own structs, you would implement [`WorkItem`] |
| 305 | /// instead. The [`run`] method on this trait will usually just perform the appropriate |
| 306 | /// `container_of` translation and then call into the [`run`][WorkItem::run] method from the |
| 307 | /// [`WorkItem`] trait. |
| 308 | /// |
| 309 | /// This trait is used when the `work_struct` field is defined using the [`Work`] helper. |
| 310 | /// |
| 311 | /// # Safety |
| 312 | /// |
| 313 | /// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with the [`run`] |
| 314 | /// method of this trait as the function pointer. |
| 315 | /// |
| 316 | /// [`__enqueue`]: RawWorkItem::__enqueue |
| 317 | /// [`run`]: WorkItemPointer::run |
| 318 | pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> { |
| 319 | /// Run this work item. |
| 320 | /// |
| 321 | /// # Safety |
| 322 | /// |
| 323 | /// The provided `work_struct` pointer must originate from a previous call to [`__enqueue`] |
| 324 | /// where the `queue_work_on` closure returned true, and the pointer must still be valid. |
| 325 | /// |
| 326 | /// [`__enqueue`]: RawWorkItem::__enqueue |
| 327 | unsafe extern "C" fn run(ptr: *mut bindings::work_struct); |
| 328 | } |
| 329 | |
| 330 | /// Defines the method that should be called when this work item is executed. |
| 331 | /// |
| 332 | /// This trait is used when the `work_struct` field is defined using the [`Work`] helper. |
| 333 | pub trait WorkItem<const ID: u64 = 0> { |
| 334 | /// The pointer type that this struct is wrapped in. This will typically be `Arc<Self>` or |
| 335 | /// `Pin<KBox<Self>>`. |
| 336 | type Pointer: WorkItemPointer<ID>; |
| 337 | |
| 338 | /// The method that should be called when this work item is executed. |
| 339 | fn run(this: Self::Pointer); |
| 340 | } |
| 341 | |
| 342 | /// Links for a work item. |
| 343 | /// |
| 344 | /// This struct contains a function pointer to the [`run`] function from the [`WorkItemPointer`] |
| 345 | /// trait, and defines the linked list pointers necessary to enqueue a work item in a workqueue. |
| 346 | /// |
| 347 | /// Wraps the kernel's C `struct work_struct`. |
| 348 | /// |
| 349 | /// This is a helper type used to associate a `work_struct` with the [`WorkItem`] that uses it. |
| 350 | /// |
| 351 | /// [`run`]: WorkItemPointer::run |
| 352 | #[pin_data] |
| 353 | #[repr(transparent)] |
| 354 | pub struct Work<T: ?Sized, const ID: u64 = 0> { |
| 355 | #[pin] |
| 356 | work: Opaque<bindings::work_struct>, |
| 357 | _inner: PhantomData<T>, |
| 358 | } |
| 359 | |
| 360 | // SAFETY: Kernel work items are usable from any thread. |
| 361 | // |
| 362 | // We do not need to constrain `T` since the work item does not actually contain a `T`. |
| 363 | unsafe impl<T: ?Sized, const ID: u64> Send for Work<T, ID> {} |
| 364 | // SAFETY: Kernel work items are usable from any thread. |
| 365 | // |
| 366 | // We do not need to constrain `T` since the work item does not actually contain a `T`. |
| 367 | unsafe impl<T: ?Sized, const ID: u64> Sync for Work<T, ID> {} |
| 368 | |
| 369 | impl<T: ?Sized, const ID: u64> Work<T, ID> { |
| 370 | /// Creates a new instance of [`Work`]. |
| 371 | #[inline] |
| 372 | pub fn new(name: &'static CStr, key: Pin<&'static LockClassKey>) -> impl PinInit<Self> |
| 373 | where |
| 374 | T: WorkItem<ID>, |
| 375 | { |
| 376 | pin_init!(Self { |
| 377 | work <- Opaque::ffi_init(|slot| { |
| 378 | // SAFETY: The `WorkItemPointer` implementation promises that `run` can be used as |
| 379 | // the work item function. |
| 380 | unsafe { |
| 381 | bindings::init_work_with_key( |
| 382 | slot, |
| 383 | Some(T::Pointer::run), |
| 384 | false, |
| 385 | name.as_char_ptr(), |
| 386 | key.as_ptr(), |
| 387 | ) |
| 388 | } |
| 389 | }), |
| 390 | _inner: PhantomData, |
| 391 | }) |
| 392 | } |
| 393 | |
| 394 | /// Get a pointer to the inner `work_struct`. |
| 395 | /// |
| 396 | /// # Safety |
| 397 | /// |
| 398 | /// The provided pointer must not be dangling and must be properly aligned. (But the memory |
| 399 | /// need not be initialized.) |
| 400 | #[inline] |
| 401 | pub unsafe fn raw_get(ptr: *const Self) -> *mut bindings::work_struct { |
| 402 | // SAFETY: The caller promises that the pointer is aligned and not dangling. |
| 403 | // |
| 404 | // A pointer cast would also be ok due to `#[repr(transparent)]`. We use `addr_of!` so that |
| 405 | // the compiler does not complain that the `work` field is unused. |
| 406 | unsafe { Opaque::raw_get(core::ptr::addr_of!((*ptr).work)) } |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | /// Declares that a type has a [`Work<T, ID>`] field. |
| 411 | /// |
| 412 | /// The intended way of using this trait is via the [`impl_has_work!`] macro. You can use the macro |
| 413 | /// like this: |
| 414 | /// |
| 415 | /// ```no_run |
| 416 | /// use kernel::workqueue::{impl_has_work, Work}; |
| 417 | /// |
| 418 | /// struct MyWorkItem { |
| 419 | /// work_field: Work<MyWorkItem, 1>, |
| 420 | /// } |
| 421 | /// |
| 422 | /// impl_has_work! { |
| 423 | /// impl HasWork<MyWorkItem, 1> for MyWorkItem { self.work_field } |
| 424 | /// } |
| 425 | /// ``` |
| 426 | /// |
| 427 | /// Note that since the [`Work`] type is annotated with an id, you can have several `work_struct` |
| 428 | /// fields by using a different id for each one. |
| 429 | /// |
| 430 | /// # Safety |
| 431 | /// |
| 432 | /// The methods [`raw_get_work`] and [`work_container_of`] must return valid pointers and must be |
| 433 | /// true inverses of each other; that is, they must satisfy the following invariants: |
| 434 | /// - `work_container_of(raw_get_work(ptr)) == ptr` for any `ptr: *mut Self`. |
| 435 | /// - `raw_get_work(work_container_of(ptr)) == ptr` for any `ptr: *mut Work<T, ID>`. |
| 436 | /// |
| 437 | /// [`impl_has_work!`]: crate::impl_has_work |
| 438 | /// [`raw_get_work`]: HasWork::raw_get_work |
| 439 | /// [`work_container_of`]: HasWork::work_container_of |
| 440 | pub unsafe trait HasWork<T, const ID: u64 = 0> { |
| 441 | /// Returns a pointer to the [`Work<T, ID>`] field. |
| 442 | /// |
| 443 | /// # Safety |
| 444 | /// |
| 445 | /// The provided pointer must point at a valid struct of type `Self`. |
| 446 | unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<T, ID>; |
| 447 | |
| 448 | /// Returns a pointer to the struct containing the [`Work<T, ID>`] field. |
| 449 | /// |
| 450 | /// # Safety |
| 451 | /// |
| 452 | /// The pointer must point at a [`Work<T, ID>`] field in a struct of type `Self`. |
| 453 | unsafe fn work_container_of(ptr: *mut Work<T, ID>) -> *mut Self; |
| 454 | } |
| 455 | |
| 456 | /// Used to safely implement the [`HasWork<T, ID>`] trait. |
| 457 | /// |
| 458 | /// # Examples |
| 459 | /// |
| 460 | /// ``` |
| 461 | /// use kernel::sync::Arc; |
| 462 | /// use kernel::workqueue::{self, impl_has_work, Work}; |
| 463 | /// |
| 464 | /// struct MyStruct<'a, T, const N: usize> { |
| 465 | /// work_field: Work<MyStruct<'a, T, N>, 17>, |
| 466 | /// f: fn(&'a [T; N]), |
| 467 | /// } |
| 468 | /// |
| 469 | /// impl_has_work! { |
| 470 | /// impl{'a, T, const N: usize} HasWork<MyStruct<'a, T, N>, 17> |
| 471 | /// for MyStruct<'a, T, N> { self.work_field } |
| 472 | /// } |
| 473 | /// ``` |
| 474 | #[macro_export] |
| 475 | macro_rules! impl_has_work { |
| 476 | ($(impl$({$($generics:tt)*})? |
| 477 | HasWork<$work_type:ty $(, $id:tt)?> |
| 478 | for $self:ty |
| 479 | { self.$field:ident } |
| 480 | )*) => {$( |
| 481 | // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right |
| 482 | // type. |
| 483 | unsafe impl$(<$($generics)+>)? $crate::workqueue::HasWork<$work_type $(, $id)?> for $self { |
| 484 | #[inline] |
| 485 | unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_type $(, $id)?> { |
| 486 | // SAFETY: The caller promises that the pointer is not dangling. |
| 487 | unsafe { |
| 488 | ::core::ptr::addr_of_mut!((*ptr).$field) |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | #[inline] |
| 493 | unsafe fn work_container_of( |
| 494 | ptr: *mut $crate::workqueue::Work<$work_type $(, $id)?>, |
| 495 | ) -> *mut Self { |
| 496 | // SAFETY: The caller promises that the pointer points at a field of the right type |
| 497 | // in the right kind of struct. |
| 498 | unsafe { $crate::container_of!(ptr, Self, $field) } |
| 499 | } |
| 500 | } |
| 501 | )*}; |
| 502 | } |
| 503 | pub use impl_has_work; |
| 504 | |
| 505 | impl_has_work! { |
| 506 | impl{T} HasWork<Self> for ClosureWork<T> { self.work } |
| 507 | } |
| 508 | |
| 509 | // SAFETY: The `__enqueue` implementation in RawWorkItem uses a `work_struct` initialized with the |
| 510 | // `run` method of this trait as the function pointer because: |
| 511 | // - `__enqueue` gets the `work_struct` from the `Work` field, using `T::raw_get_work`. |
| 512 | // - The only safe way to create a `Work` object is through `Work::new`. |
| 513 | // - `Work::new` makes sure that `T::Pointer::run` is passed to `init_work_with_key`. |
| 514 | // - Finally `Work` and `RawWorkItem` guarantee that the correct `Work` field |
| 515 | // will be used because of the ID const generic bound. This makes sure that `T::raw_get_work` |
| 516 | // uses the correct offset for the `Work` field, and `Work::new` picks the correct |
| 517 | // implementation of `WorkItemPointer` for `Arc<T>`. |
| 518 | unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T> |
| 519 | where |
| 520 | T: WorkItem<ID, Pointer = Self>, |
| 521 | T: HasWork<T, ID>, |
| 522 | { |
| 523 | unsafe extern "C" fn run(ptr: *mut bindings::work_struct) { |
| 524 | // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`. |
| 525 | let ptr = ptr as *mut Work<T, ID>; |
| 526 | // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`. |
| 527 | let ptr = unsafe { T::work_container_of(ptr) }; |
| 528 | // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership. |
| 529 | let arc = unsafe { Arc::from_raw(ptr) }; |
| 530 | |
| 531 | T::run(arc) |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | // SAFETY: The `work_struct` raw pointer is guaranteed to be valid for the duration of the call to |
| 536 | // the closure because we get it from an `Arc`, which means that the ref count will be at least 1, |
| 537 | // and we don't drop the `Arc` ourselves. If `queue_work_on` returns true, it is further guaranteed |
| 538 | // to be valid until a call to the function pointer in `work_struct` because we leak the memory it |
| 539 | // points to, and only reclaim it if the closure returns false, or in `WorkItemPointer::run`, which |
| 540 | // is what the function pointer in the `work_struct` must be pointing to, according to the safety |
| 541 | // requirements of `WorkItemPointer`. |
| 542 | unsafe impl<T, const ID: u64> RawWorkItem<ID> for Arc<T> |
| 543 | where |
| 544 | T: WorkItem<ID, Pointer = Self>, |
| 545 | T: HasWork<T, ID>, |
| 546 | { |
| 547 | type EnqueueOutput = Result<(), Self>; |
| 548 | |
| 549 | unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput |
| 550 | where |
| 551 | F: FnOnce(*mut bindings::work_struct) -> bool, |
| 552 | { |
| 553 | // Casting between const and mut is not a problem as long as the pointer is a raw pointer. |
| 554 | let ptr = Arc::into_raw(self).cast_mut(); |
| 555 | |
| 556 | // SAFETY: Pointers into an `Arc` point at a valid value. |
| 557 | let work_ptr = unsafe { T::raw_get_work(ptr) }; |
| 558 | // SAFETY: `raw_get_work` returns a pointer to a valid value. |
| 559 | let work_ptr = unsafe { Work::raw_get(work_ptr) }; |
| 560 | |
| 561 | if queue_work_on(work_ptr) { |
| 562 | Ok(()) |
| 563 | } else { |
| 564 | // SAFETY: The work queue has not taken ownership of the pointer. |
| 565 | Err(unsafe { Arc::from_raw(ptr) }) |
| 566 | } |
| 567 | } |
| 568 | } |
| 569 | |
| 570 | // SAFETY: TODO. |
| 571 | unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<KBox<T>> |
| 572 | where |
| 573 | T: WorkItem<ID, Pointer = Self>, |
| 574 | T: HasWork<T, ID>, |
| 575 | { |
| 576 | unsafe extern "C" fn run(ptr: *mut bindings::work_struct) { |
| 577 | // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`. |
| 578 | let ptr = ptr as *mut Work<T, ID>; |
| 579 | // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`. |
| 580 | let ptr = unsafe { T::work_container_of(ptr) }; |
| 581 | // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership. |
| 582 | let boxed = unsafe { KBox::from_raw(ptr) }; |
| 583 | // SAFETY: The box was already pinned when it was enqueued. |
| 584 | let pinned = unsafe { Pin::new_unchecked(boxed) }; |
| 585 | |
| 586 | T::run(pinned) |
| 587 | } |
| 588 | } |
| 589 | |
| 590 | // SAFETY: TODO. |
| 591 | unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<KBox<T>> |
| 592 | where |
| 593 | T: WorkItem<ID, Pointer = Self>, |
| 594 | T: HasWork<T, ID>, |
| 595 | { |
| 596 | type EnqueueOutput = (); |
| 597 | |
| 598 | unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput |
| 599 | where |
| 600 | F: FnOnce(*mut bindings::work_struct) -> bool, |
| 601 | { |
| 602 | // SAFETY: We're not going to move `self` or any of its fields, so its okay to temporarily |
| 603 | // remove the `Pin` wrapper. |
| 604 | let boxed = unsafe { Pin::into_inner_unchecked(self) }; |
| 605 | let ptr = KBox::into_raw(boxed); |
| 606 | |
| 607 | // SAFETY: Pointers into a `KBox` point at a valid value. |
| 608 | let work_ptr = unsafe { T::raw_get_work(ptr) }; |
| 609 | // SAFETY: `raw_get_work` returns a pointer to a valid value. |
| 610 | let work_ptr = unsafe { Work::raw_get(work_ptr) }; |
| 611 | |
| 612 | if !queue_work_on(work_ptr) { |
| 613 | // SAFETY: This method requires exclusive ownership of the box, so it cannot be in a |
| 614 | // workqueue. |
| 615 | unsafe { ::core::hint::unreachable_unchecked() } |
| 616 | } |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | /// Returns the system work queue (`system_wq`). |
| 621 | /// |
| 622 | /// It is the one used by `schedule[_delayed]_work[_on]()`. Multi-CPU multi-threaded. There are |
| 623 | /// users which expect relatively short queue flush time. |
| 624 | /// |
| 625 | /// Callers shouldn't queue work items which can run for too long. |
| 626 | pub fn system() -> &'static Queue { |
| 627 | // SAFETY: `system_wq` is a C global, always available. |
| 628 | unsafe { Queue::from_raw(bindings::system_wq) } |
| 629 | } |
| 630 | |
| 631 | /// Returns the system high-priority work queue (`system_highpri_wq`). |
| 632 | /// |
| 633 | /// It is similar to the one returned by [`system`] but for work items which require higher |
| 634 | /// scheduling priority. |
| 635 | pub fn system_highpri() -> &'static Queue { |
| 636 | // SAFETY: `system_highpri_wq` is a C global, always available. |
| 637 | unsafe { Queue::from_raw(bindings::system_highpri_wq) } |
| 638 | } |
| 639 | |
| 640 | /// Returns the system work queue for potentially long-running work items (`system_long_wq`). |
| 641 | /// |
| 642 | /// It is similar to the one returned by [`system`] but may host long running work items. Queue |
| 643 | /// flushing might take relatively long. |
| 644 | pub fn system_long() -> &'static Queue { |
| 645 | // SAFETY: `system_long_wq` is a C global, always available. |
| 646 | unsafe { Queue::from_raw(bindings::system_long_wq) } |
| 647 | } |
| 648 | |
| 649 | /// Returns the system unbound work queue (`system_unbound_wq`). |
| 650 | /// |
| 651 | /// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items |
| 652 | /// are executed immediately as long as `max_active` limit is not reached and resources are |
| 653 | /// available. |
| 654 | pub fn system_unbound() -> &'static Queue { |
| 655 | // SAFETY: `system_unbound_wq` is a C global, always available. |
| 656 | unsafe { Queue::from_raw(bindings::system_unbound_wq) } |
| 657 | } |
| 658 | |
| 659 | /// Returns the system freezable work queue (`system_freezable_wq`). |
| 660 | /// |
| 661 | /// It is equivalent to the one returned by [`system`] except that it's freezable. |
| 662 | /// |
| 663 | /// A freezable workqueue participates in the freeze phase of the system suspend operations. Work |
| 664 | /// items on the workqueue are drained and no new work item starts execution until thawed. |
| 665 | pub fn system_freezable() -> &'static Queue { |
| 666 | // SAFETY: `system_freezable_wq` is a C global, always available. |
| 667 | unsafe { Queue::from_raw(bindings::system_freezable_wq) } |
| 668 | } |
| 669 | |
| 670 | /// Returns the system power-efficient work queue (`system_power_efficient_wq`). |
| 671 | /// |
| 672 | /// It is inclined towards saving power and is converted to "unbound" variants if the |
| 673 | /// `workqueue.power_efficient` kernel parameter is specified; otherwise, it is similar to the one |
| 674 | /// returned by [`system`]. |
| 675 | pub fn system_power_efficient() -> &'static Queue { |
| 676 | // SAFETY: `system_power_efficient_wq` is a C global, always available. |
| 677 | unsafe { Queue::from_raw(bindings::system_power_efficient_wq) } |
| 678 | } |
| 679 | |
| 680 | /// Returns the system freezable power-efficient work queue (`system_freezable_power_efficient_wq`). |
| 681 | /// |
| 682 | /// It is similar to the one returned by [`system_power_efficient`] except that is freezable. |
| 683 | /// |
| 684 | /// A freezable workqueue participates in the freeze phase of the system suspend operations. Work |
| 685 | /// items on the workqueue are drained and no new work item starts execution until thawed. |
| 686 | pub fn system_freezable_power_efficient() -> &'static Queue { |
| 687 | // SAFETY: `system_freezable_power_efficient_wq` is a C global, always available. |
| 688 | unsafe { Queue::from_raw(bindings::system_freezable_power_efficient_wq) } |
| 689 | } |
| 690 | |
| 691 | /// Returns the system bottom halves work queue (`system_bh_wq`). |
| 692 | /// |
| 693 | /// It is similar to the one returned by [`system`] but for work items which |
| 694 | /// need to run from a softirq context. |
| 695 | pub fn system_bh() -> &'static Queue { |
| 696 | // SAFETY: `system_bh_wq` is a C global, always available. |
| 697 | unsafe { Queue::from_raw(bindings::system_bh_wq) } |
| 698 | } |
| 699 | |
| 700 | /// Returns the system bottom halves high-priority work queue (`system_bh_highpri_wq`). |
| 701 | /// |
| 702 | /// It is similar to the one returned by [`system_bh`] but for work items which |
| 703 | /// require higher scheduling priority. |
| 704 | pub fn system_bh_highpri() -> &'static Queue { |
| 705 | // SAFETY: `system_bh_highpri_wq` is a C global, always available. |
| 706 | unsafe { Queue::from_raw(bindings::system_bh_highpri_wq) } |
| 707 | } |
| 708 | |