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