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 includes 22 //! 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 //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h) 30 31 use crate::{bindings, prelude::*, sync::Arc, sync::LockClassKey, types::Opaque}; 32 use alloc::boxed::Box; 33 use core::marker::PhantomData; 34 use core::pin::Pin; 35 36 /// Creates a [`Work`] initialiser with the given name and a newly-created lock class. 37 #[macro_export] 38 macro_rules! new_work { 39 ($($name:literal)?) => { 40 $crate::workqueue::Work::new($crate::optional_name!($($name)?), $crate::static_lock_class!()) 41 }; 42 } 43 44 /// A kernel work queue. 45 /// 46 /// Wraps the kernel's C `struct workqueue_struct`. 47 /// 48 /// It allows work items to be queued to run on thread pools managed by the kernel. Several are 49 /// always available, for example, `system`, `system_highpri`, `system_long`, etc. 50 #[repr(transparent)] 51 pub struct Queue(Opaque<bindings::workqueue_struct>); 52 53 // SAFETY: Accesses to workqueues used by [`Queue`] are thread-safe. 54 unsafe impl Send for Queue {} 55 // SAFETY: Accesses to workqueues used by [`Queue`] are thread-safe. 56 unsafe impl Sync for Queue {} 57 58 impl Queue { 59 /// Use the provided `struct workqueue_struct` with Rust. 60 /// 61 /// # Safety 62 /// 63 /// The caller must ensure that the provided raw pointer is not dangling, that it points at a 64 /// valid workqueue, and that it remains valid until the end of 'a. 65 pub unsafe fn from_raw<'a>(ptr: *const bindings::workqueue_struct) -> &'a Queue { 66 // SAFETY: The `Queue` type is `#[repr(transparent)]`, so the pointer cast is valid. The 67 // caller promises that the pointer is not dangling. 68 unsafe { &*(ptr as *const Queue) } 69 } 70 71 /// Enqueues a work item. 72 /// 73 /// This may fail if the work item is already enqueued in a workqueue. 74 /// 75 /// The work item will be submitted using `WORK_CPU_UNBOUND`. 76 pub fn enqueue<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput 77 where 78 W: RawWorkItem<ID> + Send + 'static, 79 { 80 let queue_ptr = self.0.get(); 81 82 // SAFETY: We only return `false` if the `work_struct` is already in a workqueue. The other 83 // `__enqueue` requirements are not relevant since `W` is `Send` and static. 84 // 85 // The call to `bindings::queue_work_on` will dereference the provided raw pointer, which 86 // is ok because `__enqueue` guarantees that the pointer is valid for the duration of this 87 // closure. 88 // 89 // Furthermore, if the C workqueue code accesses the pointer after this call to 90 // `__enqueue`, then the work item was successfully enqueued, and `bindings::queue_work_on` 91 // will have returned true. In this case, `__enqueue` promises that the raw pointer will 92 // stay valid until we call the function pointer in the `work_struct`, so the access is ok. 93 unsafe { 94 w.__enqueue(move |work_ptr| { 95 bindings::queue_work_on(bindings::WORK_CPU_UNBOUND as _, queue_ptr, work_ptr) 96 }) 97 } 98 } 99 } 100 101 /// A raw work item. 102 /// 103 /// This is the low-level trait that is designed for being as general as possible. 104 /// 105 /// The `ID` parameter to this trait exists so that a single type can provide multiple 106 /// implementations of this trait. For example, if a struct has multiple `work_struct` fields, then 107 /// you will implement this trait once for each field, using a different id for each field. The 108 /// actual value of the id is not important as long as you use different ids for different fields 109 /// of the same struct. (Fields of different structs need not use different ids.) 110 /// 111 /// Note that the id is used only to select the right method to call during compilation. It wont be 112 /// part of the final executable. 113 /// 114 /// # Safety 115 /// 116 /// Implementers must ensure that any pointers passed to a `queue_work_on` closure by `__enqueue` 117 /// remain valid for the duration specified in the guarantees section of the documentation for 118 /// `__enqueue`. 119 pub unsafe trait RawWorkItem<const ID: u64> { 120 /// The return type of [`Queue::enqueue`]. 121 type EnqueueOutput; 122 123 /// Enqueues this work item on a queue using the provided `queue_work_on` method. 124 /// 125 /// # Guarantees 126 /// 127 /// If this method calls the provided closure, then the raw pointer is guaranteed to point at a 128 /// valid `work_struct` for the duration of the call to the closure. If the closure returns 129 /// true, then it is further guaranteed that the pointer remains valid until someone calls the 130 /// function pointer stored in the `work_struct`. 131 /// 132 /// # Safety 133 /// 134 /// The provided closure may only return `false` if the `work_struct` is already in a workqueue. 135 /// 136 /// If the work item type is annotated with any lifetimes, then you must not call the function 137 /// pointer after any such lifetime expires. (Never calling the function pointer is okay.) 138 /// 139 /// If the work item type is not [`Send`], then the function pointer must be called on the same 140 /// thread as the call to `__enqueue`. 141 unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput 142 where 143 F: FnOnce(*mut bindings::work_struct) -> bool; 144 } 145 146 /// Defines the method that should be called directly when a work item is executed. 147 /// 148 /// This trait is implemented by `Pin<Box<T>>` and `Arc<T>`, and is mainly intended to be 149 /// implemented for smart pointer types. For your own structs, you would implement [`WorkItem`] 150 /// instead. The `run` method on this trait will usually just perform the appropriate 151 /// `container_of` translation and then call into the `run` method from the [`WorkItem`] trait. 152 /// 153 /// This trait is used when the `work_struct` field is defined using the [`Work`] helper. 154 /// 155 /// # Safety 156 /// 157 /// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with the [`run`] 158 /// method of this trait as the function pointer. 159 /// 160 /// [`__enqueue`]: RawWorkItem::__enqueue 161 /// [`run`]: WorkItemPointer::run 162 pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> { 163 /// Run this work item. 164 /// 165 /// # Safety 166 /// 167 /// The provided `work_struct` pointer must originate from a previous call to `__enqueue` where 168 /// the `queue_work_on` closure returned true, and the pointer must still be valid. 169 unsafe extern "C" fn run(ptr: *mut bindings::work_struct); 170 } 171 172 /// Defines the method that should be called when this work item is executed. 173 /// 174 /// This trait is used when the `work_struct` field is defined using the [`Work`] helper. 175 pub trait WorkItem<const ID: u64 = 0> { 176 /// The pointer type that this struct is wrapped in. This will typically be `Arc<Self>` or 177 /// `Pin<Box<Self>>`. 178 type Pointer: WorkItemPointer<ID>; 179 180 /// The method that should be called when this work item is executed. 181 fn run(this: Self::Pointer); 182 } 183 184 /// Links for a work item. 185 /// 186 /// This struct contains a function pointer to the `run` function from the [`WorkItemPointer`] 187 /// trait, and defines the linked list pointers necessary to enqueue a work item in a workqueue. 188 /// 189 /// Wraps the kernel's C `struct work_struct`. 190 /// 191 /// This is a helper type used to associate a `work_struct` with the [`WorkItem`] that uses it. 192 #[repr(transparent)] 193 pub struct Work<T: ?Sized, const ID: u64 = 0> { 194 work: Opaque<bindings::work_struct>, 195 _inner: PhantomData<T>, 196 } 197 198 // SAFETY: Kernel work items are usable from any thread. 199 // 200 // We do not need to constrain `T` since the work item does not actually contain a `T`. 201 unsafe impl<T: ?Sized, const ID: u64> Send for Work<T, ID> {} 202 // SAFETY: Kernel work items are usable from any thread. 203 // 204 // We do not need to constrain `T` since the work item does not actually contain a `T`. 205 unsafe impl<T: ?Sized, const ID: u64> Sync for Work<T, ID> {} 206 207 impl<T: ?Sized, const ID: u64> Work<T, ID> { 208 /// Creates a new instance of [`Work`]. 209 #[inline] 210 #[allow(clippy::new_ret_no_self)] 211 pub fn new(name: &'static CStr, key: &'static LockClassKey) -> impl PinInit<Self> 212 where 213 T: WorkItem<ID>, 214 { 215 // SAFETY: The `WorkItemPointer` implementation promises that `run` can be used as the work 216 // item function. 217 unsafe { 218 kernel::init::pin_init_from_closure(move |slot| { 219 let slot = Self::raw_get(slot); 220 bindings::init_work_with_key( 221 slot, 222 Some(T::Pointer::run), 223 false, 224 name.as_char_ptr(), 225 key.as_ptr(), 226 ); 227 Ok(()) 228 }) 229 } 230 } 231 232 /// Get a pointer to the inner `work_struct`. 233 /// 234 /// # Safety 235 /// 236 /// The provided pointer must not be dangling and must be properly aligned. (But the memory 237 /// need not be initialized.) 238 #[inline] 239 pub unsafe fn raw_get(ptr: *const Self) -> *mut bindings::work_struct { 240 // SAFETY: The caller promises that the pointer is aligned and not dangling. 241 // 242 // A pointer cast would also be ok due to `#[repr(transparent)]`. We use `addr_of!` so that 243 // the compiler does not complain that the `work` field is unused. 244 unsafe { Opaque::raw_get(core::ptr::addr_of!((*ptr).work)) } 245 } 246 } 247 248 /// Declares that a type has a [`Work<T, ID>`] field. 249 /// 250 /// The intended way of using this trait is via the [`impl_has_work!`] macro. You can use the macro 251 /// like this: 252 /// 253 /// ```no_run 254 /// use kernel::impl_has_work; 255 /// use kernel::prelude::*; 256 /// use kernel::workqueue::Work; 257 /// 258 /// struct MyWorkItem { 259 /// work_field: Work<MyWorkItem, 1>, 260 /// } 261 /// 262 /// impl_has_work! { 263 /// impl HasWork<MyWorkItem, 1> for MyWorkItem { self.work_field } 264 /// } 265 /// ``` 266 /// 267 /// Note that since the `Work` type is annotated with an id, you can have several `work_struct` 268 /// fields by using a different id for each one. 269 /// 270 /// # Safety 271 /// 272 /// The [`OFFSET`] constant must be the offset of a field in Self of type [`Work<T, ID>`]. The methods on 273 /// this trait must have exactly the behavior that the definitions given below have. 274 /// 275 /// [`Work<T, ID>`]: Work 276 /// [`impl_has_work!`]: crate::impl_has_work 277 /// [`OFFSET`]: HasWork::OFFSET 278 pub unsafe trait HasWork<T, const ID: u64 = 0> { 279 /// The offset of the [`Work<T, ID>`] field. 280 /// 281 /// [`Work<T, ID>`]: Work 282 const OFFSET: usize; 283 284 /// Returns the offset of the [`Work<T, ID>`] field. 285 /// 286 /// This method exists because the [`OFFSET`] constant cannot be accessed if the type is not Sized. 287 /// 288 /// [`Work<T, ID>`]: Work 289 /// [`OFFSET`]: HasWork::OFFSET 290 #[inline] 291 fn get_work_offset(&self) -> usize { 292 Self::OFFSET 293 } 294 295 /// Returns a pointer to the [`Work<T, ID>`] field. 296 /// 297 /// # Safety 298 /// 299 /// The provided pointer must point at a valid struct of type `Self`. 300 /// 301 /// [`Work<T, ID>`]: Work 302 #[inline] 303 unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<T, ID> { 304 // SAFETY: The caller promises that the pointer is valid. 305 unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut Work<T, ID> } 306 } 307 308 /// Returns a pointer to the struct containing the [`Work<T, ID>`] field. 309 /// 310 /// # Safety 311 /// 312 /// The pointer must point at a [`Work<T, ID>`] field in a struct of type `Self`. 313 /// 314 /// [`Work<T, ID>`]: Work 315 #[inline] 316 unsafe fn work_container_of(ptr: *mut Work<T, ID>) -> *mut Self 317 where 318 Self: Sized, 319 { 320 // SAFETY: The caller promises that the pointer points at a field of the right type in the 321 // right kind of struct. 322 unsafe { (ptr as *mut u8).sub(Self::OFFSET) as *mut Self } 323 } 324 } 325 326 /// Used to safely implement the [`HasWork<T, ID>`] trait. 327 /// 328 /// # Examples 329 /// 330 /// ``` 331 /// use kernel::impl_has_work; 332 /// use kernel::sync::Arc; 333 /// use kernel::workqueue::{self, Work}; 334 /// 335 /// struct MyStruct { 336 /// work_field: Work<MyStruct, 17>, 337 /// } 338 /// 339 /// impl_has_work! { 340 /// impl HasWork<MyStruct, 17> for MyStruct { self.work_field } 341 /// } 342 /// ``` 343 /// 344 /// [`HasWork<T, ID>`]: HasWork 345 #[macro_export] 346 macro_rules! impl_has_work { 347 ($(impl$(<$($implarg:ident),*>)? 348 HasWork<$work_type:ty $(, $id:tt)?> 349 for $self:ident $(<$($selfarg:ident),*>)? 350 { self.$field:ident } 351 )*) => {$( 352 // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right 353 // type. 354 unsafe impl$(<$($implarg),*>)? $crate::workqueue::HasWork<$work_type $(, $id)?> for $self $(<$($selfarg),*>)? { 355 const OFFSET: usize = ::core::mem::offset_of!(Self, $field) as usize; 356 357 #[inline] 358 unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_type $(, $id)?> { 359 // SAFETY: The caller promises that the pointer is not dangling. 360 unsafe { 361 ::core::ptr::addr_of_mut!((*ptr).$field) 362 } 363 } 364 } 365 )*}; 366 } 367 368 unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T> 369 where 370 T: WorkItem<ID, Pointer = Self>, 371 T: HasWork<T, ID>, 372 { 373 unsafe extern "C" fn run(ptr: *mut bindings::work_struct) { 374 // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`. 375 let ptr = ptr as *mut Work<T, ID>; 376 // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`. 377 let ptr = unsafe { T::work_container_of(ptr) }; 378 // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership. 379 let arc = unsafe { Arc::from_raw(ptr) }; 380 381 T::run(arc) 382 } 383 } 384 385 unsafe impl<T, const ID: u64> RawWorkItem<ID> for Arc<T> 386 where 387 T: WorkItem<ID, Pointer = Self>, 388 T: HasWork<T, ID>, 389 { 390 type EnqueueOutput = Result<(), Self>; 391 392 unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput 393 where 394 F: FnOnce(*mut bindings::work_struct) -> bool, 395 { 396 // Casting between const and mut is not a problem as long as the pointer is a raw pointer. 397 let ptr = Arc::into_raw(self).cast_mut(); 398 399 // SAFETY: Pointers into an `Arc` point at a valid value. 400 let work_ptr = unsafe { T::raw_get_work(ptr) }; 401 // SAFETY: `raw_get_work` returns a pointer to a valid value. 402 let work_ptr = unsafe { Work::raw_get(work_ptr) }; 403 404 if queue_work_on(work_ptr) { 405 Ok(()) 406 } else { 407 // SAFETY: The work queue has not taken ownership of the pointer. 408 Err(unsafe { Arc::from_raw(ptr) }) 409 } 410 } 411 } 412 413 unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<Box<T>> 414 where 415 T: WorkItem<ID, Pointer = Self>, 416 T: HasWork<T, ID>, 417 { 418 unsafe extern "C" fn run(ptr: *mut bindings::work_struct) { 419 // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`. 420 let ptr = ptr as *mut Work<T, ID>; 421 // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`. 422 let ptr = unsafe { T::work_container_of(ptr) }; 423 // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership. 424 let boxed = unsafe { Box::from_raw(ptr) }; 425 // SAFETY: The box was already pinned when it was enqueued. 426 let pinned = unsafe { Pin::new_unchecked(boxed) }; 427 428 T::run(pinned) 429 } 430 } 431 432 unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<Box<T>> 433 where 434 T: WorkItem<ID, Pointer = Self>, 435 T: HasWork<T, ID>, 436 { 437 type EnqueueOutput = (); 438 439 unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput 440 where 441 F: FnOnce(*mut bindings::work_struct) -> bool, 442 { 443 // SAFETY: We're not going to move `self` or any of its fields, so its okay to temporarily 444 // remove the `Pin` wrapper. 445 let boxed = unsafe { Pin::into_inner_unchecked(self) }; 446 let ptr = Box::into_raw(boxed); 447 448 // SAFETY: Pointers into a `Box` point at a valid value. 449 let work_ptr = unsafe { T::raw_get_work(ptr) }; 450 // SAFETY: `raw_get_work` returns a pointer to a valid value. 451 let work_ptr = unsafe { Work::raw_get(work_ptr) }; 452 453 if !queue_work_on(work_ptr) { 454 // SAFETY: This method requires exclusive ownership of the box, so it cannot be in a 455 // workqueue. 456 unsafe { ::core::hint::unreachable_unchecked() } 457 } 458 } 459 } 460 461 /// Returns the system work queue (`system_wq`). 462 /// 463 /// It is the one used by `schedule[_delayed]_work[_on]()`. Multi-CPU multi-threaded. There are 464 /// users which expect relatively short queue flush time. 465 /// 466 /// Callers shouldn't queue work items which can run for too long. 467 pub fn system() -> &'static Queue { 468 // SAFETY: `system_wq` is a C global, always available. 469 unsafe { Queue::from_raw(bindings::system_wq) } 470 } 471 472 /// Returns the system high-priority work queue (`system_highpri_wq`). 473 /// 474 /// It is similar to the one returned by [`system`] but for work items which require higher 475 /// scheduling priority. 476 pub fn system_highpri() -> &'static Queue { 477 // SAFETY: `system_highpri_wq` is a C global, always available. 478 unsafe { Queue::from_raw(bindings::system_highpri_wq) } 479 } 480 481 /// Returns the system work queue for potentially long-running work items (`system_long_wq`). 482 /// 483 /// It is similar to the one returned by [`system`] but may host long running work items. Queue 484 /// flushing might take relatively long. 485 pub fn system_long() -> &'static Queue { 486 // SAFETY: `system_long_wq` is a C global, always available. 487 unsafe { Queue::from_raw(bindings::system_long_wq) } 488 } 489 490 /// Returns the system unbound work queue (`system_unbound_wq`). 491 /// 492 /// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items 493 /// are executed immediately as long as `max_active` limit is not reached and resources are 494 /// available. 495 pub fn system_unbound() -> &'static Queue { 496 // SAFETY: `system_unbound_wq` is a C global, always available. 497 unsafe { Queue::from_raw(bindings::system_unbound_wq) } 498 } 499 500 /// Returns the system freezable work queue (`system_freezable_wq`). 501 /// 502 /// It is equivalent to the one returned by [`system`] except that it's freezable. 503 /// 504 /// A freezable workqueue participates in the freeze phase of the system suspend operations. Work 505 /// items on the workqueue are drained and no new work item starts execution until thawed. 506 pub fn system_freezable() -> &'static Queue { 507 // SAFETY: `system_freezable_wq` is a C global, always available. 508 unsafe { Queue::from_raw(bindings::system_freezable_wq) } 509 } 510 511 /// Returns the system power-efficient work queue (`system_power_efficient_wq`). 512 /// 513 /// It is inclined towards saving power and is converted to "unbound" variants if the 514 /// `workqueue.power_efficient` kernel parameter is specified; otherwise, it is similar to the one 515 /// returned by [`system`]. 516 pub fn system_power_efficient() -> &'static Queue { 517 // SAFETY: `system_power_efficient_wq` is a C global, always available. 518 unsafe { Queue::from_raw(bindings::system_power_efficient_wq) } 519 } 520 521 /// Returns the system freezable power-efficient work queue (`system_freezable_power_efficient_wq`). 522 /// 523 /// It is similar to the one returned by [`system_power_efficient`] except that is freezable. 524 /// 525 /// A freezable workqueue participates in the freeze phase of the system suspend operations. Work 526 /// items on the workqueue are drained and no new work item starts execution until thawed. 527 pub fn system_freezable_power_efficient() -> &'static Queue { 528 // SAFETY: `system_freezable_power_efficient_wq` is a C global, always available. 529 unsafe { Queue::from_raw(bindings::system_freezable_power_efficient_wq) } 530 } 531