1 // SPDX-License-Identifier: GPL-2.0 2 3 //! Kernel types. 4 5 use crate::init::{self, PinInit}; 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 impl<T> Opaque<T> { 313 /// Creates a new opaque value. 314 pub const fn new(value: T) -> Self { 315 Self { 316 value: UnsafeCell::new(MaybeUninit::new(value)), 317 _pin: PhantomPinned, 318 } 319 } 320 321 /// Creates an uninitialised value. 322 pub const fn uninit() -> Self { 323 Self { 324 value: UnsafeCell::new(MaybeUninit::uninit()), 325 _pin: PhantomPinned, 326 } 327 } 328 329 /// Creates a pin-initializer from the given initializer closure. 330 /// 331 /// The returned initializer calls the given closure with the pointer to the inner `T` of this 332 /// `Opaque`. Since this memory is uninitialized, the closure is not allowed to read from it. 333 /// 334 /// This function is safe, because the `T` inside of an `Opaque` is allowed to be 335 /// uninitialized. Additionally, access to the inner `T` requires `unsafe`, so the caller needs 336 /// to verify at that point that the inner value is valid. 337 pub fn ffi_init(init_func: impl FnOnce(*mut T)) -> impl PinInit<Self> { 338 // SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully 339 // initialize the `T`. 340 unsafe { 341 init::pin_init_from_closure::<_, ::core::convert::Infallible>(move |slot| { 342 init_func(Self::raw_get(slot)); 343 Ok(()) 344 }) 345 } 346 } 347 348 /// Creates a fallible pin-initializer from the given initializer closure. 349 /// 350 /// The returned initializer calls the given closure with the pointer to the inner `T` of this 351 /// `Opaque`. Since this memory is uninitialized, the closure is not allowed to read from it. 352 /// 353 /// This function is safe, because the `T` inside of an `Opaque` is allowed to be 354 /// uninitialized. Additionally, access to the inner `T` requires `unsafe`, so the caller needs 355 /// to verify at that point that the inner value is valid. 356 pub fn try_ffi_init<E>( 357 init_func: impl FnOnce(*mut T) -> Result<(), E>, 358 ) -> impl PinInit<Self, E> { 359 // SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully 360 // initialize the `T`. 361 unsafe { init::pin_init_from_closure::<_, E>(move |slot| init_func(Self::raw_get(slot))) } 362 } 363 364 /// Returns a raw pointer to the opaque data. 365 pub const fn get(&self) -> *mut T { 366 UnsafeCell::get(&self.value).cast::<T>() 367 } 368 369 /// Gets the value behind `this`. 370 /// 371 /// This function is useful to get access to the value without creating intermediate 372 /// references. 373 pub const fn raw_get(this: *const Self) -> *mut T { 374 UnsafeCell::raw_get(this.cast::<UnsafeCell<MaybeUninit<T>>>()).cast::<T>() 375 } 376 } 377 378 /// Types that are _always_ reference counted. 379 /// 380 /// It allows such types to define their own custom ref increment and decrement functions. 381 /// Additionally, it allows users to convert from a shared reference `&T` to an owned reference 382 /// [`ARef<T>`]. 383 /// 384 /// This is usually implemented by wrappers to existing structures on the C side of the code. For 385 /// Rust code, the recommendation is to use [`Arc`](crate::sync::Arc) to create reference-counted 386 /// instances of a type. 387 /// 388 /// # Safety 389 /// 390 /// Implementers must ensure that increments to the reference count keep the object alive in memory 391 /// at least until matching decrements are performed. 392 /// 393 /// Implementers must also ensure that all instances are reference-counted. (Otherwise they 394 /// won't be able to honour the requirement that [`AlwaysRefCounted::inc_ref`] keep the object 395 /// alive.) 396 pub unsafe trait AlwaysRefCounted { 397 /// Increments the reference count on the object. 398 fn inc_ref(&self); 399 400 /// Decrements the reference count on the object. 401 /// 402 /// Frees the object when the count reaches zero. 403 /// 404 /// # Safety 405 /// 406 /// Callers must ensure that there was a previous matching increment to the reference count, 407 /// and that the object is no longer used after its reference count is decremented (as it may 408 /// result in the object being freed), unless the caller owns another increment on the refcount 409 /// (e.g., it calls [`AlwaysRefCounted::inc_ref`] twice, then calls 410 /// [`AlwaysRefCounted::dec_ref`] once). 411 unsafe fn dec_ref(obj: NonNull<Self>); 412 } 413 414 /// An owned reference to an always-reference-counted object. 415 /// 416 /// The object's reference count is automatically decremented when an instance of [`ARef`] is 417 /// dropped. It is also automatically incremented when a new instance is created via 418 /// [`ARef::clone`]. 419 /// 420 /// # Invariants 421 /// 422 /// The pointer stored in `ptr` is non-null and valid for the lifetime of the [`ARef`] instance. In 423 /// particular, the [`ARef`] instance owns an increment on the underlying object's reference count. 424 pub struct ARef<T: AlwaysRefCounted> { 425 ptr: NonNull<T>, 426 _p: PhantomData<T>, 427 } 428 429 // SAFETY: It is safe to send `ARef<T>` to another thread when the underlying `T` is `Sync` because 430 // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs 431 // `T` to be `Send` because any thread that has an `ARef<T>` may ultimately access `T` using a 432 // mutable reference, for example, when the reference count reaches zero and `T` is dropped. 433 unsafe impl<T: AlwaysRefCounted + Sync + Send> Send for ARef<T> {} 434 435 // SAFETY: It is safe to send `&ARef<T>` to another thread when the underlying `T` is `Sync` 436 // because it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, 437 // it needs `T` to be `Send` because any thread that has a `&ARef<T>` may clone it and get an 438 // `ARef<T>` on that thread, so the thread may ultimately access `T` using a mutable reference, for 439 // example, when the reference count reaches zero and `T` is dropped. 440 unsafe impl<T: AlwaysRefCounted + Sync + Send> Sync for ARef<T> {} 441 442 impl<T: AlwaysRefCounted> ARef<T> { 443 /// Creates a new instance of [`ARef`]. 444 /// 445 /// It takes over an increment of the reference count on the underlying object. 446 /// 447 /// # Safety 448 /// 449 /// Callers must ensure that the reference count was incremented at least once, and that they 450 /// are properly relinquishing one increment. That is, if there is only one increment, callers 451 /// must not use the underlying object anymore -- it is only safe to do so via the newly 452 /// created [`ARef`]. 453 pub unsafe fn from_raw(ptr: NonNull<T>) -> Self { 454 // INVARIANT: The safety requirements guarantee that the new instance now owns the 455 // increment on the refcount. 456 Self { 457 ptr, 458 _p: PhantomData, 459 } 460 } 461 462 /// Consumes the `ARef`, returning a raw pointer. 463 /// 464 /// This function does not change the refcount. After calling this function, the caller is 465 /// responsible for the refcount previously managed by the `ARef`. 466 /// 467 /// # Examples 468 /// 469 /// ``` 470 /// use core::ptr::NonNull; 471 /// use kernel::types::{ARef, AlwaysRefCounted}; 472 /// 473 /// struct Empty {} 474 /// 475 /// # // SAFETY: TODO. 476 /// unsafe impl AlwaysRefCounted for Empty { 477 /// fn inc_ref(&self) {} 478 /// unsafe fn dec_ref(_obj: NonNull<Self>) {} 479 /// } 480 /// 481 /// let mut data = Empty {}; 482 /// let ptr = NonNull::<Empty>::new(&mut data).unwrap(); 483 /// # // SAFETY: TODO. 484 /// let data_ref: ARef<Empty> = unsafe { ARef::from_raw(ptr) }; 485 /// let raw_ptr: NonNull<Empty> = ARef::into_raw(data_ref); 486 /// 487 /// assert_eq!(ptr, raw_ptr); 488 /// ``` 489 pub fn into_raw(me: Self) -> NonNull<T> { 490 ManuallyDrop::new(me).ptr 491 } 492 } 493 494 impl<T: AlwaysRefCounted> Clone for ARef<T> { 495 fn clone(&self) -> Self { 496 self.inc_ref(); 497 // SAFETY: We just incremented the refcount above. 498 unsafe { Self::from_raw(self.ptr) } 499 } 500 } 501 502 impl<T: AlwaysRefCounted> Deref for ARef<T> { 503 type Target = T; 504 505 fn deref(&self) -> &Self::Target { 506 // SAFETY: The type invariants guarantee that the object is valid. 507 unsafe { self.ptr.as_ref() } 508 } 509 } 510 511 impl<T: AlwaysRefCounted> From<&T> for ARef<T> { 512 fn from(b: &T) -> Self { 513 b.inc_ref(); 514 // SAFETY: We just incremented the refcount above. 515 unsafe { Self::from_raw(NonNull::from(b)) } 516 } 517 } 518 519 impl<T: AlwaysRefCounted> Drop for ARef<T> { 520 fn drop(&mut self) { 521 // SAFETY: The type invariants guarantee that the `ARef` owns the reference we're about to 522 // decrement. 523 unsafe { T::dec_ref(self.ptr) }; 524 } 525 } 526 527 /// A sum type that always holds either a value of type `L` or `R`. 528 /// 529 /// # Examples 530 /// 531 /// ``` 532 /// use kernel::types::Either; 533 /// 534 /// let left_value: Either<i32, &str> = Either::Left(7); 535 /// let right_value: Either<i32, &str> = Either::Right("right value"); 536 /// ``` 537 pub enum Either<L, R> { 538 /// Constructs an instance of [`Either`] containing a value of type `L`. 539 Left(L), 540 541 /// Constructs an instance of [`Either`] containing a value of type `R`. 542 Right(R), 543 } 544 545 /// Zero-sized type to mark types not [`Send`]. 546 /// 547 /// Add this type as a field to your struct if your type should not be sent to a different task. 548 /// Since [`Send`] is an auto trait, adding a single field that is `!Send` will ensure that the 549 /// whole type is `!Send`. 550 /// 551 /// If a type is `!Send` it is impossible to give control over an instance of the type to another 552 /// task. This is useful to include in types that store or reference task-local information. A file 553 /// descriptor is an example of such task-local information. 554 /// 555 /// This type also makes the type `!Sync`, which prevents immutable access to the value from 556 /// several threads in parallel. 557 pub type NotThreadSafe = PhantomData<*mut ()>; 558 559 /// Used to construct instances of type [`NotThreadSafe`] similar to how `PhantomData` is 560 /// constructed. 561 /// 562 /// [`NotThreadSafe`]: type@NotThreadSafe 563 #[allow(non_upper_case_globals)] 564 pub const NotThreadSafe: NotThreadSafe = PhantomData; 565