From 1f2b9a2fafedb8c0c144a49fa21314bad1f25308 Mon Sep 17 00:00:00 2001 From: Luv-Ray Date: Fri, 14 Mar 2025 10:08:55 +0800 Subject: [PATCH] alignment 512 -------- Cherry-picked from #158. --- easy-fs/src/block_cache.rs | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/easy-fs/src/block_cache.rs b/easy-fs/src/block_cache.rs index 67a3b89..786f9e0 100644 --- a/easy-fs/src/block_cache.rs +++ b/easy-fs/src/block_cache.rs @@ -1,19 +1,35 @@ use super::{BlockDevice, BLOCK_SZ}; +use alloc::boxed::Box; use alloc::collections::VecDeque; use alloc::sync::Arc; -use alloc::vec; -use alloc::vec::Vec; +use core::alloc::Layout; +use core::mem::ManuallyDrop; use core::ptr::{addr_of, addr_of_mut}; use core::slice; use lazy_static::*; use spin::Mutex; -/// use `Vec` to ensure the alignment of addr is `8` -struct CacheData(Vec); +/// Use `ManuallyDrop` to ensure data is deallocated with an alignment of `BLOCK_SZ` +struct CacheData(ManuallyDrop>); impl CacheData { - fn new() -> Self { - Self(vec![0u64; BLOCK_SZ / 8]) + pub fn new() -> Self { + let data = unsafe { + let raw = alloc::alloc::alloc(Self::layout()); + Box::from_raw(raw as *mut [u8; BLOCK_SZ]) + }; + Self(ManuallyDrop::new(data)) + } + + fn layout() -> Layout { + Layout::from_size_align(BLOCK_SZ, BLOCK_SZ).unwrap() + } +} + +impl Drop for CacheData { + fn drop(&mut self) { + let ptr = self.0.as_mut_ptr(); + unsafe { alloc::alloc::dealloc(ptr, Self::layout()) }; } }