xref: /linux/rust/kernel/alloc/kbox.rs (revision 0c1f3fe9a5f899ac95114e68959a35454af1523d)
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, VmallocPageIter};
7 use super::{AllocError, Allocator, Flags};
8 use core::alloc::Layout;
9 use core::borrow::{Borrow, BorrowMut};
10 use core::fmt;
11 use core::marker::PhantomData;
12 use core::mem::ManuallyDrop;
13 use core::mem::MaybeUninit;
14 use core::ops::{Deref, DerefMut};
15 use core::pin::Pin;
16 use core::ptr::NonNull;
17 use core::result::Result;
18 
19 use crate::ffi::c_void;
20 use crate::init::InPlaceInit;
21 use crate::page::AsPageIter;
22 use crate::types::ForeignOwnable;
23 use pin_init::{InPlaceWrite, Init, PinInit, ZeroableOption};
24 
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))]
81 pub 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))]
89 impl<T, U, A> core::ops::CoerceUnsized<Box<U, A>> for Box<T, A>
90 where
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))]
100 impl<T, U, A> core::ops::DispatchFromDyn<Box<U, A>> for Box<T, A>
101 where
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 /// ```
118 pub 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 /// ```
130 pub 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 /// ```
142 pub 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>).
146 unsafe 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`.
149 unsafe impl<T, A> Send for Box<T, A>
150 where
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`.
157 unsafe impl<T, A> Sync for Box<T, A>
158 where
159     T: Sync + ?Sized,
160     A: Allocator,
161 {
162 }
163 
164 impl<T, A> Box<T, A>
165 where
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     #[inline]
179     pub const unsafe fn from_raw(raw: *mut T) -> Self {
180         // INVARIANT: Validity of `raw` is guaranteed by the safety preconditions of this function.
181         // SAFETY: By the safety preconditions of this function, `raw` is not a NULL pointer.
182         Self(unsafe { NonNull::new_unchecked(raw) }, PhantomData)
183     }
184 
185     /// Consumes the `Box<T, A>` and returns a raw pointer.
186     ///
187     /// This will not run the destructor of `T` and for non-ZSTs the allocation will stay alive
188     /// indefinitely. Use [`Box::from_raw`] to recover the [`Box`], drop the value and free the
189     /// allocation, if any.
190     ///
191     /// # Examples
192     ///
193     /// ```
194     /// let x = KBox::new(24, GFP_KERNEL)?;
195     /// let ptr = KBox::into_raw(x);
196     /// // SAFETY: `ptr` comes from a previous call to `KBox::into_raw`.
197     /// let x = unsafe { KBox::from_raw(ptr) };
198     ///
199     /// assert_eq!(*x, 24);
200     /// # Ok::<(), Error>(())
201     /// ```
202     #[inline]
203     pub fn into_raw(b: Self) -> *mut T {
204         ManuallyDrop::new(b).0.as_ptr()
205     }
206 
207     /// Consumes and leaks the `Box<T, A>` and returns a mutable reference.
208     ///
209     /// See [`Box::into_raw`] for more details.
210     #[inline]
211     pub fn leak<'a>(b: Self) -> &'a mut T {
212         // SAFETY: `Box::into_raw` always returns a properly aligned and dereferenceable pointer
213         // which points to an initialized instance of `T`.
214         unsafe { &mut *Box::into_raw(b) }
215     }
216 }
217 
218 impl<T, A> Box<MaybeUninit<T>, A>
219 where
220     A: Allocator,
221 {
222     /// Converts a `Box<MaybeUninit<T>, A>` to a `Box<T, A>`.
223     ///
224     /// It is undefined behavior to call this function while the value inside of `b` is not yet
225     /// fully initialized.
226     ///
227     /// # Safety
228     ///
229     /// Callers must ensure that the value inside of `b` is in an initialized state.
230     pub unsafe fn assume_init(self) -> Box<T, A> {
231         let raw = Self::into_raw(self);
232 
233         // SAFETY: `raw` comes from a previous call to `Box::into_raw`. By the safety requirements
234         // of this function, the value inside the `Box` is in an initialized state. Hence, it is
235         // safe to reconstruct the `Box` as `Box<T, A>`.
236         unsafe { Box::from_raw(raw.cast()) }
237     }
238 
239     /// Writes the value and converts to `Box<T, A>`.
240     pub fn write(mut self, value: T) -> Box<T, A> {
241         (*self).write(value);
242 
243         // SAFETY: We've just initialized `b`'s value.
244         unsafe { self.assume_init() }
245     }
246 }
247 
248 impl<T, A> Box<T, A>
249 where
250     A: Allocator,
251 {
252     /// Creates a new `Box<T, A>` and initializes its contents with `x`.
253     ///
254     /// New memory is allocated with `A`. The allocation may fail, in which case an error is
255     /// returned. For ZSTs no memory is allocated.
256     pub fn new(x: T, flags: Flags) -> Result<Self, AllocError> {
257         let b = Self::new_uninit(flags)?;
258         Ok(Box::write(b, x))
259     }
260 
261     /// Creates a new `Box<T, A>` with uninitialized contents.
262     ///
263     /// New memory is allocated with `A`. The allocation may fail, in which case an error is
264     /// returned. For ZSTs no memory is allocated.
265     ///
266     /// # Examples
267     ///
268     /// ```
269     /// let b = KBox::<u64>::new_uninit(GFP_KERNEL)?;
270     /// let b = KBox::write(b, 24);
271     ///
272     /// assert_eq!(*b, 24_u64);
273     /// # Ok::<(), Error>(())
274     /// ```
275     pub fn new_uninit(flags: Flags) -> Result<Box<MaybeUninit<T>, A>, AllocError> {
276         let layout = Layout::new::<MaybeUninit<T>>();
277         let ptr = A::alloc(layout, flags)?;
278 
279         // INVARIANT: `ptr` is either a dangling pointer or points to memory allocated with `A`,
280         // which is sufficient in size and alignment for storing a `T`.
281         Ok(Box(ptr.cast(), PhantomData))
282     }
283 
284     /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then `x` will be
285     /// pinned in memory and can't be moved.
286     #[inline]
287     pub fn pin(x: T, flags: Flags) -> Result<Pin<Box<T, A>>, AllocError>
288     where
289         A: 'static,
290     {
291         Ok(Self::new(x, flags)?.into())
292     }
293 
294     /// Convert a [`Box<T,A>`] to a [`Pin<Box<T,A>>`]. If `T` does not implement
295     /// [`Unpin`], then `x` will be pinned in memory and can't be moved.
296     pub fn into_pin(this: Self) -> Pin<Self> {
297         this.into()
298     }
299 
300     /// Forgets the contents (does not run the destructor), but keeps the allocation.
301     fn forget_contents(this: Self) -> Box<MaybeUninit<T>, A> {
302         let ptr = Self::into_raw(this);
303 
304         // SAFETY: `ptr` is valid, because it came from `Box::into_raw`.
305         unsafe { Box::from_raw(ptr.cast()) }
306     }
307 
308     /// Drops the contents, but keeps the allocation.
309     ///
310     /// # Examples
311     ///
312     /// ```
313     /// let value = KBox::new([0; 32], GFP_KERNEL)?;
314     /// assert_eq!(*value, [0; 32]);
315     /// let value = KBox::drop_contents(value);
316     /// // Now we can re-use `value`:
317     /// let value = KBox::write(value, [1; 32]);
318     /// assert_eq!(*value, [1; 32]);
319     /// # Ok::<(), Error>(())
320     /// ```
321     pub fn drop_contents(this: Self) -> Box<MaybeUninit<T>, A> {
322         let ptr = this.0.as_ptr();
323 
324         // SAFETY: `ptr` is valid, because it came from `this`. After this call we never access the
325         // value stored in `this` again.
326         unsafe { core::ptr::drop_in_place(ptr) };
327 
328         Self::forget_contents(this)
329     }
330 
331     /// Moves the `Box`'s value out of the `Box` and consumes the `Box`.
332     pub fn into_inner(b: Self) -> T {
333         // SAFETY: By the type invariant `&*b` is valid for `read`.
334         let value = unsafe { core::ptr::read(&*b) };
335         let _ = Self::forget_contents(b);
336         value
337     }
338 }
339 
340 impl<T, A> From<Box<T, A>> for Pin<Box<T, A>>
341 where
342     T: ?Sized,
343     A: Allocator,
344 {
345     /// Converts a `Box<T, A>` into a `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then
346     /// `*b` will be pinned in memory and can't be moved.
347     ///
348     /// This moves `b` into `Pin` without moving `*b` or allocating and copying any memory.
349     fn from(b: Box<T, A>) -> Self {
350         // SAFETY: The value wrapped inside a `Pin<Box<T, A>>` cannot be moved or replaced as long
351         // as `T` does not implement `Unpin`.
352         unsafe { Pin::new_unchecked(b) }
353     }
354 }
355 
356 impl<T, A> InPlaceWrite<T> for Box<MaybeUninit<T>, A>
357 where
358     A: Allocator + 'static,
359 {
360     type Initialized = Box<T, A>;
361 
362     fn write_init<E>(mut self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
363         let slot = self.as_mut_ptr();
364         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
365         // slot is valid.
366         unsafe { init.__init(slot)? };
367         // SAFETY: All fields have been initialized.
368         Ok(unsafe { Box::assume_init(self) })
369     }
370 
371     fn write_pin_init<E>(mut self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
372         let slot = self.as_mut_ptr();
373         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
374         // slot is valid and will not be moved, because we pin it later.
375         unsafe { init.__pinned_init(slot)? };
376         // SAFETY: All fields have been initialized.
377         Ok(unsafe { Box::assume_init(self) }.into())
378     }
379 }
380 
381 impl<T, A> InPlaceInit<T> for Box<T, A>
382 where
383     A: Allocator + 'static,
384 {
385     type PinnedSelf = Pin<Self>;
386 
387     #[inline]
388     fn try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Pin<Self>, E>
389     where
390         E: From<AllocError>,
391     {
392         Box::<_, A>::new_uninit(flags)?.write_pin_init(init)
393     }
394 
395     #[inline]
396     fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>
397     where
398         E: From<AllocError>,
399     {
400         Box::<_, A>::new_uninit(flags)?.write_init(init)
401     }
402 }
403 
404 // SAFETY: The pointer returned by `into_foreign` comes from a well aligned
405 // pointer to `T`.
406 unsafe impl<T: 'static, A> ForeignOwnable for Box<T, A>
407 where
408     A: Allocator,
409 {
410     const FOREIGN_ALIGN: usize = core::mem::align_of::<T>();
411     type Borrowed<'a> = &'a T;
412     type BorrowedMut<'a> = &'a mut T;
413 
414     fn into_foreign(self) -> *mut c_void {
415         Box::into_raw(self).cast()
416     }
417 
418     unsafe fn from_foreign(ptr: *mut c_void) -> Self {
419         // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
420         // call to `Self::into_foreign`.
421         unsafe { Box::from_raw(ptr.cast()) }
422     }
423 
424     unsafe fn borrow<'a>(ptr: *mut c_void) -> &'a T {
425         // SAFETY: The safety requirements of this method ensure that the object remains alive and
426         // immutable for the duration of 'a.
427         unsafe { &*ptr.cast() }
428     }
429 
430     unsafe fn borrow_mut<'a>(ptr: *mut c_void) -> &'a mut T {
431         let ptr = ptr.cast();
432         // SAFETY: The safety requirements of this method ensure that the pointer is valid and that
433         // nothing else will access the value for the duration of 'a.
434         unsafe { &mut *ptr }
435     }
436 }
437 
438 // SAFETY: The pointer returned by `into_foreign` comes from a well aligned
439 // pointer to `T`.
440 unsafe impl<T: 'static, A> ForeignOwnable for Pin<Box<T, A>>
441 where
442     A: Allocator,
443 {
444     const FOREIGN_ALIGN: usize = core::mem::align_of::<T>();
445     type Borrowed<'a> = Pin<&'a T>;
446     type BorrowedMut<'a> = Pin<&'a mut T>;
447 
448     fn into_foreign(self) -> *mut c_void {
449         // SAFETY: We are still treating the box as pinned.
450         Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }).cast()
451     }
452 
453     unsafe fn from_foreign(ptr: *mut c_void) -> Self {
454         // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
455         // call to `Self::into_foreign`.
456         unsafe { Pin::new_unchecked(Box::from_raw(ptr.cast())) }
457     }
458 
459     unsafe fn borrow<'a>(ptr: *mut c_void) -> Pin<&'a T> {
460         // SAFETY: The safety requirements for this function ensure that the object is still alive,
461         // so it is safe to dereference the raw pointer.
462         // The safety requirements of `from_foreign` also ensure that the object remains alive for
463         // the lifetime of the returned value.
464         let r = unsafe { &*ptr.cast() };
465 
466         // SAFETY: This pointer originates from a `Pin<Box<T>>`.
467         unsafe { Pin::new_unchecked(r) }
468     }
469 
470     unsafe fn borrow_mut<'a>(ptr: *mut c_void) -> Pin<&'a mut T> {
471         let ptr = ptr.cast();
472         // SAFETY: The safety requirements for this function ensure that the object is still alive,
473         // so it is safe to dereference the raw pointer.
474         // The safety requirements of `from_foreign` also ensure that the object remains alive for
475         // the lifetime of the returned value.
476         let r = unsafe { &mut *ptr };
477 
478         // SAFETY: This pointer originates from a `Pin<Box<T>>`.
479         unsafe { Pin::new_unchecked(r) }
480     }
481 }
482 
483 impl<T, A> Deref for Box<T, A>
484 where
485     T: ?Sized,
486     A: Allocator,
487 {
488     type Target = T;
489 
490     fn deref(&self) -> &T {
491         // SAFETY: `self.0` is always properly aligned, dereferenceable and points to an initialized
492         // instance of `T`.
493         unsafe { self.0.as_ref() }
494     }
495 }
496 
497 impl<T, A> DerefMut for Box<T, A>
498 where
499     T: ?Sized,
500     A: Allocator,
501 {
502     fn deref_mut(&mut self) -> &mut T {
503         // SAFETY: `self.0` is always properly aligned, dereferenceable and points to an initialized
504         // instance of `T`.
505         unsafe { self.0.as_mut() }
506     }
507 }
508 
509 /// # Examples
510 ///
511 /// ```
512 /// # use core::borrow::Borrow;
513 /// # use kernel::alloc::KBox;
514 /// struct Foo<B: Borrow<u32>>(B);
515 ///
516 /// // Owned instance.
517 /// let owned = Foo(1);
518 ///
519 /// // Owned instance using `KBox`.
520 /// let owned_kbox = Foo(KBox::new(1, GFP_KERNEL)?);
521 ///
522 /// let i = 1;
523 /// // Borrowed from `i`.
524 /// let borrowed = Foo(&i);
525 /// # Ok::<(), Error>(())
526 /// ```
527 impl<T, A> Borrow<T> for Box<T, A>
528 where
529     T: ?Sized,
530     A: Allocator,
531 {
532     fn borrow(&self) -> &T {
533         self.deref()
534     }
535 }
536 
537 /// # Examples
538 ///
539 /// ```
540 /// # use core::borrow::BorrowMut;
541 /// # use kernel::alloc::KBox;
542 /// struct Foo<B: BorrowMut<u32>>(B);
543 ///
544 /// // Owned instance.
545 /// let owned = Foo(1);
546 ///
547 /// // Owned instance using `KBox`.
548 /// let owned_kbox = Foo(KBox::new(1, GFP_KERNEL)?);
549 ///
550 /// let mut i = 1;
551 /// // Borrowed from `i`.
552 /// let borrowed = Foo(&mut i);
553 /// # Ok::<(), Error>(())
554 /// ```
555 impl<T, A> BorrowMut<T> for Box<T, A>
556 where
557     T: ?Sized,
558     A: Allocator,
559 {
560     fn borrow_mut(&mut self) -> &mut T {
561         self.deref_mut()
562     }
563 }
564 
565 impl<T, A> fmt::Display for Box<T, A>
566 where
567     T: ?Sized + fmt::Display,
568     A: Allocator,
569 {
570     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571         <T as fmt::Display>::fmt(&**self, f)
572     }
573 }
574 
575 impl<T, A> fmt::Debug for Box<T, A>
576 where
577     T: ?Sized + fmt::Debug,
578     A: Allocator,
579 {
580     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
581         <T as fmt::Debug>::fmt(&**self, f)
582     }
583 }
584 
585 impl<T, A> Drop for Box<T, A>
586 where
587     T: ?Sized,
588     A: Allocator,
589 {
590     fn drop(&mut self) {
591         let layout = Layout::for_value::<T>(self);
592 
593         // SAFETY: The pointer in `self.0` is guaranteed to be valid by the type invariant.
594         unsafe { core::ptr::drop_in_place::<T>(self.deref_mut()) };
595 
596         // SAFETY:
597         // - `self.0` was previously allocated with `A`.
598         // - `layout` is equal to the `Layout´ `self.0` was allocated with.
599         unsafe { A::free(self.0.cast(), layout) };
600     }
601 }
602 
603 /// # Examples
604 ///
605 /// ```
606 /// # use kernel::prelude::*;
607 /// use kernel::alloc::allocator::VmallocPageIter;
608 /// use kernel::page::{AsPageIter, PAGE_SIZE};
609 ///
610 /// let mut vbox = VBox::new((), GFP_KERNEL)?;
611 ///
612 /// assert!(vbox.page_iter().next().is_none());
613 ///
614 /// let mut vbox = VBox::<[u8; PAGE_SIZE]>::new_uninit(GFP_KERNEL)?;
615 ///
616 /// let page = vbox.page_iter().next().expect("At least one page should be available.\n");
617 ///
618 /// // SAFETY: There is no concurrent read or write to the same page.
619 /// unsafe { page.fill_zero_raw(0, PAGE_SIZE)? };
620 /// # Ok::<(), Error>(())
621 /// ```
622 impl<T> AsPageIter for VBox<T> {
623     type Iter<'a>
624         = VmallocPageIter<'a>
625     where
626         T: 'a;
627 
628     fn page_iter(&mut self) -> Self::Iter<'_> {
629         let ptr = self.0.cast();
630         let size = core::mem::size_of::<T>();
631 
632         // SAFETY:
633         // - `ptr` is a valid pointer to the beginning of a `Vmalloc` allocation.
634         // - `ptr` is guaranteed to be valid for the lifetime of `'a`.
635         // - `size` is the size of the `Vmalloc` allocation `ptr` points to.
636         unsafe { VmallocPageIter::new(ptr, size) }
637     }
638 }
639