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