      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

    use super::{
        block_cache_sync_all, get_block_cache, BlockDevice, DirEntry, DiskInode, DiskInodeType,
        EasyFileSystem, DIRENT_SZ,
    };
    use alloc::string::String;
    use alloc::sync::Arc;
    use alloc::vec::Vec;
    use spin::{Mutex, MutexGuard};

    pub struct Inode {
        block_id: usize,
        block_offset: usize,
        fs: Arc<Mutex<EasyFileSystem>>,
        block_device: Arc<dyn BlockDevice>,
    }

    impl Inode {
        /// We should not acquire efs lock here.
        pub fn new(
            block_id: u32,
            block_offset: usize,
            fs: Arc<Mutex<EasyFileSystem>>,
            block_device: Arc<dyn BlockDevice>,
        ) -> Self {
            kprintln!("[KERN EASYFS] vfs::Inode::new() begin");
            Self {
                block_id: block_id as usize,
                block_offset,
                fs,
                block_device,
            }
        }

        fn read_disk_inode<V>(&self, f: impl FnOnce(&DiskInode) -> V) -> V {
            kprintln!("[KERN EASYFS] vfs::Inode::read_disk_inode() begin");
            get_block_cache(self.block_id, Arc::clone(&self.block_device))
                .lock()
                .read(self.block_offset, f)
        }

        fn modify_disk_inode<V>(&self, f: impl FnOnce(&mut DiskInode) -> V) -> V {
            kprintln!("[KERN EASYFS] vfs::Inode::modify_disk_inode() begin");
            get_block_cache(self.block_id, Arc::clone(&self.block_device))
                .lock()
                .modify(self.block_offset, f)
        }

        fn find_inode_id(&self, name: &str, disk_inode: &DiskInode) -> Option<u32> {
            kprintln!("[KERN EASYFS] vfs::Inode::find_inode_id() begin");
            // assert it is a directory
            assert!(disk_inode.is_dir());
            let file_count = (disk_inode.size as usize) / DIRENT_SZ;
            let mut dirent = DirEntry::empty();
            for i in 0..file_count {
                assert_eq!(
                    disk_inode.read_at(DIRENT_SZ * i, dirent.as_bytes_mut(), &self.block_device,),
                    DIRENT_SZ,
                );
                if dirent.name() == name {
                    return Some(dirent.inode_number() as u32);
                }
            }
            None
        }

        pub fn find(&self, name: &str) -> Option<Arc<Inode>> {
            kprintln!("[KERN EASYFS] vfs::Inode::find() begin");
            let fs = self.fs.lock();
            self.read_disk_inode(|disk_inode| {
                self.find_inode_id(name, disk_inode).map(|inode_id| {
                    let (block_id, block_offset) = fs.get_disk_inode_pos(inode_id);
                    Arc::new(Self::new(
                        block_id,
                        block_offset,
                        self.fs.clone(),
                        self.block_device.clone(),
                    ))
                })
            })
        }

        fn increase_size(
            &self,
            new_size: u32,
            disk_inode: &mut DiskInode,
            fs: &mut MutexGuard<EasyFileSystem>,
        ) {
            kprintln!("[KERN EASYFS] vfs::Inode::increase_size() begin");
            if new_size < disk_inode.size {
                return;
            }
            let blocks_needed = disk_inode.blocks_num_needed(new_size);
            let mut v: Vec<u32> = Vec::new();
            for _ in 0..blocks_needed {
                v.push(fs.alloc_data());
            }
            disk_inode.increase_size(new_size, v, &self.block_device);
        }

        pub fn create(&self, name: &str) -> Option<Arc<Inode>> {
            kprintln!("[KERN EASYFS] vfs::Inode::create() begin");
            let mut fs = self.fs.lock();
            let op = |root_inode: &mut DiskInode| {
                // assert it is a directory
                assert!(root_inode.is_dir());
                // has the file been created?
                self.find_inode_id(name, root_inode)
            };
            if self.modify_disk_inode(op).is_some() {
                return None;
            }
            // create a new file
            // alloc a inode with an indirect block
            let new_inode_id = fs.alloc_inode();
            // initialize inode
            let (new_inode_block_id, new_inode_block_offset) = fs.get_disk_inode_pos(new_inode_id);
            get_block_cache(new_inode_block_id as usize, Arc::clone(&self.block_device))
                .lock()
                .modify(new_inode_block_offset, |new_inode: &mut DiskInode| {
                    new_inode.initialize(DiskInodeType::File);
                });
            self.modify_disk_inode(|root_inode| {
                // append file in the dirent
                let file_count = (root_inode.size as usize) / DIRENT_SZ;
                let new_size = (file_count + 1) * DIRENT_SZ;
                // increase size
                self.increase_size(new_size as u32, root_inode, &mut fs);
                // write dirent
                let dirent = DirEntry::new(name, new_inode_id);
                root_inode.write_at(
                    file_count * DIRENT_SZ,
                    dirent.as_bytes(),
                    &self.block_device,
                );
            });

            let (block_id, block_offset) = fs.get_disk_inode_pos(new_inode_id);
            block_cache_sync_all();
            kprintln!("[KERN EASYFS] vfs::Inode::create() end");
            // return inode
            Some(Arc::new(Self::new(
                block_id,
                block_offset,
                self.fs.clone(),
                self.block_device.clone(),
            )))
            // release efs lock automatically by compiler
        }

        pub fn ls(&self) -> Vec<String> {
            kprintln!("[KERN EASYFS] vfs::Inode::ls() begin");
            let _fs = self.fs.lock();
            self.read_disk_inode(|disk_inode| {
                let file_count = (disk_inode.size as usize) / DIRENT_SZ;
                let mut v: Vec<String> = Vec::new();
                for i in 0..file_count {
                    let mut dirent = DirEntry::empty();
                    assert_eq!(
                        disk_inode.read_at(i * DIRENT_SZ, dirent.as_bytes_mut(), &self.block_device,),
                        DIRENT_SZ,
                    );
                    v.push(String::from(dirent.name()));
                }
                v
            })
        }

        pub fn read_at(&self, offset: usize, buf: &mut [u8]) -> usize {
            kprintln!("[KERN EASYFS] vfs::Inode::read_at() begin");
            let _fs = self.fs.lock();
            self.read_disk_inode(|disk_inode| disk_inode.read_at(offset, buf, &self.block_device))
        }

        pub fn write_at(&self, offset: usize, buf: &[u8]) -> usize {
            kprintln!("[KERN EASYFS] vfs::Inode::write_at() begin");
            let mut fs = self.fs.lock();
            let size = self.modify_disk_inode(|disk_inode| {
                self.increase_size((offset + buf.len()) as u32, disk_inode, &mut fs);
                disk_inode.write_at(offset, buf, &self.block_device)
            });
            block_cache_sync_all();
            size
        }

        pub fn clear(&self) {
            kprintln!("[KERN EASYFS] vfs::Inode::clear() begin");
            let mut fs = self.fs.lock();
            self.modify_disk_inode(|disk_inode| {
                let size = disk_inode.size;
                let data_blocks_dealloc = disk_inode.clear_size(&self.block_device);
                assert!(data_blocks_dealloc.len() == DiskInode::total_blocks(size) as usize);
                for data_block in data_blocks_dealloc.into_iter() {
                    fs.dealloc_data(data_block);
                }
            });
            block_cache_sync_all();
        }
    }