kernel/alloc/kbox.rs
1// SPDX-License-Identifier: GPL-2.0
2
3//! Implementation of [`Box`].
4
5#[allow(unused_imports)] // Used in doc comments.
6use super::allocator::{KVmalloc, Kmalloc, Vmalloc, VmallocPageIter};
7use super::{AllocError, Allocator, Flags, NumaNode};
8use core::alloc::Layout;
9use core::borrow::{Borrow, BorrowMut};
10use core::marker::PhantomData;
11use core::mem::ManuallyDrop;
12use core::mem::MaybeUninit;
13use core::ops::{Deref, DerefMut};
14use core::pin::Pin;
15use core::ptr::NonNull;
16use core::result::Result;
17
18use crate::ffi::c_void;
19use crate::fmt;
20use crate::init::InPlaceInit;
21use crate::page::AsPageIter;
22use crate::types::ForeignOwnable;
23use pin_init::{InPlaceWrite, Init, PinInit, ZeroableOption};
24use safety_macro::safety;
25/// The kernel's [`Box`] type -- a heap allocation for a single value of type `T`.
26///
27/// This is the kernel's version of the Rust stdlib's `Box`. There are several differences,
28/// for example no `noalias` attribute is emitted and partially moving out of a `Box` is not
29/// supported. There are also several API differences, e.g. `Box` always requires an [`Allocator`]
30/// implementation to be passed as generic, page [`Flags`] when allocating memory and all functions
31/// that may allocate memory are fallible.
32///
33/// `Box` works with any of the kernel's allocators, e.g. [`Kmalloc`], [`Vmalloc`] or [`KVmalloc`].
34/// There are aliases for `Box` with these allocators ([`KBox`], [`VBox`], [`KVBox`]).
35///
36/// When dropping a [`Box`], the value is also dropped and the heap memory is automatically freed.
37///
38/// # Examples
39///
40/// ```
41/// let b = KBox::<u64>::new(24_u64, GFP_KERNEL)?;
42///
43/// assert_eq!(*b, 24_u64);
44/// # Ok::<(), Error>(())
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!(KBox::<Huge>::new_uninit(GFP_KERNEL | __GFP_NOWARN).is_err());
53/// ```
54///
55/// ```
56/// # use kernel::bindings;
57/// const SIZE: usize = bindings::KMALLOC_MAX_SIZE as usize + 1;
58/// struct Huge([u8; SIZE]);
59///
60/// assert!(KVBox::<Huge>::new_uninit(GFP_KERNEL).is_ok());
61/// ```
62///
63/// [`Box`]es can also be used to store trait objects by coercing their type:
64///
65/// ```
66/// trait FooTrait {}
67///
68/// struct FooStruct;
69/// impl FooTrait for FooStruct {}
70///
71/// let _ = KBox::new(FooStruct, GFP_KERNEL)? as KBox<dyn FooTrait>;
72/// # Ok::<(), Error>(())
73/// ```
74///
75/// # Invariants
76///
77/// `self.0` is always properly aligned and either points to memory allocated with `A` or, for
78/// zero-sized types, is a dangling, well aligned pointer.
79#[repr(transparent)]
80#[cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, derive(core::marker::CoercePointee))]
81pub struct Box<#[cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, pointee)] T: ?Sized, A: Allocator>(
82 NonNull<T>,
83 PhantomData<A>,
84);
85
86// This is to allow coercion from `Box<T, A>` to `Box<U, A>` if `T` can be converted to the
87// dynamically-sized type (DST) `U`.
88#[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))]
89impl<T, U, A> core::ops::CoerceUnsized<Box<U, A>> for Box<T, A>
90where
91 T: ?Sized + core::marker::Unsize<U>,
92 U: ?Sized,
93 A: Allocator,
94{
95}
96
97// This is to allow `Box<U, A>` to be dispatched on when `Box<T, A>` can be coerced into `Box<U,
98// A>`.
99#[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))]
100impl<T, U, A> core::ops::DispatchFromDyn<Box<U, A>> for Box<T, A>
101where
102 T: ?Sized + core::marker::Unsize<U>,
103 U: ?Sized,
104 A: Allocator,
105{
106}
107
108/// Type alias for [`Box`] with a [`Kmalloc`] allocator.
109///
110/// # Examples
111///
112/// ```
113/// let b = KBox::new(24_u64, GFP_KERNEL)?;
114///
115/// assert_eq!(*b, 24_u64);
116/// # Ok::<(), Error>(())
117/// ```
118pub type KBox<T> = Box<T, super::allocator::Kmalloc>;
119
120/// Type alias for [`Box`] with a [`Vmalloc`] allocator.
121///
122/// # Examples
123///
124/// ```
125/// let b = VBox::new(24_u64, GFP_KERNEL)?;
126///
127/// assert_eq!(*b, 24_u64);
128/// # Ok::<(), Error>(())
129/// ```
130pub type VBox<T> = Box<T, super::allocator::Vmalloc>;
131
132/// Type alias for [`Box`] with a [`KVmalloc`] allocator.
133///
134/// # Examples
135///
136/// ```
137/// let b = KVBox::new(24_u64, GFP_KERNEL)?;
138///
139/// assert_eq!(*b, 24_u64);
140/// # Ok::<(), Error>(())
141/// ```
142pub type KVBox<T> = Box<T, super::allocator::KVmalloc>;
143
144// SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee:
145// <https://doc.rust-lang.org/stable/std/option/index.html#representation>).
146unsafe impl<T, A: Allocator> ZeroableOption for Box<T, A> {}
147
148// SAFETY: `Box` is `Send` if `T` is `Send` because the `Box` owns a `T`.
149unsafe impl<T, A> Send for Box<T, A>
150where
151 T: Send + ?Sized,
152 A: Allocator,
153{
154}
155
156// SAFETY: `Box` is `Sync` if `T` is `Sync` because the `Box` owns a `T`.
157unsafe impl<T, A> Sync for Box<T, A>
158where
159 T: Sync + ?Sized,
160 A: Allocator,
161{
162}
163
164impl<T, A> Box<T, A>
165where
166 T: ?Sized,
167 A: Allocator,
168{
169 /// Creates a new `Box<T, A>` from a raw pointer.
170 ///
171 /// # Safety
172 ///
173 /// For non-ZSTs, `raw` must point at an allocation allocated with `A` that is sufficiently
174 /// aligned for and holds a valid `T`. The caller passes ownership of the allocation to the
175 /// `Box`.
176 ///
177 /// For ZSTs, `raw` must be a dangling, well aligned pointer.
178 #[safety{ValidPtr, Allocated, Align}]
179 #[inline]
180 pub const unsafe fn from_raw(raw: *mut T) -> Self {
181 // INVARIANT: Validity of `raw` is guaranteed by the safety preconditions of this function.
182 // SAFETY: By the safety preconditions of this function, `raw` is not a NULL pointer.
183 Self(unsafe { NonNull::new_unchecked(raw) }, PhantomData)
184 }
185
186 /// Consumes the `Box<T, A>` and returns a raw pointer.
187 ///
188 /// This will not run the destructor of `T` and for non-ZSTs the allocation will stay alive
189 /// indefinitely. Use [`Box::from_raw`] to recover the [`Box`], drop the value and free the
190 /// allocation, if any.
191 ///
192 /// # Examples
193 ///
194 /// ```
195 /// let x = KBox::new(24, GFP_KERNEL)?;
196 /// let ptr = KBox::into_raw(x);
197 /// // SAFETY: `ptr` comes from a previous call to `KBox::into_raw`.
198 /// let x = unsafe { KBox::from_raw(ptr) };
199 ///
200 /// assert_eq!(*x, 24);
201 /// # Ok::<(), Error>(())
202 /// ```
203 #[inline]
204 pub fn into_raw(b: Self) -> *mut T {
205 ManuallyDrop::new(b).0.as_ptr()
206 }
207
208 /// Consumes and leaks the `Box<T, A>` and returns a mutable reference.
209 ///
210 /// See [`Box::into_raw`] for more details.
211 #[inline]
212 pub fn leak<'a>(b: Self) -> &'a mut T {
213 // SAFETY: `Box::into_raw` always returns a properly aligned and dereferenceable pointer
214 // which points to an initialized instance of `T`.
215 unsafe { &mut *Box::into_raw(b) }
216 }
217}
218
219impl<T, A> Box<MaybeUninit<T>, A>
220where
221 A: Allocator,
222{
223 /// Converts a `Box<MaybeUninit<T>, A>` to a `Box<T, A>`.
224 ///
225 /// It is undefined behavior to call this function while the value inside of `b` is not yet
226 /// fully initialized.
227 ///
228 /// # Safety
229 ///
230 /// Callers must ensure that the value inside of `b` is in an initialized state.
231 #[safety{Init}]
232 pub unsafe fn assume_init(self) -> Box<T, A> {
233 let raw = Self::into_raw(self);
234
235 // SAFETY: `raw` comes from a previous call to `Box::into_raw`. By the safety requirements
236 // of this function, the value inside the `Box` is in an initialized state. Hence, it is
237 // safe to reconstruct the `Box` as `Box<T, A>`.
238 unsafe { Box::from_raw(raw.cast()) }
239 }
240
241 /// Writes the value and converts to `Box<T, A>`.
242 pub fn write(mut self, value: T) -> Box<T, A> {
243 (*self).write(value);
244
245 // SAFETY: We've just initialized `b`'s value.
246 unsafe { self.assume_init() }
247 }
248}
249
250impl<T, A> Box<T, A>
251where
252 A: Allocator,
253{
254 /// Creates a new `Box<T, A>` and initializes its contents with `x`.
255 ///
256 /// New memory is allocated with `A`. The allocation may fail, in which case an error is
257 /// returned. For ZSTs no memory is allocated.
258 pub fn new(x: T, flags: Flags) -> Result<Self, AllocError> {
259 let b = Self::new_uninit(flags)?;
260 Ok(Box::write(b, x))
261 }
262
263 /// Creates a new `Box<T, A>` with uninitialized contents.
264 ///
265 /// New memory is allocated with `A`. The allocation may fail, in which case an error is
266 /// returned. For ZSTs no memory is allocated.
267 ///
268 /// # Examples
269 ///
270 /// ```
271 /// let b = KBox::<u64>::new_uninit(GFP_KERNEL)?;
272 /// let b = KBox::write(b, 24);
273 ///
274 /// assert_eq!(*b, 24_u64);
275 /// # Ok::<(), Error>(())
276 /// ```
277 pub fn new_uninit(flags: Flags) -> Result<Box<MaybeUninit<T>, A>, AllocError> {
278 let layout = Layout::new::<MaybeUninit<T>>();
279 let ptr = A::alloc(layout, flags, NumaNode::NO_NODE)?;
280
281 // INVARIANT: `ptr` is either a dangling pointer or points to memory allocated with `A`,
282 // which is sufficient in size and alignment for storing a `T`.
283 Ok(Box(ptr.cast(), PhantomData))
284 }
285
286 /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then `x` will be
287 /// pinned in memory and can't be moved.
288 #[inline]
289 pub fn pin(x: T, flags: Flags) -> Result<Pin<Box<T, A>>, AllocError>
290 where
291 A: 'static,
292 {
293 Ok(Self::new(x, flags)?.into())
294 }
295
296 /// Construct a pinned slice of elements `Pin<Box<[T], A>>`.
297 ///
298 /// This is a convenient means for creation of e.g. slices of structrures containing spinlocks
299 /// or mutexes.
300 ///
301 /// # Examples
302 ///
303 /// ```
304 /// use kernel::sync::{new_spinlock, SpinLock};
305 ///
306 /// struct Inner {
307 /// a: u32,
308 /// b: u32,
309 /// }
310 ///
311 /// #[pin_data]
312 /// struct Example {
313 /// c: u32,
314 /// #[pin]
315 /// d: SpinLock<Inner>,
316 /// }
317 ///
318 /// impl Example {
319 /// fn new() -> impl PinInit<Self, Error> {
320 /// try_pin_init!(Self {
321 /// c: 10,
322 /// d <- new_spinlock!(Inner { a: 20, b: 30 }),
323 /// })
324 /// }
325 /// }
326 ///
327 /// // Allocate a boxed slice of 10 `Example`s.
328 /// let s = KBox::pin_slice(
329 /// | _i | Example::new(),
330 /// 10,
331 /// GFP_KERNEL
332 /// )?;
333 ///
334 /// assert_eq!(s[5].c, 10);
335 /// assert_eq!(s[3].d.lock().a, 20);
336 /// # Ok::<(), Error>(())
337 /// ```
338 pub fn pin_slice<Func, Item, E>(
339 mut init: Func,
340 len: usize,
341 flags: Flags,
342 ) -> Result<Pin<Box<[T], A>>, E>
343 where
344 Func: FnMut(usize) -> Item,
345 Item: PinInit<T, E>,
346 E: From<AllocError>,
347 {
348 let mut buffer = super::Vec::<T, A>::with_capacity(len, flags)?;
349 for i in 0..len {
350 let ptr = buffer.spare_capacity_mut().as_mut_ptr().cast();
351 // SAFETY:
352 // - `ptr` is a valid pointer to uninitialized memory.
353 // - `ptr` is not used if an error is returned.
354 // - `ptr` won't be moved until it is dropped, i.e. it is pinned.
355 unsafe { init(i).__pinned_init(ptr)? };
356
357 // SAFETY:
358 // - `i + 1 <= len`, hence we don't exceed the capacity, due to the call to
359 // `with_capacity()` above.
360 // - The new value at index buffer.len() + 1 is the only element being added here, and
361 // it has been initialized above by `init(i).__pinned_init(ptr)`.
362 unsafe { buffer.inc_len(1) };
363 }
364
365 let (ptr, _, _) = buffer.into_raw_parts();
366 let slice = core::ptr::slice_from_raw_parts_mut(ptr, len);
367
368 // SAFETY: `slice` points to an allocation allocated with `A` (`buffer`) and holds a valid
369 // `[T]`.
370 Ok(Pin::from(unsafe { Box::from_raw(slice) }))
371 }
372
373 /// Convert a [`Box<T,A>`] to a [`Pin<Box<T,A>>`]. If `T` does not implement
374 /// [`Unpin`], then `x` will be pinned in memory and can't be moved.
375 pub fn into_pin(this: Self) -> Pin<Self> {
376 this.into()
377 }
378
379 /// Forgets the contents (does not run the destructor), but keeps the allocation.
380 fn forget_contents(this: Self) -> Box<MaybeUninit<T>, A> {
381 let ptr = Self::into_raw(this);
382
383 // SAFETY: `ptr` is valid, because it came from `Box::into_raw`.
384 unsafe { Box::from_raw(ptr.cast()) }
385 }
386
387 /// Drops the contents, but keeps the allocation.
388 ///
389 /// # Examples
390 ///
391 /// ```
392 /// let value = KBox::new([0; 32], GFP_KERNEL)?;
393 /// assert_eq!(*value, [0; 32]);
394 /// let value = KBox::drop_contents(value);
395 /// // Now we can re-use `value`:
396 /// let value = KBox::write(value, [1; 32]);
397 /// assert_eq!(*value, [1; 32]);
398 /// # Ok::<(), Error>(())
399 /// ```
400 pub fn drop_contents(this: Self) -> Box<MaybeUninit<T>, A> {
401 let ptr = this.0.as_ptr();
402
403 // SAFETY: `ptr` is valid, because it came from `this`. After this call we never access the
404 // value stored in `this` again.
405 unsafe { core::ptr::drop_in_place(ptr) };
406
407 Self::forget_contents(this)
408 }
409
410 /// Moves the `Box`'s value out of the `Box` and consumes the `Box`.
411 pub fn into_inner(b: Self) -> T {
412 // SAFETY: By the type invariant `&*b` is valid for `read`.
413 let value = unsafe { core::ptr::read(&*b) };
414 let _ = Self::forget_contents(b);
415 value
416 }
417}
418
419impl<T, A> From<Box<T, A>> for Pin<Box<T, A>>
420where
421 T: ?Sized,
422 A: Allocator,
423{
424 /// Converts a `Box<T, A>` into a `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then
425 /// `*b` will be pinned in memory and can't be moved.
426 ///
427 /// This moves `b` into `Pin` without moving `*b` or allocating and copying any memory.
428 fn from(b: Box<T, A>) -> Self {
429 // SAFETY: The value wrapped inside a `Pin<Box<T, A>>` cannot be moved or replaced as long
430 // as `T` does not implement `Unpin`.
431 unsafe { Pin::new_unchecked(b) }
432 }
433}
434
435impl<T, A> InPlaceWrite<T> for Box<MaybeUninit<T>, A>
436where
437 A: Allocator + 'static,
438{
439 type Initialized = Box<T, A>;
440
441 fn write_init<E>(mut self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
442 let slot = self.as_mut_ptr();
443 // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
444 // slot is valid.
445 unsafe { init.__init(slot)? };
446 // SAFETY: All fields have been initialized.
447 Ok(unsafe { Box::assume_init(self) })
448 }
449
450 fn write_pin_init<E>(mut self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
451 let slot = self.as_mut_ptr();
452 // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
453 // slot is valid and will not be moved, because we pin it later.
454 unsafe { init.__pinned_init(slot)? };
455 // SAFETY: All fields have been initialized.
456 Ok(unsafe { Box::assume_init(self) }.into())
457 }
458}
459
460impl<T, A> InPlaceInit<T> for Box<T, A>
461where
462 A: Allocator + 'static,
463{
464 type PinnedSelf = Pin<Self>;
465
466 #[inline]
467 fn try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Pin<Self>, E>
468 where
469 E: From<AllocError>,
470 {
471 Box::<_, A>::new_uninit(flags)?.write_pin_init(init)
472 }
473
474 #[inline]
475 fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>
476 where
477 E: From<AllocError>,
478 {
479 Box::<_, A>::new_uninit(flags)?.write_init(init)
480 }
481}
482
483// SAFETY: The pointer returned by `into_foreign` comes from a well aligned
484// pointer to `T` allocated by `A`.
485unsafe impl<T: 'static, A> ForeignOwnable for Box<T, A>
486where
487 A: Allocator,
488{
489 const FOREIGN_ALIGN: usize = if core::mem::align_of::<T>() < A::MIN_ALIGN {
490 A::MIN_ALIGN
491 } else {
492 core::mem::align_of::<T>()
493 };
494
495 type Borrowed<'a> = &'a T;
496 type BorrowedMut<'a> = &'a mut T;
497
498 fn into_foreign(self) -> *mut c_void {
499 Box::into_raw(self).cast()
500 }
501
502 unsafe fn from_foreign(ptr: *mut c_void) -> Self {
503 // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
504 // call to `Self::into_foreign`.
505 unsafe { Box::from_raw(ptr.cast()) }
506 }
507
508 unsafe fn borrow<'a>(ptr: *mut c_void) -> &'a T {
509 // SAFETY: The safety requirements of this method ensure that the object remains alive and
510 // immutable for the duration of 'a.
511 unsafe { &*ptr.cast() }
512 }
513
514 unsafe fn borrow_mut<'a>(ptr: *mut c_void) -> &'a mut T {
515 let ptr = ptr.cast();
516 // SAFETY: The safety requirements of this method ensure that the pointer is valid and that
517 // nothing else will access the value for the duration of 'a.
518 unsafe { &mut *ptr }
519 }
520}
521
522// SAFETY: The pointer returned by `into_foreign` comes from a well aligned
523// pointer to `T` allocated by `A`.
524unsafe impl<T: 'static, A> ForeignOwnable for Pin<Box<T, A>>
525where
526 A: Allocator,
527{
528 const FOREIGN_ALIGN: usize = <Box<T, A> as ForeignOwnable>::FOREIGN_ALIGN;
529 type Borrowed<'a> = Pin<&'a T>;
530 type BorrowedMut<'a> = Pin<&'a mut T>;
531
532 fn into_foreign(self) -> *mut c_void {
533 // SAFETY: We are still treating the box as pinned.
534 Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }).cast()
535 }
536
537 unsafe fn from_foreign(ptr: *mut c_void) -> Self {
538 // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
539 // call to `Self::into_foreign`.
540 unsafe { Pin::new_unchecked(Box::from_raw(ptr.cast())) }
541 }
542
543 unsafe fn borrow<'a>(ptr: *mut c_void) -> Pin<&'a T> {
544 // SAFETY: The safety requirements for this function ensure that the object is still alive,
545 // so it is safe to dereference the raw pointer.
546 // The safety requirements of `from_foreign` also ensure that the object remains alive for
547 // the lifetime of the returned value.
548 let r = unsafe { &*ptr.cast() };
549
550 // SAFETY: This pointer originates from a `Pin<Box<T>>`.
551 unsafe { Pin::new_unchecked(r) }
552 }
553
554 unsafe fn borrow_mut<'a>(ptr: *mut c_void) -> Pin<&'a mut T> {
555 let ptr = ptr.cast();
556 // SAFETY: The safety requirements for this function ensure that the object is still alive,
557 // so it is safe to dereference the raw pointer.
558 // The safety requirements of `from_foreign` also ensure that the object remains alive for
559 // the lifetime of the returned value.
560 let r = unsafe { &mut *ptr };
561
562 // SAFETY: This pointer originates from a `Pin<Box<T>>`.
563 unsafe { Pin::new_unchecked(r) }
564 }
565}
566
567impl<T, A> Deref for Box<T, A>
568where
569 T: ?Sized,
570 A: Allocator,
571{
572 type Target = T;
573
574 fn deref(&self) -> &T {
575 // SAFETY: `self.0` is always properly aligned, dereferenceable and points to an initialized
576 // instance of `T`.
577 unsafe { self.0.as_ref() }
578 }
579}
580
581impl<T, A> DerefMut for Box<T, A>
582where
583 T: ?Sized,
584 A: Allocator,
585{
586 fn deref_mut(&mut self) -> &mut T {
587 // SAFETY: `self.0` is always properly aligned, dereferenceable and points to an initialized
588 // instance of `T`.
589 unsafe { self.0.as_mut() }
590 }
591}
592
593/// # Examples
594///
595/// ```
596/// # use core::borrow::Borrow;
597/// # use kernel::alloc::KBox;
598/// struct Foo<B: Borrow<u32>>(B);
599///
600/// // Owned instance.
601/// let owned = Foo(1);
602///
603/// // Owned instance using `KBox`.
604/// let owned_kbox = Foo(KBox::new(1, GFP_KERNEL)?);
605///
606/// let i = 1;
607/// // Borrowed from `i`.
608/// let borrowed = Foo(&i);
609/// # Ok::<(), Error>(())
610/// ```
611impl<T, A> Borrow<T> for Box<T, A>
612where
613 T: ?Sized,
614 A: Allocator,
615{
616 fn borrow(&self) -> &T {
617 self.deref()
618 }
619}
620
621/// # Examples
622///
623/// ```
624/// # use core::borrow::BorrowMut;
625/// # use kernel::alloc::KBox;
626/// struct Foo<B: BorrowMut<u32>>(B);
627///
628/// // Owned instance.
629/// let owned = Foo(1);
630///
631/// // Owned instance using `KBox`.
632/// let owned_kbox = Foo(KBox::new(1, GFP_KERNEL)?);
633///
634/// let mut i = 1;
635/// // Borrowed from `i`.
636/// let borrowed = Foo(&mut i);
637/// # Ok::<(), Error>(())
638/// ```
639impl<T, A> BorrowMut<T> for Box<T, A>
640where
641 T: ?Sized,
642 A: Allocator,
643{
644 fn borrow_mut(&mut self) -> &mut T {
645 self.deref_mut()
646 }
647}
648
649impl<T, A> fmt::Display for Box<T, A>
650where
651 T: ?Sized + fmt::Display,
652 A: Allocator,
653{
654 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
655 <T as fmt::Display>::fmt(&**self, f)
656 }
657}
658
659impl<T, A> fmt::Debug for Box<T, A>
660where
661 T: ?Sized + fmt::Debug,
662 A: Allocator,
663{
664 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
665 <T as fmt::Debug>::fmt(&**self, f)
666 }
667}
668
669impl<T, A> Drop for Box<T, A>
670where
671 T: ?Sized,
672 A: Allocator,
673{
674 fn drop(&mut self) {
675 let layout = Layout::for_value::<T>(self);
676
677 // SAFETY: The pointer in `self.0` is guaranteed to be valid by the type invariant.
678 unsafe { core::ptr::drop_in_place::<T>(self.deref_mut()) };
679
680 // SAFETY:
681 // - `self.0` was previously allocated with `A`.
682 // - `layout` is equal to the `Layout´ `self.0` was allocated with.
683 unsafe { A::free(self.0.cast(), layout) };
684 }
685}
686
687/// # Examples
688///
689/// ```
690/// # use kernel::prelude::*;
691/// use kernel::alloc::allocator::VmallocPageIter;
692/// use kernel::page::{AsPageIter, PAGE_SIZE};
693///
694/// let mut vbox = VBox::new((), GFP_KERNEL)?;
695///
696/// assert!(vbox.page_iter().next().is_none());
697///
698/// let mut vbox = VBox::<[u8; PAGE_SIZE]>::new_uninit(GFP_KERNEL)?;
699///
700/// let page = vbox.page_iter().next().expect("At least one page should be available.\n");
701///
702/// // SAFETY: There is no concurrent read or write to the same page.
703/// unsafe { page.fill_zero_raw(0, PAGE_SIZE)? };
704/// # Ok::<(), Error>(())
705/// ```
706impl<T> AsPageIter for VBox<T> {
707 type Iter<'a>
708 = VmallocPageIter<'a>
709 where
710 T: 'a;
711
712 fn page_iter(&mut self) -> Self::Iter<'_> {
713 let ptr = self.0.cast();
714 let size = core::mem::size_of::<T>();
715
716 // SAFETY:
717 // - `ptr` is a valid pointer to the beginning of a `Vmalloc` allocation.
718 // - `ptr` is guaranteed to be valid for the lifetime of `'a`.
719 // - `size` is the size of the `Vmalloc` allocation `ptr` points to.
720 unsafe { VmallocPageIter::new(ptr, size) }
721 }
722}