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