diff --git a/os/src/fs/fat32/bpb.rs b/os/src/fs/fat32/bpb.rs index df53a251e6598349613f713422fed92d9c11f811..1841de1d2765e8a0ce3a0b755d76ba5680112cf8 100644 --- a/os/src/fs/fat32/bpb.rs +++ b/os/src/fs/fat32/bpb.rs @@ -5,39 +5,39 @@ use super::util::*; // Boot Sector with BPB, load from Sector 0 pub struct BootSector { // Boot - pub BS_jmpBoot: [u8; 3], // ignore. - pub BS_OEMName: [u8; 8], // usually "MSWIN4.1" - + pub BS_jmpBoot: [u8; 3], // ignore. + pub BS_OEMName: [u8; 8], // usually "MSWIN4.1" + // essential BPB - pub BPB_BytesPerSector: u16, // must 512, ..., 4096. usually 512 - pub BPB_SectorPerCluster: u8, // must 1,2,4,...,128. - pub BPB_ReservedSectorCount: u16, // usually 32 for FAT32 - pub BPB_NumFATs: u8, // usually 2 for FAT32 - pub BPB_RootEntryCount: u16, // must 0 for FAT32 - pub BPB_TotSector16: u16, // must 0 for FAT32 - pub BPB_Media: u8, // usually 0xF8, ignore. - pub BPB_FATsize16: u16, // must 0 for FAT32 - pub BPB_SectorPerTrack: u16, // use for int 0x13, ignore. - pub BPB_NumHeads: u16, // use for int 0x13, ignore. - pub BPB_HiddSec: u32, // Hideden Sector Count, ignore. - pub BPB_TotSector32: u32, // Total Sector count. + pub BPB_BytesPerSector: u16, // must 512, ..., 4096. usually 512 + pub BPB_SectorPerCluster: u8, // must 1,2,4,...,128. + pub BPB_ReservedSectorCount: u16, // usually 32 for FAT32 + pub BPB_NumFATs: u8, // usually 2 for FAT32 + pub BPB_RootEntryCount: u16, // must 0 for FAT32 + pub BPB_TotSector16: u16, // must 0 for FAT32 + pub BPB_Media: u8, // usually 0xF8, ignore. + pub BPB_FATsize16: u16, // must 0 for FAT32 + pub BPB_SectorPerTrack: u16, // use for int 0x13, ignore. + pub BPB_NumHeads: u16, // use for int 0x13, ignore. + pub BPB_HiddSec: u32, // Hideden Sector Count, ignore. + pub BPB_TotSector32: u32, // Total Sector count. // BPB For FAT32 - pub BPB_FATsize32: u32, // FAT Sector count. - pub BPB_ExtFlags: u16, // usually 0 - pub BPB_FSVer: u16, // must 0 in current version - pub BPB_RootCluster: u32, // Root Cluster id, usally 2 - pub BPB_FSInfo: u16, // FSINFO Sector id, usually 1 - pub BPB_BkBootSec: u16, // Backup Sector id, usually 6 - pub BPB_Reserved: [u8; 12], // 0 - pub BPB_DrvNum: u8, // use for 0x13, 0x80 - pub BPB_Reserved1: u8, // 0 - pub BPB_BootSig: u8, // 0x29 - pub BPB_VolID: u32, // xjb Generator + pub BPB_FATsize32: u32, // FAT Sector count. + pub BPB_ExtFlags: u16, // usually 0 + pub BPB_FSVer: u16, // must 0 in current version + pub BPB_RootCluster: u32, // Root Cluster id, usally 2 + pub BPB_FSInfo: u16, // FSINFO Sector id, usually 1 + pub BPB_BkBootSec: u16, // Backup Sector id, usually 6 + pub BPB_Reserved: [u8; 12], // 0 + pub BPB_DrvNum: u8, // use for 0x13, 0x80 + pub BPB_Reserved1: u8, // 0 + pub BPB_BootSig: u8, // 0x29 + pub BPB_VolID: u32, // xjb Generator // BS(end) - pub BS_VolLabel: [u8; 11], // 11*0x30 - pub BS_FileSysType: [u8; 8], // FAT32 0x30*3 + pub BS_VolLabel: [u8; 11], // 11*0x30 + pub BS_FileSysType: [u8; 8], // FAT32 0x30*3 } impl BootSector { @@ -49,10 +49,10 @@ impl BootSector { pub fn load(&mut self, src: &[u8; 512]) { let mut offset: usize = 0; - macro_rules ! load { + macro_rules! load { ($v: expr) => { load_fn(&mut $v, src, &mut offset); - } + }; } load!(self.BS_jmpBoot); load!(self.BS_OEMName); @@ -69,7 +69,7 @@ impl BootSector { load!(self.BPB_NumHeads); load!(self.BPB_HiddSec); load!(self.BPB_TotSector32); - + load!(self.BPB_FATsize32); load!(self.BPB_ExtFlags); load!(self.BPB_FSVer); @@ -85,13 +85,13 @@ impl BootSector { load!(self.BS_VolLabel); load!(self.BS_FileSysType); } - - pub fn store(&mut self, dest: &mut[u8; 512]) { + + pub fn store(&mut self, dest: &mut [u8; 512]) { let mut offset: usize = 0; - macro_rules ! store { + macro_rules! store { ($v: expr) => { store_fn(&$v, dest, &mut offset); - } + }; } store!(self.BS_jmpBoot); store!(self.BS_OEMName); @@ -108,7 +108,7 @@ impl BootSector { store!(self.BPB_NumHeads); store!(self.BPB_HiddSec); store!(self.BPB_TotSector32); - + store!(self.BPB_FATsize32); store!(self.BPB_ExtFlags); store!(self.BPB_FSVer); diff --git a/os/src/fs/fat32/dentry.rs b/os/src/fs/fat32/dentry.rs index fc58600be123039fd6e44f1fc5235399197cac8b..139258b1ceb82622810406c8aa68975d3271440c 100644 --- a/os/src/fs/fat32/dentry.rs +++ b/os/src/fs/fat32/dentry.rs @@ -1,25 +1,23 @@ +use alloc::{sync::Arc, vec::Vec}; -use alloc::{ - sync::Arc, - vec::Vec, -}; - -use log::{error, warn, debug, info}; +use log::{debug, error, info, warn}; use crate::{ - fs::{inode::{Inode, InodeMode, InodeMeta, InodeMetaInner}, Mutex,}, - driver::{block::{BlockDevice, self}}, - sync::mutex::SpinNoIrqLock, - utils::error::{GeneralRet, SyscallRet, SyscallErr, self}, + driver::block::{self, BlockDevice}, + fs::{ + inode::{Inode, InodeMeta, InodeMetaInner, InodeMode}, + Mutex, + }, mm::Page, + sync::mutex::SpinNoIrqLock, + utils::error::{self, GeneralRet, SyscallErr, SyscallRet}, }; use super::{ - SHORTNAME_LEN, - time::FAT32Timestamp, - LONGNAME_LEN, + disk_dentry::{DiskDirEntry, DiskLongDirEntry}, inode::FAT32Inode, - disk_dentry::{DiskLongDirEntry, DiskDirEntry}, + time::FAT32Timestamp, + LONGNAME_LEN, SHORTNAME_LEN, }; const ATTR_READ_ONLY: u8 = 0x01; @@ -42,7 +40,6 @@ pub struct FAT32DirEntry { info: Mutex<FAT32FileInfo>, } - pub struct FAT32FileInfo { short_name: [u8; SHORTNAME_LEN], long_name: [u16; LONGNAME_LEN], @@ -69,11 +66,7 @@ impl FAT32DirEntry { ) -> Option<Self> { let data: &[u8] = &dentry_data[*data_ptr..(*data_ptr + DENTRY_SIZE)]; *data_ptr += DENTRY_SIZE; - if data[0] == 0x00 { - - } - - + if data[0] == 0x00 {} let inode = FAT32DirEntry::fuck(); let info = FAT32FileInfo::new(); @@ -88,12 +81,9 @@ impl FAT32DirEntry { pub fn fuck() -> FAT32Inode { todo!(); } - } -pub struct DentryReader { - -} +pub struct DentryReader {} impl DentryReader { fn read_data(&self, data: &mut [u8]) -> Option<()> { @@ -110,9 +100,15 @@ pub fn resolve_dentry(dentry_reader: DentryReader) -> Vec<FAT32Inode> { let mut nxt_longdir_id = 0; // next longdir id let mut chksum: u8 = 0; while dentry_reader.read_data(&mut data).is_some() { - if data[0] == 0x00 { break; } - if data[0] == 0xE5 { continue; } - if data[0] == 0x05 { data[0] = 0xE5; } + if data[0] == 0x00 { + break; + } + if data[0] == 0xE5 { + continue; + } + if data[0] == 0x05 { + data[0] = 0xE5; + } if data[ATTR_ADDR] == ATTR_LONG_NAME { let processed_data = DiskLongDirEntry::new(&data); let mut id = processed_data.LDIR_Ord; @@ -125,17 +121,28 @@ pub fn resolve_dentry(dentry_reader: DentryReader) -> Vec<FAT32Inode> { error!("we expect not first long dir, but meet with first long dir"); } if nxt_longdir_id != id { - error!("we expect long dir id {}, but meet with id {}", nxt_longdir_id, id); + error!( + "we expect long dir id {}, but meet with id {}", + nxt_longdir_id, id + ); } } else { if first_longdir == false { - error!("we expect first long dir or short dir, but meet with not first long dir"); + error!( + "we expect first long dir or short dir, but meet with not first long dir" + ); } } let mut name_part: [u16; 13] = [0; 13]; - for i in 0..5 { name_part[i] = processed_data.LDIR_Name1[i]; } - for i in 5..11 { name_part[i] = processed_data.LDIR_Name2[i - 5]; } - for i in 11..13 { name_part[i] = processed_data.LDIR_Name3[i - 11]; } + for i in 0..5 { + name_part[i] = processed_data.LDIR_Name1[i]; + } + for i in 5..11 { + name_part[i] = processed_data.LDIR_Name2[i - 5]; + } + for i in 11..13 { + name_part[i] = processed_data.LDIR_Name3[i - 11]; + } if id == 1 { nxt_longdir = false; nxt_shortdir = true; @@ -148,7 +155,10 @@ pub fn resolve_dentry(dentry_reader: DentryReader) -> Vec<FAT32Inode> { chksum = processed_data.LDIR_Chksum; } else { if chksum != processed_data.LDIR_Chksum { - error!("LDIR chksum is not consistent!, {} != {}", chksum, processed_data.LDIR_Chksum); + error!( + "LDIR chksum is not consistent!, {} != {}", + chksum, processed_data.LDIR_Chksum + ); } } } else { @@ -157,4 +167,4 @@ pub fn resolve_dentry(dentry_reader: DentryReader) -> Vec<FAT32Inode> { } } ret -} \ No newline at end of file +} diff --git a/os/src/fs/fat32/disk_dentry.rs b/os/src/fs/fat32/disk_dentry.rs index e2399f1598469decfabefc62afef7fa243860daa..da708c0a89fdc0fe5dee9632fd8fab951a4c3eaa 100644 --- a/os/src/fs/fat32/disk_dentry.rs +++ b/os/src/fs/fat32/disk_dentry.rs @@ -18,8 +18,6 @@ pub struct DiskDirEntry { pub DIR_FileSize: u32, } - - #[allow(non_snake_case)] #[derive(Copy, Clone, Default)] pub struct DiskLongDirEntry { @@ -33,15 +31,14 @@ pub struct DiskLongDirEntry { pub LDIR_Name3: [u16; 2], } - impl DiskDirEntry { /// Initialize a BPB pub fn load(&mut self, src: &[u8]) { let mut offset: usize = 0; - macro_rules ! load { + macro_rules! load { ($v: expr) => { load_fn(&mut $v, src, &mut offset); - } + }; } load!(self.DIR_Name); load!(self.DIR_Attr); @@ -56,13 +53,13 @@ impl DiskDirEntry { load!(self.DIR_FstClusLO); load!(self.DIR_FileSize); } - - pub fn store(&mut self, dest: &mut[u8]) { + + pub fn store(&mut self, dest: &mut [u8]) { let mut offset: usize = 0; - macro_rules ! store { + macro_rules! store { ($v: expr) => { store_fn(&$v, dest, &mut offset); - } + }; } store!(self.DIR_Name); store!(self.DIR_Attr); @@ -89,10 +86,10 @@ impl DiskLongDirEntry { /// Initialize a BPB pub fn load(&mut self, src: &[u8]) { let mut offset: usize = 0; - macro_rules ! load { + macro_rules! load { ($v: expr) => { load_fn(&mut $v, src, &mut offset); - } + }; } load!(self.LDIR_Ord); load!(self.LDIR_Name1); @@ -103,13 +100,13 @@ impl DiskLongDirEntry { load!(self.LDIR_FstClusLO); load!(self.LDIR_Name3); } - - pub fn store(&mut self, dest: &mut[u8]) { + + pub fn store(&mut self, dest: &mut [u8]) { let mut offset: usize = 0; - macro_rules ! store { + macro_rules! store { ($v: expr) => { store_fn(&$v, dest, &mut offset); - } + }; } store!(self.LDIR_Ord); store!(self.LDIR_Name1); @@ -126,4 +123,3 @@ impl DiskLongDirEntry { ret } } - diff --git a/os/src/fs/fat32/fat.rs b/os/src/fs/fat32/fat.rs index 36c751a0e5dcedebfe3b04fd7e9b2f326cdbbd13..c70a43219894ba50dd7f1e31eee87f4dbeeb4243 100644 --- a/os/src/fs/fat32/fat.rs +++ b/os/src/fs/fat32/fat.rs @@ -1,24 +1,30 @@ -use alloc::{sync::Arc, collections::LinkedList}; +use alloc::{collections::LinkedList, sync::Arc}; use crate::{ - driver::block::{BlockDevice, self}, - fs::Mutex, utils::debug, + driver::block::{self, BlockDevice}, + fs::Mutex, + utils::debug, }; use log::debug; -use super::{FATENTRY_PER_SECTOR, FAT_CACHE_SIZE, fat32info::FAT32Info, fsinfo::FSInfo, FSI_LEADSIG, FSI_TRAILSIG, FSI_STRUCSIG, FSI_NOT_AVAILABLE}; +use super::{ + fat32info::FAT32Info, fsinfo::FSInfo, FATENTRY_PER_SECTOR, FAT_CACHE_SIZE, FSI_LEADSIG, + FSI_NOT_AVAILABLE, FSI_STRUCSIG, FSI_TRAILSIG, +}; /// 一个 FAT Sector Buffer çš„çŠ¶æ€ #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum FATSectorBufferState { Unassigned, // æœªåˆ†é… - Assigned, // 已分é…,未修改 - Dirty, // 已分é…,已修改未写回 + Assigned, // 已分é…,未修改 + Dirty, // 已分é…,已修改未写回 } impl Default for FATSectorBufferState { - fn default() -> Self { Self::Unassigned } + fn default() -> Self { + Self::Unassigned + } } #[derive(Clone, Copy)] @@ -43,8 +49,13 @@ impl FATSectorBuffer { if self.state == FATSectorBufferState::Dirty { for i in 0..fatinfo.fat_count { unsafe { - block_device.write_block(fatinfo.fat_start_sector + i * fatinfo.fat_sector_count + self.sector_no, - core::slice::from_raw_parts(self.data.as_ptr() as *const u8, self.data.len() * core::mem::size_of::<u32>())); + block_device.write_block( + fatinfo.fat_start_sector + i * fatinfo.fat_sector_count + self.sector_no, + core::slice::from_raw_parts( + self.data.as_ptr() as *const u8, + self.data.len() * core::mem::size_of::<u32>(), + ), + ); } } self.state = FATSectorBufferState::Assigned; @@ -56,13 +67,23 @@ impl FATSectorBuffer { self.state = FATSectorBufferState::Unassigned; } - pub fn init(&mut self, block_device: Arc<dyn BlockDevice>, fatinfo: Arc<FAT32Info>, sector_no: usize) { + pub fn init( + &mut self, + block_device: Arc<dyn BlockDevice>, + fatinfo: Arc<FAT32Info>, + sector_no: usize, + ) { self.free(Arc::clone(&block_device), Arc::clone(&fatinfo)); self.state = FATSectorBufferState::Assigned; self.sector_no = sector_no; unsafe { - block_device.read_block(fatinfo.fat_start_sector + self.sector_no, - core::slice::from_raw_parts_mut(self.data.as_mut_ptr() as *mut u8, self.data.len() * core::mem::size_of::<u32>())); + block_device.read_block( + fatinfo.fat_start_sector + self.sector_no, + core::slice::from_raw_parts_mut( + self.data.as_mut_ptr() as *mut u8, + self.data.len() * core::mem::size_of::<u32>(), + ), + ); } } @@ -102,10 +123,13 @@ impl FATBufferCache { fn lookup_buffer_cache(&self, sector_no: usize) -> Arc<Mutex<FATSectorBuffer>> { let mut data_locked = self.data.lock(); - if let Some((idx, _)) = data_locked.iter().enumerate() - .find(|(_, buffer)| buffer.0 == sector_no) { - let buffer = data_locked.remove(idx); - data_locked.push_front(buffer); + if let Some((idx, _)) = data_locked + .iter() + .enumerate() + .find(|(_, buffer)| buffer.0 == sector_no) + { + let buffer = data_locked.remove(idx); + data_locked.push_front(buffer); } else { if data_locked.len() == FAT_CACHE_SIZE { let buffer_replaced = data_locked.pop_back().unwrap().1; @@ -113,19 +137,25 @@ impl FATBufferCache { debug!("Fatal Error. FAT32 Run out of FAT Buffers!"); } let mut buffer_replaced_locked = buffer_replaced.lock(); - buffer_replaced_locked.init(Arc::clone(&self.block_device), Arc::clone(&self.info), sector_no); + buffer_replaced_locked.init( + Arc::clone(&self.block_device), + Arc::clone(&self.info), + sector_no, + ); data_locked.push_front((sector_no, Arc::clone(&buffer_replaced))); } else { let mut new_buffer = FATSectorBuffer::default(); - new_buffer.init(Arc::clone(&self.block_device), Arc::clone(&self.info), sector_no); + new_buffer.init( + Arc::clone(&self.block_device), + Arc::clone(&self.info), + sector_no, + ); data_locked.push_front((sector_no, Arc::new(Mutex::new(new_buffer)))); } - } Arc::clone(&data_locked.front().unwrap().1) } - fn read_fat(&self, cluster_id: usize) -> Option<u32> { if cluster_id < 2 || cluster_id > self.info.tot_cluster_count + 1 { return None; @@ -135,10 +165,16 @@ impl FATBufferCache { let fat_sector = self.lookup_buffer_cache(sector_id); let fat_sector_locked = fat_sector.lock(); if fat_sector_locked.state == FATSectorBufferState::Unassigned { - debug!("[FAT] Got an unassigned sector buffer! require = {}", sector_id); + debug!( + "[FAT] Got an unassigned sector buffer! require = {}", + sector_id + ); } if fat_sector_locked.sector_no != sector_id { - debug!("[FAT] Sector buffer is wrong! require = {}, got = {}", sector_id, fat_sector_locked.sector_no); + debug!( + "[FAT] Sector buffer is wrong! require = {}, got = {}", + sector_id, fat_sector_locked.sector_no + ); } fat_sector_locked.read(offset) } @@ -152,10 +188,16 @@ impl FATBufferCache { let fat_sector = self.lookup_buffer_cache(sector_id); let mut fat_sector_locked = fat_sector.lock(); if fat_sector_locked.state == FATSectorBufferState::Unassigned { - debug!("[FAT] Got an unassigned sector buffer! require = {}", sector_id); + debug!( + "[FAT] Got an unassigned sector buffer! require = {}", + sector_id + ); } if fat_sector_locked.sector_no != sector_id { - debug!("[FAT] Sector buffer is wrong! require = {}, got = {}", sector_id, fat_sector_locked.sector_no); + debug!( + "[FAT] Sector buffer is wrong! require = {}, got = {}", + sector_id, fat_sector_locked.sector_no + ); } fat_sector_locked.write(offset, val) } @@ -167,20 +209,29 @@ impl FATBufferCache { let fat_sector = self.lookup_buffer_cache(sector_id); let mut fat_sector_locked = fat_sector.lock(); if fat_sector_locked.state == FATSectorBufferState::Unassigned { - debug!("[FAT] Got an unassigned sector buffer! require = {}", sector_id); + debug!( + "[FAT] Got an unassigned sector buffer! require = {}", + sector_id + ); } if fat_sector_locked.sector_no != sector_id { - debug!("[FAT] Sector buffer is wrong! require = {}, got = {}", sector_id, fat_sector_locked.sector_no); + debug!( + "[FAT] Sector buffer is wrong! require = {}, got = {}", + sector_id, fat_sector_locked.sector_no + ); } fat_sector_locked.sync(Arc::clone(&self.block_device), Arc::clone(&self.info)); Some(()) } } - + fn sync_all_buffers(&self) { let data_locked = self.data.lock(); for buffer in data_locked.iter() { - buffer.1.lock().sync(Arc::clone(&self.block_device), Arc::clone(&self.info)); + buffer + .1 + .lock() + .sync(Arc::clone(&self.block_device), Arc::clone(&self.info)); } } } @@ -210,28 +261,34 @@ impl FileAllocTable { let fsinfo_raw = FSInfo::new(&fsinfo_data); if fsinfo_raw.FSI_LeadSig != FSI_LEADSIG || fsinfo_raw.FSI_TrailSig != FSI_TRAILSIG - || fsinfo_raw.FSI_StrucSig != FSI_STRUCSIG { + || fsinfo_raw.FSI_StrucSig != FSI_STRUCSIG + { debug!("fsinfo magic number 有误ï¼"); } let free_count = fsinfo_raw.FSI_Free_Count as usize; let nxt_free = fsinfo_raw.FSI_Nxt_Free as usize; - + let mut ret = Self { block_device: Arc::clone(&block_device), info: Arc::clone(&info), fatcache: FATBufferCache::new(Arc::clone(&block_device), Arc::clone(&info)), - fatmeta: Arc::new(Mutex::new(FATMeta{ free_count, nxt_free})), + fatmeta: Arc::new(Mutex::new(FATMeta { + free_count, + nxt_free, + })), }; ret.stat_free(); ret } fn stat_free(&self) { let mut fatmeta_locked = self.fatmeta.lock(); - if fatmeta_locked.free_count == (FSI_NOT_AVAILABLE as usize) || fatmeta_locked.nxt_free == (FSI_NOT_AVAILABLE as usize) { + if fatmeta_locked.free_count == (FSI_NOT_AVAILABLE as usize) + || fatmeta_locked.nxt_free == (FSI_NOT_AVAILABLE as usize) + { fatmeta_locked.free_count = 0; fatmeta_locked.nxt_free = 0; for i in 0..self.info.tot_cluster_count { - let cluster_id = i+2; + let cluster_id = i + 2; let fatentry = self.read_fat(cluster_id).unwrap() & 0x0FFFFFFF; if fatentry == 0 { fatmeta_locked.free_count += 1; @@ -249,7 +306,7 @@ impl FileAllocTable { pub fn write_fat(&self, cluster_id: usize, val: u32) -> Option<()> { self.fatcache.write_fat(cluster_id, val) } - + pub fn sync_fat(&self) { self.fatcache.sync_all_buffers(); } @@ -262,7 +319,7 @@ impl FileAllocTable { Some(fatmeta_locked.nxt_free) } else { for i in 0..self.info.tot_cluster_count { - let cluster_id = i+2; + let cluster_id = i + 2; let fatentry = self.read_fat(cluster_id).unwrap() & 0x0FFFFFFF; if fatentry == 0 { fatmeta_locked.free_count -= 1; @@ -301,6 +358,4 @@ impl FileAllocTable { fatmeta_locked.free_count += 1; Some(()) } - - } diff --git a/os/src/fs/fat32/fat32info.rs b/os/src/fs/fat32/fat32info.rs index 87a6998142f79b30f660e09575402369e61b2b88..e5e48cc91bf5f138fa3fe53134048bbc01ad82ec 100644 --- a/os/src/fs/fat32/fat32info.rs +++ b/os/src/fs/fat32/fat32info.rs @@ -18,7 +18,8 @@ impl FAT32Info { pub fn new(bs: BootSector) -> Self { let start_sector = (bs.BPB_ReservedSectorCount as usize) + (bs.BPB_NumFATs as usize) * (bs.BPB_FATsize32 as usize); - let cluster_count = (bs.BPB_TotSector32 as usize - start_sector) / (bs.BPB_SectorPerCluster as usize); + let cluster_count = + (bs.BPB_TotSector32 as usize - start_sector) / (bs.BPB_SectorPerCluster as usize); Self { bk_bootsector_id: bs.BPB_BkBootSec as usize, fsinfo_sector_id: bs.BPB_FSInfo as usize, diff --git a/os/src/fs/fat32/file.rs b/os/src/fs/fat32/file.rs index 9f6b51c924c1816fe6ffc1548e5fc6cbb4a0f3c6..de4c07432cb5a1e7f6397744620317aed7081acf 100644 --- a/os/src/fs/fat32/file.rs +++ b/os/src/fs/fat32/file.rs @@ -1,5 +1,5 @@ use alloc::{sync::Arc, vec::Vec}; -use core::cmp::{min, max}; +use core::cmp::{max, min}; use super::{fat::FileAllocTable, SECTOR_SIZE}; @@ -18,7 +18,7 @@ impl FAT32File { Self { fat: Arc::clone(&fat), clusters: clusters_vec, - size + size, } } @@ -42,7 +42,8 @@ impl FAT32File { self.get_clusters(); if delta < 0 && (self.size.unwrap() as isize) + delta >= 0 { let new_sz = ((self.size.unwrap() as isize) + delta) as usize; - let cluster_count = (new_sz + self.fat.info.sector_per_cluster * SECTOR_SIZE - 1) / (self.fat.info.sector_per_cluster * SECTOR_SIZE); + let cluster_count = (new_sz + self.fat.info.sector_per_cluster * SECTOR_SIZE - 1) + / (self.fat.info.sector_per_cluster * SECTOR_SIZE); while self.clusters.len() > cluster_count { let end0 = self.clusters.pop().unwrap(); if self.clusters.len() > 0 { @@ -55,11 +56,15 @@ impl FAT32File { self.size = Some(new_sz); } else if delta > 0 { let new_sz = self.size.unwrap() + (delta as usize); - let cluster_count = (new_sz + self.fat.info.sector_per_cluster * SECTOR_SIZE - 1) / (self.fat.info.sector_per_cluster * SECTOR_SIZE); + let cluster_count = (new_sz + self.fat.info.sector_per_cluster * SECTOR_SIZE - 1) + / (self.fat.info.sector_per_cluster * SECTOR_SIZE); while self.clusters.len() < cluster_count { let new_cluster; if self.clusters.len() > 0 { - new_cluster = self.fat.alloc_cluster(Some(*self.clusters.last().unwrap())).unwrap(); + new_cluster = self + .fat + .alloc_cluster(Some(*self.clusters.last().unwrap())) + .unwrap(); } else { new_cluster = self.fat.alloc_cluster(None).unwrap(); } @@ -76,23 +81,26 @@ impl FAT32File { let ed = min(offset + data.len(), self.size.unwrap()); let ret = ed - st; let st_cluster = st / (self.fat.info.sector_per_cluster * SECTOR_SIZE); - let ed_cluster = (ed + self.fat.info.sector_per_cluster * SECTOR_SIZE - 1) / (self.fat.info.sector_per_cluster * SECTOR_SIZE); + let ed_cluster = (ed + self.fat.info.sector_per_cluster * SECTOR_SIZE - 1) + / (self.fat.info.sector_per_cluster * SECTOR_SIZE); for cseq in st_cluster..ed_cluster { let cluster_id = self.clusters[cseq]; let sector_id = self.fat.info.cid_to_sid(cluster_id).unwrap(); for j in 0..self.fat.info.sector_per_cluster { // off=(cseq*SectorPerCluster+j) // byte=[off*SECTOR_SIZE, (off+1)*SECTOR_SIZE) - let off = cseq*self.fat.info.sector_per_cluster+j; - let sector_st = off*SECTOR_SIZE; - let sector_ed = sector_st+SECTOR_SIZE; + let off = cseq * self.fat.info.sector_per_cluster + j; + let sector_st = off * SECTOR_SIZE; + let sector_ed = sector_st + SECTOR_SIZE; if sector_ed <= st || sector_st >= ed { continue; } let cur_st = max(sector_st, st); let cur_ed = min(sector_ed, ed); let mut tmp_data: [u8; SECTOR_SIZE] = [0; SECTOR_SIZE]; - self.fat.block_device.read_block(sector_id + j, &mut tmp_data[..]); + self.fat + .block_device + .read_block(sector_id + j, &mut tmp_data[..]); for i in cur_st..cur_ed { data[i - st] = tmp_data[i - sector_st]; } @@ -107,16 +115,17 @@ impl FAT32File { let ed = min(offset + data.len(), self.size.unwrap()); let ret = ed - st; let st_cluster = st / (self.fat.info.sector_per_cluster * SECTOR_SIZE); - let ed_cluster = (ed + self.fat.info.sector_per_cluster * SECTOR_SIZE - 1) / (self.fat.info.sector_per_cluster * SECTOR_SIZE); + let ed_cluster = (ed + self.fat.info.sector_per_cluster * SECTOR_SIZE - 1) + / (self.fat.info.sector_per_cluster * SECTOR_SIZE); for cseq in st_cluster..ed_cluster { let cluster_id = self.clusters[cseq]; let sector_id = self.fat.info.cid_to_sid(cluster_id).unwrap(); for j in 0..self.fat.info.sector_per_cluster { // off=(cseq*SectorPerCluster+j) // byte=[off*SECTOR_SIZE, (off+1)*SECTOR_SIZE) - let off = cseq*self.fat.info.sector_per_cluster+j; - let sector_st = off*SECTOR_SIZE; - let sector_ed = sector_st+SECTOR_SIZE; + let off = cseq * self.fat.info.sector_per_cluster + j; + let sector_st = off * SECTOR_SIZE; + let sector_ed = sector_st + SECTOR_SIZE; if sector_ed <= st || sector_st >= ed { continue; } @@ -124,14 +133,18 @@ impl FAT32File { let cur_ed = min(sector_ed, ed); let mut tmp_data: [u8; SECTOR_SIZE] = [0; SECTOR_SIZE]; if cur_st != sector_st || cur_ed != sector_ed { - self.fat.block_device.read_block(sector_id + j, &mut tmp_data[..]); + self.fat + .block_device + .read_block(sector_id + j, &mut tmp_data[..]); } for i in cur_st..cur_ed { tmp_data[i - sector_st] = data[i - st]; } - self.fat.block_device.write_block(sector_id + j, &tmp_data[..]); + self.fat + .block_device + .write_block(sector_id + j, &tmp_data[..]); } } ret } -} \ No newline at end of file +} diff --git a/os/src/fs/fat32/fsinfo.rs b/os/src/fs/fat32/fsinfo.rs index d9e64663d1e9bfadc3c58c3dc892dd0a4389362a..bf7cdd1d3582e30453f492c6cc125b7a579fb793 100644 --- a/os/src/fs/fat32/fsinfo.rs +++ b/os/src/fs/fat32/fsinfo.rs @@ -1,4 +1,6 @@ -use crate::fs::fat32::{FSI_LEADSIG, FSI_STRUCSIG, FSI_TRAILSIG, FSI_RESERVED1_SIZE, FSI_RESERVED2_SIZE}; +use crate::fs::fat32::{ + FSI_LEADSIG, FSI_RESERVED1_SIZE, FSI_RESERVED2_SIZE, FSI_STRUCSIG, FSI_TRAILSIG, +}; use super::util::*; #[allow(non_snake_case)] @@ -22,10 +24,10 @@ impl FSInfo { pub fn load(&mut self, src: &[u8; 512]) { let mut offset: usize = 0; - macro_rules ! load { + macro_rules! load { ($v: expr) => { load_fn(&mut $v, src, &mut offset); - } + }; } load!(self.FSI_LeadSig); offset += FSI_RESERVED1_SIZE; @@ -35,13 +37,13 @@ impl FSInfo { offset += FSI_RESERVED2_SIZE; load!(self.FSI_TrailSig); } - - pub fn store(&mut self, dest: &mut[u8; 512]) { + + pub fn store(&mut self, dest: &mut [u8; 512]) { let mut offset: usize = 0; - macro_rules ! store { + macro_rules! store { ($v: expr) => { store_fn(&$v, dest, &mut offset); - } + }; } store!(FSI_LEADSIG); offset += FSI_RESERVED1_SIZE; diff --git a/os/src/fs/fat32/inode.rs b/os/src/fs/fat32/inode.rs index 4ce9a5da2533b62d3973dfa4d7f96eb4db5f84b1..da4697540b05b721f3c13ccebfc1cf1285a753b5 100644 --- a/os/src/fs/fat32/inode.rs +++ b/os/src/fs/fat32/inode.rs @@ -1,15 +1,24 @@ - -use alloc::{sync::{Arc, Weak}, vec::Vec}; use crate::{ - fs::{inode::{Inode, InodeMode, InodeMeta, InodeMetaInner}, Mutex, fat32_tmp::Fat32File, File, file}, - driver::{block::{BlockDevice, self, BLOCK_DEVICE}}, - sync::mutex::SpinNoIrqLock, - utils::error::{GeneralRet, SyscallRet, SyscallErr}, + driver::block::{self, BlockDevice, BLOCK_DEVICE}, + fs::{ + fat32_tmp::Fat32File, + file, + inode::{Inode, InodeMeta, InodeMetaInner, InodeMode}, + File, Mutex, + }, mm::Page, + sync::mutex::SpinNoIrqLock, + utils::error::{GeneralRet, SyscallErr, SyscallRet}, +}; +use alloc::{ + sync::{Arc, Weak}, + vec::Vec, }; -use super::{SHORTNAME_LEN, time::FAT32Timestamp, LONGNAME_LEN, fat::FileAllocTable, FAT32FileSystemMeta, FAT32Info, file::FAT32File}; - +use super::{ + fat::FileAllocTable, file::FAT32File, time::FAT32Timestamp, FAT32FileSystemMeta, FAT32Info, + LONGNAME_LEN, SHORTNAME_LEN, +}; #[derive(Copy, Clone)] pub enum FAT32FileType { @@ -63,13 +72,13 @@ impl FAT32Inode { fat: Arc::clone(&fat), meta: Mutex::new(meta), content: Mutex::new(FAT32File::new( - Arc::clone(&fat), - first_cluster, - match file_type { - FAT32FileType::Regfile => Some(file_size), - FAT32FileType::Directory => None, - } - )), + Arc::clone(&fat), + first_cluster, + match file_type { + FAT32FileType::Regfile => Some(file_size), + FAT32FileType::Directory => None, + }, + )), father, sons: None, } diff --git a/os/src/fs/fat32/mod.rs b/os/src/fs/fat32/mod.rs index f606cb9dbf03175a49eff65f21d9e855aa4ff070..444adbc0dcdcfdcad79990edc91d7c565e57421f 100644 --- a/os/src/fs/fat32/mod.rs +++ b/os/src/fs/fat32/mod.rs @@ -1,39 +1,37 @@ +use crate::driver::block::BlockDevice; use alloc::sync::Arc; use log::debug; -use crate::{ - driver::block::BlockDevice, -}; use self::{ bpb::BootSector, - inode::{FAT32Inode, FAT32InodeMeta}, + fat::FileAllocTable, fat32info::FAT32Info, - fat::FileAllocTable + inode::{FAT32Inode, FAT32InodeMeta}, }; mod bpb; +mod dentry; mod disk_dentry; -mod fsinfo; -mod util; mod fat; -mod dentry; -mod inode; -mod time; mod fat32info; mod file; +mod fsinfo; +mod inode; +mod time; +mod util; -const SECTOR_SIZE: usize = 512; -const SHORTNAME_LEN: usize = 11; -const LONGNAME_LEN: usize = 255; -const BOOT_SECTOR_ID: usize = 0; -const FATENTRY_PER_SECTOR: usize = 128; -const FAT_CACHE_SIZE: usize = 16; -const FSI_LEADSIG: u32 = 0x41615252; -const FSI_STRUCSIG: u32 = 0x61417272; -const FSI_TRAILSIG: u32 = 0xAA550000; -const FSI_RESERVED1_SIZE: usize = 480; -const FSI_RESERVED2_SIZE: usize = 12; -const FSI_NOT_AVAILABLE: u32 = 0xFFFFFFFF; +const SECTOR_SIZE: usize = 512; +const SHORTNAME_LEN: usize = 11; +const LONGNAME_LEN: usize = 255; +const BOOT_SECTOR_ID: usize = 0; +const FATENTRY_PER_SECTOR: usize = 128; +const FAT_CACHE_SIZE: usize = 16; +const FSI_LEADSIG: u32 = 0x41615252; +const FSI_STRUCSIG: u32 = 0x61417272; +const FSI_TRAILSIG: u32 = 0xAA550000; +const FSI_RESERVED1_SIZE: usize = 480; +const FSI_RESERVED2_SIZE: usize = 12; +const FSI_NOT_AVAILABLE: u32 = 0xFFFFFFFF; pub struct FAT32FileSystemMeta { info: Arc<FAT32Info>, @@ -61,26 +59,35 @@ impl FAT32FileSystem { return None; } let mut bs_data: [u8; SECTOR_SIZE] = [0; SECTOR_SIZE]; - self.block_device.read_block(BOOT_SECTOR_ID, &mut bs_data[..]); + self.block_device + .read_block(BOOT_SECTOR_ID, &mut bs_data[..]); let raw_bs: BootSector = BootSector::new(&bs_data); if raw_bs.BPB_BytesPerSector as usize != SECTOR_SIZE || raw_bs.BPB_RootEntryCount != 0 || raw_bs.BPB_TotSector16 != 0 || raw_bs.BPB_FATsize16 != 0 - || raw_bs.BPB_FSVer != 0 { - return None; + || raw_bs.BPB_FSVer != 0 + { + return None; } let info = Arc::new(FAT32Info::new(raw_bs)); - let fat = Arc::new(FileAllocTable::new(Arc::clone(&self.block_device), Arc::clone(&info))); - let root_inode = Arc::new( - FAT32Inode::new( - Arc::clone(&fat), - None, - info.root_cluster_id, - 0, - inode::FAT32FileType::Directory, - FAT32InodeMeta::default())); - self.meta = Some(FAT32FileSystemMeta { info: Arc::clone(&info), fat, root_inode: Arc::clone(&root_inode) }); + let fat = Arc::new(FileAllocTable::new( + Arc::clone(&self.block_device), + Arc::clone(&info), + )); + let root_inode = Arc::new(FAT32Inode::new( + Arc::clone(&fat), + None, + info.root_cluster_id, + 0, + inode::FAT32FileType::Directory, + FAT32InodeMeta::default(), + )); + self.meta = Some(FAT32FileSystemMeta { + info: Arc::clone(&info), + fat, + root_inode: Arc::clone(&root_inode), + }); Some(()) } @@ -95,7 +102,6 @@ impl FAT32FileSystem { debug!("å¸è½½å¤±è´¥äº†ï¼"); None } - } pub fn root_inode(&self) -> Option<Arc<FAT32Inode>> { @@ -117,5 +123,4 @@ impl FAT32FileSystem { Some(()) } } - } diff --git a/os/src/fs/fat32/time.rs b/os/src/fs/fat32/time.rs index 675850c114ae90d075209894fbd9519149816c43..c87e161796240468af4fd3f99e914ac73edfbf89 100644 --- a/os/src/fs/fat32/time.rs +++ b/os/src/fs/fat32/time.rs @@ -12,7 +12,6 @@ const SEC_PER_MIN: i64 = 60; const MIN_PER_HR: i64 = 60; const HR_PER_DAY: i64 = 24; - const MILLISEC_PER_MIN: i64 = MILLISEC_PER_SEC * SEC_PER_MIN; const MILLISEC_PER_HR: i64 = MILLISEC_PER_MIN * MIN_PER_HR; const MILLISEC_PER_DAY: i64 = MILLISEC_PER_HR * HR_PER_DAY; @@ -21,7 +20,6 @@ const DAY_PER_YEAR: i64 = 365; const DAY_PER_400YEAR: i64 = DAY_PER_YEAR * 400 + 97; const DAY_PER_MONTH: [i64; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - fn leap_year(year: i64) -> bool { year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) } @@ -45,7 +43,11 @@ pub fn unix_time_to_FAT32(unix_time: i64) -> FAT32Timestamp { let mut day_in_year: i64 = -1; for y in maybe_years { let start_day = year_to_day_count(y); - let day_in_y = DAY_PER_YEAR + match leap_year(y) {true => 1, false => 0}; + let day_in_y = DAY_PER_YEAR + + match leap_year(y) { + true => 1, + false => 0, + }; let day_id = day_count - start_day; if day_id >= 0 && day_id < day_in_y { day_in_year = day_id; @@ -56,7 +58,11 @@ pub fn unix_time_to_FAT32(unix_time: i64) -> FAT32Timestamp { let mut month: i64 = -1; let mut day: i64 = -1; for m in 0..12 { - let day_in_m = DAY_PER_MONTH[m] + match m == 1 && leap_year(year) { true => 1, false => 0}; + let day_in_m = DAY_PER_MONTH[m] + + match m == 1 && leap_year(year) { + true => 1, + false => 0, + }; if day_in_year < day_in_m { month = m as i64; day = day_in_year; @@ -69,7 +75,7 @@ pub fn unix_time_to_FAT32(unix_time: i64) -> FAT32Timestamp { let min = (millisec_in_day % MILLISEC_PER_HR) / MILLISEC_PER_MIN; let sec = (millisec_in_day % MILLISEC_PER_MIN) / MILLISEC_PER_SEC; let millisec = millisec_in_day % MILLISEC_PER_SEC; -// println!("year={}, month={}, day={}, hr={}, min={}, sec={}, millisec={}", year, month, day, hr, min, sec, millisec); + // println!("year={}, month={}, day={}, hr={}, min={}, sec={}, millisec={}", year, month, day, hr, min, sec, millisec); FAT32Timestamp { date: ((day + 1) + ((month + 1) << 5) + (((year - 1980) & 0x7F) << 9)) as u16, time: ((sec / 2) + (min << 5) + (hr << 11)) as u16, @@ -78,9 +84,13 @@ pub fn unix_time_to_FAT32(unix_time: i64) -> FAT32Timestamp { } fn month_to_day_count(month: i64, leap: bool) -> i64 { - let mut ret:i64 = 0; + let mut ret: i64 = 0; for i in 0..month { - ret += DAY_PER_MONTH[i as usize] + match i == 1 && leap { true => 1, false => 0}; + ret += DAY_PER_MONTH[i as usize] + + match i == 1 && leap { + true => 1, + false => 0, + }; } ret } @@ -95,7 +105,8 @@ pub fn FAT32_to_unix_time(fat32_time: FAT32Timestamp) -> i64 { let min = ((fat32_time.time >> 5) & 0x3F) as i64; let sec = (fat32_time.time & 0x1F) as i64; let millisec = (fat32_time.tenms as i64) * 10; -// println!("year={}, month={}, day={}, hr={}, min={}, sec={}, millisec={}", year, month, day, hr, min, sec, millisec); + // println!("year={}, month={}, day={}, hr={}, min={}, sec={}, millisec={}", year, month, day, hr, min, sec, millisec); (year_to_day_count(year) + month_to_day_count(month, leap_year(year)) + day) * MILLISEC_PER_DAY - + (((hr * MIN_PER_HR + min) * SEC_PER_MIN + sec * 2) * MILLISEC_PER_SEC) + millisec + + (((hr * MIN_PER_HR + min) * SEC_PER_MIN + sec * 2) * MILLISEC_PER_SEC) + + millisec } diff --git a/os/src/fs/fat32/util.rs b/os/src/fs/fat32/util.rs index 9a02e17fdf65c3c784e710c0c1142d7c5ef0ed12..48635400ba640ee83f61a368416f44abf34be99a 100644 --- a/os/src/fs/fat32/util.rs +++ b/os/src/fs/fat32/util.rs @@ -16,13 +16,15 @@ pub fn store_fn<T: Copy>(src: &T, dst: &mut [u8], offset: &mut usize) { } } - - /// rust æ•´æ•°æº¢å‡ºä¼šæŠ¥é”™ï¼Œå› æ¤æˆ‘们åªèƒ½ä½¿ç”¨ u16 累积。 pub fn shortname_checksum(data: [u8; SHORTNAME_LEN]) -> u8 { let mut ret: u16 = 0; for i in 0..SHORTNAME_LEN { - ret = (match ret & 1 {1 => 0x80, _ => 0, } + (ret >> 1) + data[i] as u16); + ret = (match ret & 1 { + 1 => 0x80, + _ => 0, + } + (ret >> 1) + + data[i] as u16); ret &= 0xFF; } ret as u8 @@ -41,4 +43,4 @@ unsigned char ChkSum (unsigned char *pFcbName) } return (Sum); } -*/ \ No newline at end of file +*/ diff --git a/os/src/fs/fat32_tmp/mod.rs b/os/src/fs/fat32_tmp/mod.rs index 485d86cbc20690b3bb5a4949db3790e65ecacfef..18d9a5deec242428256a5a4fe5829ff0ddb50448 100644 --- a/os/src/fs/fat32_tmp/mod.rs +++ b/os/src/fs/fat32_tmp/mod.rs @@ -1,13 +1,16 @@ use core::cell::UnsafeCell; +use core::panic; use alloc::string::ToString; use alloc::sync::Arc; use alloc::{boxed::Box, vec::Vec}; use fatfs::{DirEntry, Read, Seek, Write}; use lazy_static::*; -use log::{debug, error, info}; +use log::{debug, error, info, warn}; +use crate::fs::file::DefaultFile; use crate::fs::inode::INODE_CACHE; +use crate::mm::PageCache; use crate::utils::error::{self, AsyscallRet, SyscallErr}; use crate::{ driver::{block::IoDevice, BLOCK_DEVICE}, @@ -129,10 +132,10 @@ impl Inode for Fat32RootInode { inode_mode, data_len as usize, ); - meta_inner.children.insert( - dentry.as_ref().unwrap().file_name(), - Arc::new(Fat32Inode::new(dentry.unwrap(), Some(meta))), - ); + let file_name = dentry.as_ref().unwrap().file_name(); + let child = Arc::new(Fat32Inode::new(dentry.unwrap(), Some(meta))); + child.metadata().inner.lock().page_cache = Some(PageCache::new(child.clone(), 3)); + meta_inner.children.insert(file_name, child); } } @@ -232,7 +235,6 @@ impl Fat32Inode { impl Inode for Fat32Inode { fn open(&self, this: Arc<dyn Inode>, flags: OpenFlags) -> GeneralRet<Arc<dyn File>> { debug!("[Fat32Inode]: open: name: {}", self.dentry.file_name()); - let (readable, writable) = flags.read_write(); let file_meta = FileMeta { // TODO: not sure whether this file_name() is absolute path or not path: self.dentry.file_name(), @@ -242,23 +244,25 @@ impl Inode for Fat32Inode { pos: 0, }), }; - if self.dentry.is_dir() { - Ok(Arc::new(Fat32File::new( - Fat32NodeType::Dir(self.dentry.to_dir()), - Some(file_meta), - readable, - writable, - ))) - } else if self.dentry.is_file() { - Ok(Arc::new(Fat32File::new( - Fat32NodeType::File(self.dentry.to_file()), - Some(file_meta), - readable, - writable, - ))) - } else { - Err(SyscallErr::EBADF) - } + Ok(Arc::new(DefaultFile::new(file_meta))) + // let (readable, writable) = flags.read_write(); + // if self.dentry.is_dir() { + // Ok(Arc::new(Fat32File::new( + // Fat32NodeType::Dir(self.dentry.to_dir()), + // Some(file_meta), + // readable, + // writable, + // ))) + // } else if self.dentry.is_file() { + // Ok(Arc::new(Fat32File::new( + // Fat32NodeType::File(self.dentry.to_file()), + // Some(file_meta), + // readable, + // writable, + // ))) + // } else { + // Err(SyscallErr::EBADF) + // } } fn metadata(&self) -> &InodeMeta { @@ -292,10 +296,10 @@ impl Inode for Fat32Inode { inode_mode, data_len as usize, ); - meta_inner.children.insert( - dentry.as_ref().unwrap().file_name(), - Arc::new(Fat32Inode::new(dentry.unwrap(), Some(meta))), - ); + let file_name = dentry.as_ref().unwrap().file_name(); + let child = Arc::new(Fat32Inode::new(dentry.unwrap(), Some(meta))); + child.metadata().inner.lock().page_cache = Some(PageCache::new(child.clone(), 3)); + meta_inner.children.insert(file_name, child); } } @@ -344,6 +348,38 @@ impl Inode for Fat32Inode { .insert(new_inode.metadata().name.clone(), new_inode); Ok(()) } + + fn read(&self, offset: usize, buf: &mut [u8]) -> GeneralRet<usize> { + if self.dentry.is_dir() { + return Err(SyscallErr::EISDIR); + } + let mut file = self.dentry.to_file(); + if file.seek(fatfs::SeekFrom::Start(offset as u64)).is_err() { + return Err(SyscallErr::EINVAL); + } + if let Some(bytes) = file.read(buf).ok() { + return Ok(bytes); + } else { + warn!("fatfs read file failed!"); + return Err(SyscallErr::EINVAL); + } + } + + fn write(&self, offset: usize, buf: &[u8]) -> GeneralRet<usize> { + if self.dentry.is_dir() { + return Err(SyscallErr::EISDIR); + } + let mut file = self.dentry.to_file(); + if file.seek(fatfs::SeekFrom::Start(offset as u64)).is_err() { + return Err(SyscallErr::EINVAL); + } + if let Some(bytes) = file.write(buf).ok() { + return Ok(bytes); + } else { + warn!("fatfs write file failed!"); + return Err(SyscallErr::EINVAL); + } + } } pub struct Fat32File { @@ -491,7 +527,7 @@ impl File for Fat32File { let _sum_guard = SumGuard::new(); let mut inner = self.inner.lock(); let bytes = match &mut inner.node { - Fat32NodeType::Dir(dir) => panic!(), + Fat32NodeType::Dir(_) => panic!(), Fat32NodeType::File(file) => { let res = file.write(buf); debug!( @@ -555,74 +591,6 @@ pub fn list_apps_fat32() { info!("/************************************/"); } -///Open file with flags -pub fn open_file(name: &str, flags: OpenFlags) -> Option<Arc<Fat32File>> { - stack_trace!(); - // TODO support different kinds of files dispatching - // (e.g. /dev/sda, /proc/1234, /usr/bin) - debug!("[open_file] name: {}", name); - - let (readable, writable) = flags.read_write(); - let root_dir = ROOT_FS.fat_fs.root_dir(); - if flags.contains(OpenFlags::CREATE) { - if let Some(inode) = root_dir.open_file(name).ok() { - Some(Arc::new(Fat32File::new( - Fat32NodeType::File(inode), - None, - readable, - writable, - ))) - } else { - debug!("create file {}", name); - Some(Arc::new(Fat32File::new( - Fat32NodeType::File(root_dir.create_file(name).unwrap()), - None, - readable, - writable, - ))) - } - } else { - if let Some(inode) = root_dir.open_file(name).ok() { - Some(Arc::new(Fat32File::new( - Fat32NodeType::File(inode), - None, - readable, - writable, - ))) - } else { - None - } - } -} - -// pub fn open_dir(name: &str, flags: OpenFlags) -> Option<Arc<Fat32File>> { -// // TODO support different kinds of files dispatching -// // (e.g. /dev/sda, /proc/1234, /usr/bin) - -// // stack_trace!(); -// let (readable, writable) = flags.read_write(); -// if flags.contains(OpenFlags::CREATE) { -// if let Some(inode) = ROOT_INODE.find(name) { -// // clear size -// inode.clear(); -// Some(Arc::new(OSInode::new(readable, writable, inode))) -// } else { -// // create file -// ROOT_INODE -// .create(name) -// .map(|inode| Arc::new(OSInode::new(readable, writable, inode))) -// } -// } else { -// debug!("name: {}", name); -// ROOT_INODE.find(name).map(|inode| { -// if flags.contains(OpenFlags::TRUNC) { -// inode.clear(); -// } -// Arc::new(OSInode::new(readable, writable, inode)) -// }) -// } -// } - pub fn init() -> GeneralRet<()> { info!("start to init fatfs..."); diff --git a/os/src/fs/file.rs b/os/src/fs/file.rs index 2ee523aadc428669c6a5957cc40618a82823a646..0b5054eac715bb40fd2821ef8820c473421c0f8b 100644 --- a/os/src/fs/file.rs +++ b/os/src/fs/file.rs @@ -1,4 +1,4 @@ -use alloc::{boxed::Box, string::String, sync::Arc}; +use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec}; use crate::{ config::fs::FILE_PAGE_SIZE, @@ -53,6 +53,13 @@ pub trait File: Send + Sync { fn seek(&self, offset: usize) -> SyscallRet { todo!() } + + /// Read all data from this file synchronously + /// TODO: add async version + fn sync_read_all(&self) -> GeneralRet<Vec<u8>> { + todo!() + } + // TODO: not sure the args fn mmap(&self) -> GeneralRet<VmArea> { todo!() @@ -96,14 +103,20 @@ impl File for DefaultFile { } /// For default file, data must be read from page cache first + /// TODO: change to real async fn read<'a>(&'a self, buf: &'a mut [u8]) -> AsyscallRet { + Box::pin(async move { self.sync_read(buf) }) + } + + /// For default file, data must be written to page cache first + fn write<'a>(&'a self, buf: &'a [u8]) -> AsyscallRet { Box::pin(async move { let mut file_meta = self.metadata().inner.lock(); let mut inode_meta = file_meta.inode.as_ref().unwrap().metadata().inner.lock(); // Calculate buf end according to inode meta // TODO now calculate buf end at first, which may need modifying - // beacuse buf end may be changed by other thread + // beacuse buf end may change by other thread let mut buf_end = inode_meta.data_len - file_meta.pos; if buf_end > buf.len() { buf_end = buf.len(); @@ -128,7 +141,7 @@ impl File for DefaultFile { buf_offset_end = buf_end; } - let bytes = page.read(page_offset, &mut buf[buf_offset..buf_offset_end])?; + let bytes = page.write(page_offset, &buf[buf_offset..buf_offset_end])?; file_offset += bytes; res += bytes; buf_offset = buf_offset_end; @@ -140,48 +153,59 @@ impl File for DefaultFile { }) } - /// For default file, data must be written to page cache first - fn write<'a>(&'a self, buf: &'a [u8]) -> AsyscallRet { - Box::pin(async move { - let mut file_meta = self.metadata().inner.lock(); - let mut inode_meta = file_meta.inode.as_ref().unwrap().metadata().inner.lock(); - - // Calculate buf end according to inode meta - // TODO now calculate buf end at first, which may need modifying - // beacuse buf end may change by other thread - let mut buf_end = inode_meta.data_len - file_meta.pos; - if buf_end > buf.len() { - buf_end = buf.len(); + fn sync_read(&self, buf: &mut [u8]) -> SyscallRet { + let mut file_meta = self.metadata().inner.lock(); + let mut inode_meta = file_meta.inode.as_ref().unwrap().metadata().inner.lock(); + + // Calculate buf end according to inode meta + // TODO now calculate buf end at first, which may need modifying + // beacuse buf end may be changed by other thread + let mut buf_end = inode_meta.data_len - file_meta.pos; + if buf_end > buf.len() { + buf_end = buf.len(); + } + + let mut buf_offset = 0; + let mut res = 0; + let mut file_offset = file_meta.pos; + + while buf_offset < buf_end { + // Get the page from page cache + let page = inode_meta + .page_cache + .as_mut() + .unwrap() + .get_page(file_meta.pos)?; + + // Read this page + let page_offset = file_offset % FILE_PAGE_SIZE; + let mut buf_offset_end = buf_offset + (FILE_PAGE_SIZE - page_offset); + if buf_offset_end > buf_end { + buf_offset_end = buf_end; } - let mut buf_offset = 0; - let mut res = 0; - let mut file_offset = file_meta.pos; - - while buf_offset < buf_end { - // Get the page from page cache - let page = inode_meta - .page_cache - .as_mut() - .unwrap() - .get_page(file_meta.pos)?; + let bytes = page.read(page_offset, &mut buf[buf_offset..buf_offset_end])?; + file_offset += bytes; + res += bytes; + buf_offset = buf_offset_end; + } - // Read this page - let page_offset = file_offset % FILE_PAGE_SIZE; - let mut buf_offset_end = buf_offset + (FILE_PAGE_SIZE - page_offset); - if buf_offset_end > buf_end { - buf_offset_end = buf_end; - } + drop(inode_meta); + file_meta.pos = file_offset; + Ok(res as isize) + } - let bytes = page.write(page_offset, &buf[buf_offset..buf_offset_end])?; - file_offset += bytes; - res += bytes; - buf_offset = buf_offset_end; + fn sync_read_all(&self) -> GeneralRet<Vec<u8>> { + // let mut inner = self.inner.lock(); + let mut buffer = [0u8; 512]; + let mut v: Vec<u8> = Vec::new(); + loop { + let len = self.sync_read(&mut buffer)?; + if len == 0 { + break; } - - drop(inode_meta); - file_meta.pos = file_offset; - Ok(res as isize) - }) + v.extend_from_slice(&buffer[..len as usize]); + } + Ok(v) } } diff --git a/os/src/fs/file_system.rs b/os/src/fs/file_system.rs index 8f4fc00090339d1293a56ad2751e41cd8557a222..765ea91290ab77821e1aabdf177620e054b8c13f 100644 --- a/os/src/fs/file_system.rs +++ b/os/src/fs/file_system.rs @@ -12,7 +12,7 @@ use crate::{ }, }; -use super::{testfs::TestFs, FAT32FileSystem, Inode, Mutex}; +use super::{testfs::TestFs, Inode}; #[derive(Clone)] pub enum FileSystemType { diff --git a/os/src/fs/inode.rs b/os/src/fs/inode.rs index dcfd3cff57b2fcc130caaf88fbad5ee57dd4bcbe..f3ed215a02089e97a5bd28113ed3910ab0371f19 100644 --- a/os/src/fs/inode.rs +++ b/os/src/fs/inode.rs @@ -1,28 +1,17 @@ -use core::{ - cell::SyncUnsafeCell, - mem::size_of, - sync::atomic::{AtomicUsize, Ordering}, -}; +use core::sync::atomic::{AtomicUsize, Ordering}; use alloc::{ collections::BTreeMap, string::{String, ToString}, sync::{Arc, Weak}, - vec::Vec, }; use lazy_static::*; use log::{debug, warn}; use crate::{ - driver::block::BlockDevice, - mm::{Page, PageCache}, + mm::PageCache, timer::get_time_ms, - utils::{ - error::{GeneralRet, SyscallRet}, - hash_table::HashTable, - mem::uninit_memory, - path::Path, - }, + utils::{error::GeneralRet, hash_table::HashTable, path::Path}, }; use super::{ @@ -58,7 +47,7 @@ pub enum InodeMode { // TODO add more(like R / W / X etc) } -static INODE_NUMBER: AtomicUsize = AtomicUsize::new(0); +// static INODE_NUMBER: AtomicUsize = AtomicUsize::new(0); static INODE_UID_ALLOCATOR: AtomicUsize = AtomicUsize::new(1); @@ -111,27 +100,27 @@ pub trait Inode: Send + Sync { /// You should call this function through the parent inode /// You should give a relative path - fn mkdir(&self, this: Arc<dyn Inode>, pathname: &str, mode: InodeMode) -> GeneralRet<()> { + fn mkdir(&self, _this: Arc<dyn Inode>, _pathname: &str, _mode: InodeMode) -> GeneralRet<()> { todo!() } - fn rmdir(&self, name: &str, mode: InodeMode) -> GeneralRet<()> { + fn rmdir(&self, _name: &str, _mode: InodeMode) -> GeneralRet<()> { todo!() } fn mknod( &self, - this: Arc<dyn Inode>, - pathname: &str, - mode: InodeMode, - dev_id: usize, + _this: Arc<dyn Inode>, + _pathname: &str, + _mode: InodeMode, + _dev_id: usize, ) -> GeneralRet<()> { todo!() } /// Read data at the given file offset from block device - fn read(&self, offset: usize, buf: &mut [u8]) -> GeneralRet<usize> { + fn read(&self, _offset: usize, _buf: &mut [u8]) -> GeneralRet<usize> { todo!() } /// Write data to the given file offset in block device - fn write(&self, offset: usize, buf: &[u8]) -> GeneralRet<usize> { + fn write(&self, _offset: usize, _buf: &[u8]) -> GeneralRet<usize> { todo!() } diff --git a/os/src/fs/inode_tmp.rs b/os/src/fs/inode_tmp.rs deleted file mode 100644 index a92632976651c81514d753c5f509f68ba43f309e..0000000000000000000000000000000000000000 --- a/os/src/fs/inode_tmp.rs +++ /dev/null @@ -1,182 +0,0 @@ -/// This mod is just temporarily used -use super::file::{File, FileMeta}; -use crate::{ - driver::BLOCK_DEVICE, - processor::SumGuard, - stack_trace, - sync::mutex::SpinNoIrqLock, - utils::error::{AsyscallRet, SyscallRet}, -}; - -use alloc::boxed::Box; -use alloc::sync::Arc; -use alloc::vec::Vec; -use bitflags::*; -use easy_fs::{EasyFileSystem, Inode}; -use lazy_static::*; -use log::{debug, info}; -/// A wrapper around a filesystem inode -/// to implement File trait atop -pub struct OSInode { - readable: bool, - writable: bool, - inner: SpinNoIrqLock<OSInodeInner>, // inner: UnSafeCell<OSInodeInner>, -} -/// The OS inode inner in 'UPSafeCell' -pub struct OSInodeInner { - offset: usize, - inode: Arc<Inode>, -} - -impl OSInode { - /// Construct an OS inode from a inode - pub fn new(readable: bool, writable: bool, inode: Arc<Inode>) -> Self { - Self { - readable, - writable, - inner: unsafe { SpinNoIrqLock::new(OSInodeInner { offset: 0, inode }) }, - } - } - /// Read all data inside a inode into vector - pub fn read_all(&self) -> Vec<u8> { - let mut inner = self.inner.lock(); - let mut buffer = [0u8; 512]; - let mut v: Vec<u8> = Vec::new(); - loop { - let len = inner.inode.read_at(inner.offset, &mut buffer); - if len == 0 { - break; - } - inner.offset += len; - v.extend_from_slice(&buffer[..len]); - } - v - } -} - -lazy_static! { - pub static ref ROOT_INODE: Arc<Inode> = { - todo!() - // let efs = EasyFileSystem::open(BLOCK_DEVICE.clone()); - // // println!("hhhhhhhhhhhhh"); - // let ret =Arc::new(EasyFileSystem::root_inode(&efs)); - // ret - }; -} - -/// List all files in the filesystems -pub fn list_apps() { - info!("/************** APPS ****************/"); - for app in ROOT_INODE.ls() { - info!("{}", app); - } - info!("/************************************/"); -} - -bitflags! { - ///Open file flags - pub struct OpenFlags: u32 { - ///Read only - const RDONLY = 0; - ///Write only - const WRONLY = 1 << 0; - ///Read & Write - const RDWR = 1 << 1; - ///Allow create - const CREATE = 1 << 9; - ///Clear file and return an empty one - const TRUNC = 1 << 10; - } -} - -impl OpenFlags { - /// Do not check validity for simplicity - /// Return (readable, writable) - pub fn read_write(&self) -> (bool, bool) { - if self.is_empty() { - (true, false) - } else if self.contains(Self::WRONLY) { - (false, true) - } else { - (true, true) - } - } -} -///Open file with flags -pub fn open_file(name: &str, flags: OpenFlags) -> Option<Arc<OSInode>> { - // TODO support different kinds of files dispatching - // (e.g. /dev/sda, /proc/1234, /usr/bin) - - stack_trace!(); - let (readable, writable) = flags.read_write(); - if flags.contains(OpenFlags::CREATE) { - if let Some(inode) = ROOT_INODE.find(name) { - // clear size - inode.clear(); - Some(Arc::new(OSInode::new(readable, writable, inode))) - } else { - // create file - ROOT_INODE - .create(name) - .map(|inode| Arc::new(OSInode::new(readable, writable, inode))) - } - } else { - debug!("name: {}", name); - ROOT_INODE.find(name).map(|inode| { - if flags.contains(OpenFlags::TRUNC) { - inode.clear(); - } - Arc::new(OSInode::new(readable, writable, inode)) - }) - } -} - -// #[async_trait] -impl File for OSInode { - fn readable(&self) -> bool { - self.readable - } - fn writable(&self) -> bool { - self.writable - } - fn metadata(&self) -> &FileMeta { - todo!() - } - fn read<'a>(&'a self, buf: &'a mut [u8]) -> AsyscallRet { - // TODO: change into async read - Box::pin(async move { - let mut inner = self.inner.lock(); - let mut total_read_size = 0usize; - let _sum_guard = SumGuard::new(); - total_read_size = inner.inode.read_at(inner.offset, buf); - inner.offset += total_read_size; - - debug!("read size {}", total_read_size); - // for slice in buf.iter_mut() { - // let read_size = inner.inode.read_at(inner.offset, *slice); - // if read_size == 0 { - // break; - // } - // inner.offset += read_size; - // total_read_size += read_size; - // } - Ok(total_read_size as isize) - }) - } - fn write<'a>(&'a self, buf: &'a [u8]) -> AsyscallRet { - Box::pin(async move { - // TODO: change into async write - let mut inner = self.inner.lock(); - let mut total_write_size = 0usize; - let _sum_guard = SumGuard::new(); - total_write_size = inner.inode.write_at(inner.offset, buf); - // for slice in buf.buffers.iter() { - // let write_size = inner.inode.write_at(inner.offset, *slice); - // assert_eq!(write_size, slice.len()); - // inner.offset += write_size; - // total_write_size += write_size; - // } - Ok(total_write_size as isize) - }) - } -} diff --git a/os/src/fs/mod.rs b/os/src/fs/mod.rs index 18f103051e495e968eafbf5553ec2132f8561b25..46feeba474d0cda9cd9efd6a6c683d17fc672f17 100644 --- a/os/src/fs/mod.rs +++ b/os/src/fs/mod.rs @@ -10,7 +10,6 @@ pub mod kstat; pub mod utsname; // pub mod inode_fat32_tmp; pub mod fat32_tmp; -pub mod inode_tmp; pub mod pipe; mod procfs; mod stdio; diff --git a/os/src/fs/pipe.rs b/os/src/fs/pipe.rs index 502ceb8ac41c478cad36dc413071f6864a6634b0..f974cc75b47ea9bba2eca4e6f3eb526b06eb4f8f 100644 --- a/os/src/fs/pipe.rs +++ b/os/src/fs/pipe.rs @@ -1,12 +1,11 @@ use alloc::boxed::Box; use alloc::sync::{Arc, Weak}; use log::debug; -use riscv::register::satp::{self, Satp}; use crate::process; use crate::processor::SumGuard; use crate::sync::mutex::SpinNoIrqLock; -use crate::utils::error::{AsyscallRet, SyscallRet}; +use crate::utils::error::AsyscallRet; use super::file::{File, FileMeta}; diff --git a/os/src/fs/stdio.rs b/os/src/fs/stdio.rs index e6aeacd910e2373d78f3c3bed597159f9bfaf0d2..b2854e07354ae25257a855af82ba1166ebb6f0ca 100644 --- a/os/src/fs/stdio.rs +++ b/os/src/fs/stdio.rs @@ -1,14 +1,14 @@ use core::sync::atomic::{AtomicU8, Ordering}; use alloc::boxed::Box; -use log::{debug, warn}; +use log::warn; use crate::{ process, processor::SumGuard, sbi::console_getchar, sync::mutex::SpinNoIrqLock, - utils::error::{AgeneralRet, AsyscallRet, GeneralRet, SyscallErr, SyscallRet}, + utils::error::{AsyscallRet, GeneralRet, SyscallErr}, }; use super::file::{File, FileMeta}; diff --git a/os/src/mm/heap_allocator.rs b/os/src/mm/heap_allocator.rs index 5da2bed6496bbe63dc4a767a4e2d5e3a5abc2a17..d59e72be51868894c420abca6fd2c56d824e07b5 100644 --- a/os/src/mm/heap_allocator.rs +++ b/os/src/mm/heap_allocator.rs @@ -1,7 +1,7 @@ //! The global allocator use crate::config::mm::KERNEL_HEAP_SIZE; use buddy_system_allocator::LockedHeap; -use log::{debug, info, error}; +use log::{debug, error, info}; #[global_allocator] /// heap allocator instance diff --git a/os/src/mm/memory_set/mod.rs b/os/src/mm/memory_set/mod.rs index b24590ea95e2eee2807811cf8d362dd5c33e5e9c..735648eb5413fab26c44bd4c64e8878ffe795bbe 100644 --- a/os/src/mm/memory_set/mod.rs +++ b/os/src/mm/memory_set/mod.rs @@ -1,13 +1,11 @@ -use core::{arch::asm, cell::SyncUnsafeCell}; +use core::cell::SyncUnsafeCell; -use alloc::{boxed::Box, collections::BTreeMap, sync::Arc, vec, vec::Vec}; -use log::{debug, error, info, trace, warn}; -use riscv::register::{satp, scause::Scause}; +use alloc::{boxed::Box, collections::BTreeMap, sync::Arc, vec::Vec}; +use log::{debug, error, info, warn}; use crate::{ config::{ board::MEMORY_END, - board::MMIO, mm::PAGE_SIZE, mm::{MMAP_TOP, USER_STACK_SIZE}, }, @@ -24,8 +22,7 @@ pub use self::{ }; use super::{ - address::SimpleRange, page_table::PTEFlags, PageTable, PageTableEntry, PhysAddr, VirtAddr, - VirtPageNum, + address::SimpleRange, page_table::PTEFlags, PageTable, PageTableEntry, VirtAddr, VirtPageNum, }; /// diff --git a/os/src/mm/memory_set/page_fault_handler.rs b/os/src/mm/memory_set/page_fault_handler.rs index 49d0df5fd410a66836ca532a9dc6567fe1693ae2..aa8fa7e283a83c0adc4e03902a6a2c860bf13e47 100644 --- a/os/src/mm/memory_set/page_fault_handler.rs +++ b/os/src/mm/memory_set/page_fault_handler.rs @@ -1,28 +1,18 @@ -use core::cell::UnsafeCell; - -use alloc::{ - boxed::Box, - sync::{Arc, Weak}, -}; +use alloc::{boxed::Box, sync::Arc}; use log::{debug, info}; use riscv::register::scause::Scause; use crate::{ - config::mm::PAGE_SIZE, fs::OpenFlags, - mm::{ - frame_alloc, page_table::PTEFlags, FrameTracker, MapPermission, PageTable, PageTableEntry, - PhysPageNum, VirtAddr, - }, + mm::{frame_alloc, page_table::PTEFlags, PageTable, VirtAddr}, processor::current_process, sync::mutex::SpinNoIrqLock, - syscall::MmapFlags, utils::error::{GeneralRet, SyscallErr}, }; use super::VmArea; -type Mutex<T> = SpinNoIrqLock<T>; +// type Mutex<T> = SpinNoIrqLock<T>; /// General page fault handler pub trait PageFaultHandler: Send + Sync { diff --git a/os/src/mm/memory_set/vm_area.rs b/os/src/mm/memory_set/vm_area.rs index 9375fb45e56a4b583c8d5b0e3ad8741ade1ec680..d1d851ad8ca764510bd27afcee81cf7b0d0358e3 100644 --- a/os/src/mm/memory_set/vm_area.rs +++ b/os/src/mm/memory_set/vm_area.rs @@ -1,10 +1,10 @@ use alloc::{boxed::Box, collections::BTreeMap, sync::Arc}; use core::cell::UnsafeCell; -use log::{debug, warn}; +use log::warn; use crate::{ config::{mm::KERNEL_DIRECT_OFFSET, mm::PAGE_SIZE}, - fs::{File, Inode}, + fs::File, mm::{ address::{StepByOne, VPNRange}, frame_alloc, @@ -16,7 +16,7 @@ use crate::{ utils::error::{GeneralRet, SyscallErr}, }; -use super::{page_fault_handler::PageFaultHandler, MapPermission, MapType, MemorySet}; +use super::{page_fault_handler::PageFaultHandler, MapPermission, MapType}; /// pub struct FrameManager(pub BTreeMap<VirtPageNum, Arc<FrameTracker>>); diff --git a/os/src/mm/page_cache.rs b/os/src/mm/page_cache.rs index c8028e7ff59791ff6c4488bde39c642f5e1b9466..1badad1c5c6ecbffa56b69d1c3079866bb01b29b 100644 --- a/os/src/mm/page_cache.rs +++ b/os/src/mm/page_cache.rs @@ -1,8 +1,7 @@ use alloc::{ sync::{Arc, Weak}, - vec::Vec, }; -use log::info; +use log::{info, trace}; use crate::{config::mm::PAGE_SIZE_BITS, fs::Inode, utils::error::GeneralRet}; @@ -20,9 +19,9 @@ pub struct PageCache { impl PageCache { /// Create a new page cache - pub fn new(inode: &Arc<dyn Inode>, level_num: usize) -> Self { + pub fn new(inode: Arc<dyn Inode>, level_num: usize) -> Self { Self { - inode: Some(Arc::downgrade(inode)), + inode: Some(Arc::downgrade(&inode)), pages: RadixTree::new(level_num), } } @@ -36,6 +35,7 @@ impl PageCache { } /// Get a page according to the given file offset pub fn get_page(&mut self, offset: usize) -> GeneralRet<Arc<Page>> { + trace!("[PageCache]: get page at file offset {:#x}", offset); if let Some(page) = self.lookup(offset) { Ok(page) } else { diff --git a/os/src/mm/radix_tree.rs b/os/src/mm/radix_tree.rs index 34967779bc7b1711978fbb7aa17e67933743f8fb..c3ae57c3a9f22156b4086f3f45e2f9fe0dcb89d2 100644 --- a/os/src/mm/radix_tree.rs +++ b/os/src/mm/radix_tree.rs @@ -1,5 +1,5 @@ use alloc::{sync::Arc, vec, vec::Vec}; -use log::debug; +use log::{debug, trace}; use crate::{config::fs::RADIX_TREE_MAP_SHIFT, sync::mutex::SpinNoIrqLock}; @@ -81,7 +81,7 @@ impl<T: Clone> RadixTree<T> { let mut children = parent.children.lock(); if children[*index].is_none() { if i == indice.len() - 1 { - debug!("[Radix tree]: insert a new leaf, key: {:#x}", key); + trace!("[Radix tree]: insert a new leaf, key: {:#x}", key); children[*index] = Some(RadixTreeNode::LeafNode(RadixTreeLeafNode { key, data: value, @@ -100,7 +100,7 @@ impl<T: Clone> RadixTree<T> { parent = node; } RadixTreeNode::LeafNode(_) => { - debug!( + trace!( "[Radix tree]: replace old leaf with a new one, key: {:#x}", key ); diff --git a/os/src/syscall/fs.rs b/os/src/syscall/fs.rs index 2ff6991ddb61ca0a3534593ad0025ecbd06493d4..83115d372b493f126cca330508c835d17bba240e 100644 --- a/os/src/syscall/fs.rs +++ b/os/src/syscall/fs.rs @@ -11,15 +11,15 @@ use crate::config::fs::RLIMIT_NOFILE; use crate::fs::kstat::{KSTAT, KSTAT_SIZE}; use crate::fs::pipe::make_pipe; use crate::fs::{ - dirent, inode, Dirent, FAT32FileSystem, File, FileSystem, FileSystemType, Inode, InodeMode, - Iovec, StatFlags, UtsName, DIRENT_SIZE, FILE_SYSTEM_MANAGER, + inode, Dirent, FileSystem, FileSystemType, Inode, InodeMode, Iovec, StatFlags, UtsName, + DIRENT_SIZE, FILE_SYSTEM_MANAGER, }; use crate::fs::{OpenFlags, UTSNAME_SIZE}; use crate::mm::user_check::UserCheck; use crate::process::thread; use crate::processor::{current_process, SumGuard}; use crate::signal::SigSet; -use crate::syscall::{MmapFlags, MmapProt, AT_FDCWD, SEEK_CUR, SEEK_END, SEEK_SET}; +use crate::syscall::{AT_FDCWD, SEEK_CUR, SEEK_END, SEEK_SET}; use crate::timer::{get_time_ms, TimeSpec}; use crate::utils::error::{SyscallErr, SyscallRet}; use crate::utils::path::Path; diff --git a/os/src/syscall/mm.rs b/os/src/syscall/mm.rs index 98e2434eba163cbf37bb3bb3162668c8700e6af9..c282cd0c33e203d86bff92029977370b58a90f41 100644 --- a/os/src/syscall/mm.rs +++ b/os/src/syscall/mm.rs @@ -1,7 +1,7 @@ use log::debug; use crate::{ - config::{fs::FILE_PAGE_SIZE, mm::PAGE_SIZE}, + config::mm::PAGE_SIZE, mm::{ memory_set::{ page_fault_handler::{MmapPageFaultHandler, SBrkPageFaultHandler}, diff --git a/os/src/syscall/process.rs b/os/src/syscall/process.rs index a68baafb68532de4e00acd0087e60a33228882a7..28d4850acfc997117bddbc9c72fb650d8ac682cb 100644 --- a/os/src/syscall/process.rs +++ b/os/src/syscall/process.rs @@ -1,3 +1,4 @@ +use crate::fs::inode::open_file; use crate::fs::OpenFlags; use crate::loader::get_app_data_by_name; use crate::mm::user_check::UserCheck; @@ -13,7 +14,7 @@ use crate::utils::string::c_str_to_string; use crate::{fs, process, stack_trace}; use alloc::string::{String, ToString}; use alloc::vec::Vec; -use log::{debug, info, warn}; +use log::{debug, info, trace, warn}; use super::{TimeSpec, TimeVal, Tms}; @@ -351,13 +352,22 @@ pub fn sys_execve(path: *const u8, mut args: *const usize, mut envs: *const usiz Err(SyscallErr::EACCES) } } else { - if let Some(app_inode) = fs::fat32_tmp::open_file(&path, OpenFlags::RDONLY) { - let elf_data = app_inode.read_all(); + if let Some(app_inode) = open_file(&path, OpenFlags::RDONLY) { + let app_file = app_inode.open(app_inode.clone(), OpenFlags::RDONLY)?; + trace!("try to read all data in file {}", path); + let elf_data = app_file.sync_read_all()?; current_process().exec(&elf_data, args_vec, envs_vec) } else { warn!("[sys_exec] Cannot find this elf file {}", path); Err(SyscallErr::EACCES) } + // if let Some(app_inode) = fs::fat32_tmp::open_file(&path, OpenFlags::RDONLY) { + // let elf_data = app_inode.read_all(); + // current_process().exec(&elf_data, args_vec, envs_vec) + // } else { + // warn!("[sys_exec] Cannot find this elf file {}", path); + // Err(SyscallErr::EACCES) + // } } // if let Some(data) = get_app_data_by_name(&path) { // let process = current_process();