summaryrefslogtreecommitdiff
path: root/ayafs-core/src/memory/cached_block.rs
blob: 24f08c0e21f97c7ed42bcd510fd45d33aae44c09 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
use crate::block_device::{BlockDevice, BLOCK_SIZE};
use crate::disk::block::Block;
use crate::AyaFS;
use lru::LruCache;
use std::num::NonZeroUsize;
use std::sync::Arc;
use log::debug;

#[derive(Clone)]
pub struct CachedBlock<T: Block> {
    pub block: T,
    pub index: usize,
    pub dirty: bool,
}

pub fn convert_mut<U: Block, T: Block>(input_block: &mut CachedBlock<U>) -> &mut CachedBlock<T> {
    let ptr = input_block as *const CachedBlock<U> as *mut u8;
    let block = ptr.cast::<CachedBlock<T>>();
    unsafe { &mut *block }
}

pub fn convert<U: Block, T: Block>(input_block: &CachedBlock<U>) -> &CachedBlock<T> {
    let ptr = input_block as *const CachedBlock<U> as *mut u8;
    let block = ptr.cast::<CachedBlock<T>>();
    unsafe { &*block }
}

pub(crate) struct BlockCache<T: Block> {
    device: Arc<dyn BlockDevice>,
    cache: LruCache<usize, CachedBlock<T>>,
    pub global_offset: usize,
}

impl<T: Block> BlockCache<T> {
    pub(crate) fn new(device: Arc<dyn BlockDevice>, cache_size: usize, global_offset: usize) -> Self {
        Self {
            device,
            cache: LruCache::new(NonZeroUsize::new(cache_size).unwrap()),
            global_offset,
        }
    }

    pub(crate) fn write_back(&self) {
        for (_, cached_block) in self.cache.iter() {
            if cached_block.dirty {
                debug!("write_back: dirty block {}", self.global_offset + cached_block.index);
                let block_buffer = unsafe {
                    let block_ptr = &cached_block.block as *const T as *const u8;
                    std::slice::from_raw_parts(block_ptr, std::mem::size_of::<T>())
                };
                self.device.write(self.global_offset + cached_block.index, block_buffer);
            } else {
                debug!("write_back: clean block {}", self.global_offset + cached_block.index);
            }
        }
    }

    pub(crate) fn load_block(&mut self, index: usize) -> bool {
        if self.cache.contains(&index) == false {
            let mut buffer = [0u8; BLOCK_SIZE];
            self.device.read(self.global_offset + index, &mut buffer);
            let block: T = unsafe { std::mem::transmute_copy(&buffer) };
            let cached_block = CachedBlock {
                block,
                index,
                dirty: false,
            };
            if let Some((old_index, old_block)) = self.cache.push(index, cached_block) {
                assert_ne!(old_index, index); // 只有 block 不在 cache 里的时候才会插入
                if old_block.dirty {
                    debug!("write_back: evicted dirty block {} while loading {}", self.global_offset + old_block.index, self.global_offset + index);
                    let old_block_buffer = unsafe {
                        let old_block_ptr = &old_block.block as *const T as *mut u8;
                        std::slice::from_raw_parts(old_block_ptr, BLOCK_SIZE)
                    };
                    self.device.write(self.global_offset + old_block.index, old_block_buffer);
                }
            }
        }
        true
    }

    /// 从 LRU cache 里获取一个 block 的引用, 如果没有在 cache 中会加载.
    /// 这个函数不应该返回 None
    pub(crate) fn get_block<U: Block>(&mut self, index: usize) -> Option<&CachedBlock<U>> {
        if !self.cache.contains(&index) {
            debug!("get_block(global_block_id: {}) loading from disk", index + self.global_offset);
            self.load_block(index);
        }

        if let Some(block) = self.cache.get(&index) {
            debug!("get_block(global_block_id: {}) found", index + self.global_offset);
            Some(convert::<T, U>(block))
        } else {
            debug!("get_block(global_block_id: {}) not found", index + self.global_offset);
            None
        }
        // debug!("get_block(global_block_id: {}) found", index + self.global_offset);
        // self.cache.get(&index).map(convert::<T, U>)
    }

    /// 从 LRU cache 里获取一个 block 的可变引用, 如果没有在 cache 中会加载.
    /// 这个函数不应该返回 None
    pub(crate) fn get_block_mut<U: Block>(&mut self, index: usize) -> Option<&mut CachedBlock<U>> {
        if !self.cache.contains(&index) {
            debug!("get_block_mut(global_block_id: {}) loading from disk", index + self.global_offset);
            self.load_block(index);
        }

        if let Some(block) = self.cache.get_mut(&index) {
            debug!("get_block_mut(global_block_id: {}) found", index + self.global_offset);
            block.dirty = true;
            Some(convert_mut::<T, U>(block))
        } else {
            debug!("get_block_mut(global_block_id: {}) not found", index + self.global_offset);
            None
        }

        // self.cache.get_mut(&index).map(|block| {
        //     debug!("get_block_mut(global_block_id: {}) found", index + self.global_offset);
        //     block.dirty = true;
        //     convert_mut::<T, U>(block)
        // })
    }

    /// 向 LRU cache 中插入一个全新初始化的 block
    /// 这个 block 全 0, 而且是 dirty 的, 即使被挤出去也会触发一次落盘
    pub(crate) fn init_block(&mut self, index: usize) {
        let allocated_block = CachedBlock {
            block: T::default(),
            index,
            dirty: true,
        };
        if let Some((old_index, old_block)) = self.cache.push(index, allocated_block) {
            if old_block.dirty {
                let old_block_ptr = &old_block.block as *const T as *mut u8;
                let old_block_buffer =
                    unsafe { std::slice::from_raw_parts(old_block_ptr, BLOCK_SIZE) };
                self.device.write(self.global_offset + old_index, old_block_buffer);
            }
        }
    }

    #[allow(unused)]
    /// 从 LRU cache 中读取一个 block 的引用, *不会* 影响 LRU cache 的结构, 如果没有在 cache 中不会加载.
    pub(crate) fn peek_block<U: Block>(&self, index: usize) -> Option<&CachedBlock<U>> {
        self.cache.peek(&index).map(convert::<T, U>)
    }

    #[allow(unused)]
    /// 从 LRU cache 中读取一个 block 的可变引用, *不会* 影响 LRU cache 的结构, 如果没有在 cache 中不会加载.
    pub(crate) fn peek_block_mut<U: Block>(&mut self, index: usize) -> Option<&mut CachedBlock<U>> {
        self.cache.peek_mut(&index).map(convert_mut::<T, U>)
    }

    pub(crate) fn update_block<U: Block>(&mut self, block: CachedBlock<U>) -> bool {
        if self.cache.contains(&block.index) {
            let mut data_block = convert::<U, T>(&block).clone();
            data_block.dirty = true; // TODO 需要把显式写回的都标记为 dirty 吗
            let (entry, _value) = self.cache.push(block.index, data_block).unwrap();
            assert_eq!(entry, block.index);
            debug!("update_block(global_block_id: {})", block.index + self.global_offset);
            true
        } else {
            false
        }
    }

    fn pop(&mut self, entry: usize) -> Option<CachedBlock<T>> {
        debug!("pop_block(global_block_id: {})", entry + self.global_offset);
        self.cache.pop(&entry)
    }
}

impl AyaFS {
    pub(crate) fn init_block(&mut self, index: usize) {
        self.cached_blocks.init_block(index);
    }

    pub(crate) fn get_block<T: Block>(&mut self, index: usize) -> Option<&CachedBlock<T>> {
        if self.data_bitmap.query(index) {
            debug!("get_block(block_id: {}) found", index);
            Some(self.cached_blocks.get_block::<T>(index).unwrap())
        } else {
            debug!("get_block(block_id: {}) not exist", index);
            self.cached_blocks.pop(index);
            None
        }
        // self.data_bitmap
        //     .query(index)
        //     .then(|| self.cached_blocks.get_block::<T>(index).unwrap())
        // 返回 None 当且仅当 data_bitmap 中这个 block 为 invalid
    }

    pub(crate) fn get_block_mut<T: Block>(&mut self, index: usize) -> Option<&mut CachedBlock<T>> {
        if self.data_bitmap.query(index) {
            Some(self.cached_blocks.get_block_mut::<T>(index).unwrap())
        } else {
            self.cached_blocks.pop(index);
            None
        }
        // self.data_bitmap
        //     .query(index)
        //     .then(|| self.cached_blocks.get_block_mut::<T>(index).unwrap())
        // 返回 None 当且仅当 data_bitmap 中这个 block 为 invalid
    }

    #[allow(unused)]
    pub(crate) fn peek_block<T: Block>(&self, index: usize) -> Option<&CachedBlock<T>> {
        self.data_bitmap
            .query(index)
            .then(|| self.cached_blocks.peek_block::<T>(index).unwrap())
        // 返回 None 当且仅当 data_bitmap 中这个 block 为 invalid
    }

    #[allow(unused)]
    pub(crate) fn peek_block_mut<T: Block>(&mut self, index: usize) -> Option<&mut CachedBlock<T>> {
        self.data_bitmap
            .query(index)
            .then(|| self.cached_blocks.peek_block_mut::<T>(index).unwrap())
        // 返回 None 当且仅当 data_bitmap 中这个 block 为 invalid
    }

    pub(crate) fn update_block<T: Block>(&mut self, block: CachedBlock<T>) -> bool {
        self.cached_blocks.update_block(block)
    }
}