From 4fcba84b9cff2c57db02b1e46f0f297d82ed7b63 Mon Sep 17 00:00:00 2001 From: GZTime Date: Mon, 20 Mar 2023 03:51:17 +0800 Subject: [PATCH] chore: tidy up --- pkg/boot/src/lib.rs | 1 - pkg/fs/src/device/fat16.rs | 6 +-- pkg/fs/src/device/random.rs | 14 +++--- pkg/fs/src/lib.rs | 12 +++--- pkg/fs/src/structs/dir_entry.rs | 4 +- pkg/fs/src/structs/partition.rs | 8 +--- pkg/kernel/src/drivers/ata.rs | 11 +++-- pkg/kernel/src/drivers/console.rs | 10 ++++- pkg/kernel/src/drivers/filesystem.rs | 2 +- pkg/kernel/src/drivers/gop.rs | 2 +- pkg/kernel/src/drivers/input.rs | 8 +--- pkg/kernel/src/interrupt/syscall/service.rs | 6 +-- pkg/kernel/src/memory/mod.rs | 2 +- pkg/kernel/src/process/manager.rs | 48 ++++++++++++++------- pkg/kernel/src/process/mod.rs | 18 +++++--- pkg/kernel/src/process/process.rs | 19 ++++---- pkg/kernel/src/tasks/executor.rs | 6 +++ pkg/kernel/src/utils/resource.rs | 8 ++-- 18 files changed, 102 insertions(+), 83 deletions(-) diff --git a/pkg/boot/src/lib.rs b/pkg/boot/src/lib.rs index 0169a2e..3c7b25e 100644 --- a/pkg/boot/src/lib.rs +++ b/pkg/boot/src/lib.rs @@ -1,5 +1,4 @@ #![no_std] -#[allow(dead_code)] pub use uefi::data_types::chars::*; pub use uefi::data_types::*; pub use uefi::prelude::SystemTable; diff --git a/pkg/fs/src/device/fat16.rs b/pkg/fs/src/device/fat16.rs index 3a29238..592a07f 100644 --- a/pkg/fs/src/device/fat16.rs +++ b/pkg/fs/src/device/fat16.rs @@ -92,7 +92,7 @@ where let end = (entry + 1) * DirEntry::LEN; trace!("Entry: {}..{}", start, end); let dir_entry = DirEntry::parse(&block.inner()[start..end]) - .map_err(|x| VolumeError::FileNameError(x))?; + .map_err(VolumeError::FileNameError)?; if dir_entry.is_eod() { return Ok(()); @@ -123,7 +123,7 @@ where dir: &Directory, name: &str, ) -> Result { - let match_name = ShortFileName::parse(name).map_err(|x| VolumeError::FileNameError(x))?; + let match_name = ShortFileName::parse(name).map_err(VolumeError::FileNameError)?; let mut current_cluster = Some(dir.cluster); let mut dir_sector_num = self.cluster_to_sector(&dir.cluster); @@ -168,7 +168,7 @@ where pub fn next_cluster(&self, cluster: Cluster) -> Result { let fat_offset = (cluster.0 * 2) as usize; let cur_fat_sector = self.fat_start + fat_offset / Block::SIZE; - let offset = (fat_offset % Block::SIZE) as usize; + let offset = fat_offset % Block::SIZE; let block = self.volume.read_block(cur_fat_sector).unwrap(); let fat_entry = u16::from_le_bytes( block.inner()[offset..=offset + 1] diff --git a/pkg/fs/src/device/random.rs b/pkg/fs/src/device/random.rs index d8a89f9..7ffe5b7 100644 --- a/pkg/fs/src/device/random.rs +++ b/pkg/fs/src/device/random.rs @@ -19,15 +19,13 @@ impl Device for Random { } } Ok(size) - } else { - if let Some(mut rng) = GLOBAL_RNG.get().and_then(spin::Mutex::try_lock) { - for i in 0..size { - buf[offset + i] = rng.next_u32() as u8; - } - Ok(size) - } else { - Err(DeviceError::ReadError) + } else if let Some(mut rng) = GLOBAL_RNG.get().and_then(spin::Mutex::try_lock) { + for i in 0..size { + buf[offset + i] = rng.next_u32() as u8; } + Ok(size) + } else { + Err(DeviceError::ReadError) } } diff --git a/pkg/fs/src/lib.rs b/pkg/fs/src/lib.rs index 0f309a1..63d4ab0 100644 --- a/pkg/fs/src/lib.rs +++ b/pkg/fs/src/lib.rs @@ -140,13 +140,13 @@ where let mut length = file.length() as usize; for i in 0..=file.length() as usize / Block::SIZE { let sector = volume.cluster_to_sector(&file.start_cluster()); - let block = volume.read_block(sector as usize + i).unwrap(); + let block = volume.read_block(sector + i).unwrap(); if length > Block::SIZE { data[i * Block::SIZE..(i + 1) * Block::SIZE].copy_from_slice(&block.inner()[..]); length -= Block::SIZE; } else { - data[i * Block::SIZE..i * Block::SIZE + length as usize] - .copy_from_slice(&block.inner()[..length as usize]); + data[i * Block::SIZE..i * Block::SIZE + length] + .copy_from_slice(&block.inner()[..length]); break; } } @@ -168,13 +168,13 @@ where let mut length = file.length() as usize; for i in 0..=file.length() as usize / Block::SIZE { let sector = volume.cluster_to_sector(&file.start_cluster()); - let block = volume.read_block(sector as usize + i).unwrap(); + let block = volume.read_block(sector + i).unwrap(); if length > Block::SIZE { buf[i * Block::SIZE..(i + 1) * Block::SIZE].copy_from_slice(&block.inner()[..]); length -= Block::SIZE; } else { - buf[i * Block::SIZE..i * Block::SIZE + length as usize] - .copy_from_slice(&block.inner()[..length as usize]); + buf[i * Block::SIZE..i * Block::SIZE + length] + .copy_from_slice(&block.inner()[..length]); break; } } diff --git a/pkg/fs/src/structs/dir_entry.rs b/pkg/fs/src/structs/dir_entry.rs index 04d6230..d5de19c 100644 --- a/pkg/fs/src/structs/dir_entry.rs +++ b/pkg/fs/src/structs/dir_entry.rs @@ -232,7 +232,7 @@ impl ShortFileName { } // Denotes the start of the file extension b'.' => { - if idx >= 1 && idx <= 8 { + if (1..=8).contains(&idx) { seen_dot = true; idx = 8; } else { @@ -243,7 +243,7 @@ impl ShortFileName { let ch = ch.to_ascii_uppercase(); trace!("char: '{}', at: {}", ch as char, idx); if seen_dot { - if idx >= 8 && idx < 11 { + if (8..11).contains(&idx) { sfn.ext[idx - 8] = ch; } else { return Err(FilenameError::NameTooLong); diff --git a/pkg/fs/src/structs/partition.rs b/pkg/fs/src/structs/partition.rs index cb9b97a..e8bca37 100644 --- a/pkg/fs/src/structs/partition.rs +++ b/pkg/fs/src/structs/partition.rs @@ -27,17 +27,11 @@ impl MBRPartitions { } } -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Default)] pub struct PartitionMetaData { data: [u8; 16], } -impl Default for PartitionMetaData { - fn default() -> Self { - Self { data: [0u8; 16] } - } -} - impl PartitionMetaData { /// Attempt to parse a Boot Parameter Block from a 512 byte sector. pub fn parse(data: &[u8; 16]) -> PartitionMetaData { diff --git a/pkg/kernel/src/drivers/ata.rs b/pkg/kernel/src/drivers/ata.rs index 889916c..589a7d9 100644 --- a/pkg/kernel/src/drivers/ata.rs +++ b/pkg/kernel/src/drivers/ata.rs @@ -4,6 +4,7 @@ //! reference: https://wiki.osdev.org/ATA_PIO_Mode //! reference: https://github.com/xfoxfu/rust-xos/blob/main/kernel/src/drivers/ide.rs +use alloc::boxed::Box; use alloc::{string::String, vec::Vec}; use bit_field::BitField; use core::hint::spin_loop; @@ -64,8 +65,8 @@ impl Bus { status: PortReadOnly::new(io_base + 7), command: PortWriteOnly::new(io_base + 7), - alternate_status: PortReadOnly::new(ctrl_base + 0), - control: PortWriteOnly::new(ctrl_base + 0), + alternate_status: PortReadOnly::new(ctrl_base), + control: PortWriteOnly::new(ctrl_base), drive_blockess: PortReadOnly::new(ctrl_base + 1), } } @@ -217,7 +218,9 @@ impl Bus { } } match (self.cylinder_low(), self.cylinder_high()) { - (0x00, 0x00) => Ok(IdentifyResponse::Ata([(); 256].map(|_| self.read_data()))), + (0x00, 0x00) => Ok(IdentifyResponse::Ata(Box::new( + [(); 256].map(|_| self.read_data()), + ))), (0x14, 0xEB) => Ok(IdentifyResponse::Atapi), (0x3C, 0x3C) => Ok(IdentifyResponse::Sata), (_, _) => Err(()), @@ -278,7 +281,7 @@ pub struct Drive { } enum IdentifyResponse { - Ata([u16; 256]), + Ata(Box<[u16; 256]>), Atapi, Sata, None, diff --git a/pkg/kernel/src/drivers/console.rs b/pkg/kernel/src/drivers/console.rs index a933ffc..c16f9d6 100644 --- a/pkg/kernel/src/drivers/console.rs +++ b/pkg/kernel/src/drivers/console.rs @@ -49,6 +49,12 @@ impl Console { } } +impl Default for Console { + fn default() -> Self { + Self::new() + } +} + impl Console { pub fn size(&self) -> (isize, isize) { let size: Size = get_display_for_sure().size(); @@ -133,8 +139,8 @@ impl Console { } pub fn move_cursor(&mut self, dx: isize, dy: isize) { - self.x_pos = self.x_pos as isize + dx; - self.y_pos = self.y_pos as isize + dy; + self.x_pos += dx; + self.y_pos += dy; } pub fn draw_hint(&mut self) { diff --git a/pkg/kernel/src/drivers/filesystem.rs b/pkg/kernel/src/drivers/filesystem.rs index 9272e71..491c076 100644 --- a/pkg/kernel/src/drivers/filesystem.rs +++ b/pkg/kernel/src/drivers/filesystem.rs @@ -47,7 +47,7 @@ pub fn resolve_path(root_path: &str) -> Option { path = path[pos + 1..].to_string(); trace!("Resolving path: {}", path); - if path.len() == 0 { + if path.is_empty() { break; } } diff --git a/pkg/kernel/src/drivers/gop.rs b/pkg/kernel/src/drivers/gop.rs index 564b58d..579c39f 100644 --- a/pkg/kernel/src/drivers/gop.rs +++ b/pkg/kernel/src/drivers/gop.rs @@ -41,7 +41,7 @@ impl<'a> GOPDisplay<'a> { let buffer = unsafe { core::slice::from_raw_parts_mut( graphic.fb_addr as *mut u32, - graphic.mode.resolution().0 as usize * graphic.mode.resolution().1 as usize, + graphic.mode.resolution().0 * graphic.mode.resolution().1, ) }; diff --git a/pkg/kernel/src/drivers/input.rs b/pkg/kernel/src/drivers/input.rs index d4d6bd0..c672221 100644 --- a/pkg/kernel/src/drivers/input.rs +++ b/pkg/kernel/src/drivers/input.rs @@ -24,13 +24,7 @@ pub fn push_key(key: DecodedKey) { } pub fn try_get_key() -> Option { - interrupts::without_interrupts(|| { - if let Some(key) = get_input_buf_for_sure().pop() { - Some(key) - } else { - None - } - }) + interrupts::without_interrupts(|| get_input_buf_for_sure().pop()) } pub fn get_key() -> DecodedKey { diff --git a/pkg/kernel/src/interrupt/syscall/service.rs b/pkg/kernel/src/interrupt/syscall/service.rs index 5c618ea..fae3615 100644 --- a/pkg/kernel/src/interrupt/syscall/service.rs +++ b/pkg/kernel/src/interrupt/syscall/service.rs @@ -23,7 +23,7 @@ pub fn sys_allocate(args: &SyscallArgs) -> usize { let layout = unsafe { (args.arg0 as *const Layout).as_ref().unwrap() }; let ptr = crate::memory::user::USER_ALLOCATOR .lock() - .allocate_first_fit(layout.clone()) + .allocate_first_fit(*layout) .unwrap() .as_ptr(); ptr as usize @@ -36,7 +36,7 @@ pub fn sys_deallocate(args: &SyscallArgs) { unsafe { crate::memory::user::USER_ALLOCATOR .lock() - .deallocate(core::ptr::NonNull::new_unchecked(ptr), layout.clone()); + .deallocate(core::ptr::NonNull::new_unchecked(ptr), *layout); } } @@ -122,7 +122,7 @@ pub fn sys_open(args: &SyscallArgs) -> usize { trace!("sys_open: opened: {} at fd={}", path, &fd); - u8::from(fd) as usize + fd as usize } pub fn sys_close(args: &SyscallArgs) -> usize { diff --git a/pkg/kernel/src/memory/mod.rs b/pkg/kernel/src/memory/mod.rs index a119f43..1e4b9fd 100644 --- a/pkg/kernel/src/memory/mod.rs +++ b/pkg/kernel/src/memory/mod.rs @@ -10,7 +10,7 @@ pub use frames::*; pub use paging::*; pub fn init(boot_info: &'static boot::BootInfo) { - let physical_memory_offset = x86_64::VirtAddr::new_truncate(PHYSICAL_OFFSET as u64); + let physical_memory_offset = x86_64::VirtAddr::new_truncate(PHYSICAL_OFFSET); let memory_map = &boot_info.memory_map; let mut mem_size = 0; diff --git a/pkg/kernel/src/process/manager.rs b/pkg/kernel/src/process/manager.rs index 42dbfcc..742cc99 100644 --- a/pkg/kernel/src/process/manager.rs +++ b/pkg/kernel/src/process/manager.rs @@ -1,8 +1,10 @@ use super::*; use crate::memory::{ + self, allocator::{ALLOCATOR, HEAP_SIZE}, get_frame_alloc_for_sure, - user::{USER_ALLOCATOR, USER_HEAP_SIZE}, self, PAGE_SIZE, + user::{USER_ALLOCATOR, USER_HEAP_SIZE}, + PAGE_SIZE, }; use crate::utils::Registers; use alloc::collections::BTreeMap; @@ -160,14 +162,14 @@ impl ProcessManager { proc_data: Option, ) -> ProcessId { let mut p = Process::new( - &mut *crate::memory::get_frame_alloc_for_sure(), + &mut crate::memory::get_frame_alloc_for_sure(), name, parent, self.get_kernel_page_table(), proc_data, ); p.pause(); - p.init_elf(&elf); + p.init_elf(elf); p.init_stack_frame( VirtAddr::new_truncate(elf.header.pt2.entry_point()), VirtAddr::new_truncate(STACK_INIT_TOP), @@ -187,7 +189,7 @@ impl ProcessManager { proc_data: Option, ) -> ProcessId { let mut p = Process::new( - &mut *crate::memory::get_frame_alloc_for_sure(), + &mut crate::memory::get_frame_alloc_for_sure(), name, parent, self.get_kernel_page_table(), @@ -202,7 +204,8 @@ impl ProcessManager { } pub fn print_process_list(&self) { - let mut output = String::from(" PID | PPID | Process Name | Ticks | Memory | Status\n"); + let mut output = + String::from(" PID | PPID | Process Name | Ticks | Memory | Status\n"); for p in self.processes.iter() { output += format!("{}\n", p).as_str(); } @@ -218,37 +221,50 @@ impl ProcessManager { let frames_recycled = alloc.recycled_count(); let frames_total = alloc.frames_total(); + let (sys_used, sys_used_unit) = memory::humanized_size(heap_used as u64); + let (sys_size, sys_size_unit) = memory::humanized_size(heap_size as u64); + output += format!( - "System : {:>7.*} KiB/ {:>7.*} KiB ({:>5.2}%)\n", + "System : {:>6.*} {} / {:>6.*} {} ({:>5.2}%)\n", 2, - heap_used as f64 / 1024f64, + sys_used, + sys_used_unit, 2, - heap_size as f64 / 1024f64, + sys_size, + sys_size_unit, heap_used as f64 / heap_size as f64 * 100.0 ) .as_str(); + let (user_used, user_used_unit) = memory::humanized_size(user_heap_used as u64); + let (user_size, user_size_unit) = memory::humanized_size(user_heap_size as u64); + output += format!( - "User : {:>7.*} KiB/ {:>7.*} KiB ({:>5.2}%)\n", + "User : {:>6.*} {} / {:>6.*} {} ({:>5.2}%)\n", 2, - user_heap_used as f64 / 1024f64, + user_used, + user_used_unit, 2, - user_heap_size as f64 / 1024f64, + user_size, + user_size_unit, user_heap_used as f64 / user_heap_size as f64 * 100.0 ) .as_str(); // put used/total frames in MiB - let (used_size, used_unit) = memory::humanized_size(frames_used as u64 * PAGE_SIZE); + let (used_size, used_unit) = + memory::humanized_size((frames_used - frames_recycled) as u64 * PAGE_SIZE); let (tot_size, tot_unit) = memory::humanized_size(frames_total as u64 * PAGE_SIZE); output += format!( - "Memory : {:>7.*} {}/ {:>7.*} {} ({:>5.2}%) [{} recycled]\n", + "Memory : {:>6.*} {} / {:>6.*} {} ({:>5.2}%) [{} recycled]\n", 2, - used_size, used_unit, + used_size, + used_unit, 2, - tot_size, tot_unit, - frames_used as f64 / frames_total as f64 * 100.0, + tot_size, + tot_unit, + (frames_used - frames_recycled) as f64 / frames_total as f64 * 100.0, frames_recycled ) .as_str(); diff --git a/pkg/kernel/src/process/mod.rs b/pkg/kernel/src/process/mod.rs index ac384ea..1585094 100644 --- a/pkg/kernel/src/process/mod.rs +++ b/pkg/kernel/src/process/mod.rs @@ -4,6 +4,7 @@ mod sync; use core::sync::atomic::{AtomicU16, Ordering}; +use alloc::collections::btree_map::Entry; use fs::File; use manager::*; use process::*; @@ -71,6 +72,12 @@ impl ProcessId { } } +impl Default for ProcessId { + fn default() -> Self { + Self::new() + } +} + impl core::fmt::Display for ProcessId { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.0) @@ -190,13 +197,12 @@ pub fn kill(pid: ProcessId, regs: &mut Registers, sf: &mut InterruptStackFrame) pub fn new_sem(key: u32, value: usize) -> isize { if let Some(mut sems) = get_sem_manager() { let sid = SemaphoreId::new(key); - // trace!("New Semaphore#{}", key); - if !sems.contains_key(&sid) { - sems.insert(sid, Semaphore::new(value)); + if let Entry::Vacant(e) = sems.entry(sid) { + e.insert(Semaphore::new(value)); return 0; } } - return 1; + 1 } pub fn sem_up(key: u32) -> isize { @@ -212,7 +218,7 @@ pub fn sem_up(key: u32) -> isize { return 0; } } - return 1; + 1 } pub fn sem_down(key: u32, regs: &mut Registers, sf: &mut InterruptStackFrame) { @@ -270,7 +276,7 @@ pub fn try_resolve_page_fault( pub fn spawn(file: &File) -> Result { let size = file.length(); let pages = (size as usize + 0x1000 - 1) / 0x1000; - let mut buf = vec![0u8; (pages * 0x1000) as usize]; + let mut buf = vec![0u8; pages * 0x1000]; fs::read_to_buf(get_volume(), file, &mut buf).map_err(|_| "Failed to read file")?; diff --git a/pkg/kernel/src/process/process.rs b/pkg/kernel/src/process/process.rs index d6286ea..f35bfb9 100644 --- a/pkg/kernel/src/process/process.rs +++ b/pkg/kernel/src/process/process.rs @@ -130,7 +130,7 @@ impl Process { } pub fn page_table_addr(&self) -> PhysFrame { - self.page_table_addr.0.clone() + self.page_table_addr.0 } pub fn is_running(&self) -> bool { @@ -146,8 +146,8 @@ impl Process { } pub fn save(&mut self, regs: &mut Registers, sf: &mut InterruptStackFrame) { - self.regs = unsafe { regs.as_mut().read().clone() }; - self.stack_frame = unsafe { sf.as_mut().read().clone() }; + self.regs = unsafe { regs.as_mut().read() }; + self.stack_frame = unsafe { sf.as_mut().read() }; self.status = ProgramStatus::Ready; } @@ -324,7 +324,7 @@ impl Process { (physical_to_virtual(frame.start_address().as_u64()) as *mut PageTable) .as_mut() .unwrap(), - VirtAddr::new_truncate(crate::memory::PHYSICAL_OFFSET as u64), + VirtAddr::new_truncate(crate::memory::PHYSICAL_OFFSET), ) } } @@ -356,7 +356,7 @@ impl Process { let cur_stack_base = stack_info.start.start_address().as_u64(); // make new stack frame - let mut new_stack_frame = self.stack_frame.clone(); + let mut new_stack_frame = self.stack_frame; // cal new stack pointer new_stack_frame.stack_pointer += new_stack_base - cur_stack_base; // clone new stack content @@ -386,7 +386,7 @@ impl Process { status: ProgramStatus::Created, ticks_passed: 0, stack_frame: new_stack_frame, - regs: self.regs.clone(), + regs: self.regs, page_table_addr: (self.page_table_addr.0, Cr3::read().1), page_table: Some(owned_page_table), children: Vec::new(), @@ -406,7 +406,7 @@ impl Process { ); trace!("{:#?}", &child); - return child; + child } pub fn set_parent(&mut self, pid: ProcessId) { @@ -439,10 +439,7 @@ impl Process { elf::map_range(STACT_INIT_BOT, STACK_DEF_PAGE, &mut page_table, alloc, true).unwrap(); // record memory usage - self.proc_data.code_memory_usage = code_segments - .iter() - .map(|seg| seg.count()) - .fold(0, |acc, x| acc + x); + self.proc_data.code_memory_usage = code_segments.iter().map(|seg| seg.count()).sum(); self.proc_data.stack_memory_usage = stack_segment.count(); diff --git a/pkg/kernel/src/tasks/executor.rs b/pkg/kernel/src/tasks/executor.rs index db7ffb0..a5ba5af 100644 --- a/pkg/kernel/src/tasks/executor.rs +++ b/pkg/kernel/src/tasks/executor.rs @@ -13,6 +13,12 @@ pub struct Executor { waker_cache: BTreeMap, } +impl Default for Executor { + fn default() -> Self { + Self::new() + } +} + impl Executor { pub fn new() -> Self { Executor { diff --git a/pkg/kernel/src/utils/resource.rs b/pkg/kernel/src/utils/resource.rs index 87f0c3a..3a17626 100644 --- a/pkg/kernel/src/utils/resource.rs +++ b/pkg/kernel/src/utils/resource.rs @@ -43,13 +43,13 @@ impl Resource { pub fn write(&self, buf: &[u8]) -> Result { match self { Resource::File(_) => unimplemented!(), - Resource::Console(stdio) => match stdio { - &StdIO::Stdin => Err(()), - &StdIO::Stdout => { + Resource::Console(stdio) => match *stdio { + StdIO::Stdin => Err(()), + StdIO::Stdout => { print!("{}", String::from_utf8_lossy(buf)); Ok(buf.len()) } - &StdIO::Stderr => { + StdIO::Stderr => { warn!("{}", String::from_utf8_lossy(buf)); Ok(buf.len()) }