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::MaybeUninit, 10 ops::{Deref, DerefMut}, 11 }; 12 use pin_init::{PinInit, Wrapper, Zeroable}; 13 14 #[doc(hidden)] 15 pub mod for_lt; 16 pub use for_lt::ForLt; 17 18 /// Used to transfer ownership to and from foreign (non-Rust) languages. 19 /// 20 /// Ownership is transferred from Rust to a foreign language by calling [`Self::into_foreign`] and 21 /// later may be transferred back to Rust by calling [`Self::from_foreign`]. 22 /// 23 /// This trait is meant to be used in cases when Rust objects are stored in C objects and 24 /// eventually "freed" back to Rust. 25 /// 26 /// # Safety 27 /// 28 /// - Implementations must satisfy the guarantees of [`Self::into_foreign`]. 29 pub unsafe trait ForeignOwnable: Sized { 30 /// The alignment of pointers returned by `into_foreign`. 31 const FOREIGN_ALIGN: usize; 32 33 /// Type used to immutably borrow a value that is currently foreign-owned. 34 type Borrowed<'a> 35 where 36 Self: 'a; 37 38 /// Type used to mutably borrow a value that is currently foreign-owned. 39 type BorrowedMut<'a> 40 where 41 Self: 'a; 42 43 /// Converts a Rust-owned object to a foreign-owned one. 44 /// 45 /// The foreign representation is a pointer to void. Aside from the guarantees listed below, 46 /// there are no other guarantees for this pointer. For example, it might be invalid, dangling 47 /// or pointing to uninitialized memory. Using it in any way except for [`from_foreign`], 48 /// [`try_from_foreign`], [`borrow`], or [`borrow_mut`] can result in undefined behavior. 49 /// 50 /// # Guarantees 51 /// 52 /// - Minimum alignment of returned pointer is [`Self::FOREIGN_ALIGN`]. 53 /// - The returned pointer is not null. 54 /// 55 /// [`from_foreign`]: Self::from_foreign 56 /// [`try_from_foreign`]: Self::try_from_foreign 57 /// [`borrow`]: Self::borrow 58 /// [`borrow_mut`]: Self::borrow_mut 59 fn into_foreign(self) -> *mut c_void; 60 61 /// Converts a foreign-owned object back to a Rust-owned one. 62 /// 63 /// # Safety 64 /// 65 /// The provided pointer must have been returned by a previous call to [`into_foreign`], and it 66 /// must not be passed to `from_foreign` more than once. 67 /// 68 /// [`into_foreign`]: Self::into_foreign 69 unsafe fn from_foreign(ptr: *mut c_void) -> Self; 70 71 /// Tries to convert a foreign-owned object back to a Rust-owned one. 72 /// 73 /// A convenience wrapper over [`ForeignOwnable::from_foreign`] that returns [`None`] if `ptr` 74 /// is null. 75 /// 76 /// # Safety 77 /// 78 /// `ptr` must either be null or satisfy the safety requirements for [`from_foreign`]. 79 /// 80 /// [`from_foreign`]: Self::from_foreign 81 unsafe fn try_from_foreign(ptr: *mut c_void) -> Option<Self> { 82 if ptr.is_null() { 83 None 84 } else { 85 // SAFETY: Since `ptr` is not null here, then `ptr` satisfies the safety requirements 86 // of `from_foreign` given the safety requirements of this function. 87 unsafe { Some(Self::from_foreign(ptr)) } 88 } 89 } 90 91 /// Borrows a foreign-owned object immutably. 92 /// 93 /// This method provides a way to access a foreign-owned value from Rust immutably. It provides 94 /// you with exactly the same abilities as an `&Self` when the value is Rust-owned. 95 /// 96 /// # Safety 97 /// 98 /// The provided pointer must have been returned by a previous call to [`into_foreign`], and if 99 /// the pointer is ever passed to [`from_foreign`], then that call must happen after the end of 100 /// the lifetime `'a`. 101 /// 102 /// [`into_foreign`]: Self::into_foreign 103 /// [`from_foreign`]: Self::from_foreign 104 unsafe fn borrow<'a>(ptr: *mut c_void) -> Self::Borrowed<'a>; 105 106 /// Borrows a foreign-owned object mutably. 107 /// 108 /// This method provides a way to access a foreign-owned value from Rust mutably. It provides 109 /// you with exactly the same abilities as an `&mut Self` when the value is Rust-owned, except 110 /// that the address of the object must not be changed. 111 /// 112 /// Note that for types like [`Arc`], an `&mut Arc<T>` only gives you immutable access to the 113 /// inner value, so this method also only provides immutable access in that case. 114 /// 115 /// In the case of `Box<T>`, this method gives you the ability to modify the inner `T`, but it 116 /// does not let you change the box itself. That is, you cannot change which allocation the box 117 /// points at. 118 /// 119 /// # Safety 120 /// 121 /// The provided pointer must have been returned by a previous call to [`into_foreign`], and if 122 /// the pointer is ever passed to [`from_foreign`], then that call must happen after the end of 123 /// the lifetime `'a`. 124 /// 125 /// The lifetime `'a` must not overlap with the lifetime of any other call to [`borrow`] or 126 /// `borrow_mut` on the same object. 127 /// 128 /// [`into_foreign`]: Self::into_foreign 129 /// [`from_foreign`]: Self::from_foreign 130 /// [`borrow`]: Self::borrow 131 /// [`Arc`]: crate::sync::Arc 132 unsafe fn borrow_mut<'a>(ptr: *mut c_void) -> Self::BorrowedMut<'a>; 133 } 134 135 // SAFETY: The pointer returned by `into_foreign` comes from a well aligned 136 // pointer to `()`. 137 unsafe impl ForeignOwnable for () { 138 const FOREIGN_ALIGN: usize = core::mem::align_of::<()>(); 139 type Borrowed<'a> = (); 140 type BorrowedMut<'a> = (); 141 142 fn into_foreign(self) -> *mut c_void { 143 core::ptr::NonNull::dangling().as_ptr() 144 } 145 146 unsafe fn from_foreign(_: *mut c_void) -> Self {} 147 148 unsafe fn borrow<'a>(_: *mut c_void) -> Self::Borrowed<'a> {} 149 unsafe fn borrow_mut<'a>(_: *mut c_void) -> Self::BorrowedMut<'a> {} 150 } 151 152 /// Runs a cleanup function/closure when dropped. 153 /// 154 /// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running. 155 /// 156 /// # Examples 157 /// 158 /// In the example below, we have multiple exit paths and we want to log regardless of which one is 159 /// taken: 160 /// 161 /// ``` 162 /// # use kernel::types::ScopeGuard; 163 /// fn example1(arg: bool) { 164 /// let _log = ScopeGuard::new(|| pr_info!("example1 completed\n")); 165 /// 166 /// if arg { 167 /// return; 168 /// } 169 /// 170 /// pr_info!("Do something...\n"); 171 /// } 172 /// 173 /// # example1(false); 174 /// # example1(true); 175 /// ``` 176 /// 177 /// In the example below, we want to log the same message on all early exits but a different one on 178 /// the main exit path: 179 /// 180 /// ``` 181 /// # use kernel::types::ScopeGuard; 182 /// fn example2(arg: bool) { 183 /// let log = ScopeGuard::new(|| pr_info!("example2 returned early\n")); 184 /// 185 /// if arg { 186 /// return; 187 /// } 188 /// 189 /// // (Other early returns...) 190 /// 191 /// log.dismiss(); 192 /// pr_info!("example2 no early return\n"); 193 /// } 194 /// 195 /// # example2(false); 196 /// # example2(true); 197 /// ``` 198 /// 199 /// In the example below, we need a mutable object (the vector) to be accessible within the log 200 /// function, so we wrap it in the [`ScopeGuard`]: 201 /// 202 /// ``` 203 /// # use kernel::types::ScopeGuard; 204 /// fn example3(arg: bool) -> Result { 205 /// let mut vec = 206 /// ScopeGuard::new_with_data(KVec::new(), |v| pr_info!("vec had {} elements\n", v.len())); 207 /// 208 /// vec.push(10u8, GFP_KERNEL)?; 209 /// if arg { 210 /// return Ok(()); 211 /// } 212 /// vec.push(20u8, GFP_KERNEL)?; 213 /// Ok(()) 214 /// } 215 /// 216 /// # assert_eq!(example3(false), Ok(())); 217 /// # assert_eq!(example3(true), Ok(())); 218 /// ``` 219 /// 220 /// # Invariants 221 /// 222 /// The value stored in the struct is nearly always `Some(_)`, except between 223 /// [`ScopeGuard::dismiss`] and [`ScopeGuard::drop`]: in this case, it will be `None` as the value 224 /// will have been returned to the caller. Since [`ScopeGuard::dismiss`] consumes the guard, 225 /// callers won't be able to use it anymore. 226 pub struct ScopeGuard<T, F: FnOnce(T)>(Option<(T, F)>); 227 228 impl<T, F: FnOnce(T)> ScopeGuard<T, F> { 229 /// Creates a new guarded object wrapping the given data and with the given cleanup function. 230 pub fn new_with_data(data: T, cleanup_func: F) -> Self { 231 // INVARIANT: The struct is being initialised with `Some(_)`. 232 Self(Some((data, cleanup_func))) 233 } 234 235 /// Prevents the cleanup function from running and returns the guarded data. 236 pub fn dismiss(mut self) -> T { 237 // INVARIANT: This is the exception case in the invariant; it is not visible to callers 238 // because this function consumes `self`. 239 self.0.take().unwrap().0 240 } 241 } 242 243 impl ScopeGuard<(), fn(())> { 244 /// Creates a new guarded object with the given cleanup function. 245 pub fn new(cleanup: impl FnOnce()) -> ScopeGuard<(), impl FnOnce(())> { 246 ScopeGuard::new_with_data((), move |()| cleanup()) 247 } 248 } 249 250 impl<T, F: FnOnce(T)> Deref for ScopeGuard<T, F> { 251 type Target = T; 252 253 fn deref(&self) -> &T { 254 // The type invariants guarantee that `unwrap` will succeed. 255 &self.0.as_ref().unwrap().0 256 } 257 } 258 259 impl<T, F: FnOnce(T)> DerefMut for ScopeGuard<T, F> { 260 fn deref_mut(&mut self) -> &mut T { 261 // The type invariants guarantee that `unwrap` will succeed. 262 &mut self.0.as_mut().unwrap().0 263 } 264 } 265 266 impl<T, F: FnOnce(T)> Drop for ScopeGuard<T, F> { 267 fn drop(&mut self) { 268 // Run the cleanup function if one is still present. 269 if let Some((data, cleanup)) = self.0.take() { 270 cleanup(data) 271 } 272 } 273 } 274 275 /// Stores an opaque value. 276 /// 277 /// [`Opaque<T>`] is meant to be used with FFI objects that are never interpreted by Rust code. 278 /// 279 /// It is used to wrap structs from the C side, like for example `Opaque<bindings::mutex>`. 280 /// It gets rid of all the usual assumptions that Rust has for a value: 281 /// 282 /// * The value is allowed to be uninitialized (for example have invalid bit patterns: `3` for a 283 /// [`bool`]). 284 /// * The value is allowed to be mutated, when a `&Opaque<T>` exists on the Rust side. 285 /// * No uniqueness for mutable references: it is fine to have multiple `&mut Opaque<T>` point to 286 /// the same value. 287 /// * The value is not allowed to be shared with other threads (i.e. it is `!Sync`). 288 /// 289 /// This has to be used for all values that the C side has access to, because it can't be ensured 290 /// that the C side is adhering to the usual constraints that Rust needs. 291 /// 292 /// Using [`Opaque<T>`] allows to continue to use references on the Rust side even for values shared 293 /// with C. 294 /// 295 /// # Examples 296 /// 297 /// ``` 298 /// use kernel::types::Opaque; 299 /// # // Emulate a C struct binding which is from C, maybe uninitialized or not, only the C side 300 /// # // knows. 301 /// # mod bindings { 302 /// # pub struct Foo { 303 /// # pub val: u8, 304 /// # } 305 /// # } 306 /// 307 /// // `foo.val` is assumed to be handled on the C side, so we use `Opaque` to wrap it. 308 /// pub struct Foo { 309 /// foo: Opaque<bindings::Foo>, 310 /// } 311 /// 312 /// impl Foo { 313 /// pub fn get_val(&self) -> u8 { 314 /// let ptr = Opaque::get(&self.foo); 315 /// 316 /// // SAFETY: `Self` is valid from C side. 317 /// unsafe { (*ptr).val } 318 /// } 319 /// } 320 /// 321 /// // Create an instance of `Foo` with the `Opaque` wrapper. 322 /// let foo = Foo { 323 /// foo: Opaque::new(bindings::Foo { val: 0xdb }), 324 /// }; 325 /// 326 /// assert_eq!(foo.get_val(), 0xdb); 327 /// ``` 328 #[repr(transparent)] 329 pub struct Opaque<T> { 330 value: UnsafeCell<MaybeUninit<T>>, 331 _pin: PhantomPinned, 332 } 333 334 // SAFETY: `Opaque<T>` allows the inner value to be any bit pattern, including all zeros. 335 unsafe impl<T> Zeroable for Opaque<T> {} 336 337 impl<T> Opaque<T> { 338 /// Creates a new opaque value. 339 pub const fn new(value: T) -> Self { 340 Self { 341 value: UnsafeCell::new(MaybeUninit::new(value)), 342 _pin: PhantomPinned, 343 } 344 } 345 346 /// Creates an uninitialised value. 347 pub const fn uninit() -> Self { 348 Self { 349 value: UnsafeCell::new(MaybeUninit::uninit()), 350 _pin: PhantomPinned, 351 } 352 } 353 354 /// Creates a new zeroed opaque value. 355 pub const fn zeroed() -> Self { 356 Self { 357 value: UnsafeCell::new(MaybeUninit::zeroed()), 358 _pin: PhantomPinned, 359 } 360 } 361 362 /// Creates a 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 ffi_init(init_func: impl FnOnce(*mut T)) -> impl PinInit<Self> { 371 // SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully 372 // initialize the `T`. 373 unsafe { 374 pin_init::pin_init_from_closure::<_, ::core::convert::Infallible>(move |slot| { 375 init_func(Self::cast_into(slot)); 376 Ok(()) 377 }) 378 } 379 } 380 381 /// Creates a fallible pin-initializer from the given initializer closure. 382 /// 383 /// The returned initializer calls the given closure with the pointer to the inner `T` of this 384 /// `Opaque`. Since this memory is uninitialized, the closure is not allowed to read from it. 385 /// 386 /// This function is safe, because the `T` inside of an `Opaque` is allowed to be 387 /// uninitialized. Additionally, access to the inner `T` requires `unsafe`, so the caller needs 388 /// to verify at that point that the inner value is valid. 389 pub fn try_ffi_init<E>( 390 init_func: impl FnOnce(*mut T) -> Result<(), E>, 391 ) -> impl PinInit<Self, E> { 392 // SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully 393 // initialize the `T`. 394 unsafe { 395 pin_init::pin_init_from_closure::<_, E>(move |slot| init_func(Self::cast_into(slot))) 396 } 397 } 398 399 /// Returns a raw pointer to the opaque data. 400 pub const fn get(&self) -> *mut T { 401 UnsafeCell::get(&self.value).cast::<T>() 402 } 403 404 /// Gets the value behind `this`. 405 /// 406 /// This function is useful to get access to the value without creating intermediate 407 /// references. 408 pub const fn cast_into(this: *const Self) -> *mut T { 409 UnsafeCell::raw_get(this.cast::<UnsafeCell<MaybeUninit<T>>>()).cast::<T>() 410 } 411 412 /// The opposite operation of [`Opaque::cast_into`]. 413 pub const fn cast_from(this: *const T) -> *const Self { 414 this.cast() 415 } 416 } 417 418 impl<T> Wrapper<T> for Opaque<T> { 419 /// Create an opaque pin-initializer from the given pin-initializer. 420 fn pin_init<E>(slot: impl PinInit<T, E>) -> impl PinInit<Self, E> { 421 Self::try_ffi_init(|ptr: *mut T| { 422 // SAFETY: 423 // - `ptr` is a valid pointer to uninitialized memory, 424 // - `slot` is not accessed on error, 425 // - `slot` is pinned in memory. 426 unsafe { PinInit::<T, E>::__pinned_init(slot, ptr) } 427 }) 428 } 429 } 430 431 /// Zero-sized type to mark types not [`Send`]. 432 /// 433 /// Add this type as a field to your struct if your type should not be sent to a different task. 434 /// Since [`Send`] is an auto trait, adding a single field that is `!Send` will ensure that the 435 /// whole type is `!Send`. 436 /// 437 /// If a type is `!Send` it is impossible to give control over an instance of the type to another 438 /// task. This is useful to include in types that store or reference task-local information. A file 439 /// descriptor is an example of such task-local information. 440 /// 441 /// This type also makes the type `!Sync`, which prevents immutable access to the value from 442 /// several threads in parallel. 443 pub type NotThreadSafe = PhantomData<*mut ()>; 444 445 /// Used to construct instances of type [`NotThreadSafe`] similar to how `PhantomData` is 446 /// constructed. 447 /// 448 /// [`NotThreadSafe`]: type@NotThreadSafe 449 #[allow(non_upper_case_globals)] 450 pub const NotThreadSafe: NotThreadSafe = PhantomData; 451