1 // SPDX-License-Identifier: GPL-2.0 2 3 //! Kernel types. 4 5 use crate::ffi::c_void; 6 use core::{ 7 cell::UnsafeCell, 8 marker::{PhantomData, PhantomPinned}, 9 mem::{ManuallyDrop, MaybeUninit}, 10 ops::{Deref, DerefMut}, 11 ptr::NonNull, 12 }; 13 use pin_init::{PinInit, Zeroable}; 14 15 /// Used to transfer ownership to and from foreign (non-Rust) languages. 16 /// 17 /// Ownership is transferred from Rust to a foreign language by calling [`Self::into_foreign`] and 18 /// later may be transferred back to Rust by calling [`Self::from_foreign`]. 19 /// 20 /// This trait is meant to be used in cases when Rust objects are stored in C objects and 21 /// eventually "freed" back to Rust. 22 /// 23 /// # Safety 24 /// 25 /// - Implementations must satisfy the guarantees of [`Self::into_foreign`]. 26 pub unsafe trait ForeignOwnable: Sized { 27 /// The alignment of pointers returned by `into_foreign`. 28 const FOREIGN_ALIGN: usize; 29 30 /// Type used to immutably borrow a value that is currently foreign-owned. 31 type Borrowed<'a>; 32 33 /// Type used to mutably borrow a value that is currently foreign-owned. 34 type BorrowedMut<'a>; 35 36 /// Converts a Rust-owned object to a foreign-owned one. 37 /// 38 /// The foreign representation is a pointer to void. Aside from the guarantees listed below, 39 /// there are no other guarantees for this pointer. For example, it might be invalid, dangling 40 /// or pointing to uninitialized memory. Using it in any way except for [`from_foreign`], 41 /// [`try_from_foreign`], [`borrow`], or [`borrow_mut`] can result in undefined behavior. 42 /// 43 /// # Guarantees 44 /// 45 /// - Minimum alignment of returned pointer is [`Self::FOREIGN_ALIGN`]. 46 /// 47 /// [`from_foreign`]: Self::from_foreign 48 /// [`try_from_foreign`]: Self::try_from_foreign 49 /// [`borrow`]: Self::borrow 50 /// [`borrow_mut`]: Self::borrow_mut 51 fn into_foreign(self) -> *mut c_void; 52 53 /// Converts a foreign-owned object back to a Rust-owned one. 54 /// 55 /// # Safety 56 /// 57 /// The provided pointer must have been returned by a previous call to [`into_foreign`], and it 58 /// must not be passed to `from_foreign` more than once. 59 /// 60 /// [`into_foreign`]: Self::into_foreign 61 unsafe fn from_foreign(ptr: *mut c_void) -> Self; 62 63 /// Tries to convert a foreign-owned object back to a Rust-owned one. 64 /// 65 /// A convenience wrapper over [`ForeignOwnable::from_foreign`] that returns [`None`] if `ptr` 66 /// is null. 67 /// 68 /// # Safety 69 /// 70 /// `ptr` must either be null or satisfy the safety requirements for [`from_foreign`]. 71 /// 72 /// [`from_foreign`]: Self::from_foreign 73 unsafe fn try_from_foreign(ptr: *mut c_void) -> Option<Self> { 74 if ptr.is_null() { 75 None 76 } else { 77 // SAFETY: Since `ptr` is not null here, then `ptr` satisfies the safety requirements 78 // of `from_foreign` given the safety requirements of this function. 79 unsafe { Some(Self::from_foreign(ptr)) } 80 } 81 } 82 83 /// Borrows a foreign-owned object immutably. 84 /// 85 /// This method provides a way to access a foreign-owned value from Rust immutably. It provides 86 /// you with exactly the same abilities as an `&Self` when the value is Rust-owned. 87 /// 88 /// # Safety 89 /// 90 /// The provided pointer must have been returned by a previous call to [`into_foreign`], and if 91 /// the pointer is ever passed to [`from_foreign`], then that call must happen after the end of 92 /// the lifetime `'a`. 93 /// 94 /// [`into_foreign`]: Self::into_foreign 95 /// [`from_foreign`]: Self::from_foreign 96 unsafe fn borrow<'a>(ptr: *mut c_void) -> Self::Borrowed<'a>; 97 98 /// Borrows a foreign-owned object mutably. 99 /// 100 /// This method provides a way to access a foreign-owned value from Rust mutably. It provides 101 /// you with exactly the same abilities as an `&mut Self` when the value is Rust-owned, except 102 /// that the address of the object must not be changed. 103 /// 104 /// Note that for types like [`Arc`], an `&mut Arc<T>` only gives you immutable access to the 105 /// inner value, so this method also only provides immutable access in that case. 106 /// 107 /// In the case of `Box<T>`, this method gives you the ability to modify the inner `T`, but it 108 /// does not let you change the box itself. That is, you cannot change which allocation the box 109 /// points at. 110 /// 111 /// # Safety 112 /// 113 /// The provided pointer must have been returned by a previous call to [`into_foreign`], and if 114 /// the pointer is ever passed to [`from_foreign`], then that call must happen after the end of 115 /// the lifetime `'a`. 116 /// 117 /// The lifetime `'a` must not overlap with the lifetime of any other call to [`borrow`] or 118 /// `borrow_mut` on the same object. 119 /// 120 /// [`into_foreign`]: Self::into_foreign 121 /// [`from_foreign`]: Self::from_foreign 122 /// [`borrow`]: Self::borrow 123 /// [`Arc`]: crate::sync::Arc 124 unsafe fn borrow_mut<'a>(ptr: *mut c_void) -> Self::BorrowedMut<'a>; 125 } 126 127 // SAFETY: The pointer returned by `into_foreign` comes from a well aligned 128 // pointer to `()`. 129 unsafe impl ForeignOwnable for () { 130 const FOREIGN_ALIGN: usize = core::mem::align_of::<()>(); 131 type Borrowed<'a> = (); 132 type BorrowedMut<'a> = (); 133 134 fn into_foreign(self) -> *mut c_void { 135 core::ptr::NonNull::dangling().as_ptr() 136 } 137 138 unsafe fn from_foreign(_: *mut c_void) -> Self {} 139 140 unsafe fn borrow<'a>(_: *mut c_void) -> Self::Borrowed<'a> {} 141 unsafe fn borrow_mut<'a>(_: *mut c_void) -> Self::BorrowedMut<'a> {} 142 } 143 144 /// Runs a cleanup function/closure when dropped. 145 /// 146 /// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running. 147 /// 148 /// # Examples 149 /// 150 /// In the example below, we have multiple exit paths and we want to log regardless of which one is 151 /// taken: 152 /// 153 /// ``` 154 /// # use kernel::types::ScopeGuard; 155 /// fn example1(arg: bool) { 156 /// let _log = ScopeGuard::new(|| pr_info!("example1 completed\n")); 157 /// 158 /// if arg { 159 /// return; 160 /// } 161 /// 162 /// pr_info!("Do something...\n"); 163 /// } 164 /// 165 /// # example1(false); 166 /// # example1(true); 167 /// ``` 168 /// 169 /// In the example below, we want to log the same message on all early exits but a different one on 170 /// the main exit path: 171 /// 172 /// ``` 173 /// # use kernel::types::ScopeGuard; 174 /// fn example2(arg: bool) { 175 /// let log = ScopeGuard::new(|| pr_info!("example2 returned early\n")); 176 /// 177 /// if arg { 178 /// return; 179 /// } 180 /// 181 /// // (Other early returns...) 182 /// 183 /// log.dismiss(); 184 /// pr_info!("example2 no early return\n"); 185 /// } 186 /// 187 /// # example2(false); 188 /// # example2(true); 189 /// ``` 190 /// 191 /// In the example below, we need a mutable object (the vector) to be accessible within the log 192 /// function, so we wrap it in the [`ScopeGuard`]: 193 /// 194 /// ``` 195 /// # use kernel::types::ScopeGuard; 196 /// fn example3(arg: bool) -> Result { 197 /// let mut vec = 198 /// ScopeGuard::new_with_data(KVec::new(), |v| pr_info!("vec had {} elements\n", v.len())); 199 /// 200 /// vec.push(10u8, GFP_KERNEL)?; 201 /// if arg { 202 /// return Ok(()); 203 /// } 204 /// vec.push(20u8, GFP_KERNEL)?; 205 /// Ok(()) 206 /// } 207 /// 208 /// # assert_eq!(example3(false), Ok(())); 209 /// # assert_eq!(example3(true), Ok(())); 210 /// ``` 211 /// 212 /// # Invariants 213 /// 214 /// The value stored in the struct is nearly always `Some(_)`, except between 215 /// [`ScopeGuard::dismiss`] and [`ScopeGuard::drop`]: in this case, it will be `None` as the value 216 /// will have been returned to the caller. Since [`ScopeGuard::dismiss`] consumes the guard, 217 /// callers won't be able to use it anymore. 218 pub struct ScopeGuard<T, F: FnOnce(T)>(Option<(T, F)>); 219 220 impl<T, F: FnOnce(T)> ScopeGuard<T, F> { 221 /// Creates a new guarded object wrapping the given data and with the given cleanup function. 222 pub fn new_with_data(data: T, cleanup_func: F) -> Self { 223 // INVARIANT: The struct is being initialised with `Some(_)`. 224 Self(Some((data, cleanup_func))) 225 } 226 227 /// Prevents the cleanup function from running and returns the guarded data. 228 pub fn dismiss(mut self) -> T { 229 // INVARIANT: This is the exception case in the invariant; it is not visible to callers 230 // because this function consumes `self`. 231 self.0.take().unwrap().0 232 } 233 } 234 235 impl ScopeGuard<(), fn(())> { 236 /// Creates a new guarded object with the given cleanup function. 237 pub fn new(cleanup: impl FnOnce()) -> ScopeGuard<(), impl FnOnce(())> { 238 ScopeGuard::new_with_data((), move |()| cleanup()) 239 } 240 } 241 242 impl<T, F: FnOnce(T)> Deref for ScopeGuard<T, F> { 243 type Target = T; 244 245 fn deref(&self) -> &T { 246 // The type invariants guarantee that `unwrap` will succeed. 247 &self.0.as_ref().unwrap().0 248 } 249 } 250 251 impl<T, F: FnOnce(T)> DerefMut for ScopeGuard<T, F> { 252 fn deref_mut(&mut self) -> &mut T { 253 // The type invariants guarantee that `unwrap` will succeed. 254 &mut self.0.as_mut().unwrap().0 255 } 256 } 257 258 impl<T, F: FnOnce(T)> Drop for ScopeGuard<T, F> { 259 fn drop(&mut self) { 260 // Run the cleanup function if one is still present. 261 if let Some((data, cleanup)) = self.0.take() { 262 cleanup(data) 263 } 264 } 265 } 266 267 /// Stores an opaque value. 268 /// 269 /// [`Opaque<T>`] is meant to be used with FFI objects that are never interpreted by Rust code. 270 /// 271 /// It is used to wrap structs from the C side, like for example `Opaque<bindings::mutex>`. 272 /// It gets rid of all the usual assumptions that Rust has for a value: 273 /// 274 /// * The value is allowed to be uninitialized (for example have invalid bit patterns: `3` for a 275 /// [`bool`]). 276 /// * The value is allowed to be mutated, when a `&Opaque<T>` exists on the Rust side. 277 /// * No uniqueness for mutable references: it is fine to have multiple `&mut Opaque<T>` point to 278 /// the same value. 279 /// * The value is not allowed to be shared with other threads (i.e. it is `!Sync`). 280 /// 281 /// This has to be used for all values that the C side has access to, because it can't be ensured 282 /// that the C side is adhering to the usual constraints that Rust needs. 283 /// 284 /// Using [`Opaque<T>`] allows to continue to use references on the Rust side even for values shared 285 /// with C. 286 /// 287 /// # Examples 288 /// 289 /// ``` 290 /// # #![expect(unreachable_pub, clippy::disallowed_names)] 291 /// use kernel::types::Opaque; 292 /// # // Emulate a C struct binding which is from C, maybe uninitialized or not, only the C side 293 /// # // knows. 294 /// # mod bindings { 295 /// # pub struct Foo { 296 /// # pub val: u8, 297 /// # } 298 /// # } 299 /// 300 /// // `foo.val` is assumed to be handled on the C side, so we use `Opaque` to wrap it. 301 /// pub struct Foo { 302 /// foo: Opaque<bindings::Foo>, 303 /// } 304 /// 305 /// impl Foo { 306 /// pub fn get_val(&self) -> u8 { 307 /// let ptr = Opaque::get(&self.foo); 308 /// 309 /// // SAFETY: `Self` is valid from C side. 310 /// unsafe { (*ptr).val } 311 /// } 312 /// } 313 /// 314 /// // Create an instance of `Foo` with the `Opaque` wrapper. 315 /// let foo = Foo { 316 /// foo: Opaque::new(bindings::Foo { val: 0xdb }), 317 /// }; 318 /// 319 /// assert_eq!(foo.get_val(), 0xdb); 320 /// ``` 321 #[repr(transparent)] 322 pub struct Opaque<T> { 323 value: UnsafeCell<MaybeUninit<T>>, 324 _pin: PhantomPinned, 325 } 326 327 // SAFETY: `Opaque<T>` allows the inner value to be any bit pattern, including all zeros. 328 unsafe impl<T> Zeroable for Opaque<T> {} 329 330 impl<T> Opaque<T> { 331 /// Creates a new opaque value. 332 pub const fn new(value: T) -> Self { 333 Self { 334 value: UnsafeCell::new(MaybeUninit::new(value)), 335 _pin: PhantomPinned, 336 } 337 } 338 339 /// Creates an uninitialised value. 340 pub const fn uninit() -> Self { 341 Self { 342 value: UnsafeCell::new(MaybeUninit::uninit()), 343 _pin: PhantomPinned, 344 } 345 } 346 347 /// Creates a new zeroed opaque value. 348 pub const fn zeroed() -> Self { 349 Self { 350 value: UnsafeCell::new(MaybeUninit::zeroed()), 351 _pin: PhantomPinned, 352 } 353 } 354 355 /// Create an opaque pin-initializer from the given pin-initializer. 356 pub fn pin_init(slot: impl PinInit<T>) -> impl PinInit<Self> { 357 Self::ffi_init(|ptr: *mut T| { 358 // SAFETY: 359 // - `ptr` is a valid pointer to uninitialized memory, 360 // - `slot` is not accessed on error; the call is infallible, 361 // - `slot` is pinned in memory. 362 let _ = unsafe { PinInit::<T>::__pinned_init(slot, ptr) }; 363 }) 364 } 365 366 /// Creates a pin-initializer from the given initializer closure. 367 /// 368 /// The returned initializer calls the given closure with the pointer to the inner `T` of this 369 /// `Opaque`. Since this memory is uninitialized, the closure is not allowed to read from it. 370 /// 371 /// This function is safe, because the `T` inside of an `Opaque` is allowed to be 372 /// uninitialized. Additionally, access to the inner `T` requires `unsafe`, so the caller needs 373 /// to verify at that point that the inner value is valid. 374 pub fn ffi_init(init_func: impl FnOnce(*mut T)) -> impl PinInit<Self> { 375 // SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully 376 // initialize the `T`. 377 unsafe { 378 pin_init::pin_init_from_closure::<_, ::core::convert::Infallible>(move |slot| { 379 init_func(Self::raw_get(slot)); 380 Ok(()) 381 }) 382 } 383 } 384 385 /// Creates a fallible pin-initializer from the given initializer closure. 386 /// 387 /// The returned initializer calls the given closure with the pointer to the inner `T` of this 388 /// `Opaque`. Since this memory is uninitialized, the closure is not allowed to read from it. 389 /// 390 /// This function is safe, because the `T` inside of an `Opaque` is allowed to be 391 /// uninitialized. Additionally, access to the inner `T` requires `unsafe`, so the caller needs 392 /// to verify at that point that the inner value is valid. 393 pub fn try_ffi_init<E>( 394 init_func: impl FnOnce(*mut T) -> Result<(), E>, 395 ) -> impl PinInit<Self, E> { 396 // SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully 397 // initialize the `T`. 398 unsafe { 399 pin_init::pin_init_from_closure::<_, E>(move |slot| init_func(Self::raw_get(slot))) 400 } 401 } 402 403 /// Returns a raw pointer to the opaque data. 404 pub const fn get(&self) -> *mut T { 405 UnsafeCell::get(&self.value).cast::<T>() 406 } 407 408 /// Gets the value behind `this`. 409 /// 410 /// This function is useful to get access to the value without creating intermediate 411 /// references. 412 pub const fn raw_get(this: *const Self) -> *mut T { 413 UnsafeCell::raw_get(this.cast::<UnsafeCell<MaybeUninit<T>>>()).cast::<T>() 414 } 415 } 416 417 /// Types that are _always_ reference counted. 418 /// 419 /// It allows such types to define their own custom ref increment and decrement functions. 420 /// Additionally, it allows users to convert from a shared reference `&T` to an owned reference 421 /// [`ARef<T>`]. 422 /// 423 /// This is usually implemented by wrappers to existing structures on the C side of the code. For 424 /// Rust code, the recommendation is to use [`Arc`](crate::sync::Arc) to create reference-counted 425 /// instances of a type. 426 /// 427 /// # Safety 428 /// 429 /// Implementers must ensure that increments to the reference count keep the object alive in memory 430 /// at least until matching decrements are performed. 431 /// 432 /// Implementers must also ensure that all instances are reference-counted. (Otherwise they 433 /// won't be able to honour the requirement that [`AlwaysRefCounted::inc_ref`] keep the object 434 /// alive.) 435 pub unsafe trait AlwaysRefCounted { 436 /// Increments the reference count on the object. 437 fn inc_ref(&self); 438 439 /// Decrements the reference count on the object. 440 /// 441 /// Frees the object when the count reaches zero. 442 /// 443 /// # Safety 444 /// 445 /// Callers must ensure that there was a previous matching increment to the reference count, 446 /// and that the object is no longer used after its reference count is decremented (as it may 447 /// result in the object being freed), unless the caller owns another increment on the refcount 448 /// (e.g., it calls [`AlwaysRefCounted::inc_ref`] twice, then calls 449 /// [`AlwaysRefCounted::dec_ref`] once). 450 unsafe fn dec_ref(obj: NonNull<Self>); 451 } 452 453 /// An owned reference to an always-reference-counted object. 454 /// 455 /// The object's reference count is automatically decremented when an instance of [`ARef`] is 456 /// dropped. It is also automatically incremented when a new instance is created via 457 /// [`ARef::clone`]. 458 /// 459 /// # Invariants 460 /// 461 /// The pointer stored in `ptr` is non-null and valid for the lifetime of the [`ARef`] instance. In 462 /// particular, the [`ARef`] instance owns an increment on the underlying object's reference count. 463 pub struct ARef<T: AlwaysRefCounted> { 464 ptr: NonNull<T>, 465 _p: PhantomData<T>, 466 } 467 468 // SAFETY: It is safe to send `ARef<T>` to another thread when the underlying `T` is `Sync` because 469 // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs 470 // `T` to be `Send` because any thread that has an `ARef<T>` may ultimately access `T` using a 471 // mutable reference, for example, when the reference count reaches zero and `T` is dropped. 472 unsafe impl<T: AlwaysRefCounted + Sync + Send> Send for ARef<T> {} 473 474 // SAFETY: It is safe to send `&ARef<T>` to another thread when the underlying `T` is `Sync` 475 // because it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, 476 // it needs `T` to be `Send` because any thread that has a `&ARef<T>` may clone it and get an 477 // `ARef<T>` on that thread, so the thread may ultimately access `T` using a mutable reference, for 478 // example, when the reference count reaches zero and `T` is dropped. 479 unsafe impl<T: AlwaysRefCounted + Sync + Send> Sync for ARef<T> {} 480 481 impl<T: AlwaysRefCounted> ARef<T> { 482 /// Creates a new instance of [`ARef`]. 483 /// 484 /// It takes over an increment of the reference count on the underlying object. 485 /// 486 /// # Safety 487 /// 488 /// Callers must ensure that the reference count was incremented at least once, and that they 489 /// are properly relinquishing one increment. That is, if there is only one increment, callers 490 /// must not use the underlying object anymore -- it is only safe to do so via the newly 491 /// created [`ARef`]. 492 pub unsafe fn from_raw(ptr: NonNull<T>) -> Self { 493 // INVARIANT: The safety requirements guarantee that the new instance now owns the 494 // increment on the refcount. 495 Self { 496 ptr, 497 _p: PhantomData, 498 } 499 } 500 501 /// Consumes the `ARef`, returning a raw pointer. 502 /// 503 /// This function does not change the refcount. After calling this function, the caller is 504 /// responsible for the refcount previously managed by the `ARef`. 505 /// 506 /// # Examples 507 /// 508 /// ``` 509 /// use core::ptr::NonNull; 510 /// use kernel::types::{ARef, AlwaysRefCounted}; 511 /// 512 /// struct Empty {} 513 /// 514 /// # // SAFETY: TODO. 515 /// unsafe impl AlwaysRefCounted for Empty { 516 /// fn inc_ref(&self) {} 517 /// unsafe fn dec_ref(_obj: NonNull<Self>) {} 518 /// } 519 /// 520 /// let mut data = Empty {}; 521 /// let ptr = NonNull::<Empty>::new(&mut data).unwrap(); 522 /// # // SAFETY: TODO. 523 /// let data_ref: ARef<Empty> = unsafe { ARef::from_raw(ptr) }; 524 /// let raw_ptr: NonNull<Empty> = ARef::into_raw(data_ref); 525 /// 526 /// assert_eq!(ptr, raw_ptr); 527 /// ``` 528 pub fn into_raw(me: Self) -> NonNull<T> { 529 ManuallyDrop::new(me).ptr 530 } 531 } 532 533 impl<T: AlwaysRefCounted> Clone for ARef<T> { 534 fn clone(&self) -> Self { 535 self.inc_ref(); 536 // SAFETY: We just incremented the refcount above. 537 unsafe { Self::from_raw(self.ptr) } 538 } 539 } 540 541 impl<T: AlwaysRefCounted> Deref for ARef<T> { 542 type Target = T; 543 544 fn deref(&self) -> &Self::Target { 545 // SAFETY: The type invariants guarantee that the object is valid. 546 unsafe { self.ptr.as_ref() } 547 } 548 } 549 550 impl<T: AlwaysRefCounted> From<&T> for ARef<T> { 551 fn from(b: &T) -> Self { 552 b.inc_ref(); 553 // SAFETY: We just incremented the refcount above. 554 unsafe { Self::from_raw(NonNull::from(b)) } 555 } 556 } 557 558 impl<T: AlwaysRefCounted> Drop for ARef<T> { 559 fn drop(&mut self) { 560 // SAFETY: The type invariants guarantee that the `ARef` owns the reference we're about to 561 // decrement. 562 unsafe { T::dec_ref(self.ptr) }; 563 } 564 } 565 566 /// A sum type that always holds either a value of type `L` or `R`. 567 /// 568 /// # Examples 569 /// 570 /// ``` 571 /// use kernel::types::Either; 572 /// 573 /// let left_value: Either<i32, &str> = Either::Left(7); 574 /// let right_value: Either<i32, &str> = Either::Right("right value"); 575 /// ``` 576 pub enum Either<L, R> { 577 /// Constructs an instance of [`Either`] containing a value of type `L`. 578 Left(L), 579 580 /// Constructs an instance of [`Either`] containing a value of type `R`. 581 Right(R), 582 } 583 584 /// Zero-sized type to mark types not [`Send`]. 585 /// 586 /// Add this type as a field to your struct if your type should not be sent to a different task. 587 /// Since [`Send`] is an auto trait, adding a single field that is `!Send` will ensure that the 588 /// whole type is `!Send`. 589 /// 590 /// If a type is `!Send` it is impossible to give control over an instance of the type to another 591 /// task. This is useful to include in types that store or reference task-local information. A file 592 /// descriptor is an example of such task-local information. 593 /// 594 /// This type also makes the type `!Sync`, which prevents immutable access to the value from 595 /// several threads in parallel. 596 pub type NotThreadSafe = PhantomData<*mut ()>; 597 598 /// Used to construct instances of type [`NotThreadSafe`] similar to how `PhantomData` is 599 /// constructed. 600 /// 601 /// [`NotThreadSafe`]: type@NotThreadSafe 602 #[allow(non_upper_case_globals)] 603 pub const NotThreadSafe: NotThreadSafe = PhantomData; 604