Skip to content

Commit c548c79

Browse files
committed
alignment 512
1 parent b02a7a1 commit c548c79

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

easy-fs/src/block_cache.rs

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,36 @@
1+
use core::alloc::Layout;
2+
use core::mem::ManuallyDrop;
13
use core::ptr::{addr_of, addr_of_mut};
24
use core::slice;
35

46
use super::{BlockDevice, BLOCK_SZ};
7+
use alloc::boxed::Box;
58
use alloc::collections::VecDeque;
69
use alloc::sync::Arc;
7-
use alloc::vec;
8-
use alloc::vec::Vec;
910
use lazy_static::*;
1011
use spin::Mutex;
1112

12-
/// use `Vec<u64>` to ensure the alignment of addr is `8`
13-
struct CacheData(Vec<u64>);
13+
/// Use `ManuallyDrop` to ensure data is deallocated with an alignment of `BLOCK_SZ`
14+
struct CacheData(ManuallyDrop<Box<[u8; BLOCK_SZ]>>);
1415

1516
impl CacheData {
16-
fn new() -> Self {
17-
Self(vec![0u64; BLOCK_SZ / 8])
17+
pub fn new() -> Self {
18+
let data = unsafe {
19+
let raw = alloc::alloc::alloc(Self::layout());
20+
Box::from_raw(raw as *mut [u8; BLOCK_SZ])
21+
};
22+
Self(ManuallyDrop::new(data))
23+
}
24+
25+
fn layout() -> Layout {
26+
Layout::from_size_align(BLOCK_SZ, BLOCK_SZ).unwrap()
27+
}
28+
}
29+
30+
impl Drop for CacheData {
31+
fn drop(&mut self) {
32+
let ptr = self.0.as_mut_ptr();
33+
unsafe { alloc::alloc::dealloc(ptr, Self::layout()) };
1834
}
1935
}
2036

0 commit comments

Comments
 (0)