Re: [PATCH v2 1/3] rust: alloc: add Box::zeroed()

Alice Ryhl
2026-05-05T15:48:49Z

On Tue, May 05, 2026 at 05:23:07PM +0200, Danilo Krummrich wrote:
> Add Box::zeroed() for T: Zeroable types.
>
> This allocates with __GFP_ZERO directly, letting the underlying
> allocator deal with zeroing out the memory compared to
> Box::new(T::zeroed(), flags).
>
> Signed-off-by: Danilo Krummrich <dakr@kernel.org>

Reviewed-by: Alice Ryhl <aliceryhl@google.com>

> rust/kernel/alloc/kbox.rs | 22 ++++++++++++++++++++++
> 1 file changed, 22 insertions(+)
>
> diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs
> index bd6da02c7ab8..c824ed6e1523 100644
> --- a/rust/kernel/alloc/kbox.rs
> +++ b/rust/kernel/alloc/kbox.rs
> @@ -19,6 +19,7 @@
> use crate::fmt;
> use crate::init::InPlaceInit;
> use crate::page::AsPageIter;
> +use crate::prelude::*;
> use crate::types::ForeignOwnable;
> use pin_init::{InPlaceWrite, Init, PinInit, ZeroableOption};

I suspect some of these imports can be removed when you add the prelude.

> @@ -256,6 +257,27 @@ pub fn new_uninit(flags: Flags) -> Result<Box<MaybeUninit<T>, A>, AllocError> {
> Ok(Box(ptr.cast(), PhantomData))
> }
>
> + /// Creates a new zero-initialized `Box<T, A>`.
> + ///
> + /// New memory is allocated with `A` and the [`__GFP_ZERO`] flag. The allocation may fail, in
> + /// which case an error is returned. For ZSTs no memory is allocated.
> + ///
> + /// # Examples
> + ///
> + /// ```
> + /// let b = KBox::<[u8; 128]>::zeroed(GFP_KERNEL)?;
> + /// assert_eq!(*b, [0; 128]);
> + /// # Ok::<(), Error>(())
> + /// ```
> + pub fn zeroed(flags: Flags) -> Result<Self, AllocError>

#[inline]?

Alice