Skip to content

Commit b3a3394

Browse files
alloc::slab: add SlabHeader::from_object and as_slab to cleanup
Signed-off-by: Andy-Python-Programmer <[email protected]>
1 parent 35efdda commit b3a3394

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed

src/aero_kernel/src/mem/alloc.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -83,10 +83,8 @@ impl Allocator {
8383

8484
let _guard = IrqGuard::new();
8585
if layout.size() <= 1024 {
86-
let slab_header = (ptr as usize & !(0xfff)) as *mut SlabHeader;
87-
88-
let slab_header = unsafe { &mut *slab_header };
89-
slab_header.ptr.dealloc(ptr);
86+
let slab_header = SlabHeader::from_object(ptr);
87+
slab_header.as_slab().dealloc(ptr);
9088
}
9189
}
9290
}

src/aero_kernel/src/mem/slab.rs

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,30 @@ use crate::utils::sync::Mutex;
2626

2727
#[repr(C)]
2828
pub struct SlabHeader {
29-
pub ptr: UnsafeRef<SmallSlab>,
29+
/// Reference to the slab pool.
30+
ptr: UnsafeRef<SmallSlab>,
31+
}
32+
33+
impl SlabHeader {
34+
/// Gets the [`SlabHeader`] from an allocated object.
35+
pub fn from_object<'a>(ptr: *const u8) -> &'a Self {
36+
assert!(!ptr.is_null());
37+
38+
let ptr = (ptr as usize & !(0xfff)) as *mut SlabHeader;
39+
unsafe { &*ptr }
40+
}
41+
42+
/// Returns the slab pool to which this header belongs to.
43+
pub fn as_slab<'a>(&'a self) -> &'a SmallSlab {
44+
self.ptr.as_ref()
45+
}
3046
}
3147

3248
const_assert_eq!(core::mem::size_of::<SlabHeader>(), 8);
3349

50+
unsafe impl Send for SlabHeader {}
51+
unsafe impl Sync for SlabHeader {}
52+
3453
/// For small slabs, the [`BufCtl`]s are stored inline.
3554
struct BufCtl(Option<NonNull<BufCtl>>);
3655

@@ -48,6 +67,9 @@ impl BufCtl {
4867

4968
const_assert_eq!(core::mem::size_of::<BufCtl>(), 8);
5069

70+
unsafe impl Send for BufCtl {}
71+
unsafe impl Sync for BufCtl {}
72+
5173
/// Used for allocations smaller than `1/8` of a page.
5274
pub struct SmallSlab {
5375
/// Size of the slab.
@@ -136,6 +158,3 @@ impl SmallSlab {
136158
self.size
137159
}
138160
}
139-
140-
unsafe impl Send for SmallSlab {}
141-
unsafe impl Sync for SmallSlab {}

0 commit comments

Comments
 (0)