Skip to content

Commit 0fccd3a

Browse files
wedsonaffbq
authored andcommitted
rust: alloc: introduce the BoxExt trait
Make fallible versions of `new` and `new_uninit` methods available in `Box` even though it doesn't implement them because we build `alloc` with the `no_global_oom_handling` config. They also have an extra `flags` parameter that allows callers to pass flags to the allocator. Signed-off-by: Wedson Almeida Filho <[email protected]> Link: https://lore.kernel.org/r/[email protected]
1 parent ad4cb3a commit 0fccd3a

File tree

6 files changed

+72
-9
lines changed

6 files changed

+72
-9
lines changed

rust/kernel/alloc.rs

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#[cfg(not(test))]
66
#[cfg(not(testlib))]
77
mod allocator;
8+
pub mod box_ext;
89
pub mod vec_ext;
910

1011
/// Flags to be used when allocating memory.

rust/kernel/alloc/allocator.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ struct KernelAllocator;
1616
///
1717
/// - `ptr` can be either null or a pointer which has been allocated by this allocator.
1818
/// - `new_layout` must have a non-zero size.
19-
unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: Flags) -> *mut u8 {
19+
pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: Flags) -> *mut u8 {
2020
// Customized layouts from `Layout::from_size_align()` can have size < align, so pad first.
2121
let layout = new_layout.pad_to_align();
2222

rust/kernel/alloc/box_ext.rs

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! Extensions to [`Box`] for fallible allocations.
4+
5+
use super::Flags;
6+
use alloc::boxed::Box;
7+
use core::alloc::AllocError;
8+
use core::mem::MaybeUninit;
9+
use core::result::Result;
10+
11+
/// Extensions to [`Box`].
12+
pub trait BoxExt<T>: Sized {
13+
/// Allocates a new box.
14+
///
15+
/// The allocation may fail, in which case an error is returned.
16+
fn new(x: T, flags: Flags) -> Result<Self, AllocError>;
17+
18+
/// Allocates a new uninitialised box.
19+
///
20+
/// The allocation may fail, in which case an error is returned.
21+
fn new_uninit(flags: Flags) -> Result<Box<MaybeUninit<T>>, AllocError>;
22+
}
23+
24+
impl<T> BoxExt<T> for Box<T> {
25+
fn new(x: T, flags: Flags) -> Result<Self, AllocError> {
26+
let mut b = <Self as BoxExt<_>>::new_uninit(flags)?;
27+
b.write(x);
28+
// SAFETY: The contents were just initialised in the line above.
29+
Ok(unsafe { b.assume_init() })
30+
}
31+
32+
#[cfg(any(test, testlib))]
33+
fn new_uninit(_flags: Flags) -> Result<Box<MaybeUninit<T>>, AllocError> {
34+
Ok(Box::new_uninit())
35+
}
36+
37+
#[cfg(not(any(test, testlib)))]
38+
fn new_uninit(flags: Flags) -> Result<Box<MaybeUninit<T>>, AllocError> {
39+
let ptr = if core::mem::size_of::<MaybeUninit<T>>() == 0 {
40+
core::ptr::NonNull::<_>::dangling().as_ptr()
41+
} else {
42+
let layout = core::alloc::Layout::new::<MaybeUninit<T>>();
43+
44+
// SAFETY: Memory is being allocated (first arg is null). The only other source of
45+
// safety issues is sleeping on atomic context, which is addressed by klint. Lastly,
46+
// the type is not a SZT (checked above).
47+
let ptr =
48+
unsafe { super::allocator::krealloc_aligned(core::ptr::null_mut(), layout, flags) };
49+
if ptr.is_null() {
50+
return Err(AllocError);
51+
}
52+
53+
ptr.cast::<MaybeUninit<T>>()
54+
};
55+
56+
// SAFETY: For non-zero-sized types, we allocate above using the global allocator. For
57+
// zero-sized types, we use `NonNull::dangling`.
58+
Ok(unsafe { Box::from_raw(ptr) })
59+
}
60+
}

rust/kernel/init.rs

+7-6
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,7 @@
210210
//! [`pin_init!`]: crate::pin_init!
211211
212212
use crate::{
213+
alloc::{box_ext::BoxExt, flags::*},
213214
error::{self, Error},
214215
sync::UniqueArc,
215216
types::{Opaque, ScopeGuard},
@@ -305,9 +306,9 @@ macro_rules! stack_pin_init {
305306
///
306307
/// stack_try_pin_init!(let foo: Result<Pin<&mut Foo>, AllocError> = pin_init!(Foo {
307308
/// a <- new_mutex!(42),
308-
/// b: Box::try_new(Bar {
309+
/// b: Box::new(Bar {
309310
/// x: 64,
310-
/// })?,
311+
/// }, GFP_KERNEL)?,
311312
/// }));
312313
/// let foo = foo.unwrap();
313314
/// pr_info!("a: {}", &*foo.a.lock());
@@ -331,9 +332,9 @@ macro_rules! stack_pin_init {
331332
///
332333
/// stack_try_pin_init!(let foo: Pin<&mut Foo> =? pin_init!(Foo {
333334
/// a <- new_mutex!(42),
334-
/// b: Box::try_new(Bar {
335+
/// b: Box::new(Bar {
335336
/// x: 64,
336-
/// })?,
337+
/// }, GFP_KERNEL)?,
337338
/// }));
338339
/// pr_info!("a: {}", &*foo.a.lock());
339340
/// # Ok::<_, AllocError>(())
@@ -1158,7 +1159,7 @@ impl<T> InPlaceInit<T> for Box<T> {
11581159
where
11591160
E: From<AllocError>,
11601161
{
1161-
let mut this = Box::try_new_uninit()?;
1162+
let mut this = <Box<_> as BoxExt<_>>::new_uninit(GFP_KERNEL)?;
11621163
let slot = this.as_mut_ptr();
11631164
// SAFETY: When init errors/panics, slot will get deallocated but not dropped,
11641165
// slot is valid and will not be moved, because we pin it later.
@@ -1172,7 +1173,7 @@ impl<T> InPlaceInit<T> for Box<T> {
11721173
where
11731174
E: From<AllocError>,
11741175
{
1175-
let mut this = Box::try_new_uninit()?;
1176+
let mut this = <Box<_> as BoxExt<_>>::new_uninit(GFP_KERNEL)?;
11761177
let slot = this.as_mut_ptr();
11771178
// SAFETY: When init errors/panics, slot will get deallocated but not dropped,
11781179
// slot is valid.

rust/kernel/prelude.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
#[doc(no_inline)]
1515
pub use core::pin::Pin;
1616

17-
pub use crate::alloc::{flags::*, vec_ext::VecExt};
17+
pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt};
1818

1919
#[doc(no_inline)]
2020
pub use alloc::{boxed::Box, vec::Vec};

rust/kernel/sync/arc.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
//! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html
1717
1818
use crate::{
19+
alloc::{box_ext::BoxExt, flags::*},
1920
bindings,
2021
error::{self, Error},
2122
init::{self, InPlaceInit, Init, PinInit},
@@ -170,7 +171,7 @@ impl<T> Arc<T> {
170171
data: contents,
171172
};
172173

173-
let inner = Box::try_new(value)?;
174+
let inner = <Box<_> as BoxExt<_>>::new(value, GFP_KERNEL)?;
174175

175176
// SAFETY: We just created `inner` with a reference count of 1, which is owned by the new
176177
// `Arc` object.

0 commit comments

Comments
 (0)