1ba20915bSWedson Almeida Filho // SPDX-License-Identifier: GPL-2.0 2ba20915bSWedson Almeida Filho 3ba20915bSWedson Almeida Filho //! Kernel types. 4ba20915bSWedson Almeida Filho 54d4692a2SWedson Almeida Filho use core::{ 64d4692a2SWedson Almeida Filho cell::UnsafeCell, 70b4e3b6fSBenno Lossin marker::{PhantomData, PhantomPinned}, 896fff2dcSKartik Prajapati mem::{ManuallyDrop, MaybeUninit}, 94d4692a2SWedson Almeida Filho ops::{Deref, DerefMut}, 10f1fbd6a8SWedson Almeida Filho ptr::NonNull, 114d4692a2SWedson Almeida Filho }; 12*dbd5058bSBenno Lossin use pin_init::{PinInit, Zeroable}; 134d4692a2SWedson Almeida Filho 140fc4424dSWedson Almeida Filho /// Used to transfer ownership to and from foreign (non-Rust) languages. 150fc4424dSWedson Almeida Filho /// 160fc4424dSWedson Almeida Filho /// Ownership is transferred from Rust to a foreign language by calling [`Self::into_foreign`] and 170fc4424dSWedson Almeida Filho /// later may be transferred back to Rust by calling [`Self::from_foreign`]. 180fc4424dSWedson Almeida Filho /// 190fc4424dSWedson Almeida Filho /// This trait is meant to be used in cases when Rust objects are stored in C objects and 200fc4424dSWedson Almeida Filho /// eventually "freed" back to Rust. 210fc4424dSWedson Almeida Filho pub trait ForeignOwnable: Sized { 22c27e705cSAlice Ryhl /// Type used to immutably borrow a value that is currently foreign-owned. 230fc4424dSWedson Almeida Filho type Borrowed<'a>; 240fc4424dSWedson Almeida Filho 25c27e705cSAlice Ryhl /// Type used to mutably borrow a value that is currently foreign-owned. 26c27e705cSAlice Ryhl type BorrowedMut<'a>; 27c27e705cSAlice Ryhl 280fc4424dSWedson Almeida Filho /// Converts a Rust-owned object to a foreign-owned one. 290fc4424dSWedson Almeida Filho /// 307adcdd57SBenno Lossin /// The foreign representation is a pointer to void. There are no guarantees for this pointer. 317adcdd57SBenno Lossin /// For example, it might be invalid, dangling or pointing to uninitialized memory. Using it in 32c27e705cSAlice Ryhl /// any way except for [`from_foreign`], [`try_from_foreign`], [`borrow`], or [`borrow_mut`] can 33c27e705cSAlice Ryhl /// result in undefined behavior. 34c27e705cSAlice Ryhl /// 35c27e705cSAlice Ryhl /// [`from_foreign`]: Self::from_foreign 36c27e705cSAlice Ryhl /// [`try_from_foreign`]: Self::try_from_foreign 37c27e705cSAlice Ryhl /// [`borrow`]: Self::borrow 38c27e705cSAlice Ryhl /// [`borrow_mut`]: Self::borrow_mut into_foreign(self) -> *mut crate::ffi::c_void3914686571STamir Duberstein fn into_foreign(self) -> *mut crate::ffi::c_void; 400fc4424dSWedson Almeida Filho 410fc4424dSWedson Almeida Filho /// Converts a foreign-owned object back to a Rust-owned one. 420fc4424dSWedson Almeida Filho /// 430fc4424dSWedson Almeida Filho /// # Safety 440fc4424dSWedson Almeida Filho /// 45c27e705cSAlice Ryhl /// The provided pointer must have been returned by a previous call to [`into_foreign`], and it 46c27e705cSAlice Ryhl /// must not be passed to `from_foreign` more than once. 47c27e705cSAlice Ryhl /// 48c27e705cSAlice Ryhl /// [`into_foreign`]: Self::into_foreign from_foreign(ptr: *mut crate::ffi::c_void) -> Self4914686571STamir Duberstein unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) -> Self; 505bc81841SObei Sideg 515bc81841SObei Sideg /// Tries to convert a foreign-owned object back to a Rust-owned one. 525bc81841SObei Sideg /// 535bc81841SObei Sideg /// A convenience wrapper over [`ForeignOwnable::from_foreign`] that returns [`None`] if `ptr` 545bc81841SObei Sideg /// is null. 555bc81841SObei Sideg /// 565bc81841SObei Sideg /// # Safety 575bc81841SObei Sideg /// 58c27e705cSAlice Ryhl /// `ptr` must either be null or satisfy the safety requirements for [`from_foreign`]. 59c27e705cSAlice Ryhl /// 60c27e705cSAlice Ryhl /// [`from_foreign`]: Self::from_foreign try_from_foreign(ptr: *mut crate::ffi::c_void) -> Option<Self>6114686571STamir Duberstein unsafe fn try_from_foreign(ptr: *mut crate::ffi::c_void) -> Option<Self> { 625bc81841SObei Sideg if ptr.is_null() { 635bc81841SObei Sideg None 645bc81841SObei Sideg } else { 655bc81841SObei Sideg // SAFETY: Since `ptr` is not null here, then `ptr` satisfies the safety requirements 665bc81841SObei Sideg // of `from_foreign` given the safety requirements of this function. 675bc81841SObei Sideg unsafe { Some(Self::from_foreign(ptr)) } 685bc81841SObei Sideg } 695bc81841SObei Sideg } 70c6b97538STamir Duberstein 71c27e705cSAlice Ryhl /// Borrows a foreign-owned object immutably. 72c27e705cSAlice Ryhl /// 73c27e705cSAlice Ryhl /// This method provides a way to access a foreign-owned value from Rust immutably. It provides 74c27e705cSAlice Ryhl /// you with exactly the same abilities as an `&Self` when the value is Rust-owned. 75c6b97538STamir Duberstein /// 76c6b97538STamir Duberstein /// # Safety 77c6b97538STamir Duberstein /// 78c27e705cSAlice Ryhl /// The provided pointer must have been returned by a previous call to [`into_foreign`], and if 79c27e705cSAlice Ryhl /// the pointer is ever passed to [`from_foreign`], then that call must happen after the end of 80cd1ed11aSBorys Tyran /// the lifetime `'a`. 81c27e705cSAlice Ryhl /// 82c27e705cSAlice Ryhl /// [`into_foreign`]: Self::into_foreign 83c27e705cSAlice Ryhl /// [`from_foreign`]: Self::from_foreign borrow<'a>(ptr: *mut crate::ffi::c_void) -> Self::Borrowed<'a>84c6b97538STamir Duberstein unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> Self::Borrowed<'a>; 85c27e705cSAlice Ryhl 86c27e705cSAlice Ryhl /// Borrows a foreign-owned object mutably. 87c27e705cSAlice Ryhl /// 88c27e705cSAlice Ryhl /// This method provides a way to access a foreign-owned value from Rust mutably. It provides 89c27e705cSAlice Ryhl /// you with exactly the same abilities as an `&mut Self` when the value is Rust-owned, except 90c27e705cSAlice Ryhl /// that the address of the object must not be changed. 91c27e705cSAlice Ryhl /// 92c27e705cSAlice Ryhl /// Note that for types like [`Arc`], an `&mut Arc<T>` only gives you immutable access to the 93c27e705cSAlice Ryhl /// inner value, so this method also only provides immutable access in that case. 94c27e705cSAlice Ryhl /// 95c27e705cSAlice Ryhl /// In the case of `Box<T>`, this method gives you the ability to modify the inner `T`, but it 96c27e705cSAlice Ryhl /// does not let you change the box itself. That is, you cannot change which allocation the box 97c27e705cSAlice Ryhl /// points at. 98c27e705cSAlice Ryhl /// 99c27e705cSAlice Ryhl /// # Safety 100c27e705cSAlice Ryhl /// 101c27e705cSAlice Ryhl /// The provided pointer must have been returned by a previous call to [`into_foreign`], and if 102c27e705cSAlice Ryhl /// the pointer is ever passed to [`from_foreign`], then that call must happen after the end of 103cd1ed11aSBorys Tyran /// the lifetime `'a`. 104c27e705cSAlice Ryhl /// 105cd1ed11aSBorys Tyran /// The lifetime `'a` must not overlap with the lifetime of any other call to [`borrow`] or 106c27e705cSAlice Ryhl /// `borrow_mut` on the same object. 107c27e705cSAlice Ryhl /// 108c27e705cSAlice Ryhl /// [`into_foreign`]: Self::into_foreign 109c27e705cSAlice Ryhl /// [`from_foreign`]: Self::from_foreign 110c27e705cSAlice Ryhl /// [`borrow`]: Self::borrow 111c27e705cSAlice Ryhl /// [`Arc`]: crate::sync::Arc borrow_mut<'a>(ptr: *mut crate::ffi::c_void) -> Self::BorrowedMut<'a>112c27e705cSAlice Ryhl unsafe fn borrow_mut<'a>(ptr: *mut crate::ffi::c_void) -> Self::BorrowedMut<'a>; 1130fc4424dSWedson Almeida Filho } 1140fc4424dSWedson Almeida Filho 11571185944SWedson Almeida Filho impl ForeignOwnable for () { 11671185944SWedson Almeida Filho type Borrowed<'a> = (); 117c27e705cSAlice Ryhl type BorrowedMut<'a> = (); 11871185944SWedson Almeida Filho into_foreign(self) -> *mut crate::ffi::c_void11914686571STamir Duberstein fn into_foreign(self) -> *mut crate::ffi::c_void { 12071185944SWedson Almeida Filho core::ptr::NonNull::dangling().as_ptr() 12171185944SWedson Almeida Filho } 12271185944SWedson Almeida Filho from_foreign(_: *mut crate::ffi::c_void) -> Self12314686571STamir Duberstein unsafe fn from_foreign(_: *mut crate::ffi::c_void) -> Self {} 124c6b97538STamir Duberstein borrow<'a>(_: *mut crate::ffi::c_void) -> Self::Borrowed<'a>125c6b97538STamir Duberstein unsafe fn borrow<'a>(_: *mut crate::ffi::c_void) -> Self::Borrowed<'a> {} borrow_mut<'a>(_: *mut crate::ffi::c_void) -> Self::BorrowedMut<'a>126c27e705cSAlice Ryhl unsafe fn borrow_mut<'a>(_: *mut crate::ffi::c_void) -> Self::BorrowedMut<'a> {} 12771185944SWedson Almeida Filho } 12871185944SWedson Almeida Filho 1294d4692a2SWedson Almeida Filho /// Runs a cleanup function/closure when dropped. 1304d4692a2SWedson Almeida Filho /// 1314d4692a2SWedson Almeida Filho /// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running. 1324d4692a2SWedson Almeida Filho /// 1334d4692a2SWedson Almeida Filho /// # Examples 1344d4692a2SWedson Almeida Filho /// 1354d4692a2SWedson Almeida Filho /// In the example below, we have multiple exit paths and we want to log regardless of which one is 1364d4692a2SWedson Almeida Filho /// taken: 1376269fadfSValentin Obst /// 1384d4692a2SWedson Almeida Filho /// ``` 139ed615fb8SMiguel Ojeda /// # use kernel::types::ScopeGuard; 1404d4692a2SWedson Almeida Filho /// fn example1(arg: bool) { 1414d4692a2SWedson Almeida Filho /// let _log = ScopeGuard::new(|| pr_info!("example1 completed\n")); 1424d4692a2SWedson Almeida Filho /// 1434d4692a2SWedson Almeida Filho /// if arg { 1444d4692a2SWedson Almeida Filho /// return; 1454d4692a2SWedson Almeida Filho /// } 1464d4692a2SWedson Almeida Filho /// 1474d4692a2SWedson Almeida Filho /// pr_info!("Do something...\n"); 1484d4692a2SWedson Almeida Filho /// } 1494d4692a2SWedson Almeida Filho /// 1504d4692a2SWedson Almeida Filho /// # example1(false); 1514d4692a2SWedson Almeida Filho /// # example1(true); 1524d4692a2SWedson Almeida Filho /// ``` 1534d4692a2SWedson Almeida Filho /// 1544d4692a2SWedson Almeida Filho /// In the example below, we want to log the same message on all early exits but a different one on 1554d4692a2SWedson Almeida Filho /// the main exit path: 1566269fadfSValentin Obst /// 1574d4692a2SWedson Almeida Filho /// ``` 158ed615fb8SMiguel Ojeda /// # use kernel::types::ScopeGuard; 1594d4692a2SWedson Almeida Filho /// fn example2(arg: bool) { 1604d4692a2SWedson Almeida Filho /// let log = ScopeGuard::new(|| pr_info!("example2 returned early\n")); 1614d4692a2SWedson Almeida Filho /// 1624d4692a2SWedson Almeida Filho /// if arg { 1634d4692a2SWedson Almeida Filho /// return; 1644d4692a2SWedson Almeida Filho /// } 1654d4692a2SWedson Almeida Filho /// 1664d4692a2SWedson Almeida Filho /// // (Other early returns...) 1674d4692a2SWedson Almeida Filho /// 1684d4692a2SWedson Almeida Filho /// log.dismiss(); 1694d4692a2SWedson Almeida Filho /// pr_info!("example2 no early return\n"); 1704d4692a2SWedson Almeida Filho /// } 1714d4692a2SWedson Almeida Filho /// 1724d4692a2SWedson Almeida Filho /// # example2(false); 1734d4692a2SWedson Almeida Filho /// # example2(true); 1744d4692a2SWedson Almeida Filho /// ``` 1754d4692a2SWedson Almeida Filho /// 1764d4692a2SWedson Almeida Filho /// In the example below, we need a mutable object (the vector) to be accessible within the log 1774d4692a2SWedson Almeida Filho /// function, so we wrap it in the [`ScopeGuard`]: 1786269fadfSValentin Obst /// 1794d4692a2SWedson Almeida Filho /// ``` 180ed615fb8SMiguel Ojeda /// # use kernel::types::ScopeGuard; 1814d4692a2SWedson Almeida Filho /// fn example3(arg: bool) -> Result { 1824d4692a2SWedson Almeida Filho /// let mut vec = 18358eff8e8SDanilo Krummrich /// ScopeGuard::new_with_data(KVec::new(), |v| pr_info!("vec had {} elements\n", v.len())); 1844d4692a2SWedson Almeida Filho /// 1855ab560ceSWedson Almeida Filho /// vec.push(10u8, GFP_KERNEL)?; 1864d4692a2SWedson Almeida Filho /// if arg { 1874d4692a2SWedson Almeida Filho /// return Ok(()); 1884d4692a2SWedson Almeida Filho /// } 1895ab560ceSWedson Almeida Filho /// vec.push(20u8, GFP_KERNEL)?; 1904d4692a2SWedson Almeida Filho /// Ok(()) 1914d4692a2SWedson Almeida Filho /// } 1924d4692a2SWedson Almeida Filho /// 1934d4692a2SWedson Almeida Filho /// # assert_eq!(example3(false), Ok(())); 1944d4692a2SWedson Almeida Filho /// # assert_eq!(example3(true), Ok(())); 1954d4692a2SWedson Almeida Filho /// ``` 1964d4692a2SWedson Almeida Filho /// 1974d4692a2SWedson Almeida Filho /// # Invariants 1984d4692a2SWedson Almeida Filho /// 1994d4692a2SWedson Almeida Filho /// The value stored in the struct is nearly always `Some(_)`, except between 2004d4692a2SWedson Almeida Filho /// [`ScopeGuard::dismiss`] and [`ScopeGuard::drop`]: in this case, it will be `None` as the value 2014d4692a2SWedson Almeida Filho /// will have been returned to the caller. Since [`ScopeGuard::dismiss`] consumes the guard, 2024d4692a2SWedson Almeida Filho /// callers won't be able to use it anymore. 2034d4692a2SWedson Almeida Filho pub struct ScopeGuard<T, F: FnOnce(T)>(Option<(T, F)>); 2044d4692a2SWedson Almeida Filho 2054d4692a2SWedson Almeida Filho impl<T, F: FnOnce(T)> ScopeGuard<T, F> { 2064d4692a2SWedson Almeida Filho /// Creates a new guarded object wrapping the given data and with the given cleanup function. new_with_data(data: T, cleanup_func: F) -> Self2074d4692a2SWedson Almeida Filho pub fn new_with_data(data: T, cleanup_func: F) -> Self { 2084d4692a2SWedson Almeida Filho // INVARIANT: The struct is being initialised with `Some(_)`. 2094d4692a2SWedson Almeida Filho Self(Some((data, cleanup_func))) 2104d4692a2SWedson Almeida Filho } 2114d4692a2SWedson Almeida Filho 2124d4692a2SWedson Almeida Filho /// Prevents the cleanup function from running and returns the guarded data. dismiss(mut self) -> T2134d4692a2SWedson Almeida Filho pub fn dismiss(mut self) -> T { 2144d4692a2SWedson Almeida Filho // INVARIANT: This is the exception case in the invariant; it is not visible to callers 2154d4692a2SWedson Almeida Filho // because this function consumes `self`. 2164d4692a2SWedson Almeida Filho self.0.take().unwrap().0 2174d4692a2SWedson Almeida Filho } 2184d4692a2SWedson Almeida Filho } 2194d4692a2SWedson Almeida Filho 2204d4692a2SWedson Almeida Filho impl ScopeGuard<(), fn(())> { 2214d4692a2SWedson Almeida Filho /// Creates a new guarded object with the given cleanup function. new(cleanup: impl FnOnce()) -> ScopeGuard<(), impl FnOnce(())>2224d4692a2SWedson Almeida Filho pub fn new(cleanup: impl FnOnce()) -> ScopeGuard<(), impl FnOnce(())> { 2233fcc2339SMiguel Ojeda ScopeGuard::new_with_data((), move |()| cleanup()) 2244d4692a2SWedson Almeida Filho } 2254d4692a2SWedson Almeida Filho } 2264d4692a2SWedson Almeida Filho 2274d4692a2SWedson Almeida Filho impl<T, F: FnOnce(T)> Deref for ScopeGuard<T, F> { 2284d4692a2SWedson Almeida Filho type Target = T; 2294d4692a2SWedson Almeida Filho deref(&self) -> &T2304d4692a2SWedson Almeida Filho fn deref(&self) -> &T { 2314d4692a2SWedson Almeida Filho // The type invariants guarantee that `unwrap` will succeed. 2324d4692a2SWedson Almeida Filho &self.0.as_ref().unwrap().0 2334d4692a2SWedson Almeida Filho } 2344d4692a2SWedson Almeida Filho } 2354d4692a2SWedson Almeida Filho 2364d4692a2SWedson Almeida Filho impl<T, F: FnOnce(T)> DerefMut for ScopeGuard<T, F> { deref_mut(&mut self) -> &mut T2374d4692a2SWedson Almeida Filho fn deref_mut(&mut self) -> &mut T { 2384d4692a2SWedson Almeida Filho // The type invariants guarantee that `unwrap` will succeed. 2394d4692a2SWedson Almeida Filho &mut self.0.as_mut().unwrap().0 2404d4692a2SWedson Almeida Filho } 2414d4692a2SWedson Almeida Filho } 2424d4692a2SWedson Almeida Filho 2434d4692a2SWedson Almeida Filho impl<T, F: FnOnce(T)> Drop for ScopeGuard<T, F> { drop(&mut self)2444d4692a2SWedson Almeida Filho fn drop(&mut self) { 2454d4692a2SWedson Almeida Filho // Run the cleanup function if one is still present. 2464d4692a2SWedson Almeida Filho if let Some((data, cleanup)) = self.0.take() { 2474d4692a2SWedson Almeida Filho cleanup(data) 2484d4692a2SWedson Almeida Filho } 2494d4692a2SWedson Almeida Filho } 2504d4692a2SWedson Almeida Filho } 251b9ecf9b9SWedson Almeida Filho 252b9ecf9b9SWedson Almeida Filho /// Stores an opaque value. 253b9ecf9b9SWedson Almeida Filho /// 254ab2ebb7bSDirk Behme /// [`Opaque<T>`] is meant to be used with FFI objects that are never interpreted by Rust code. 255718c4069SDirk Behme /// 256718c4069SDirk Behme /// It is used to wrap structs from the C side, like for example `Opaque<bindings::mutex>`. 257718c4069SDirk Behme /// It gets rid of all the usual assumptions that Rust has for a value: 258718c4069SDirk Behme /// 259718c4069SDirk Behme /// * The value is allowed to be uninitialized (for example have invalid bit patterns: `3` for a 260718c4069SDirk Behme /// [`bool`]). 261718c4069SDirk Behme /// * The value is allowed to be mutated, when a `&Opaque<T>` exists on the Rust side. 262718c4069SDirk Behme /// * No uniqueness for mutable references: it is fine to have multiple `&mut Opaque<T>` point to 263718c4069SDirk Behme /// the same value. 264718c4069SDirk Behme /// * The value is not allowed to be shared with other threads (i.e. it is `!Sync`). 265718c4069SDirk Behme /// 266718c4069SDirk Behme /// This has to be used for all values that the C side has access to, because it can't be ensured 267718c4069SDirk Behme /// that the C side is adhering to the usual constraints that Rust needs. 268718c4069SDirk Behme /// 269ab2ebb7bSDirk Behme /// Using [`Opaque<T>`] allows to continue to use references on the Rust side even for values shared 270718c4069SDirk Behme /// with C. 271718c4069SDirk Behme /// 272718c4069SDirk Behme /// # Examples 273718c4069SDirk Behme /// 274718c4069SDirk Behme /// ``` 275718c4069SDirk Behme /// # #![expect(unreachable_pub, clippy::disallowed_names)] 276718c4069SDirk Behme /// use kernel::types::Opaque; 277718c4069SDirk Behme /// # // Emulate a C struct binding which is from C, maybe uninitialized or not, only the C side 278718c4069SDirk Behme /// # // knows. 279718c4069SDirk Behme /// # mod bindings { 280718c4069SDirk Behme /// # pub struct Foo { 281718c4069SDirk Behme /// # pub val: u8, 282718c4069SDirk Behme /// # } 283718c4069SDirk Behme /// # } 284718c4069SDirk Behme /// 285718c4069SDirk Behme /// // `foo.val` is assumed to be handled on the C side, so we use `Opaque` to wrap it. 286718c4069SDirk Behme /// pub struct Foo { 287718c4069SDirk Behme /// foo: Opaque<bindings::Foo>, 288718c4069SDirk Behme /// } 289718c4069SDirk Behme /// 290718c4069SDirk Behme /// impl Foo { 291718c4069SDirk Behme /// pub fn get_val(&self) -> u8 { 292718c4069SDirk Behme /// let ptr = Opaque::get(&self.foo); 293718c4069SDirk Behme /// 294718c4069SDirk Behme /// // SAFETY: `Self` is valid from C side. 295718c4069SDirk Behme /// unsafe { (*ptr).val } 296718c4069SDirk Behme /// } 297718c4069SDirk Behme /// } 298718c4069SDirk Behme /// 299718c4069SDirk Behme /// // Create an instance of `Foo` with the `Opaque` wrapper. 300718c4069SDirk Behme /// let foo = Foo { 301718c4069SDirk Behme /// foo: Opaque::new(bindings::Foo { val: 0xdb }), 302718c4069SDirk Behme /// }; 303718c4069SDirk Behme /// 304718c4069SDirk Behme /// assert_eq!(foo.get_val(), 0xdb); 305718c4069SDirk Behme /// ``` 306b9ecf9b9SWedson Almeida Filho #[repr(transparent)] 3070b4e3b6fSBenno Lossin pub struct Opaque<T> { 3080b4e3b6fSBenno Lossin value: UnsafeCell<MaybeUninit<T>>, 3090b4e3b6fSBenno Lossin _pin: PhantomPinned, 3100b4e3b6fSBenno Lossin } 311b9ecf9b9SWedson Almeida Filho 3129d29c682SBenno Lossin // SAFETY: `Opaque<T>` allows the inner value to be any bit pattern, including all zeros. 3139d29c682SBenno Lossin unsafe impl<T> Zeroable for Opaque<T> {} 3149d29c682SBenno Lossin 315b9ecf9b9SWedson Almeida Filho impl<T> Opaque<T> { 316b9ecf9b9SWedson Almeida Filho /// Creates a new opaque value. new(value: T) -> Self317b9ecf9b9SWedson Almeida Filho pub const fn new(value: T) -> Self { 3180b4e3b6fSBenno Lossin Self { 3190b4e3b6fSBenno Lossin value: UnsafeCell::new(MaybeUninit::new(value)), 3200b4e3b6fSBenno Lossin _pin: PhantomPinned, 3210b4e3b6fSBenno Lossin } 322b9ecf9b9SWedson Almeida Filho } 323b9ecf9b9SWedson Almeida Filho 324b9ecf9b9SWedson Almeida Filho /// Creates an uninitialised value. uninit() -> Self325b9ecf9b9SWedson Almeida Filho pub const fn uninit() -> Self { 3260b4e3b6fSBenno Lossin Self { 3270b4e3b6fSBenno Lossin value: UnsafeCell::new(MaybeUninit::uninit()), 3280b4e3b6fSBenno Lossin _pin: PhantomPinned, 3290b4e3b6fSBenno Lossin } 330b9ecf9b9SWedson Almeida Filho } 331b9ecf9b9SWedson Almeida Filho 3322d3bf6ffSDanilo Krummrich /// Create an opaque pin-initializer from the given pin-initializer. pin_init(slot: impl PinInit<T>) -> impl PinInit<Self>3332d3bf6ffSDanilo Krummrich pub fn pin_init(slot: impl PinInit<T>) -> impl PinInit<Self> { 3342d3bf6ffSDanilo Krummrich Self::ffi_init(|ptr: *mut T| { 3352d3bf6ffSDanilo Krummrich // SAFETY: 3362d3bf6ffSDanilo Krummrich // - `ptr` is a valid pointer to uninitialized memory, 3372d3bf6ffSDanilo Krummrich // - `slot` is not accessed on error; the call is infallible, 3382d3bf6ffSDanilo Krummrich // - `slot` is pinned in memory. 339*dbd5058bSBenno Lossin let _ = unsafe { PinInit::<T>::__pinned_init(slot, ptr) }; 3402d3bf6ffSDanilo Krummrich }) 3412d3bf6ffSDanilo Krummrich } 3422d3bf6ffSDanilo Krummrich 343692e8935SBenno Lossin /// Creates a pin-initializer from the given initializer closure. 344692e8935SBenno Lossin /// 345692e8935SBenno Lossin /// The returned initializer calls the given closure with the pointer to the inner `T` of this 346692e8935SBenno Lossin /// `Opaque`. Since this memory is uninitialized, the closure is not allowed to read from it. 347692e8935SBenno Lossin /// 348692e8935SBenno Lossin /// This function is safe, because the `T` inside of an `Opaque` is allowed to be 349692e8935SBenno Lossin /// uninitialized. Additionally, access to the inner `T` requires `unsafe`, so the caller needs 350692e8935SBenno Lossin /// to verify at that point that the inner value is valid. ffi_init(init_func: impl FnOnce(*mut T)) -> impl PinInit<Self>351692e8935SBenno Lossin pub fn ffi_init(init_func: impl FnOnce(*mut T)) -> impl PinInit<Self> { 352692e8935SBenno Lossin // SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully 353692e8935SBenno Lossin // initialize the `T`. 354692e8935SBenno Lossin unsafe { 355*dbd5058bSBenno Lossin pin_init::pin_init_from_closure::<_, ::core::convert::Infallible>(move |slot| { 356692e8935SBenno Lossin init_func(Self::raw_get(slot)); 357692e8935SBenno Lossin Ok(()) 358692e8935SBenno Lossin }) 359692e8935SBenno Lossin } 360692e8935SBenno Lossin } 361692e8935SBenno Lossin 362a69dc41aSAlice Ryhl /// Creates a fallible pin-initializer from the given initializer closure. 363a69dc41aSAlice Ryhl /// 364a69dc41aSAlice Ryhl /// The returned initializer calls the given closure with the pointer to the inner `T` of this 365a69dc41aSAlice Ryhl /// `Opaque`. Since this memory is uninitialized, the closure is not allowed to read from it. 366a69dc41aSAlice Ryhl /// 367a69dc41aSAlice Ryhl /// This function is safe, because the `T` inside of an `Opaque` is allowed to be 368a69dc41aSAlice Ryhl /// uninitialized. Additionally, access to the inner `T` requires `unsafe`, so the caller needs 369a69dc41aSAlice Ryhl /// to verify at that point that the inner value is valid. try_ffi_init<E>( init_func: impl FnOnce(*mut T) -> Result<(), E>, ) -> impl PinInit<Self, E>370a69dc41aSAlice Ryhl pub fn try_ffi_init<E>( 371a69dc41aSAlice Ryhl init_func: impl FnOnce(*mut T) -> Result<(), E>, 372a69dc41aSAlice Ryhl ) -> impl PinInit<Self, E> { 373a69dc41aSAlice Ryhl // SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully 374a69dc41aSAlice Ryhl // initialize the `T`. 375*dbd5058bSBenno Lossin unsafe { 376*dbd5058bSBenno Lossin pin_init::pin_init_from_closure::<_, E>(move |slot| init_func(Self::raw_get(slot))) 377*dbd5058bSBenno Lossin } 378a69dc41aSAlice Ryhl } 379a69dc41aSAlice Ryhl 380b9ecf9b9SWedson Almeida Filho /// Returns a raw pointer to the opaque data. get(&self) -> *mut T381be2ca1e0SBoqun Feng pub const fn get(&self) -> *mut T { 3820b4e3b6fSBenno Lossin UnsafeCell::get(&self.value).cast::<T>() 383b9ecf9b9SWedson Almeida Filho } 3843ff6e785SBenno Lossin 3853ff6e785SBenno Lossin /// Gets the value behind `this`. 3863ff6e785SBenno Lossin /// 3873ff6e785SBenno Lossin /// This function is useful to get access to the value without creating intermediate 3883ff6e785SBenno Lossin /// references. raw_get(this: *const Self) -> *mut T3893ff6e785SBenno Lossin pub const fn raw_get(this: *const Self) -> *mut T { 39035cad617SAlice Ryhl UnsafeCell::raw_get(this.cast::<UnsafeCell<MaybeUninit<T>>>()).cast::<T>() 3913ff6e785SBenno Lossin } 392b9ecf9b9SWedson Almeida Filho } 393b9ecf9b9SWedson Almeida Filho 394f1fbd6a8SWedson Almeida Filho /// Types that are _always_ reference counted. 395f1fbd6a8SWedson Almeida Filho /// 396f1fbd6a8SWedson Almeida Filho /// It allows such types to define their own custom ref increment and decrement functions. 397f1fbd6a8SWedson Almeida Filho /// Additionally, it allows users to convert from a shared reference `&T` to an owned reference 398f1fbd6a8SWedson Almeida Filho /// [`ARef<T>`]. 399f1fbd6a8SWedson Almeida Filho /// 400f1fbd6a8SWedson Almeida Filho /// This is usually implemented by wrappers to existing structures on the C side of the code. For 401f1fbd6a8SWedson Almeida Filho /// Rust code, the recommendation is to use [`Arc`](crate::sync::Arc) to create reference-counted 402f1fbd6a8SWedson Almeida Filho /// instances of a type. 403f1fbd6a8SWedson Almeida Filho /// 404f1fbd6a8SWedson Almeida Filho /// # Safety 405f1fbd6a8SWedson Almeida Filho /// 406f1fbd6a8SWedson Almeida Filho /// Implementers must ensure that increments to the reference count keep the object alive in memory 407f1fbd6a8SWedson Almeida Filho /// at least until matching decrements are performed. 408f1fbd6a8SWedson Almeida Filho /// 409f1fbd6a8SWedson Almeida Filho /// Implementers must also ensure that all instances are reference-counted. (Otherwise they 410f1fbd6a8SWedson Almeida Filho /// won't be able to honour the requirement that [`AlwaysRefCounted::inc_ref`] keep the object 411f1fbd6a8SWedson Almeida Filho /// alive.) 412f1fbd6a8SWedson Almeida Filho pub unsafe trait AlwaysRefCounted { 413f1fbd6a8SWedson Almeida Filho /// Increments the reference count on the object. inc_ref(&self)414f1fbd6a8SWedson Almeida Filho fn inc_ref(&self); 415f1fbd6a8SWedson Almeida Filho 416f1fbd6a8SWedson Almeida Filho /// Decrements the reference count on the object. 417f1fbd6a8SWedson Almeida Filho /// 418f1fbd6a8SWedson Almeida Filho /// Frees the object when the count reaches zero. 419f1fbd6a8SWedson Almeida Filho /// 420f1fbd6a8SWedson Almeida Filho /// # Safety 421f1fbd6a8SWedson Almeida Filho /// 422f1fbd6a8SWedson Almeida Filho /// Callers must ensure that there was a previous matching increment to the reference count, 423f1fbd6a8SWedson Almeida Filho /// and that the object is no longer used after its reference count is decremented (as it may 424f1fbd6a8SWedson Almeida Filho /// result in the object being freed), unless the caller owns another increment on the refcount 425f1fbd6a8SWedson Almeida Filho /// (e.g., it calls [`AlwaysRefCounted::inc_ref`] twice, then calls 426f1fbd6a8SWedson Almeida Filho /// [`AlwaysRefCounted::dec_ref`] once). dec_ref(obj: NonNull<Self>)427f1fbd6a8SWedson Almeida Filho unsafe fn dec_ref(obj: NonNull<Self>); 428f1fbd6a8SWedson Almeida Filho } 429f1fbd6a8SWedson Almeida Filho 430f1fbd6a8SWedson Almeida Filho /// An owned reference to an always-reference-counted object. 431f1fbd6a8SWedson Almeida Filho /// 432f1fbd6a8SWedson Almeida Filho /// The object's reference count is automatically decremented when an instance of [`ARef`] is 433f1fbd6a8SWedson Almeida Filho /// dropped. It is also automatically incremented when a new instance is created via 434f1fbd6a8SWedson Almeida Filho /// [`ARef::clone`]. 435f1fbd6a8SWedson Almeida Filho /// 436f1fbd6a8SWedson Almeida Filho /// # Invariants 437f1fbd6a8SWedson Almeida Filho /// 438f1fbd6a8SWedson Almeida Filho /// The pointer stored in `ptr` is non-null and valid for the lifetime of the [`ARef`] instance. In 439f1fbd6a8SWedson Almeida Filho /// particular, the [`ARef`] instance owns an increment on the underlying object's reference count. 440f1fbd6a8SWedson Almeida Filho pub struct ARef<T: AlwaysRefCounted> { 441f1fbd6a8SWedson Almeida Filho ptr: NonNull<T>, 442f1fbd6a8SWedson Almeida Filho _p: PhantomData<T>, 443f1fbd6a8SWedson Almeida Filho } 444f1fbd6a8SWedson Almeida Filho 445be7724cdSAlice Ryhl // SAFETY: It is safe to send `ARef<T>` to another thread when the underlying `T` is `Sync` because 446be7724cdSAlice Ryhl // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs 447be7724cdSAlice Ryhl // `T` to be `Send` because any thread that has an `ARef<T>` may ultimately access `T` using a 448be7724cdSAlice Ryhl // mutable reference, for example, when the reference count reaches zero and `T` is dropped. 449be7724cdSAlice Ryhl unsafe impl<T: AlwaysRefCounted + Sync + Send> Send for ARef<T> {} 450be7724cdSAlice Ryhl 451be7724cdSAlice Ryhl // SAFETY: It is safe to send `&ARef<T>` to another thread when the underlying `T` is `Sync` 452be7724cdSAlice Ryhl // because it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, 453be7724cdSAlice Ryhl // it needs `T` to be `Send` because any thread that has a `&ARef<T>` may clone it and get an 454be7724cdSAlice Ryhl // `ARef<T>` on that thread, so the thread may ultimately access `T` using a mutable reference, for 455be7724cdSAlice Ryhl // example, when the reference count reaches zero and `T` is dropped. 456be7724cdSAlice Ryhl unsafe impl<T: AlwaysRefCounted + Sync + Send> Sync for ARef<T> {} 457be7724cdSAlice Ryhl 458f1fbd6a8SWedson Almeida Filho impl<T: AlwaysRefCounted> ARef<T> { 459f1fbd6a8SWedson Almeida Filho /// Creates a new instance of [`ARef`]. 460f1fbd6a8SWedson Almeida Filho /// 461f1fbd6a8SWedson Almeida Filho /// It takes over an increment of the reference count on the underlying object. 462f1fbd6a8SWedson Almeida Filho /// 463f1fbd6a8SWedson Almeida Filho /// # Safety 464f1fbd6a8SWedson Almeida Filho /// 465f1fbd6a8SWedson Almeida Filho /// Callers must ensure that the reference count was incremented at least once, and that they 466f1fbd6a8SWedson Almeida Filho /// are properly relinquishing one increment. That is, if there is only one increment, callers 467f1fbd6a8SWedson Almeida Filho /// must not use the underlying object anymore -- it is only safe to do so via the newly 468f1fbd6a8SWedson Almeida Filho /// created [`ARef`]. from_raw(ptr: NonNull<T>) -> Self469f1fbd6a8SWedson Almeida Filho pub unsafe fn from_raw(ptr: NonNull<T>) -> Self { 470f1fbd6a8SWedson Almeida Filho // INVARIANT: The safety requirements guarantee that the new instance now owns the 471f1fbd6a8SWedson Almeida Filho // increment on the refcount. 472f1fbd6a8SWedson Almeida Filho Self { 473f1fbd6a8SWedson Almeida Filho ptr, 474f1fbd6a8SWedson Almeida Filho _p: PhantomData, 475f1fbd6a8SWedson Almeida Filho } 476f1fbd6a8SWedson Almeida Filho } 47796fff2dcSKartik Prajapati 47896fff2dcSKartik Prajapati /// Consumes the `ARef`, returning a raw pointer. 47996fff2dcSKartik Prajapati /// 48096fff2dcSKartik Prajapati /// This function does not change the refcount. After calling this function, the caller is 48196fff2dcSKartik Prajapati /// responsible for the refcount previously managed by the `ARef`. 48296fff2dcSKartik Prajapati /// 48396fff2dcSKartik Prajapati /// # Examples 48496fff2dcSKartik Prajapati /// 48596fff2dcSKartik Prajapati /// ``` 48696fff2dcSKartik Prajapati /// use core::ptr::NonNull; 48796fff2dcSKartik Prajapati /// use kernel::types::{ARef, AlwaysRefCounted}; 48896fff2dcSKartik Prajapati /// 48996fff2dcSKartik Prajapati /// struct Empty {} 49096fff2dcSKartik Prajapati /// 491db4f72c9SMiguel Ojeda /// # // SAFETY: TODO. 49296fff2dcSKartik Prajapati /// unsafe impl AlwaysRefCounted for Empty { 49396fff2dcSKartik Prajapati /// fn inc_ref(&self) {} 49496fff2dcSKartik Prajapati /// unsafe fn dec_ref(_obj: NonNull<Self>) {} 49596fff2dcSKartik Prajapati /// } 49696fff2dcSKartik Prajapati /// 49796fff2dcSKartik Prajapati /// let mut data = Empty {}; 498aa991a2aSTamir Duberstein /// let ptr = NonNull::<Empty>::new(&mut data).unwrap(); 499db4f72c9SMiguel Ojeda /// # // SAFETY: TODO. 50096fff2dcSKartik Prajapati /// let data_ref: ARef<Empty> = unsafe { ARef::from_raw(ptr) }; 50196fff2dcSKartik Prajapati /// let raw_ptr: NonNull<Empty> = ARef::into_raw(data_ref); 50296fff2dcSKartik Prajapati /// 50396fff2dcSKartik Prajapati /// assert_eq!(ptr, raw_ptr); 50496fff2dcSKartik Prajapati /// ``` into_raw(me: Self) -> NonNull<T>50596fff2dcSKartik Prajapati pub fn into_raw(me: Self) -> NonNull<T> { 50696fff2dcSKartik Prajapati ManuallyDrop::new(me).ptr 50796fff2dcSKartik Prajapati } 508f1fbd6a8SWedson Almeida Filho } 509f1fbd6a8SWedson Almeida Filho 510f1fbd6a8SWedson Almeida Filho impl<T: AlwaysRefCounted> Clone for ARef<T> { clone(&self) -> Self511f1fbd6a8SWedson Almeida Filho fn clone(&self) -> Self { 512f1fbd6a8SWedson Almeida Filho self.inc_ref(); 513f1fbd6a8SWedson Almeida Filho // SAFETY: We just incremented the refcount above. 514f1fbd6a8SWedson Almeida Filho unsafe { Self::from_raw(self.ptr) } 515f1fbd6a8SWedson Almeida Filho } 516f1fbd6a8SWedson Almeida Filho } 517f1fbd6a8SWedson Almeida Filho 518f1fbd6a8SWedson Almeida Filho impl<T: AlwaysRefCounted> Deref for ARef<T> { 519f1fbd6a8SWedson Almeida Filho type Target = T; 520f1fbd6a8SWedson Almeida Filho deref(&self) -> &Self::Target521f1fbd6a8SWedson Almeida Filho fn deref(&self) -> &Self::Target { 522f1fbd6a8SWedson Almeida Filho // SAFETY: The type invariants guarantee that the object is valid. 523f1fbd6a8SWedson Almeida Filho unsafe { self.ptr.as_ref() } 524f1fbd6a8SWedson Almeida Filho } 525f1fbd6a8SWedson Almeida Filho } 526f1fbd6a8SWedson Almeida Filho 527f1fbd6a8SWedson Almeida Filho impl<T: AlwaysRefCounted> From<&T> for ARef<T> { from(b: &T) -> Self528f1fbd6a8SWedson Almeida Filho fn from(b: &T) -> Self { 529f1fbd6a8SWedson Almeida Filho b.inc_ref(); 530f1fbd6a8SWedson Almeida Filho // SAFETY: We just incremented the refcount above. 531f1fbd6a8SWedson Almeida Filho unsafe { Self::from_raw(NonNull::from(b)) } 532f1fbd6a8SWedson Almeida Filho } 533f1fbd6a8SWedson Almeida Filho } 534f1fbd6a8SWedson Almeida Filho 535f1fbd6a8SWedson Almeida Filho impl<T: AlwaysRefCounted> Drop for ARef<T> { drop(&mut self)536f1fbd6a8SWedson Almeida Filho fn drop(&mut self) { 537f1fbd6a8SWedson Almeida Filho // SAFETY: The type invariants guarantee that the `ARef` owns the reference we're about to 538f1fbd6a8SWedson Almeida Filho // decrement. 539f1fbd6a8SWedson Almeida Filho unsafe { T::dec_ref(self.ptr) }; 540f1fbd6a8SWedson Almeida Filho } 541f1fbd6a8SWedson Almeida Filho } 542f1fbd6a8SWedson Almeida Filho 543ba20915bSWedson Almeida Filho /// A sum type that always holds either a value of type `L` or `R`. 544d4073170SNell Shamrell-Harrington /// 545d4073170SNell Shamrell-Harrington /// # Examples 546d4073170SNell Shamrell-Harrington /// 547d4073170SNell Shamrell-Harrington /// ``` 548d4073170SNell Shamrell-Harrington /// use kernel::types::Either; 549d4073170SNell Shamrell-Harrington /// 550d4073170SNell Shamrell-Harrington /// let left_value: Either<i32, &str> = Either::Left(7); 551d4073170SNell Shamrell-Harrington /// let right_value: Either<i32, &str> = Either::Right("right value"); 552d4073170SNell Shamrell-Harrington /// ``` 553ba20915bSWedson Almeida Filho pub enum Either<L, R> { 554ba20915bSWedson Almeida Filho /// Constructs an instance of [`Either`] containing a value of type `L`. 555ba20915bSWedson Almeida Filho Left(L), 556ba20915bSWedson Almeida Filho 557ba20915bSWedson Almeida Filho /// Constructs an instance of [`Either`] containing a value of type `R`. 558ba20915bSWedson Almeida Filho Right(R), 559ba20915bSWedson Almeida Filho } 560b33bf37aSAlice Ryhl 561e7572e5dSAlice Ryhl /// Zero-sized type to mark types not [`Send`]. 562e7572e5dSAlice Ryhl /// 563e7572e5dSAlice Ryhl /// Add this type as a field to your struct if your type should not be sent to a different task. 564e7572e5dSAlice Ryhl /// Since [`Send`] is an auto trait, adding a single field that is `!Send` will ensure that the 565e7572e5dSAlice Ryhl /// whole type is `!Send`. 566e7572e5dSAlice Ryhl /// 567e7572e5dSAlice Ryhl /// If a type is `!Send` it is impossible to give control over an instance of the type to another 568e7572e5dSAlice Ryhl /// task. This is useful to include in types that store or reference task-local information. A file 569e7572e5dSAlice Ryhl /// descriptor is an example of such task-local information. 570e7572e5dSAlice Ryhl /// 571e7572e5dSAlice Ryhl /// This type also makes the type `!Sync`, which prevents immutable access to the value from 572e7572e5dSAlice Ryhl /// several threads in parallel. 573e7572e5dSAlice Ryhl pub type NotThreadSafe = PhantomData<*mut ()>; 574e7572e5dSAlice Ryhl 575e7572e5dSAlice Ryhl /// Used to construct instances of type [`NotThreadSafe`] similar to how `PhantomData` is 576e7572e5dSAlice Ryhl /// constructed. 577e7572e5dSAlice Ryhl /// 578e7572e5dSAlice Ryhl /// [`NotThreadSafe`]: type@NotThreadSafe 579e7572e5dSAlice Ryhl #[allow(non_upper_case_globals)] 580e7572e5dSAlice Ryhl pub const NotThreadSafe: NotThreadSafe = PhantomData; 581