      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

    use super::{BlockDevice, BLOCK_SZ};
    use alloc::collections::VecDeque;
    use alloc::sync::Arc;
    use lazy_static::*;
    use spin::Mutex;

    pub struct BlockCache {
        cache: [u8; BLOCK_SZ],
        block_id: usize,
        block_device: Arc<dyn BlockDevice>,
        modified: bool,
    }

    impl BlockCache {
        /// Load a new BlockCache from disk.
        pub fn new(block_id: usize, block_device: Arc<dyn BlockDevice>) -> Self {
            //kprintln!("[KERN EASYFS] block_cache::BlockCache::new() begin");
            let mut cache = [0u8; BLOCK_SZ];
            block_device.read_block(block_id, &mut cache);
            Self {
                cache,
                block_id,
                block_device,
                modified: false,
            }
        }

        fn addr_of_offset(&self, offset: usize) -> usize {
            &self.cache[offset] as *const _ as usize
        }

        pub fn get_ref<T>(&self, offset: usize) -> &T
        where
            T: Sized,
        {
            let type_size = core::mem::size_of::<T>();
            assert!(offset + type_size <= BLOCK_SZ);
            let addr = self.addr_of_offset(offset);
            unsafe { &*(addr as *const T) }
        }

        pub fn get_mut<T>(&mut self, offset: usize) -> &mut T
        where
            T: Sized,
        {
            let type_size = core::mem::size_of::<T>();
            assert!(offset + type_size <= BLOCK_SZ);
            self.modified = true;
            let addr = self.addr_of_offset(offset);
            unsafe { &mut *(addr as *mut T) }
        }

        pub fn read<T, V>(&self, offset: usize, f: impl FnOnce(&T) -> V) -> V {
            f(self.get_ref(offset))
        }

        pub fn modify<T, V>(&mut self, offset: usize, f: impl FnOnce(&mut T) -> V) -> V {
            f(self.get_mut(offset))
        }

        pub fn sync(&mut self) {
            if self.modified {
                self.modified = false;
                self.block_device.write_block(self.block_id, &self.cache);
            }
        }
    }

    impl Drop for BlockCache {
        fn drop(&mut self) {
            self.sync()
        }
    }

    const BLOCK_CACHE_SIZE: usize = 16;

    pub struct BlockCacheManager {
        queue: VecDeque<(usize, Arc<Mutex<BlockCache>>)>,
    }

    impl BlockCacheManager {
        pub fn new() -> Self {
            kprintln!("[KERN EASYFS] block_cache::BlockCacheManager::new() begin");
            Self {
                queue: VecDeque::new(),
            }
        }

        pub fn get_block_cache(
            &mut self,
            block_id: usize,
            block_device: Arc<dyn BlockDevice>,
        ) -> Arc<Mutex<BlockCache>> {
            //kprintln!("[KERN EASYFS] block_cache::BlockCacheManager::get_block_cache() begin");
            if let Some(pair) = self.queue.iter().find(|pair| pair.0 == block_id) {
                Arc::clone(&pair.1)
            } else {
                // substitute
                if self.queue.len() == BLOCK_CACHE_SIZE {
                    // from front to tail
                    if let Some((idx, _)) = self
                        .queue
                        .iter()
                        .enumerate()
                        .find(|(_, pair)| Arc::strong_count(&pair.1) == 1)
                    {
                        self.queue.drain(idx..=idx);
                    } else {
                        panic!("Run out of BlockCache!");
                    }
                }
                // load block into mem and push back
                let block_cache = Arc::new(Mutex::new(BlockCache::new(
                    block_id,
                    Arc::clone(&block_device),
                )));
                self.queue.push_back((block_id, Arc::clone(&block_cache)));
                block_cache
            }
        }
    }

    lazy_static! {
        pub static ref BLOCK_CACHE_MANAGER: Mutex<BlockCacheManager> = {
            kprintln!("[KERN EASYFS] block_cache::lazy_static!BLOCK_CACHE_MANAGER begin");
            Mutex::new(BlockCacheManager::new())
        };
    }

    pub fn get_block_cache(
        block_id: usize,
        block_device: Arc<dyn BlockDevice>,
    ) -> Arc<Mutex<BlockCache>> {
        //kprintln!("[KERN EASYFS] block_cache::get_block_cache() begin");
        BLOCK_CACHE_MANAGER
            .lock()
            .get_block_cache(block_id, block_device)
    }

    pub fn block_cache_sync_all() {
        kprintln!("[KERN EASYFS] block_cache::block_cache_sync_all() begin");
        let manager = BLOCK_CACHE_MANAGER.lock();
        for (_, cache) in manager.queue.iter() {
            cache.lock().sync();
        }
    }