kbox.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. // SPDX-License-Identifier: GPL-2.0
  2. //! Implementation of [`Box`].
  3. #[allow(unused_imports)] // Used in doc comments.
  4. use super::allocator::{KVmalloc, Kmalloc, Vmalloc};
  5. use super::{AllocError, Allocator, Flags};
  6. use core::alloc::Layout;
  7. use core::fmt;
  8. use core::marker::PhantomData;
  9. use core::mem::ManuallyDrop;
  10. use core::mem::MaybeUninit;
  11. use core::ops::{Deref, DerefMut};
  12. use core::pin::Pin;
  13. use core::ptr::NonNull;
  14. use core::result::Result;
  15. use crate::init::{InPlaceInit, InPlaceWrite, Init, PinInit};
  16. use crate::types::ForeignOwnable;
  17. /// The kernel's [`Box`] type -- a heap allocation for a single value of type `T`.
  18. ///
  19. /// This is the kernel's version of the Rust stdlib's `Box`. There are several differences,
  20. /// for example no `noalias` attribute is emitted and partially moving out of a `Box` is not
  21. /// supported. There are also several API differences, e.g. `Box` always requires an [`Allocator`]
  22. /// implementation to be passed as generic, page [`Flags`] when allocating memory and all functions
  23. /// that may allocate memory are fallible.
  24. ///
  25. /// `Box` works with any of the kernel's allocators, e.g. [`Kmalloc`], [`Vmalloc`] or [`KVmalloc`].
  26. /// There are aliases for `Box` with these allocators ([`KBox`], [`VBox`], [`KVBox`]).
  27. ///
  28. /// When dropping a [`Box`], the value is also dropped and the heap memory is automatically freed.
  29. ///
  30. /// # Examples
  31. ///
  32. /// ```
  33. /// let b = KBox::<u64>::new(24_u64, GFP_KERNEL)?;
  34. ///
  35. /// assert_eq!(*b, 24_u64);
  36. /// # Ok::<(), Error>(())
  37. /// ```
  38. ///
  39. /// ```
  40. /// # use kernel::bindings;
  41. /// const SIZE: usize = bindings::KMALLOC_MAX_SIZE as usize + 1;
  42. /// struct Huge([u8; SIZE]);
  43. ///
  44. /// assert!(KBox::<Huge>::new_uninit(GFP_KERNEL | __GFP_NOWARN).is_err());
  45. /// ```
  46. ///
  47. /// ```
  48. /// # use kernel::bindings;
  49. /// const SIZE: usize = bindings::KMALLOC_MAX_SIZE as usize + 1;
  50. /// struct Huge([u8; SIZE]);
  51. ///
  52. /// assert!(KVBox::<Huge>::new_uninit(GFP_KERNEL).is_ok());
  53. /// ```
  54. ///
  55. /// # Invariants
  56. ///
  57. /// `self.0` is always properly aligned and either points to memory allocated with `A` or, for
  58. /// zero-sized types, is a dangling, well aligned pointer.
  59. #[repr(transparent)]
  60. pub struct Box<T: ?Sized, A: Allocator>(NonNull<T>, PhantomData<A>);
  61. /// Type alias for [`Box`] with a [`Kmalloc`] allocator.
  62. ///
  63. /// # Examples
  64. ///
  65. /// ```
  66. /// let b = KBox::new(24_u64, GFP_KERNEL)?;
  67. ///
  68. /// assert_eq!(*b, 24_u64);
  69. /// # Ok::<(), Error>(())
  70. /// ```
  71. pub type KBox<T> = Box<T, super::allocator::Kmalloc>;
  72. /// Type alias for [`Box`] with a [`Vmalloc`] allocator.
  73. ///
  74. /// # Examples
  75. ///
  76. /// ```
  77. /// let b = VBox::new(24_u64, GFP_KERNEL)?;
  78. ///
  79. /// assert_eq!(*b, 24_u64);
  80. /// # Ok::<(), Error>(())
  81. /// ```
  82. pub type VBox<T> = Box<T, super::allocator::Vmalloc>;
  83. /// Type alias for [`Box`] with a [`KVmalloc`] allocator.
  84. ///
  85. /// # Examples
  86. ///
  87. /// ```
  88. /// let b = KVBox::new(24_u64, GFP_KERNEL)?;
  89. ///
  90. /// assert_eq!(*b, 24_u64);
  91. /// # Ok::<(), Error>(())
  92. /// ```
  93. pub type KVBox<T> = Box<T, super::allocator::KVmalloc>;
  94. // SAFETY: `Box` is `Send` if `T` is `Send` because the `Box` owns a `T`.
  95. unsafe impl<T, A> Send for Box<T, A>
  96. where
  97. T: Send + ?Sized,
  98. A: Allocator,
  99. {
  100. }
  101. // SAFETY: `Box` is `Sync` if `T` is `Sync` because the `Box` owns a `T`.
  102. unsafe impl<T, A> Sync for Box<T, A>
  103. where
  104. T: Sync + ?Sized,
  105. A: Allocator,
  106. {
  107. }
  108. impl<T, A> Box<T, A>
  109. where
  110. T: ?Sized,
  111. A: Allocator,
  112. {
  113. /// Creates a new `Box<T, A>` from a raw pointer.
  114. ///
  115. /// # Safety
  116. ///
  117. /// For non-ZSTs, `raw` must point at an allocation allocated with `A` that is sufficiently
  118. /// aligned for and holds a valid `T`. The caller passes ownership of the allocation to the
  119. /// `Box`.
  120. ///
  121. /// For ZSTs, `raw` must be a dangling, well aligned pointer.
  122. #[inline]
  123. pub const unsafe fn from_raw(raw: *mut T) -> Self {
  124. // INVARIANT: Validity of `raw` is guaranteed by the safety preconditions of this function.
  125. // SAFETY: By the safety preconditions of this function, `raw` is not a NULL pointer.
  126. Self(unsafe { NonNull::new_unchecked(raw) }, PhantomData)
  127. }
  128. /// Consumes the `Box<T, A>` and returns a raw pointer.
  129. ///
  130. /// This will not run the destructor of `T` and for non-ZSTs the allocation will stay alive
  131. /// indefinitely. Use [`Box::from_raw`] to recover the [`Box`], drop the value and free the
  132. /// allocation, if any.
  133. ///
  134. /// # Examples
  135. ///
  136. /// ```
  137. /// let x = KBox::new(24, GFP_KERNEL)?;
  138. /// let ptr = KBox::into_raw(x);
  139. /// // SAFETY: `ptr` comes from a previous call to `KBox::into_raw`.
  140. /// let x = unsafe { KBox::from_raw(ptr) };
  141. ///
  142. /// assert_eq!(*x, 24);
  143. /// # Ok::<(), Error>(())
  144. /// ```
  145. #[inline]
  146. pub fn into_raw(b: Self) -> *mut T {
  147. ManuallyDrop::new(b).0.as_ptr()
  148. }
  149. /// Consumes and leaks the `Box<T, A>` and returns a mutable reference.
  150. ///
  151. /// See [`Box::into_raw`] for more details.
  152. #[inline]
  153. pub fn leak<'a>(b: Self) -> &'a mut T {
  154. // SAFETY: `Box::into_raw` always returns a properly aligned and dereferenceable pointer
  155. // which points to an initialized instance of `T`.
  156. unsafe { &mut *Box::into_raw(b) }
  157. }
  158. }
  159. impl<T, A> Box<MaybeUninit<T>, A>
  160. where
  161. A: Allocator,
  162. {
  163. /// Converts a `Box<MaybeUninit<T>, A>` to a `Box<T, A>`.
  164. ///
  165. /// It is undefined behavior to call this function while the value inside of `b` is not yet
  166. /// fully initialized.
  167. ///
  168. /// # Safety
  169. ///
  170. /// Callers must ensure that the value inside of `b` is in an initialized state.
  171. pub unsafe fn assume_init(self) -> Box<T, A> {
  172. let raw = Self::into_raw(self);
  173. // SAFETY: `raw` comes from a previous call to `Box::into_raw`. By the safety requirements
  174. // of this function, the value inside the `Box` is in an initialized state. Hence, it is
  175. // safe to reconstruct the `Box` as `Box<T, A>`.
  176. unsafe { Box::from_raw(raw.cast()) }
  177. }
  178. /// Writes the value and converts to `Box<T, A>`.
  179. pub fn write(mut self, value: T) -> Box<T, A> {
  180. (*self).write(value);
  181. // SAFETY: We've just initialized `b`'s value.
  182. unsafe { self.assume_init() }
  183. }
  184. }
  185. impl<T, A> Box<T, A>
  186. where
  187. A: Allocator,
  188. {
  189. /// Creates a new `Box<T, A>` and initializes its contents with `x`.
  190. ///
  191. /// New memory is allocated with `A`. The allocation may fail, in which case an error is
  192. /// returned. For ZSTs no memory is allocated.
  193. pub fn new(x: T, flags: Flags) -> Result<Self, AllocError> {
  194. let b = Self::new_uninit(flags)?;
  195. Ok(Box::write(b, x))
  196. }
  197. /// Creates a new `Box<T, A>` with uninitialized contents.
  198. ///
  199. /// New memory is allocated with `A`. The allocation may fail, in which case an error is
  200. /// returned. For ZSTs no memory is allocated.
  201. ///
  202. /// # Examples
  203. ///
  204. /// ```
  205. /// let b = KBox::<u64>::new_uninit(GFP_KERNEL)?;
  206. /// let b = KBox::write(b, 24);
  207. ///
  208. /// assert_eq!(*b, 24_u64);
  209. /// # Ok::<(), Error>(())
  210. /// ```
  211. pub fn new_uninit(flags: Flags) -> Result<Box<MaybeUninit<T>, A>, AllocError> {
  212. let layout = Layout::new::<MaybeUninit<T>>();
  213. let ptr = A::alloc(layout, flags)?;
  214. // INVARIANT: `ptr` is either a dangling pointer or points to memory allocated with `A`,
  215. // which is sufficient in size and alignment for storing a `T`.
  216. Ok(Box(ptr.cast(), PhantomData))
  217. }
  218. /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then `x` will be
  219. /// pinned in memory and can't be moved.
  220. #[inline]
  221. pub fn pin(x: T, flags: Flags) -> Result<Pin<Box<T, A>>, AllocError>
  222. where
  223. A: 'static,
  224. {
  225. Ok(Self::new(x, flags)?.into())
  226. }
  227. /// Forgets the contents (does not run the destructor), but keeps the allocation.
  228. fn forget_contents(this: Self) -> Box<MaybeUninit<T>, A> {
  229. let ptr = Self::into_raw(this);
  230. // SAFETY: `ptr` is valid, because it came from `Box::into_raw`.
  231. unsafe { Box::from_raw(ptr.cast()) }
  232. }
  233. /// Drops the contents, but keeps the allocation.
  234. ///
  235. /// # Examples
  236. ///
  237. /// ```
  238. /// let value = KBox::new([0; 32], GFP_KERNEL)?;
  239. /// assert_eq!(*value, [0; 32]);
  240. /// let value = KBox::drop_contents(value);
  241. /// // Now we can re-use `value`:
  242. /// let value = KBox::write(value, [1; 32]);
  243. /// assert_eq!(*value, [1; 32]);
  244. /// # Ok::<(), Error>(())
  245. /// ```
  246. pub fn drop_contents(this: Self) -> Box<MaybeUninit<T>, A> {
  247. let ptr = this.0.as_ptr();
  248. // SAFETY: `ptr` is valid, because it came from `this`. After this call we never access the
  249. // value stored in `this` again.
  250. unsafe { core::ptr::drop_in_place(ptr) };
  251. Self::forget_contents(this)
  252. }
  253. /// Moves the `Box`'s value out of the `Box` and consumes the `Box`.
  254. pub fn into_inner(b: Self) -> T {
  255. // SAFETY: By the type invariant `&*b` is valid for `read`.
  256. let value = unsafe { core::ptr::read(&*b) };
  257. let _ = Self::forget_contents(b);
  258. value
  259. }
  260. }
  261. impl<T, A> From<Box<T, A>> for Pin<Box<T, A>>
  262. where
  263. T: ?Sized,
  264. A: Allocator,
  265. {
  266. /// Converts a `Box<T, A>` into a `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then
  267. /// `*b` will be pinned in memory and can't be moved.
  268. ///
  269. /// This moves `b` into `Pin` without moving `*b` or allocating and copying any memory.
  270. fn from(b: Box<T, A>) -> Self {
  271. // SAFETY: The value wrapped inside a `Pin<Box<T, A>>` cannot be moved or replaced as long
  272. // as `T` does not implement `Unpin`.
  273. unsafe { Pin::new_unchecked(b) }
  274. }
  275. }
  276. impl<T, A> InPlaceWrite<T> for Box<MaybeUninit<T>, A>
  277. where
  278. A: Allocator + 'static,
  279. {
  280. type Initialized = Box<T, A>;
  281. fn write_init<E>(mut self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
  282. let slot = self.as_mut_ptr();
  283. // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
  284. // slot is valid.
  285. unsafe { init.__init(slot)? };
  286. // SAFETY: All fields have been initialized.
  287. Ok(unsafe { Box::assume_init(self) })
  288. }
  289. fn write_pin_init<E>(mut self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
  290. let slot = self.as_mut_ptr();
  291. // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
  292. // slot is valid and will not be moved, because we pin it later.
  293. unsafe { init.__pinned_init(slot)? };
  294. // SAFETY: All fields have been initialized.
  295. Ok(unsafe { Box::assume_init(self) }.into())
  296. }
  297. }
  298. impl<T, A> InPlaceInit<T> for Box<T, A>
  299. where
  300. A: Allocator + 'static,
  301. {
  302. type PinnedSelf = Pin<Self>;
  303. #[inline]
  304. fn try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Pin<Self>, E>
  305. where
  306. E: From<AllocError>,
  307. {
  308. Box::<_, A>::new_uninit(flags)?.write_pin_init(init)
  309. }
  310. #[inline]
  311. fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>
  312. where
  313. E: From<AllocError>,
  314. {
  315. Box::<_, A>::new_uninit(flags)?.write_init(init)
  316. }
  317. }
  318. impl<T: 'static, A> ForeignOwnable for Box<T, A>
  319. where
  320. A: Allocator,
  321. {
  322. type Borrowed<'a> = &'a T;
  323. fn into_foreign(self) -> *const crate::ffi::c_void {
  324. Box::into_raw(self) as _
  325. }
  326. unsafe fn from_foreign(ptr: *const crate::ffi::c_void) -> Self {
  327. // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
  328. // call to `Self::into_foreign`.
  329. unsafe { Box::from_raw(ptr as _) }
  330. }
  331. unsafe fn borrow<'a>(ptr: *const crate::ffi::c_void) -> &'a T {
  332. // SAFETY: The safety requirements of this method ensure that the object remains alive and
  333. // immutable for the duration of 'a.
  334. unsafe { &*ptr.cast() }
  335. }
  336. }
  337. impl<T: 'static, A> ForeignOwnable for Pin<Box<T, A>>
  338. where
  339. A: Allocator,
  340. {
  341. type Borrowed<'a> = Pin<&'a T>;
  342. fn into_foreign(self) -> *const crate::ffi::c_void {
  343. // SAFETY: We are still treating the box as pinned.
  344. Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _
  345. }
  346. unsafe fn from_foreign(ptr: *const crate::ffi::c_void) -> Self {
  347. // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
  348. // call to `Self::into_foreign`.
  349. unsafe { Pin::new_unchecked(Box::from_raw(ptr as _)) }
  350. }
  351. unsafe fn borrow<'a>(ptr: *const crate::ffi::c_void) -> Pin<&'a T> {
  352. // SAFETY: The safety requirements for this function ensure that the object is still alive,
  353. // so it is safe to dereference the raw pointer.
  354. // The safety requirements of `from_foreign` also ensure that the object remains alive for
  355. // the lifetime of the returned value.
  356. let r = unsafe { &*ptr.cast() };
  357. // SAFETY: This pointer originates from a `Pin<Box<T>>`.
  358. unsafe { Pin::new_unchecked(r) }
  359. }
  360. }
  361. impl<T, A> Deref for Box<T, A>
  362. where
  363. T: ?Sized,
  364. A: Allocator,
  365. {
  366. type Target = T;
  367. fn deref(&self) -> &T {
  368. // SAFETY: `self.0` is always properly aligned, dereferenceable and points to an initialized
  369. // instance of `T`.
  370. unsafe { self.0.as_ref() }
  371. }
  372. }
  373. impl<T, A> DerefMut for Box<T, A>
  374. where
  375. T: ?Sized,
  376. A: Allocator,
  377. {
  378. fn deref_mut(&mut self) -> &mut T {
  379. // SAFETY: `self.0` is always properly aligned, dereferenceable and points to an initialized
  380. // instance of `T`.
  381. unsafe { self.0.as_mut() }
  382. }
  383. }
  384. impl<T, A> fmt::Debug for Box<T, A>
  385. where
  386. T: ?Sized + fmt::Debug,
  387. A: Allocator,
  388. {
  389. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  390. fmt::Debug::fmt(&**self, f)
  391. }
  392. }
  393. impl<T, A> Drop for Box<T, A>
  394. where
  395. T: ?Sized,
  396. A: Allocator,
  397. {
  398. fn drop(&mut self) {
  399. let layout = Layout::for_value::<T>(self);
  400. // SAFETY: The pointer in `self.0` is guaranteed to be valid by the type invariant.
  401. unsafe { core::ptr::drop_in_place::<T>(self.deref_mut()) };
  402. // SAFETY:
  403. // - `self.0` was previously allocated with `A`.
  404. // - `layout` is equal to the `Layout´ `self.0` was allocated with.
  405. unsafe { A::free(self.0.cast(), layout) };
  406. }
  407. }