Skip to content

Commit e40a640

Browse files
Danilo Krummrichfbq
authored andcommitted
rust: treewide: switch to our kernel Box type
Now that we got the kernel `Box` type in place, convert all existing `Box` users to make use of it. Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Benno Lossin <benno.lossin@proton.me> Signed-off-by: Danilo Krummrich <dakr@kernel.org> Reviewed-by: Gary Guo <gary@garyguo.net> Link: https://lore.kernel.org/r/20240911225449.152928-11-dakr@kernel.org
1 parent 67109d2 commit e40a640

10 files changed

Lines changed: 81 additions & 76 deletions

File tree

drivers/block/rnull.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ module! {
3232
}
3333

3434
struct NullBlkModule {
35-
_disk: Pin<Box<Mutex<GenDisk<NullBlkDevice>>>>,
35+
_disk: Pin<KBox<Mutex<GenDisk<NullBlkDevice>>>>,
3636
}
3737

3838
impl kernel::Module for NullBlkModule {
@@ -47,7 +47,7 @@ impl kernel::Module for NullBlkModule {
4747
.rotational(false)
4848
.build(format_args!("rnullb{}", 0), tagset)?;
4949

50-
let disk = Box::pin_init(new_mutex!(disk, "nullb:disk"), flags::GFP_KERNEL)?;
50+
let disk = KBox::pin_init(new_mutex!(disk, "nullb:disk"), flags::GFP_KERNEL)?;
5151

5252
Ok(Self { _disk: disk })
5353
}

rust/kernel/init.rs

Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
//! To initialize a `struct` with an in-place constructor you will need two things:
1414
//! - an in-place constructor,
1515
//! - a memory location that can hold your `struct` (this can be the [stack], an [`Arc<T>`],
16-
//! [`UniqueArc<T>`], [`Box<T>`] or any other smart pointer that implements [`InPlaceInit`]).
16+
//! [`UniqueArc<T>`], [`KBox<T>`] or any other smart pointer that implements [`InPlaceInit`]).
1717
//!
1818
//! To get an in-place constructor there are generally three options:
1919
//! - directly creating an in-place constructor using the [`pin_init!`] macro,
@@ -68,7 +68,7 @@
6868
//! # a <- new_mutex!(42, "Foo::a"),
6969
//! # b: 24,
7070
//! # });
71-
//! let foo: Result<Pin<Box<Foo>>> = Box::pin_init(foo, GFP_KERNEL);
71+
//! let foo: Result<Pin<KBox<Foo>>> = KBox::pin_init(foo, GFP_KERNEL);
7272
//! ```
7373
//!
7474
//! For more information see the [`pin_init!`] macro.
@@ -93,14 +93,14 @@
9393
//! struct DriverData {
9494
//! #[pin]
9595
//! status: Mutex<i32>,
96-
//! buffer: Box<[u8; 1_000_000]>,
96+
//! buffer: KBox<[u8; 1_000_000]>,
9797
//! }
9898
//!
9999
//! impl DriverData {
100100
//! fn new() -> impl PinInit<Self, Error> {
101101
//! try_pin_init!(Self {
102102
//! status <- new_mutex!(0, "DriverData::status"),
103-
//! buffer: Box::init(kernel::init::zeroed(), GFP_KERNEL)?,
103+
//! buffer: KBox::init(kernel::init::zeroed(), GFP_KERNEL)?,
104104
//! })
105105
//! }
106106
//! }
@@ -211,7 +211,7 @@
211211
//! [`pin_init!`]: crate::pin_init!
212212
213213
use crate::{
214-
alloc::{box_ext::BoxExt, AllocError, Flags},
214+
alloc::{box_ext::BoxExt, AllocError, Flags, KBox},
215215
error::{self, Error},
216216
sync::Arc,
217217
sync::UniqueArc,
@@ -298,7 +298,7 @@ macro_rules! stack_pin_init {
298298
/// struct Foo {
299299
/// #[pin]
300300
/// a: Mutex<usize>,
301-
/// b: Box<Bar>,
301+
/// b: KBox<Bar>,
302302
/// }
303303
///
304304
/// struct Bar {
@@ -307,7 +307,7 @@ macro_rules! stack_pin_init {
307307
///
308308
/// stack_try_pin_init!(let foo: Result<Pin<&mut Foo>, AllocError> = pin_init!(Foo {
309309
/// a <- new_mutex!(42),
310-
/// b: Box::new(Bar {
310+
/// b: KBox::new(Bar {
311311
/// x: 64,
312312
/// }, GFP_KERNEL)?,
313313
/// }));
@@ -324,7 +324,7 @@ macro_rules! stack_pin_init {
324324
/// struct Foo {
325325
/// #[pin]
326326
/// a: Mutex<usize>,
327-
/// b: Box<Bar>,
327+
/// b: KBox<Bar>,
328328
/// }
329329
///
330330
/// struct Bar {
@@ -333,7 +333,7 @@ macro_rules! stack_pin_init {
333333
///
334334
/// stack_try_pin_init!(let foo: Pin<&mut Foo> =? pin_init!(Foo {
335335
/// a <- new_mutex!(42),
336-
/// b: Box::new(Bar {
336+
/// b: KBox::new(Bar {
337337
/// x: 64,
338338
/// }, GFP_KERNEL)?,
339339
/// }));
@@ -392,7 +392,7 @@ macro_rules! stack_try_pin_init {
392392
/// },
393393
/// });
394394
/// # initializer }
395-
/// # Box::pin_init(demo(), GFP_KERNEL).unwrap();
395+
/// # KBox::pin_init(demo(), GFP_KERNEL).unwrap();
396396
/// ```
397397
///
398398
/// Arbitrary Rust expressions can be used to set the value of a variable.
@@ -462,7 +462,7 @@ macro_rules! stack_try_pin_init {
462462
/// # })
463463
/// # }
464464
/// # }
465-
/// let foo = Box::pin_init(Foo::new(), GFP_KERNEL);
465+
/// let foo = KBox::pin_init(Foo::new(), GFP_KERNEL);
466466
/// ```
467467
///
468468
/// They can also easily embed it into their own `struct`s:
@@ -594,15 +594,15 @@ macro_rules! pin_init {
594594
/// use kernel::{init::{self, PinInit}, error::Error};
595595
/// #[pin_data]
596596
/// struct BigBuf {
597-
/// big: Box<[u8; 1024 * 1024 * 1024]>,
597+
/// big: KBox<[u8; 1024 * 1024 * 1024]>,
598598
/// small: [u8; 1024 * 1024],
599599
/// ptr: *mut u8,
600600
/// }
601601
///
602602
/// impl BigBuf {
603603
/// fn new() -> impl PinInit<Self, Error> {
604604
/// try_pin_init!(Self {
605-
/// big: Box::init(init::zeroed(), GFP_KERNEL)?,
605+
/// big: KBox::init(init::zeroed(), GFP_KERNEL)?,
606606
/// small: [0; 1024 * 1024],
607607
/// ptr: core::ptr::null_mut(),
608608
/// }? Error)
@@ -694,16 +694,16 @@ macro_rules! init {
694694
/// # Examples
695695
///
696696
/// ```rust
697-
/// use kernel::{init::{PinInit, zeroed}, error::Error};
697+
/// use kernel::{alloc::KBox, init::{PinInit, zeroed}, error::Error};
698698
/// struct BigBuf {
699-
/// big: Box<[u8; 1024 * 1024 * 1024]>,
699+
/// big: KBox<[u8; 1024 * 1024 * 1024]>,
700700
/// small: [u8; 1024 * 1024],
701701
/// }
702702
///
703703
/// impl BigBuf {
704704
/// fn new() -> impl Init<Self, Error> {
705705
/// try_init!(Self {
706-
/// big: Box::init(zeroed(), GFP_KERNEL)?,
706+
/// big: KBox::init(zeroed(), GFP_KERNEL)?,
707707
/// small: [0; 1024 * 1024],
708708
/// }? Error)
709709
/// }
@@ -814,8 +814,8 @@ macro_rules! assert_pinned {
814814
/// A pin-initializer for the type `T`.
815815
///
816816
/// To use this initializer, you will need a suitable memory location that can hold a `T`. This can
817-
/// be [`Box<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use the
818-
/// [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc<T>`] on this.
817+
/// be [`KBox<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use
818+
/// the [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc<T>`] on this.
819819
///
820820
/// Also see the [module description](self).
821821
///
@@ -894,7 +894,7 @@ pub unsafe trait PinInit<T: ?Sized, E = Infallible>: Sized {
894894
}
895895

896896
/// An initializer returned by [`PinInit::pin_chain`].
897-
pub struct ChainPinInit<I, F, T: ?Sized, E>(I, F, __internal::Invariant<(E, Box<T>)>);
897+
pub struct ChainPinInit<I, F, T: ?Sized, E>(I, F, __internal::Invariant<(E, KBox<T>)>);
898898

899899
// SAFETY: The `__pinned_init` function is implemented such that it
900900
// - returns `Ok(())` on successful initialization,
@@ -920,8 +920,8 @@ where
920920
/// An initializer for `T`.
921921
///
922922
/// To use this initializer, you will need a suitable memory location that can hold a `T`. This can
923-
/// be [`Box<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use the
924-
/// [`InPlaceInit::init`] function of a smart pointer like [`Arc<T>`] on this. Because
923+
/// be [`KBox<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use
924+
/// the [`InPlaceInit::init`] function of a smart pointer like [`Arc<T>`] on this. Because
925925
/// [`PinInit<T, E>`] is a super trait, you can use every function that takes it as well.
926926
///
927927
/// Also see the [module description](self).
@@ -993,7 +993,7 @@ pub unsafe trait Init<T: ?Sized, E = Infallible>: PinInit<T, E> {
993993
}
994994

995995
/// An initializer returned by [`Init::chain`].
996-
pub struct ChainInit<I, F, T: ?Sized, E>(I, F, __internal::Invariant<(E, Box<T>)>);
996+
pub struct ChainInit<I, F, T: ?Sized, E>(I, F, __internal::Invariant<(E, KBox<T>)>);
997997

998998
// SAFETY: The `__init` function is implemented such that it
999999
// - returns `Ok(())` on successful initialization,
@@ -1077,8 +1077,9 @@ pub fn uninit<T, E>() -> impl Init<MaybeUninit<T>, E> {
10771077
/// # Examples
10781078
///
10791079
/// ```rust
1080-
/// use kernel::{error::Error, init::init_array_from_fn};
1081-
/// let array: Box<[usize; 1_000]> = Box::init::<Error>(init_array_from_fn(|i| i), GFP_KERNEL).unwrap();
1080+
/// use kernel::{alloc::KBox, error::Error, init::init_array_from_fn};
1081+
/// let array: KBox<[usize; 1_000]> =
1082+
/// KBox::init::<Error>(init_array_from_fn(|i| i), GFP_KERNEL).unwrap();
10821083
/// assert_eq!(array.len(), 1_000);
10831084
/// ```
10841085
pub fn init_array_from_fn<I, const N: usize, T, E>(
@@ -1451,7 +1452,7 @@ impl_zeroable! {
14511452
//
14521453
// In this case we are allowed to use `T: ?Sized`, since all zeros is the `None` variant.
14531454
{<T: ?Sized>} Option<NonNull<T>>,
1454-
{<T: ?Sized>} Option<Box<T>>,
1455+
{<T: ?Sized>} Option<KBox<T>>,
14551456

14561457
// SAFETY: `null` pointer is valid.
14571458
//

rust/kernel/init/__internal.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ pub unsafe trait InitData: Copy {
102102
}
103103
}
104104

105-
pub struct AllData<T: ?Sized>(PhantomData<fn(Box<T>) -> Box<T>>);
105+
pub struct AllData<T: ?Sized>(PhantomData<fn(KBox<T>) -> KBox<T>>);
106106

107107
impl<T: ?Sized> Clone for AllData<T> {
108108
fn clone(&self) -> Self {

rust/kernel/rbtree.rs

Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
//! Reference: <https://docs.kernel.org/core-api/rbtree.html>
88
99
use crate::{alloc::Flags, bindings, container_of, error::Result, prelude::*};
10-
use alloc::boxed::Box;
1110
use core::{
1211
cmp::{Ord, Ordering},
1312
marker::PhantomData,
@@ -497,7 +496,7 @@ impl<K, V> Drop for RBTree<K, V> {
497496
// but it is not observable. The loop invariant is still maintained.
498497

499498
// SAFETY: `this` is valid per the loop invariant.
500-
unsafe { drop(Box::from_raw(this.cast_mut())) };
499+
unsafe { drop(KBox::from_raw(this.cast_mut())) };
501500
}
502501
}
503502
}
@@ -764,7 +763,7 @@ impl<'a, K, V> Cursor<'a, K, V> {
764763
// point to the links field of `Node<K, V>` objects.
765764
let this = unsafe { container_of!(self.current.as_ptr(), Node<K, V>, links) }.cast_mut();
766765
// SAFETY: `this` is valid by the type invariants as described above.
767-
let node = unsafe { Box::from_raw(this) };
766+
let node = unsafe { KBox::from_raw(this) };
768767
let node = RBTreeNode { node };
769768
// SAFETY: The reference to the tree used to create the cursor outlives the cursor, so
770769
// the tree cannot change. By the tree invariant, all nodes are valid.
@@ -809,7 +808,7 @@ impl<'a, K, V> Cursor<'a, K, V> {
809808
// point to the links field of `Node<K, V>` objects.
810809
let this = unsafe { container_of!(neighbor, Node<K, V>, links) }.cast_mut();
811810
// SAFETY: `this` is valid by the type invariants as described above.
812-
let node = unsafe { Box::from_raw(this) };
811+
let node = unsafe { KBox::from_raw(this) };
813812
return Some(RBTreeNode { node });
814813
}
815814
None
@@ -1035,15 +1034,15 @@ impl<K, V> Iterator for IterRaw<K, V> {
10351034
/// It contains the memory needed to hold a node that can be inserted into a red-black tree. One
10361035
/// can be obtained by directly allocating it ([`RBTreeNodeReservation::new`]).
10371036
pub struct RBTreeNodeReservation<K, V> {
1038-
node: Box<MaybeUninit<Node<K, V>>>,
1037+
node: KBox<MaybeUninit<Node<K, V>>>,
10391038
}
10401039

10411040
impl<K, V> RBTreeNodeReservation<K, V> {
10421041
/// Allocates memory for a node to be eventually initialised and inserted into the tree via a
10431042
/// call to [`RBTree::insert`].
10441043
pub fn new(flags: Flags) -> Result<RBTreeNodeReservation<K, V>> {
10451044
Ok(RBTreeNodeReservation {
1046-
node: <Box<_> as BoxExt<_>>::new_uninit(flags)?,
1045+
node: KBox::new_uninit(flags)?,
10471046
})
10481047
}
10491048
}
@@ -1059,14 +1058,15 @@ impl<K, V> RBTreeNodeReservation<K, V> {
10591058
/// Initialises a node reservation.
10601059
///
10611060
/// It then becomes an [`RBTreeNode`] that can be inserted into a tree.
1062-
pub fn into_node(mut self, key: K, value: V) -> RBTreeNode<K, V> {
1063-
self.node.write(Node {
1064-
key,
1065-
value,
1066-
links: bindings::rb_node::default(),
1067-
});
1068-
// SAFETY: We just wrote to it.
1069-
let node = unsafe { self.node.assume_init() };
1061+
pub fn into_node(self, key: K, value: V) -> RBTreeNode<K, V> {
1062+
let node = KBox::write(
1063+
self.node,
1064+
Node {
1065+
key,
1066+
value,
1067+
links: bindings::rb_node::default(),
1068+
},
1069+
);
10701070
RBTreeNode { node }
10711071
}
10721072
}
@@ -1076,7 +1076,7 @@ impl<K, V> RBTreeNodeReservation<K, V> {
10761076
/// The node is fully initialised (with key and value) and can be inserted into a tree without any
10771077
/// extra allocations or failure paths.
10781078
pub struct RBTreeNode<K, V> {
1079-
node: Box<Node<K, V>>,
1079+
node: KBox<Node<K, V>>,
10801080
}
10811081

10821082
impl<K, V> RBTreeNode<K, V> {
@@ -1088,7 +1088,9 @@ impl<K, V> RBTreeNode<K, V> {
10881088

10891089
/// Get the key and value from inside the node.
10901090
pub fn to_key_value(self) -> (K, V) {
1091-
(self.node.key, self.node.value)
1091+
let node = KBox::into_inner(self.node);
1092+
1093+
(node.key, node.value)
10921094
}
10931095
}
10941096

@@ -1110,7 +1112,7 @@ impl<K, V> RBTreeNode<K, V> {
11101112
/// may be freed (but only for the key/value; memory for the node itself is kept for reuse).
11111113
pub fn into_reservation(self) -> RBTreeNodeReservation<K, V> {
11121114
RBTreeNodeReservation {
1113-
node: Box::drop_contents(self.node),
1115+
node: KBox::drop_contents(self.node),
11141116
}
11151117
}
11161118
}
@@ -1161,7 +1163,7 @@ impl<'a, K, V> RawVacantEntry<'a, K, V> {
11611163
/// The `node` must have a key such that inserting it here does not break the ordering of this
11621164
/// [`RBTree`].
11631165
fn insert(self, node: RBTreeNode<K, V>) -> &'a mut V {
1164-
let node = Box::into_raw(node.node);
1166+
let node = KBox::into_raw(node.node);
11651167

11661168
// SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when
11671169
// the node is removed or replaced.
@@ -1235,21 +1237,24 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> {
12351237
// SAFETY: The node was a node in the tree, but we removed it, so we can convert it
12361238
// back into a box.
12371239
node: unsafe {
1238-
Box::from_raw(container_of!(self.node_links, Node<K, V>, links).cast_mut())
1240+
KBox::from_raw(container_of!(self.node_links, Node<K, V>, links).cast_mut())
12391241
},
12401242
}
12411243
}
12421244

12431245
/// Takes the value of the entry out of the map, and returns it.
12441246
pub fn remove(self) -> V {
1245-
self.remove_node().node.value
1247+
let rb_node = self.remove_node();
1248+
let node = KBox::into_inner(rb_node.node);
1249+
1250+
node.value
12461251
}
12471252

12481253
/// Swap the current node for the provided node.
12491254
///
12501255
/// The key of both nodes must be equal.
12511256
fn replace(self, node: RBTreeNode<K, V>) -> RBTreeNode<K, V> {
1252-
let node = Box::into_raw(node.node);
1257+
let node = KBox::into_raw(node.node);
12531258

12541259
// SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when
12551260
// the node is removed or replaced.
@@ -1265,7 +1270,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> {
12651270
// - `self.node_ptr` produces a valid pointer to a node in the tree.
12661271
// - Now that we removed this entry from the tree, we can convert the node to a box.
12671272
let old_node =
1268-
unsafe { Box::from_raw(container_of!(self.node_links, Node<K, V>, links).cast_mut()) };
1273+
unsafe { KBox::from_raw(container_of!(self.node_links, Node<K, V>, links).cast_mut()) };
12691274

12701275
RBTreeNode { node: old_node }
12711276
}

0 commit comments

Comments
 (0)