aboutsummaryrefslogtreecommitdiffstats
path: root/rust
diff options
authorDanilo Krummrich <dakr@kernel.org>2026-05-05 17:23:07 +0200
committerDanilo Krummrich <dakr@kernel.org>2026-05-11 15:26:12 +0200
commitabb21500e7e5dcf2d1b1a4a02b2ee77b3d5061b6 (patch)
tree45ae516218ee82565cbae488336e627efd009459 /rust
parent254f49634ee16a731174d2ae34bc50bd5f45e731 (diff)
downloadlinux-next-history-abb21500e7e5dcf2d1b1a4a02b2ee77b3d5061b6.tar.gz
rust: alloc: add Box::zeroed()
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). Reviewed-by: Alice Ryhl <aliceryhl@google.com> Link: https://patch.msgid.link/20260505152400.3905096-2-dakr@kernel.org Signed-off-by: Danilo Krummrich <dakr@kernel.org>
Diffstat (limited to 'rust')
-rw-r--r--rust/kernel/alloc/kbox.rs22
1 files changed, 22 insertions, 0 deletions
diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs
index bd6da02c7ab8f..c824ed6e15233 100644
--- a/rust/kernel/alloc/kbox.rs
+++ b/rust/kernel/alloc/kbox.rs
@@ -19,6 +19,7 @@ use crate::ffi::c_void;
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};
@@ -256,6 +257,27 @@ where
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>
+ where
+ T: Zeroable,
+ {
+ // SAFETY: `__GFP_ZERO` guarantees the memory is zeroed; `T: Zeroable` guarantees that
+ // all-zeroes is a valid bit pattern for `T`.
+ Ok(unsafe { Self::new_uninit(flags | __GFP_ZERO)?.assume_init() })
+ }
+
/// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then `x` will be
/// pinned in memory and can't be moved.
#[inline]