Skip to content

Commit 88f0e11

Browse files
Luv-Raywyfcyx
authored andcommitted
alignment 512
-------- Cherry-picked from #158.
1 parent ecfe089 commit 88f0e11

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,19 +1,35 @@
11
use super::{BlockDevice, BLOCK_SZ};
2+
use alloc::boxed::Box;
23
use alloc::collections::VecDeque;
34
use alloc::sync::Arc;
4-
use alloc::vec;
5-
use alloc::vec::Vec;
5+
use core::alloc::Layout;
6+
use core::mem::ManuallyDrop;
67
use core::ptr::{addr_of, addr_of_mut};
78
use core::slice;
89
use lazy_static::*;
910
use spin::Mutex;
1011

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

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

0 commit comments

Comments
 (0)