Skip to content

Commit 8373147

Browse files
Danilo Krummrichojeda
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> Reviewed-by: Gary Guo <gary@garyguo.net> Signed-off-by: Danilo Krummrich <dakr@kernel.org> Link: https://lore.kernel.org/r/20241004154149.93856-13-dakr@kernel.org Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
1 parent c8cfa8d commit 8373147

File tree

10 files changed

+81
-76
lines changed

10 files changed

+81
-76
lines changed

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.
@@ -92,14 +92,14 @@
9292
//! struct DriverData {
9393
//! #[pin]
9494
//! status: Mutex<i32>,
95-
//! buffer: Box<[u8; 1_000_000]>,
95+
//! buffer: KBox<[u8; 1_000_000]>,
9696
//! }
9797
//!
9898
//! impl DriverData {
9999
//! fn new() -> impl PinInit<Self, Error> {
100100
//! try_pin_init!(Self {
101101
//! status <- new_mutex!(0, "DriverData::status"),
102-
//! buffer: Box::init(kernel::init::zeroed(), GFP_KERNEL)?,
102+
//! buffer: KBox::init(kernel::init::zeroed(), GFP_KERNEL)?,
103103
//! })
104104
//! }
105105
//! }
@@ -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
/// }));
@@ -391,7 +391,7 @@ macro_rules! stack_try_pin_init {
391391
/// },
392392
/// });
393393
/// # initializer }
394-
/// # Box::pin_init(demo(), GFP_KERNEL).unwrap();
394+
/// # KBox::pin_init(demo(), GFP_KERNEL).unwrap();
395395
/// ```
396396
///
397397
/// Arbitrary Rust expressions can be used to set the value of a variable.
@@ -460,7 +460,7 @@ macro_rules! stack_try_pin_init {
460460
/// # })
461461
/// # }
462462
/// # }
463-
/// let foo = Box::pin_init(Foo::new(), GFP_KERNEL);
463+
/// let foo = KBox::pin_init(Foo::new(), GFP_KERNEL);
464464
/// ```
465465
///
466466
/// They can also easily embed it into their own `struct`s:
@@ -592,15 +592,15 @@ macro_rules! pin_init {
592592
/// use kernel::{init::{self, PinInit}, error::Error};
593593
/// #[pin_data]
594594
/// struct BigBuf {
595-
/// big: Box<[u8; 1024 * 1024 * 1024]>,
595+
/// big: KBox<[u8; 1024 * 1024 * 1024]>,
596596
/// small: [u8; 1024 * 1024],
597597
/// ptr: *mut u8,
598598
/// }
599599
///
600600
/// impl BigBuf {
601601
/// fn new() -> impl PinInit<Self, Error> {
602602
/// try_pin_init!(Self {
603-
/// big: Box::init(init::zeroed(), GFP_KERNEL)?,
603+
/// big: KBox::init(init::zeroed(), GFP_KERNEL)?,
604604
/// small: [0; 1024 * 1024],
605605
/// ptr: core::ptr::null_mut(),
606606
/// }? Error)
@@ -692,16 +692,16 @@ macro_rules! init {
692692
/// # Examples
693693
///
694694
/// ```rust
695-
/// use kernel::{init::{PinInit, zeroed}, error::Error};
695+
/// use kernel::{alloc::KBox, init::{PinInit, zeroed}, error::Error};
696696
/// struct BigBuf {
697-
/// big: Box<[u8; 1024 * 1024 * 1024]>,
697+
/// big: KBox<[u8; 1024 * 1024 * 1024]>,
698698
/// small: [u8; 1024 * 1024],
699699
/// }
700700
///
701701
/// impl BigBuf {
702702
/// fn new() -> impl Init<Self, Error> {
703703
/// try_init!(Self {
704-
/// big: Box::init(zeroed(), GFP_KERNEL)?,
704+
/// big: KBox::init(zeroed(), GFP_KERNEL)?,
705705
/// small: [0; 1024 * 1024],
706706
/// }? Error)
707707
/// }
@@ -812,8 +812,8 @@ macro_rules! assert_pinned {
812812
/// A pin-initializer for the type `T`.
813813
///
814814
/// To use this initializer, you will need a suitable memory location that can hold a `T`. This can
815-
/// be [`Box<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use the
816-
/// [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc<T>`] on this.
815+
/// be [`KBox<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use
816+
/// the [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc<T>`] on this.
817817
///
818818
/// Also see the [module description](self).
819819
///
@@ -893,7 +893,7 @@ pub unsafe trait PinInit<T: ?Sized, E = Infallible>: Sized {
893893
}
894894

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

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

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

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

14581459
// SAFETY: `null` pointer is valid.
14591460
//

rust/kernel/init/__internal.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ pub unsafe trait InitData: Copy {
105105
}
106106
}
107107

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

110110
impl<T: ?Sized> Clone for AllData<T> {
111111
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
@@ -1038,15 +1037,15 @@ impl<K, V> Iterator for IterRaw<K, V> {
10381037
/// It contains the memory needed to hold a node that can be inserted into a red-black tree. One
10391038
/// can be obtained by directly allocating it ([`RBTreeNodeReservation::new`]).
10401039
pub struct RBTreeNodeReservation<K, V> {
1041-
node: Box<MaybeUninit<Node<K, V>>>,
1040+
node: KBox<MaybeUninit<Node<K, V>>>,
10421041
}
10431042

10441043
impl<K, V> RBTreeNodeReservation<K, V> {
10451044
/// Allocates memory for a node to be eventually initialised and inserted into the tree via a
10461045
/// call to [`RBTree::insert`].
10471046
pub fn new(flags: Flags) -> Result<RBTreeNodeReservation<K, V>> {
10481047
Ok(RBTreeNodeReservation {
1049-
node: <Box<_> as BoxExt<_>>::new_uninit(flags)?,
1048+
node: KBox::new_uninit(flags)?,
10501049
})
10511050
}
10521051
}
@@ -1062,14 +1061,15 @@ impl<K, V> RBTreeNodeReservation<K, V> {
10621061
/// Initialises a node reservation.
10631062
///
10641063
/// It then becomes an [`RBTreeNode`] that can be inserted into a tree.
1065-
pub fn into_node(mut self, key: K, value: V) -> RBTreeNode<K, V> {
1066-
self.node.write(Node {
1067-
key,
1068-
value,
1069-
links: bindings::rb_node::default(),
1070-
});
1071-
// SAFETY: We just wrote to it.
1072-
let node = unsafe { self.node.assume_init() };
1064+
pub fn into_node(self, key: K, value: V) -> RBTreeNode<K, V> {
1065+
let node = KBox::write(
1066+
self.node,
1067+
Node {
1068+
key,
1069+
value,
1070+
links: bindings::rb_node::default(),
1071+
},
1072+
);
10731073
RBTreeNode { node }
10741074
}
10751075
}
@@ -1079,7 +1079,7 @@ impl<K, V> RBTreeNodeReservation<K, V> {
10791079
/// The node is fully initialised (with key and value) and can be inserted into a tree without any
10801080
/// extra allocations or failure paths.
10811081
pub struct RBTreeNode<K, V> {
1082-
node: Box<Node<K, V>>,
1082+
node: KBox<Node<K, V>>,
10831083
}
10841084

10851085
impl<K, V> RBTreeNode<K, V> {
@@ -1091,7 +1091,9 @@ impl<K, V> RBTreeNode<K, V> {
10911091

10921092
/// Get the key and value from inside the node.
10931093
pub fn to_key_value(self) -> (K, V) {
1094-
(self.node.key, self.node.value)
1094+
let node = KBox::into_inner(self.node);
1095+
1096+
(node.key, node.value)
10951097
}
10961098
}
10971099

@@ -1113,7 +1115,7 @@ impl<K, V> RBTreeNode<K, V> {
11131115
/// may be freed (but only for the key/value; memory for the node itself is kept for reuse).
11141116
pub fn into_reservation(self) -> RBTreeNodeReservation<K, V> {
11151117
RBTreeNodeReservation {
1116-
node: Box::drop_contents(self.node),
1118+
node: KBox::drop_contents(self.node),
11171119
}
11181120
}
11191121
}
@@ -1164,7 +1166,7 @@ impl<'a, K, V> RawVacantEntry<'a, K, V> {
11641166
/// The `node` must have a key such that inserting it here does not break the ordering of this
11651167
/// [`RBTree`].
11661168
fn insert(self, node: RBTreeNode<K, V>) -> &'a mut V {
1167-
let node = Box::into_raw(node.node);
1169+
let node = KBox::into_raw(node.node);
11681170

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

12461248
/// Takes the value of the entry out of the map, and returns it.
12471249
pub fn remove(self) -> V {
1248-
self.remove_node().node.value
1250+
let rb_node = self.remove_node();
1251+
let node = KBox::into_inner(rb_node.node);
1252+
1253+
node.value
12491254
}
12501255

12511256
/// Swap the current node for the provided node.
12521257
///
12531258
/// The key of both nodes must be equal.
12541259
fn replace(self, node: RBTreeNode<K, V>) -> RBTreeNode<K, V> {
1255-
let node = Box::into_raw(node.node);
1260+
let node = KBox::into_raw(node.node);
12561261

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

12731278
RBTreeNode { node: old_node }
12741279
}

0 commit comments

Comments
 (0)