diff --git a/limine.cfg b/limine.cfg index 496d0e7..6411c62 100644 --- a/limine.cfg +++ b/limine.cfg @@ -5,6 +5,6 @@ TIMEOUT=3 PROTOCOL=limine KERNEL_PATH=boot:///boot/CappuccinOS.elf - KERNEL_CMDLINE=fat_in_mem=false + KERNEL_CMDLINE=fat_in_mem=true big_fat_phony MODULE_PATH=boot:///boot/initramfs.img \ No newline at end of file diff --git a/src/arch/mod.rs b/src/arch/mod.rs index 88ae2e8..e9b49a6 100644 --- a/src/arch/mod.rs +++ b/src/arch/mod.rs @@ -1,4 +1,4 @@ -#[cfg(any(target_arch = "x86_64"))] +#[cfg(target_arch = "x86_64")] pub use self::x86_64::*; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] diff --git a/src/arch/x86_64/interrupts/exceptions.rs b/src/arch/x86_64/interrupts/exceptions.rs index b2f888e..6cf35b3 100644 --- a/src/arch/x86_64/interrupts/exceptions.rs +++ b/src/arch/x86_64/interrupts/exceptions.rs @@ -116,12 +116,12 @@ exception_function!(0xFF, generic_handler, true); pub fn set_exceptions() { for i in 0..32 { - idt_set_gate(i, generic_handler as u64); + idt_set_gate(i, generic_handler as usize); } - idt_set_gate(0x00, div_error as u64); - idt_set_gate(0x06, invalid_opcode as u64); - idt_set_gate(0x08, double_fault as u64); - idt_set_gate(0x0D, general_protection_fault as u64); - idt_set_gate(0x0E, page_fault as u64); + idt_set_gate(0x00, div_error as usize); + idt_set_gate(0x06, invalid_opcode as usize); + idt_set_gate(0x08, double_fault as usize); + idt_set_gate(0x0D, general_protection_fault as usize); + idt_set_gate(0x0E, page_fault as usize); } diff --git a/src/arch/x86_64/interrupts/mod.rs b/src/arch/x86_64/interrupts/mod.rs index 10c0dbe..f8525aa 100755 --- a/src/arch/x86_64/interrupts/mod.rs +++ b/src/arch/x86_64/interrupts/mod.rs @@ -36,6 +36,7 @@ struct IdtPtr { static IDT: Mutex<[IdtEntry; 256]> = Mutex::new([IdtEntry::new(); 256]); +#[derive(Clone, Copy)] #[repr(u8)] pub enum InterruptIndex { Timer = PIC_1_OFFSET, @@ -43,8 +44,8 @@ pub enum InterruptIndex { } impl InterruptIndex { - pub fn as_u8(self) -> u8 { - self as u8 + pub fn as_u8(&self) -> u8 { + *self as u8 } } @@ -58,7 +59,7 @@ static mut IDT_PTR: IdtPtr = IdtPtr { base: 0, }; -pub fn idt_set_gate(num: u8, function_ptr: u64) { +pub fn idt_set_gate(num: u8, function_ptr: usize) { let base = function_ptr; IDT.lock().write()[num as usize] = IdtEntry { base_lo: (base & 0xFFFF) as u16, @@ -98,13 +99,13 @@ fn idt_init() { // Set every interrupt to the "null" interrupt handler (it does nothing) for num in 0..=255 { - idt_set_gate(num, null_interrupt_handler as u64); + idt_set_gate(num, null_interrupt_handler as usize); } exceptions::set_exceptions(); - idt_set_gate(InterruptIndex::Timer.as_u8(), timer_handler as u64); - idt_set_gate(0x80, syscall as u64); + idt_set_gate(InterruptIndex::Timer.as_u8(), timer_handler as usize); + idt_set_gate(0x80, syscall as usize); core::arch::asm!( "lidt [{}]", diff --git a/src/arch/x86_common/io.rs b/src/arch/x86_common/io.rs index fbb28a7..fff91b3 100644 --- a/src/arch/x86_common/io.rs +++ b/src/arch/x86_common/io.rs @@ -71,6 +71,23 @@ pub unsafe fn insw(port: u16, buffer: *mut u16, count: usize) { } } +/// Outputs `count` 16-bit values from the specified `port` into the `buffer`. +/// +/// # Safety +/// +/// This function panics if the supplied buffer's size is smaller than `count`. +#[inline(always)] +pub unsafe fn outsw(port: u16, buffer: *mut u16, count: usize) { + unsafe { + asm!("cld", + "rep outsw", + in("dx") port, + inout("rdi") buffer => _, + inout("rcx") count => _ + ); + } +} + #[inline(always)] pub fn outl(port: u16, value: u32) { unsafe { diff --git a/src/arch/x86_common/pic.rs b/src/arch/x86_common/pic.rs index 74ccd29..5f9efb7 100644 --- a/src/arch/x86_common/pic.rs +++ b/src/arch/x86_common/pic.rs @@ -1,7 +1,7 @@ // Originally from pic8259 (https://docs.rs/pic8259/0.10.1/pic8259/) // But this one feeds my addiction of not adding unnecessary crates // And I can read and learn about the PIC too ig -// Driver for the 8086 PIC, we might switch to the APIC later on. +// Driver for the 8086 PIC, we will switch to the APIC later on. use super::io::{io_wait, outb}; @@ -114,11 +114,10 @@ impl ChainedPics { } pub fn notify_end_of_interrupt(&mut self, interrupt_id: u8) { - if self.handles_interrupt(interrupt_id) { - if self.pics[1].handles_interrupt(interrupt_id) { - self.pics[1].end_of_interrupt(); - } + if self.handles_interrupt(interrupt_id) && self.pics[1].handles_interrupt(interrupt_id) { + self.pics[1].end_of_interrupt(); } + self.pics[0].end_of_interrupt(); } } diff --git a/src/arch/x86_common/stack_trace.rs b/src/arch/x86_common/stack_trace.rs index 075e61d..24bf04f 100644 --- a/src/arch/x86_common/stack_trace.rs +++ b/src/arch/x86_common/stack_trace.rs @@ -35,7 +35,11 @@ pub fn print_stack_trace(max_frames: usize, rbp: u64) { } fn get_function_name(function_address: u64) -> Result<(String, u64), ()> { - if crate::drivers::fs::vfs::VFS_INSTANCES.lock().read().len() == 0 { + if crate::drivers::fs::vfs::VFS_INSTANCES + .lock() + .read() + .is_empty() + { return Err(()); } @@ -58,7 +62,7 @@ fn get_function_name(function_address: u64) -> Result<(String, u64), ()> { } let (address, function_name) = ( - u64::from_str_radix(&line_parts[0], 16).ok().ok_or(())?, + u64::from_str_radix(line_parts[0], 16).ok().ok_or(())?, line_parts[1], ); diff --git a/src/drivers/acpi.rs b/src/drivers/acpi.rs index 922364a..482e8d7 100644 --- a/src/drivers/acpi.rs +++ b/src/drivers/acpi.rs @@ -4,7 +4,7 @@ use limine::RsdpRequest; static RSDP_REQUEST: RsdpRequest = RsdpRequest::new(0); #[repr(C, packed)] -struct RSDP { +struct Rsdp { signature: [u8; 8], checksum: u8, oem_id: [u8; 6], @@ -19,10 +19,10 @@ struct RSDP { } const RSDP_V1_LENGTH: usize = 20; -const RSDP_V2_EXT_LENGTH: usize = core::mem::size_of::() - RSDP_V1_LENGTH; +const RSDP_V2_EXT_LENGTH: usize = core::mem::size_of::() - RSDP_V1_LENGTH; const RSDP_SIG: [u8; 8] = *b"RSD PTR "; -impl RSDP { +impl Rsdp { pub fn is_valid(&self) -> bool { if self.signature != RSDP_SIG { return false; @@ -39,7 +39,7 @@ impl RSDP { }; let bytes = - unsafe { core::slice::from_raw_parts(self as *const RSDP as *const u8, length) }; + unsafe { core::slice::from_raw_parts(self as *const Rsdp as *const u8, length) }; let sum = bytes.iter().fold(0u8, |sum, &byte| sum.wrapping_add(byte)); if sum != 0 { @@ -60,7 +60,7 @@ pub fn init_acpi() { let rsdp_address = &rsdp_response.unwrap().address; - let rsdp_table: &RSDP = unsafe { &*(rsdp_address.as_ptr().unwrap() as *const RSDP) }; + let rsdp_table: &Rsdp = unsafe { &*(rsdp_address.as_ptr().unwrap() as *const Rsdp) }; if !rsdp_table.is_valid() { log_error!("Failed to initialize ACPI: RSDP was not valid!"); @@ -68,7 +68,7 @@ pub fn init_acpi() { } log_info!("{}", rsdp_table.revision); - let mut facp: Option<&ACPISDTHeader> = None; + let mut facp: Option<&AcpiSdtHeader> = None; let rsdt_address = rsdp_table.rsdt_address; facp = find_facp(rsdt_address as *const u32, rsdp_table.revision); @@ -80,7 +80,7 @@ pub fn init_acpi() { } #[repr(C)] -struct ACPISDTHeader { +struct AcpiSdtHeader { signature: [u8; 4], length: u32, revision: u8, @@ -92,7 +92,7 @@ struct ACPISDTHeader { creator_revision: u32, } -fn check_rsdt_checksum(table_header: *const ACPISDTHeader) -> bool { +fn check_rsdt_checksum(table_header: *const AcpiSdtHeader) -> bool { let mut sum: u8 = 0; for i in 0..unsafe { (*table_header).length } { @@ -103,23 +103,23 @@ fn check_rsdt_checksum(table_header: *const ACPISDTHeader) -> bool { } #[repr(C)] -struct RSDT { - h: ACPISDTHeader, +struct Rsdt { + h: AcpiSdtHeader, pointer_to_other_sdt: *const u32, } -fn find_facp(root_sdt: *const u32, revision: u8) -> Option<&'static ACPISDTHeader> { - let rsdt: &mut RSDT = unsafe { &mut *(root_sdt as *mut RSDT) }; +fn find_facp(root_sdt: *const u32, revision: u8) -> Option<&'static AcpiSdtHeader> { + let rsdt: &mut Rsdt = unsafe { &mut *(root_sdt as *mut Rsdt) }; rsdt.pointer_to_other_sdt = - [(rsdt.h.length - core::mem::size_of::() as u32) / 4].as_ptr(); + [(rsdt.h.length - core::mem::size_of::() as u32) / 4].as_ptr(); let entry_bytes = if revision > 0 { 8 } else { 4 }; - let entries = (rsdt.h.length - core::mem::size_of::() as u32) / entry_bytes; + let entries = (rsdt.h.length - core::mem::size_of::() as u32) / entry_bytes; for i in 0..entries { crate::println!("{i}"); - let h = unsafe { rsdt.pointer_to_other_sdt.add(i as usize) as *const ACPISDTHeader }; + let h = unsafe { rsdt.pointer_to_other_sdt.add(i as usize) as *const AcpiSdtHeader }; let signature_bytes = unsafe { (*h).signature }; let signature_str = core::str::from_utf8(&signature_bytes).unwrap_or(""); diff --git a/src/drivers/fs/fat.rs b/src/drivers/fs/fat.rs index c61626f..9e31632 100755 --- a/src/drivers/fs/fat.rs +++ b/src/drivers/fs/fat.rs @@ -7,7 +7,7 @@ use alloc::{ use crate::drivers::storage::drive::{BlockDevice, GPTPartitionEntry}; -use super::vfs::{VFSDirectory, VFSFile, VFSFileSystem}; +use super::vfs::{VfsDirectory, VfsFile, VfsFileSystem}; // The first Cluster (perhaps 0xF0FFFF0F) is the FAT ID // The second cluster stores the end-of-cluster-chain marker @@ -144,9 +144,9 @@ pub struct FileEntry { file_size: u32, } -pub struct FATFS<'a> { +pub struct FatFs<'a> { // Block device Info - drive: Box<&'a dyn BlockDevice>, + drive: &'a dyn BlockDevice, partition: GPTPartitionEntry, // FAT info fs_info: FSInfo, @@ -158,7 +158,7 @@ pub struct FATFS<'a> { sectors_per_fat: usize, } -impl<'a> FATFS<'a> { +impl<'a> FatFs<'a> { pub fn new(drive: &'a dyn BlockDevice, partition: GPTPartitionEntry) -> Result { let bpb_bytes = drive .read(partition.start_sector, 1) @@ -173,7 +173,7 @@ impl<'a> FATFS<'a> { } // We're trusting it - if let Some(system_identifier_string) = system_identifier.ok() { + if let Ok(system_identifier_string) = system_identifier { if !system_identifier_string.contains("FAT32") { return Err(()); } @@ -249,7 +249,7 @@ impl<'a> FATFS<'a> { let cluster_size = bpb.sectors_per_cluster as usize * 512; return Ok(Self { - drive: Box::new(drive), + drive, partition, fs_info, fat, @@ -336,19 +336,17 @@ impl<'a> FATFS<'a> { } } - if name.replacen(".", "", 1).len() <= 11 { - let search_parts: Vec<&str> = name.split(".").collect(); + if name.replacen('.', "", 1).len() <= 11 { + let search_parts: Vec<&str> = name.split('.').collect(); let filename = core::str::from_utf8(&file_entry.file_name).unwrap(); let extension = core::str::from_utf8(&file_entry.extension).unwrap(); - if search_parts.len() == 1 - && !filename.contains(&search_parts[0].to_ascii_uppercase()) - { - continue; - } else if search_parts.len() > 1 - && (!filename.contains(&search_parts[0].to_ascii_uppercase()) - || !extension.contains(&search_parts[1].to_ascii_uppercase())) + if (search_parts.len() == 1 + && !filename.contains(&search_parts[0].to_ascii_uppercase())) + || (search_parts.len() > 1 + && (!filename.contains(&search_parts[0].to_ascii_uppercase()) + || !extension.contains(&search_parts[1].to_ascii_uppercase()))) { continue; } @@ -432,8 +430,8 @@ impl<'a> FATFS<'a> { } } -impl<'a> VFSFileSystem for FATFS<'a> { - fn open(&self, path: &str) -> Result, ()> { +impl<'a> VfsFileSystem for FatFs<'a> { + fn open(&self, path: &str) -> Result, ()> { let path_componenets: Vec<&str> = path.trim_start_matches('/').split('/').collect(); let mut current_cluster = self.bpb.root_dir_cluster as usize; @@ -446,7 +444,7 @@ impl<'a> VFSFileSystem for FATFS<'a> { as usize; } else { return Ok(Box::new(FatFile { - fat_fs: &self, + fat_fs: self, file_entry, })); } @@ -455,17 +453,17 @@ impl<'a> VFSFileSystem for FATFS<'a> { return Err(()); } - fn read_dir(&self, path: &str) -> Result, ()> { + fn read_dir(&self, path: &str) -> Result, ()> { unimplemented!(); } } struct FatFile<'a> { - fat_fs: &'a FATFS<'a>, + fat_fs: &'a FatFs<'a>, file_entry: FileEntry, } -impl<'a> VFSFile for FatFile<'a> { +impl<'a> VfsFile for FatFile<'a> { fn read(&self) -> Result, ()> { let mut file: Vec = Vec::with_capacity(self.file_entry.file_size as usize); let mut file_ptr_index = 0; @@ -512,12 +510,12 @@ impl<'a> VFSFile for FatFile<'a> { } struct FatDirectory<'a> { - fat_fs: &'a FATFS<'a>, + fat_fs: &'a FatFs<'a>, directory_cluster: usize, } -impl<'a> VFSDirectory for FatDirectory<'a> { - fn list_files(&self) -> Result]>, ()> { +impl<'a> VfsDirectory for FatDirectory<'a> { + fn list_files(&self) -> Result]>, ()> { unimplemented!(); } } diff --git a/src/drivers/fs/initramfs/compressors/gzip.rs b/src/drivers/fs/initramfs/compressors/gzip.rs index fea0d8a..d1ca684 100644 --- a/src/drivers/fs/initramfs/compressors/gzip.rs +++ b/src/drivers/fs/initramfs/compressors/gzip.rs @@ -7,19 +7,20 @@ enum ZlibCompressionLevel { Best, } -impl Into for u8 { - fn into(self) -> ZlibCompressionLevel { - match self { - 0 => ZlibCompressionLevel::Fastest, - 1 => ZlibCompressionLevel::Fast, - 2 => ZlibCompressionLevel::Default, - 3 => ZlibCompressionLevel::Best, - _ => panic!("Unexpected compression level {self}"), +impl From for ZlibCompressionLevel { + fn from(value: u8) -> Self { + match value { + 0 => Self::Fastest, + 1 => Self::Fast, + 2 => Self::Default, + 3 => Self::Best, + _ => panic!("Unexpected compression level {value}"), } } } -// ZLIB steam, see RFC 1950 +// RFC 1950: "ZLIB Compressed Data Format Specification" +// RFC 1951: "DEFLATE Compressed Data Format Specification" pub fn uncompress_data(bytes: &[u8]) -> &[u8] { assert!(bytes.len() > 2); diff --git a/src/drivers/fs/initramfs/mod.rs b/src/drivers/fs/initramfs/mod.rs index 70b742e..66bc6df 100755 --- a/src/drivers/fs/initramfs/mod.rs +++ b/src/drivers/fs/initramfs/mod.rs @@ -1,16 +1,13 @@ pub mod compressors; -use core::{ - fmt::{self, Debug}, - ops::{Index, Range, RangeFrom, RangeFull}, -}; +use core::fmt::{self, Debug}; use alloc::{boxed::Box, sync::Arc, vec::Vec}; use limine::ModuleRequest; use crate::libs::math::ceil; -use super::vfs::{VFSDirectory, VFSFile, VFSFileSystem}; +use super::vfs::{VfsDirectory, VfsFile, VfsFileSystem}; pub static MODULE_REQUEST: ModuleRequest = ModuleRequest::new(0); @@ -98,7 +95,7 @@ impl Squashfs<'_> { let squashfs_data: &[u8] = unsafe { core::slice::from_raw_parts(ptr, length) }; - let superblock = SquashfsSuperblock::new(&squashfs_data)?; + let superblock = SquashfsSuperblock::new(squashfs_data)?; let data_table = &squashfs_data [core::mem::size_of::()..superblock.inode_table as usize]; @@ -158,7 +155,7 @@ impl Squashfs<'_> { } fn read_inode(&self, inode_num: u32) -> Inode { - let inode_table = &self.get_decompressed_table(&self.inode_table, (true, None)); + let inode_table = &self.get_decompressed_table(self.inode_table, (true, None)); let inode_offset = inode_num as usize; @@ -211,14 +208,10 @@ impl Squashfs<'_> { let mut buffer: Vec = Vec::with_capacity(8192); if table_is_compressed { - let bytes = if metadata_block.0 { - &table[2..] - } else { - &table - }; + let bytes = if metadata_block.0 { &table[2..] } else { table }; match self.superblock.compressor { - SquashfsCompressionType::GZIP => { + SquashfsCompressionType::Gzip => { buffer.extend_from_slice(compressors::gzip::uncompress_data(bytes)); } _ => { @@ -241,8 +234,8 @@ impl Squashfs<'_> { } } -impl<'a> VFSFileSystem for Squashfs<'a> { - fn open(&self, path: &str) -> Result, ()> { +impl<'a> VfsFileSystem for Squashfs<'a> { + fn open(&self, path: &str) -> Result, ()> { let path_components: Vec<&str> = path.trim_start_matches('/').split('/').collect(); let mut current_dir = self.read_root_dir(); @@ -273,7 +266,7 @@ impl<'a> VFSFileSystem for Squashfs<'a> { return Err(()); } - fn read_dir(&self, path: &str) -> Result, ()> { + fn read_dir(&self, path: &str) -> Result, ()> { unimplemented!() } } @@ -486,7 +479,7 @@ impl<'a> BasicFileInode<'a> { } } -impl<'a> VFSFile for BasicFileInode<'a> { +impl<'a> VfsFile for BasicFileInode<'a> { fn read(&self) -> Result, ()> { // TODO: handle tail end packing (somehow?) let block_count = @@ -584,23 +577,23 @@ enum InodeFileType { ExtendedSocked = 13, } -impl Into for u16 { - fn into(self) -> InodeFileType { - match self { - 1 => InodeFileType::BasicDirectory, - 2 => InodeFileType::BasicFile, - 3 => InodeFileType::BasicSymlink, - 4 => InodeFileType::BasicBlockDevice, - 5 => InodeFileType::BasicCharDevice, - 6 => InodeFileType::BasicPipe, - 7 => InodeFileType::BasicSocked, - 8 => InodeFileType::ExtendedDirectory, - 9 => InodeFileType::ExtendedFile, - 10 => InodeFileType::ExtendedSymlink, - 11 => InodeFileType::ExtendedBlockDevice, - 12 => InodeFileType::ExtendedPipe, - 13 => InodeFileType::ExtendedSocked, - _ => panic!("Unexpected Inode file type {self}!"), +impl From for InodeFileType { + fn from(value: u16) -> Self { + match value { + 1 => Self::BasicDirectory, + 2 => Self::BasicFile, + 3 => Self::BasicSymlink, + 4 => Self::BasicBlockDevice, + 5 => Self::BasicCharDevice, + 6 => Self::BasicPipe, + 7 => Self::BasicSocked, + 8 => Self::ExtendedDirectory, + 9 => Self::ExtendedFile, + 10 => Self::ExtendedSymlink, + 11 => Self::ExtendedBlockDevice, + 12 => Self::ExtendedPipe, + 13 => Self::ExtendedSocked, + _ => panic!("Unexpected Inode file type {value}!"), } } } @@ -608,12 +601,12 @@ impl Into for u16 { #[repr(u16)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum SquashfsCompressionType { - GZIP = 1, - LZMA = 2, - LZO = 3, - XZ = 4, - LZ4 = 5, - ZSTD = 6, + Gzip = 1, + Lzma = 2, + Lzo = 3, + Xz = 4, + Lz4 = 5, + Zstd = 6, } #[repr(u16)] @@ -632,6 +625,7 @@ enum SquashfsFlags { UncompressedIDTable = 0x0800, } +#[allow(dead_code)] #[derive(Debug)] struct SquashfsFeatures { uncompressed_inodes: bool, @@ -648,15 +642,15 @@ struct SquashfsFeatures { uncompressed_id_table: bool, } -impl Into for u16 { - fn into(self) -> SquashfsCompressionType { - match self { - 1 => SquashfsCompressionType::GZIP, - 2 => SquashfsCompressionType::LZMA, - 3 => SquashfsCompressionType::LZO, - 4 => SquashfsCompressionType::XZ, - 5 => SquashfsCompressionType::LZ4, - 6 => SquashfsCompressionType::ZSTD, +impl From for SquashfsCompressionType { + fn from(value: u16) -> Self { + match value { + 1 => Self::Gzip, + 2 => Self::Lzma, + 3 => Self::Lzo, + 4 => Self::Xz, + 5 => Self::Lz4, + 6 => Self::Zstd, _ => panic!("Unexpected Squashfs compression type!"), } } diff --git a/src/drivers/fs/vfs.rs b/src/drivers/fs/vfs.rs index 9989ba3..f820ef2 100755 --- a/src/drivers/fs/vfs.rs +++ b/src/drivers/fs/vfs.rs @@ -2,38 +2,37 @@ use alloc::{boxed::Box, sync::Arc, vec::Vec}; use crate::libs::mutex::Mutex; -pub trait VFSFileSystem { - fn open(&self, path: &str) -> Result, ()>; - fn read_dir(&self, path: &str) -> Result, ()>; +pub trait VfsFileSystem { + fn open(&self, path: &str) -> Result, ()>; + fn read_dir(&self, path: &str) -> Result, ()>; } -pub trait VFSFile { +pub trait VfsFile { fn read(&self) -> Result, ()>; } -pub trait VFSDirectory { - fn list_files(&self) -> Result]>, ()>; +pub trait VfsDirectory { + fn list_files(&self) -> Result]>, ()>; } -pub static VFS_INSTANCES: Mutex> = Mutex::new(Vec::new()); +pub static VFS_INSTANCES: Mutex> = Mutex::new(Vec::new()); -pub struct VFS { - file_system: Box, +pub struct Vfs { + file_system: Box, } -impl VFS { - pub fn new(file_system: Box) -> Self { +impl Vfs { + pub fn new(file_system: Box) -> Self { return Self { file_system }; } - pub fn open(&self, path: &str) -> Result, ()> { + pub fn open(&self, path: &str) -> Result, ()> { return self.file_system.open(path); } - pub fn read_dir(&self, path: &str) -> Result, ()> { + pub fn read_dir(&self, path: &str) -> Result, ()> { return self.file_system.read_dir(path); } - // Add more VFS methods as needed } pub fn init() { diff --git a/src/drivers/keyboard.rs b/src/drivers/keyboard.rs index 0073ddc..7ffd7f3 100755 --- a/src/drivers/keyboard.rs +++ b/src/drivers/keyboard.rs @@ -53,7 +53,7 @@ pub fn init() -> Result<(), KBDError> { idt_set_gate( InterruptIndex::Keyboard.as_u8(), - crate::drivers::keyboard::keyboard_interrupt_handler as u64, + crate::drivers::keyboard::keyboard_interrupt_handler as usize, ); // Enable PS/2 Devices (second then first) @@ -70,7 +70,8 @@ pub fn init() -> Result<(), KBDError> { pub fn set_leds(led_byte: u8) { // Command bytes outb(KBD_DATA_PORT, 0xED); - while !(inb(KBD_DATA_PORT) == 0xfa) {} + while inb(KBD_DATA_PORT) != 0xFA {} + // Data byte outb(KBD_DATA_PORT, led_byte); } @@ -84,207 +85,149 @@ fn parse_key(mut scancode: u8) -> Option> { let pressed = scancode & 0x80 == 0x0; scancode &= !(1 << 7); - let key: Option>; - - match scancode { - 0x01 => { - key = Some(Key { - pressed, - name: "Esc", - character: Some('\u{001B}'), - }); - } - 0x02 => { - return Some(Key { - pressed, - name: "1", - character: Some('1'), - }); - } - 0x03 => { - return Some(Key { - pressed, - name: "2", - character: Some('2'), - }); - } - 0x04 => { - return Some(Key { - pressed, - name: "3", - character: Some('3'), - }); - } - 0x05 => { - return Some(Key { - pressed, - name: "4", - character: Some('4'), - }); - } - 0x06 => { - return Some(Key { - pressed, - name: "5", - character: Some('5'), - }); - } - 0x07 => { - return Some(Key { - pressed, - name: "6", - character: Some('6'), - }); - } - 0x08 => { - return Some(Key { - pressed, - name: "7", - character: Some('7'), - }); - } - 0x09 => { - return Some(Key { - pressed, - name: "8", - character: Some('8'), - }); - } - 0x0A => { - return Some(Key { - pressed, - name: "9", - character: Some('9'), - }); - } - 0x0B => { - return Some(Key { - pressed, - name: "0", - character: Some('0'), - }); - } - 0x0C => { - return Some(Key { - pressed, - name: "-", - character: Some('-'), - }); - } - 0x0D => { - return Some(Key { - pressed, - name: "=", - character: Some('='), - }); - } - 0x0E => { - return Some(Key { - pressed, - name: "Backspace", - character: Some('\u{0008}'), - }); - } - 0x0F => { - return Some(Key { - pressed, - name: "Tab", - character: Some('\u{0009}'), - }); - } - 0x10 => { - return Some(Key { - pressed, - name: "q", - character: Some('q'), - }); - } - 0x11 => { - return Some(Key { - pressed, - name: "w", - character: Some('w'), - }); - } - 0x12 => { - return Some(Key { - pressed, - name: "e", - character: Some('e'), - }); - } - 0x13 => { - return Some(Key { - pressed, - name: "r", - character: Some('r'), - }); - } - 0x14 => { - return Some(Key { - pressed, - name: "t", - character: Some('t'), - }); - } - 0x15 => { - return Some(Key { - pressed, - name: "y", - character: Some('y'), - }); - } - 0x16 => { - return Some(Key { - pressed, - name: "u", - character: Some('u'), - }); - } - 0x17 => { - return Some(Key { - pressed, - name: "i", - character: Some('i'), - }); - } - 0x18 => { - return Some(Key { - pressed, - name: "o", - character: Some('o'), - }); - } - 0x19 => { - return Some(Key { - pressed, - name: "p", - character: Some('p'), - }); - } - 0x1A => { - return Some(Key { - pressed, - name: "[", - character: Some('['), - }); - } - 0x1B => { - return Some(Key { - pressed, - name: "]", - character: Some(']'), - }); - } - 0x1C => { - return Some(Key { - pressed, - name: "Enter", - character: Some('\u{000A}'), - }); - } + let key: Option> = match scancode { + 0x01 => Some(Key { + pressed, + name: "Esc", + character: Some('\u{001B}'), + }), + 0x02 => Some(Key { + pressed, + name: "1", + character: Some('1'), + }), + 0x03 => Some(Key { + pressed, + name: "2", + character: Some('2'), + }), + 0x04 => Some(Key { + pressed, + name: "3", + character: Some('3'), + }), + 0x05 => Some(Key { + pressed, + name: "4", + character: Some('4'), + }), + 0x06 => Some(Key { + pressed, + name: "5", + character: Some('5'), + }), + 0x07 => Some(Key { + pressed, + name: "6", + character: Some('6'), + }), + 0x08 => Some(Key { + pressed, + name: "7", + character: Some('7'), + }), + 0x09 => Some(Key { + pressed, + name: "8", + character: Some('8'), + }), + 0x0A => Some(Key { + pressed, + name: "9", + character: Some('9'), + }), + 0x0B => Some(Key { + pressed, + name: "0", + character: Some('0'), + }), + 0x0C => Some(Key { + pressed, + name: "-", + character: Some('-'), + }), + 0x0D => Some(Key { + pressed, + name: "=", + character: Some('='), + }), + 0x0E => Some(Key { + pressed, + name: "Backspace", + character: Some('\u{0008}'), + }), + 0x0F => Some(Key { + pressed, + name: "Tab", + character: Some('\u{0009}'), + }), + 0x10 => Some(Key { + pressed, + name: "q", + character: Some('q'), + }), + 0x11 => Some(Key { + pressed, + name: "w", + character: Some('w'), + }), + 0x12 => Some(Key { + pressed, + name: "e", + character: Some('e'), + }), + 0x13 => Some(Key { + pressed, + name: "r", + character: Some('r'), + }), + 0x14 => Some(Key { + pressed, + name: "t", + character: Some('t'), + }), + 0x15 => Some(Key { + pressed, + name: "y", + character: Some('y'), + }), + 0x16 => Some(Key { + pressed, + name: "u", + character: Some('u'), + }), + 0x17 => Some(Key { + pressed, + name: "i", + character: Some('i'), + }), + 0x18 => Some(Key { + pressed, + name: "o", + character: Some('o'), + }), + 0x19 => Some(Key { + pressed, + name: "p", + character: Some('p'), + }), + 0x1A => Some(Key { + pressed, + name: "[", + character: Some('['), + }), + 0x1B => Some(Key { + pressed, + name: "]", + character: Some(']'), + }), + 0x1C => Some(Key { + pressed, + name: "Enter", + character: Some('\u{000A}'), + }), 0x1D => { - if EXTENDED_KEY.load(Ordering::SeqCst) == true { + if EXTENDED_KEY.load(Ordering::SeqCst) { return Some(Key { pressed, name: "RCtrl", @@ -292,301 +235,219 @@ fn parse_key(mut scancode: u8) -> Option> { }); } - return Some(Key { + Some(Key { pressed, name: "LCtrl", character: None, - }); - } - 0x1E => { - return Some(Key { - pressed, - name: "a", - character: Some('a'), - }); - } - 0x1F => { - return Some(Key { - pressed, - name: "s", - character: Some('s'), - }); - } - 0x20 => { - return Some(Key { - pressed, - name: "d", - character: Some('d'), - }); - } - 0x21 => { - return Some(Key { - pressed, - name: "f", - character: Some('f'), - }); - } - 0x22 => { - return Some(Key { - pressed, - name: "g", - character: Some('g'), - }); - } - 0x23 => { - return Some(Key { - pressed, - name: "h", - character: Some('h'), - }); - } - 0x24 => { - return Some(Key { - pressed, - name: "j", - character: Some('j'), - }); - } - 0x25 => { - return Some(Key { - pressed, - name: "k", - character: Some('k'), - }); - } - 0x26 => { - return Some(Key { - pressed, - name: "l", - character: Some('l'), - }); - } - 0x27 => { - return Some(Key { - pressed, - name: ";", - character: Some(';'), - }); - } - 0x28 => { - return Some(Key { - pressed, - name: "'", - character: Some('\''), - }); - } - 0x29 => { - return Some(Key { - pressed, - name: "`", - character: Some('`'), - }); - } - 0x2A => { - return Some(Key { - pressed, - name: "LShift", - character: None, - }); - } - 0x2B => { - return Some(Key { - pressed, - name: "\\", - character: Some('\\'), - }); - } - 0x2C => { - return Some(Key { - pressed, - name: "z", - character: Some('z'), - }); - } - 0x2D => { - return Some(Key { - pressed, - name: "x", - character: Some('x'), - }); - } - 0x2E => { - return Some(Key { - pressed, - name: "c", - character: Some('c'), - }); - } - 0x2F => { - return Some(Key { - pressed, - name: "v", - character: Some('v'), - }); - } - 0x30 => { - return Some(Key { - pressed, - name: "b", - character: Some('b'), - }); - } - 0x31 => { - return Some(Key { - pressed, - name: "n", - character: Some('n'), - }); - } - 0x32 => { - return Some(Key { - pressed, - name: "m", - character: Some('m'), - }); - } - 0x33 => { - return Some(Key { - pressed, - name: ",", - character: Some(','), - }); - } - 0x34 => { - return Some(Key { - pressed, - name: ".", - character: Some('.'), - }); - } - 0x35 => { - return Some(Key { - pressed, - name: "/", - character: Some('/'), - }); - } - 0x36 => { - return Some(Key { - pressed, - name: "RShift", - character: None, - }); - } - 0x37 => { - return Some(Key { - pressed, - name: "*", - character: Some('*'), - }); - } - 0x38 => { - return Some(Key { - pressed, - name: "Alt", - character: None, - }); - } - 0x39 => { - return Some(Key { - pressed, - name: " ", - character: Some(' '), - }); - } - 0x3A => { - return Some(Key { - pressed, - name: "CapsLock", - character: None, - }); - } - 0x3B => { - return Some(Key { - pressed, - name: "F1", - character: None, - }); - } - 0x3C => { - return Some(Key { - pressed, - name: "F2", - character: None, - }); - } - 0x3D => { - return Some(Key { - pressed, - name: "F3", - character: None, - }); - } - 0x3E => { - return Some(Key { - pressed, - name: "F4", - character: None, - }); - } - 0x3F => { - return Some(Key { - pressed, - name: "F5", - character: None, - }); - } - 0x40 => { - return Some(Key { - pressed, - name: "F6", - character: None, - }); - } - 0x41 => { - return Some(Key { - pressed, - name: "F7", - character: None, - }); - } - 0x42 => { - return Some(Key { - pressed, - name: "F8", - character: None, - }); - } - 0x43 => { - return Some(Key { - pressed, - name: "F9", - character: None, - }); - } - 0x44 => { - return Some(Key { - pressed, - name: "F10", - character: None, - }); - } - 0x45 => { - return Some(Key { - pressed, - name: "NumLock", - character: None, - }); - } - 0x46 => { - return Some(Key { - pressed, - name: "ScrLock", - character: None, - }); + }) } + 0x1E => Some(Key { + pressed, + name: "a", + character: Some('a'), + }), + 0x1F => Some(Key { + pressed, + name: "s", + character: Some('s'), + }), + 0x20 => Some(Key { + pressed, + name: "d", + character: Some('d'), + }), + 0x21 => Some(Key { + pressed, + name: "f", + character: Some('f'), + }), + 0x22 => Some(Key { + pressed, + name: "g", + character: Some('g'), + }), + 0x23 => Some(Key { + pressed, + name: "h", + character: Some('h'), + }), + 0x24 => Some(Key { + pressed, + name: "j", + character: Some('j'), + }), + 0x25 => Some(Key { + pressed, + name: "k", + character: Some('k'), + }), + 0x26 => Some(Key { + pressed, + name: "l", + character: Some('l'), + }), + 0x27 => Some(Key { + pressed, + name: ";", + character: Some(';'), + }), + 0x28 => Some(Key { + pressed, + name: "'", + character: Some('\''), + }), + 0x29 => Some(Key { + pressed, + name: "`", + character: Some('`'), + }), + 0x2A => Some(Key { + pressed, + name: "LShift", + character: None, + }), + 0x2B => Some(Key { + pressed, + name: "\\", + character: Some('\\'), + }), + 0x2C => Some(Key { + pressed, + name: "z", + character: Some('z'), + }), + 0x2D => Some(Key { + pressed, + name: "x", + character: Some('x'), + }), + 0x2E => Some(Key { + pressed, + name: "c", + character: Some('c'), + }), + 0x2F => Some(Key { + pressed, + name: "v", + character: Some('v'), + }), + 0x30 => Some(Key { + pressed, + name: "b", + character: Some('b'), + }), + 0x31 => Some(Key { + pressed, + name: "n", + character: Some('n'), + }), + 0x32 => Some(Key { + pressed, + name: "m", + character: Some('m'), + }), + 0x33 => Some(Key { + pressed, + name: ",", + character: Some(','), + }), + 0x34 => Some(Key { + pressed, + name: ".", + character: Some('.'), + }), + 0x35 => Some(Key { + pressed, + name: "/", + character: Some('/'), + }), + 0x36 => Some(Key { + pressed, + name: "RShift", + character: None, + }), + 0x37 => Some(Key { + pressed, + name: "*", + character: Some('*'), + }), + 0x38 => Some(Key { + pressed, + name: "Alt", + character: None, + }), + 0x39 => Some(Key { + pressed, + name: " ", + character: Some(' '), + }), + 0x3A => Some(Key { + pressed, + name: "CapsLock", + character: None, + }), + 0x3B => Some(Key { + pressed, + name: "F1", + character: None, + }), + 0x3C => Some(Key { + pressed, + name: "F2", + character: None, + }), + 0x3D => Some(Key { + pressed, + name: "F3", + character: None, + }), + 0x3E => Some(Key { + pressed, + name: "F4", + character: None, + }), + 0x3F => Some(Key { + pressed, + name: "F5", + character: None, + }), + 0x40 => Some(Key { + pressed, + name: "F6", + character: None, + }), + 0x41 => Some(Key { + pressed, + name: "F7", + character: None, + }), + 0x42 => Some(Key { + pressed, + name: "F8", + character: None, + }), + 0x43 => Some(Key { + pressed, + name: "F9", + character: None, + }), + 0x44 => Some(Key { + pressed, + name: "F10", + character: None, + }), + 0x45 => Some(Key { + pressed, + name: "NumLock", + character: None, + }), + 0x46 => Some(Key { + pressed, + name: "ScrLock", + character: None, + }), 0x47 => { - if EXTENDED_KEY.load(Ordering::SeqCst) == true { + if EXTENDED_KEY.load(Ordering::SeqCst) { return Some(Key { pressed, name: "Home", @@ -594,14 +455,14 @@ fn parse_key(mut scancode: u8) -> Option> { }); } - return Some(Key { + Some(Key { pressed, name: "Keypad 7", character: Some('7'), - }); + }) } 0x48 => { - if EXTENDED_KEY.load(Ordering::SeqCst) == true { + if EXTENDED_KEY.load(Ordering::SeqCst) { return Some(Key { pressed, name: "CurUp", @@ -609,14 +470,14 @@ fn parse_key(mut scancode: u8) -> Option> { }); } - return Some(Key { + Some(Key { pressed, name: "Keypad 8", character: Some('8'), - }); + }) } 0x49 => { - if EXTENDED_KEY.load(Ordering::SeqCst) == true { + if EXTENDED_KEY.load(Ordering::SeqCst) { return Some(Key { pressed, name: "PgUp", @@ -624,21 +485,19 @@ fn parse_key(mut scancode: u8) -> Option> { }); } - return Some(Key { + Some(Key { pressed, name: "Keypad 9", character: Some('9'), - }); - } - 0x4A => { - return Some(Key { - pressed, - name: "-", - character: Some('-'), - }); + }) } + 0x4A => Some(Key { + pressed, + name: "-", + character: Some('-'), + }), 0x4B => { - if EXTENDED_KEY.load(Ordering::SeqCst) == true { + if EXTENDED_KEY.load(Ordering::SeqCst) { return Some(Key { pressed, name: "CurLeft", @@ -646,21 +505,19 @@ fn parse_key(mut scancode: u8) -> Option> { }); } - return Some(Key { + Some(Key { pressed, name: "Keypad 4", character: Some('4'), - }); - } - 0x4C => { - return Some(Key { - pressed, - name: "Keypad 5", - character: Some('5'), - }); + }) } + 0x4C => Some(Key { + pressed, + name: "Keypad 5", + character: Some('5'), + }), 0x4D => { - if EXTENDED_KEY.load(Ordering::SeqCst) == true { + if EXTENDED_KEY.load(Ordering::SeqCst) { return Some(Key { pressed, name: "CurRight", @@ -668,21 +525,19 @@ fn parse_key(mut scancode: u8) -> Option> { }); } - return Some(Key { + Some(Key { pressed, name: "Keypad 6", character: Some('6'), - }); - } - 0x4E => { - return Some(Key { - pressed, - name: "+", - character: Some('+'), - }); + }) } + 0x4E => Some(Key { + pressed, + name: "+", + character: Some('+'), + }), 0x4F => { - if EXTENDED_KEY.load(Ordering::SeqCst) == true { + if EXTENDED_KEY.load(Ordering::SeqCst) { return Some(Key { pressed, name: "End", @@ -690,14 +545,14 @@ fn parse_key(mut scancode: u8) -> Option> { }); } - return Some(Key { + Some(Key { pressed, name: "Keypad 1", character: Some('1'), - }); + }) } 0x50 => { - if EXTENDED_KEY.load(Ordering::SeqCst) == true { + if EXTENDED_KEY.load(Ordering::SeqCst) { return Some(Key { pressed, name: "CurDown", @@ -705,14 +560,14 @@ fn parse_key(mut scancode: u8) -> Option> { }); } - return Some(Key { + Some(Key { pressed, name: "Keypad 2", character: Some('2'), - }); + }) } 0x51 => { - if EXTENDED_KEY.load(Ordering::SeqCst) == true { + if EXTENDED_KEY.load(Ordering::SeqCst) { return Some(Key { pressed, name: "PgDn", @@ -720,14 +575,14 @@ fn parse_key(mut scancode: u8) -> Option> { }); } - return Some(Key { + Some(Key { pressed, name: "Keypad 3", character: Some('3'), - }); + }) } 0x52 => { - if EXTENDED_KEY.load(Ordering::SeqCst) == true { + if EXTENDED_KEY.load(Ordering::SeqCst) { return Some(Key { pressed, name: "Insert", @@ -735,14 +590,14 @@ fn parse_key(mut scancode: u8) -> Option> { }); } - return Some(Key { + Some(Key { pressed, name: "Keypad 0", character: Some('0'), - }); + }) } 0x53 => { - if EXTENDED_KEY.load(Ordering::SeqCst) == true { + if EXTENDED_KEY.load(Ordering::SeqCst) { return Some(Key { pressed, name: "Del", @@ -750,28 +605,24 @@ fn parse_key(mut scancode: u8) -> Option> { }); } - return Some(Key { + Some(Key { pressed, name: "Keypad .", character: Some('.'), - }); + }) } - 0x57 => { - return Some(Key { - pressed, - name: "F11", - character: None, - }); - } - 0x58 => { - return Some(Key { - pressed, - name: "F12", - character: None, - }); - } - _ => key = None, - } + 0x57 => Some(Key { + pressed, + name: "F11", + character: None, + }), + 0x58 => Some(Key { + pressed, + name: "F12", + character: None, + }), + _ => None, + }; return key; } diff --git a/src/drivers/pci.rs b/src/drivers/pci.rs index 4044ea4..db1309f 100755 --- a/src/drivers/pci.rs +++ b/src/drivers/pci.rs @@ -170,15 +170,13 @@ fn check_function(bus: u8, device: u8, func: u8) { .write() .push(PciDevice::new(bus, device, func)); - let class_code: u8; - let subclass_code: u8; - let secondary_bus: u8; + let _secondary_bus: u8; - class_code = read_pci_class_code(bus, device, func); - subclass_code = read_pci_subclass_code(bus, device, func); + let class_code = read_pci_class_code(bus, device, func); + let subclass_code = read_pci_subclass_code(bus, device, func); if class_code == 0x06 && subclass_code == 0x04 { - secondary_bus = read_pci_to_pci_secondary_bus(bus, device, func); + _secondary_bus = read_pci_to_pci_secondary_bus(bus, device, func); // TODO: This causes an infinite loop on baremetal // check_bus(secondary_bus); } diff --git a/src/drivers/serial.rs b/src/drivers/serial.rs index 1895a33..d95e713 100644 --- a/src/drivers/serial.rs +++ b/src/drivers/serial.rs @@ -20,16 +20,16 @@ pub static POISONED: AtomicBool = AtomicBool::new(false); pub fn init_serial() -> u8 { outb(PORT + 1, 0x00); outb(PORT + 3, 0x80); - outb(PORT + 0, 0x03); + outb(PORT, 0x03); outb(PORT + 1, 0x00); outb(PORT + 3, 0x03); outb(PORT + 2, 0xC7); outb(PORT + 4, 0x0B); outb(PORT + 4, 0x1E); - outb(PORT + 0, 0xAE); + outb(PORT, 0xAE); // Check if serial is faulty - if inb(PORT + 0) != 0xAE { + if inb(PORT) != 0xAE { crate::log_error!("Serial Driver failed to initialize"); POISONED.store(true, core::sync::atomic::Ordering::Relaxed); return 1; diff --git a/src/drivers/storage/drive.rs b/src/drivers/storage/drive.rs index b572110..a1464f3 100644 --- a/src/drivers/storage/drive.rs +++ b/src/drivers/storage/drive.rs @@ -3,7 +3,7 @@ use alloc::sync::Arc; pub trait BlockDevice { fn sector_count(&self) -> u64; fn read(&self, sector: u64, sector_count: usize) -> Result, ()>; - fn write(&self, sector: u64, data: &[u8]) -> Result<(), ()>; + fn write(&self, sector: u64, data: &mut [u8]) -> Result<(), ()>; } #[derive(Clone, Copy, Debug, Default)] diff --git a/src/drivers/storage/ide.rs b/src/drivers/storage/ide.rs index e29b333..719b940 100755 --- a/src/drivers/storage/ide.rs +++ b/src/drivers/storage/ide.rs @@ -3,7 +3,7 @@ use core::mem::size_of; use alloc::{boxed::Box, sync::Arc, vec::Vec}; use crate::{ - arch::io::{inb, insw, inw, outb}, + arch::io::{inb, insw, inw, outb, outsw, outw}, drivers::{ fs::fat, storage::drive::{GPTBlock, GPTPartitionEntry}, @@ -161,29 +161,7 @@ enum ATADriveDirection { Write = 0x01, } -static DRIVE_ID: Mutex<[[u16; 256]; 2]> = Mutex::new([[0u16; 256]; 2]); - pub fn init() { - // for pci_device in super::pci::PCI_DEVICES.lock().read() { - // if pci_device.class_code != 0x01 || pci_device.subclass_code != 0x01 { - // continue; - // } - - // let (bar0, bar1, bar2, bar3, bar4, _) = - // super::pci::get_pci_bar_addresses(pci_device.bus, pci_device.device, pci_device.func); - - // crate::println!( - // "bar0: {} bar1: {} bar2: {} bar3: {} bar4: {}", - // bar0, - // bar1, - // bar2, - // bar3, - // bar4 - // ); - - // ide_initialize(bar0, bar1, bar2, bar3, bar4); - // } - // crate::println!("{:?}", ata_identify_drive(0xB0)); ide_initialize(0x1F0, 0x3F6, 0x170, 0x376, 0x000); } @@ -193,7 +171,7 @@ struct ATABus { control_bar: u16, } -impl<'a> ATABus { +impl ATABus { fn new(io_bar: u16, control_bar: u16) -> Arc { let io_bar = io_bar & 0xFFFC; let control_bar = control_bar & 0xFFFC; @@ -207,7 +185,7 @@ impl<'a> ATABus { pub fn select(&self, drive: u8) { outb( self.io_bar + ATADriveDataRegister::DeviceSelect as u16, - drive as u8, + drive, ); } @@ -310,6 +288,50 @@ impl<'a> ATABus { sector: u64, sector_count: usize, ) -> Result, ()> { + let mut buffer: Vec = Vec::with_capacity(ATA_SECTOR_SIZE * sector_count); + unsafe { buffer.set_len(buffer.capacity()) }; + + self.ide_access( + drive, + sector, + sector_count, + ATADriveDirection::Read, + buffer.as_mut_slice(), + )?; + + return Ok(Arc::from(buffer)); + } + + pub fn write( + &self, + drive: ATADriveType, + sector: u64, + sector_count: usize, + buffer: &mut [u8], + ) -> Result<(), ()> { + if buffer.len() < ATA_SECTOR_SIZE * sector_count { + return Err(()); + } + + self.ide_access( + drive, + sector, + sector_count, + ATADriveDirection::Write, + buffer, + )?; + + return Ok(()); + } + + fn ide_access( + &self, + drive: ATADriveType, + sector: u64, + sector_count: usize, + direction: ATADriveDirection, + buffer: &mut [u8], + ) -> Result<(), ()> { self.await_busy(); let using_lba48 = sector >= (1 << 28) - 1; @@ -342,7 +364,7 @@ impl<'a> ATABus { ); outb( self.io_bar + ATADriveDataRegister::LBA0 as u16, - (sector >> 16) as u8, + sector as u8, ); outb( self.io_bar + ATADriveDataRegister::LBA1 as u16, @@ -350,10 +372,13 @@ impl<'a> ATABus { ); outb( self.io_bar + ATADriveDataRegister::LBA2 as u16, - sector as u8, + (sector >> 16) as u8, ); - self.send_command(ATADriveCommand::ReadPIOExt); + match direction { + ATADriveDirection::Read => self.send_command(ATADriveCommand::ReadPIOExt), + ATADriveDirection::Write => self.send_command(ATADriveCommand::WritePIOExt), + } } else { self.select(0xE0 | (drive as u8) | ((sector >> 24) as u8 & 0x0F)); @@ -374,39 +399,64 @@ impl<'a> ATABus { (sector >> 16) as u8, ); - self.send_command(ATADriveCommand::ReadPIO); + match direction { + ATADriveDirection::Read => self.send_command(ATADriveCommand::ReadPIO), + ATADriveDirection::Write => self.send_command(ATADriveCommand::WritePIO), + } } // sector count * 512 = bytes in array - let array_size = (sector_count as usize) * ATA_SECTOR_SIZE; + let array_size = (sector_count) * ATA_SECTOR_SIZE; + + // Since this is an internal function, this should never fail + assert!(buffer.len() >= array_size); // Allocate memory for the array that stores the sector data - let mut buffer = Vec::new(); - buffer.reserve_exact(array_size); - + let mut buffer_offset = 0; for i in 0..sector_count { self.wait_for_drive_ready() .map_err(|_| crate::log_error!("Error reading IDE Device"))?; // # Safety // - // We know that buffer is the exact size of count, so it will never panic:tm: - unsafe { - insw( - self.io_bar + ATADriveDataRegister::Data as u16, - (buffer.as_mut_ptr() as *mut u16) - .add((i as usize * ATA_SECTOR_SIZE) / size_of::()), - ATA_SECTOR_SIZE / size_of::() as usize, - ); + // We know that buffer is at least sector_count * ATA_SECTOR_SIZE, so it will never panic:tm: + // unsafe { + // match direction { + // ATADriveDirection::Read => insw( + // self.io_bar + ATADriveDataRegister::Data as u16, + // (buffer.as_mut_ptr() as *mut u16) + // .add((i * ATA_SECTOR_SIZE) / size_of::()), + // ATA_SECTOR_SIZE / size_of::(), + // ), + // ATADriveDirection::Write => outsw( + // self.io_bar + ATADriveDataRegister::Data as u16, + // (buffer.as_mut_ptr() as *mut u16) + // .add((i * ATA_SECTOR_SIZE) / size_of::()), + // ATA_SECTOR_SIZE / size_of::(), + // ), + // } + // } - buffer.set_len(buffer.len() + ATA_SECTOR_SIZE); + for chunk in + buffer[buffer_offset..(buffer_offset + ATA_SECTOR_SIZE)].chunks_exact_mut(2) + { + match direction { + ATADriveDirection::Read => { + let word = + inw(self.io_bar + ATADriveDataRegister::Data as u16).to_le_bytes(); + chunk.copy_from_slice(&word); + } + ATADriveDirection::Write => { + let word = u16::from_le_bytes(chunk.try_into().unwrap()); + outw(self.io_bar + ATADriveDataRegister::Data as u16, word); + } + } } + + buffer_offset += ATA_SECTOR_SIZE; } - // Turn Vec into Arc in favor of Arc's constant time copy - let arc_data: Arc<[u8]> = Arc::from(buffer); - - return Ok(arc_data); + return Ok(()); } fn software_reset(&self) { @@ -460,7 +510,7 @@ impl ATADrive { impl BlockDevice for ATADrive { fn read(&self, sector: u64, sector_count: usize) -> Result, ()> { - if (sector + sector_count as u64) > self.sector_count() as u64 { + if (sector + sector_count as u64) > self.sector_count() { return Err(()); } @@ -475,8 +525,14 @@ impl BlockDevice for ATADrive { return unsafe { *(sectors as *const u32) } as u64; } - fn write(&self, sector: u64, data: &[u8]) -> Result<(), ()> { - panic!("TODO: ATA Drive writes"); + fn write(&self, sector: u64, buffer: &mut [u8]) -> Result<(), ()> { + let sector_count = buffer.len() / 512; + + self.bus.software_reset(); + + return self + .bus + .write(self.drive_type, sector, sector_count, buffer); } } @@ -500,8 +556,8 @@ fn ide_initialize(bar0: u32, bar1: u32, _bar2: u32, _bar3: u32, _bar4: u32) { let drive = ATADrive::new(bus.clone(), drive_type); - if drive.is_ok() { - DRIVES.lock().write().push(drive.unwrap()); + if let Ok(drive) = drive { + DRIVES.lock().write().push(drive); } } @@ -520,7 +576,7 @@ fn ide_initialize(bar0: u32, bar1: u32, _bar2: u32, _bar3: u32, _bar4: u32) { crate::log_info!( "ATA: Drive 0 has {} sectors ({} MB)", sectors, - (sectors as u64 * ATA_SECTOR_SIZE as u64) / 1024 / 1024 + (sectors * ATA_SECTOR_SIZE as u64) / 1024 / 1024 ); let mbr_sector = drive.read(0, 1).expect("Failed to read first sector"); @@ -601,7 +657,7 @@ fn ide_initialize(bar0: u32, bar1: u32, _bar2: u32, _bar3: u32, _bar4: u32) { } for &partition in partitions.iter() { - let fat_fs = fat::FATFS::new(drive, partition); + let fat_fs = fat::FatFs::new(drive, partition); if fat_fs.is_err() { continue; @@ -609,14 +665,36 @@ fn ide_initialize(bar0: u32, bar1: u32, _bar2: u32, _bar3: u32, _bar4: u32) { let fat_fs = fat_fs.unwrap(); - let vfs = crate::drivers::fs::vfs::VFS::new(Box::new(fat_fs)); + let vfs = crate::drivers::fs::vfs::Vfs::new(Box::new(fat_fs)); crate::drivers::fs::vfs::VFS_INSTANCES .lock() .write() .push(vfs); + + crate::println!( + "{:?}", + crate::drivers::fs::vfs::VFS_INSTANCES + .lock() + .read() + .last() + .unwrap() + .open("/example.txt") + .unwrap() + .read() + ); } + let mut buffer = Vec::with_capacity(4096); + unsafe { buffer.set_len(buffer.capacity()) }; + buffer.fill(0x69_u8); + + let _ = drive.write(0, &mut buffer); + + let data = drive.read(0, 1); + + crate::println!("{:X?}", data); + crate::println!("{:?}", partitions); } } diff --git a/src/drivers/video/mod.rs b/src/drivers/video/mod.rs index 70c24b5..d9a6682 100755 --- a/src/drivers/video/mod.rs +++ b/src/drivers/video/mod.rs @@ -18,12 +18,8 @@ pub fn fill_screen(color: u32, mirror_buffer: Option) { let buffer_size = (framebuffer.pitch / (framebuffer.bpp / 8)) * framebuffer.height; unsafe { - if mirror_buffer.is_some() { - crate::libs::util::memset32( - mirror_buffer.unwrap().pointer as *mut u32, - color, - buffer_size, - ); + if let Some(mirror_buffer) = mirror_buffer { + crate::libs::util::memset32(mirror_buffer.pointer as *mut u32, color, buffer_size); } crate::libs::util::memset32(framebuffer_ptr as *mut u32, color, buffer_size); @@ -55,8 +51,8 @@ pub fn put_char( for (row_idx, &character_byte) in character_array.iter().enumerate() { let mut byte = [bg; 8]; - for bit in 0..8 { - byte[bit] = [bg, fg][((character_byte >> (7 - bit)) & 0b00000001) as usize] + for (i, bit) in byte.iter_mut().enumerate() { + *bit = [bg, fg][((character_byte >> (7 - i)) & 0b00000001) as usize] } let row_start_offset = (start_y as usize + row_idx) * framebuffer.pitch @@ -198,14 +194,8 @@ pub fn get_framebuffer() -> Option { let framebuffer_response = crate::drivers::video::FRAMEBUFFER_REQUEST .get_response() - .get(); + .get()?; - if framebuffer_response.is_none() { - return None; - } - - // eww, variable redeclaration - let framebuffer_response = framebuffer_response.unwrap(); if framebuffer_response.framebuffer_count < 1 { return None; } @@ -215,7 +205,7 @@ pub fn get_framebuffer() -> Option { let framebuffer = Framebuffer::new( framebuffer_response.bpp as usize, framebuffer_response.pitch as usize, - framebuffer_response.address.as_ptr().unwrap() as *mut u8, + framebuffer_response.address.as_ptr().unwrap(), framebuffer_response.width as usize, framebuffer_response.height as usize, ); diff --git a/src/libs/lazy.rs b/src/libs/lazy.rs index 75c2b97..fb20eda 100755 --- a/src/libs/lazy.rs +++ b/src/libs/lazy.rs @@ -14,7 +14,7 @@ impl T> Lazy { pub const fn new(init_func: F) -> Self { Lazy { value: UnsafeCell::new(None), - init_func: init_func, + init_func, initialized: AtomicBool::new(false), } } diff --git a/src/libs/logging.rs b/src/libs/logging.rs index 1149ece..dcefb55 100644 --- a/src/libs/logging.rs +++ b/src/libs/logging.rs @@ -1,14 +1,14 @@ #[macro_export] macro_rules! log_info { - ($($arg:tt)*) => (crate::println!("\033[97m[ \033[90m? \033[97m]\033[0m {}", &alloc::format!($($arg)*))); + ($($arg:tt)*) => ($crate::println!("\033[97m[ \033[90m? \033[97m]\033[0m {}", &alloc::format!($($arg)*))); } #[macro_export] macro_rules! log_error { - ($($arg:tt)*) => (crate::println!("\033[97m[ \033[91m! \033[97m]\033[0m {}", &alloc::format!($($arg)*))); + ($($arg:tt)*) => ($crate::println!("\033[97m[ \033[91m! \033[97m]\033[0m {}", &alloc::format!($($arg)*))); } #[macro_export] macro_rules! log_ok { - ($($arg:tt)*) => (crate::println!("\033[97m[ \033[92m* \033[97m]\033[0;m {}", &alloc::format!($($arg)*))); + ($($arg:tt)*) => ($crate::println!("\033[97m[ \033[92m* \033[97m]\033[0;m {}", &alloc::format!($($arg)*))); } diff --git a/src/libs/math.rs b/src/libs/math.rs index 8c229be..717e494 100644 --- a/src/libs/math.rs +++ b/src/libs/math.rs @@ -66,13 +66,12 @@ pub fn ceil(x: f64) -> f64 { let u: u64 = x.to_bits(); let e: i64 = (u >> 52 & 0x7ff) as i64; - let y: f64; if e >= 0x3ff + 52 || x == 0. { return x; } - y = if (u >> 63) != 0 { + let y = if (u >> 63) != 0 { x - TOINT + TOINT - x } else { x + TOINT - TOINT - x diff --git a/src/libs/util.rs b/src/libs/util.rs index 1f63497..a444123 100644 --- a/src/libs/util.rs +++ b/src/libs/util.rs @@ -3,7 +3,7 @@ pub unsafe fn memset32(dst: *mut u32, val: u32, count: usize) { if cfg!(not(any(target_arch = "x86", target_arch = "x86_64"))) { let mut buf = dst; unsafe { - while buf < dst.offset(count as isize) { + while buf < dst.add(count) { core::ptr::write_volatile(buf, val); buf = buf.offset(1); } diff --git a/src/main.rs b/src/main.rs index 20ea398..6c20190 100755 --- a/src/main.rs +++ b/src/main.rs @@ -56,6 +56,15 @@ pub struct KernelFeatures { pub fat_in_mem: bool, } +impl KernelFeatures { + fn update_option(&mut self, option: &str, value: &str) { + match option { + "fat_in_mem" => self.fat_in_mem = value == "true", + _ => {} + } + } +} + pub static KERNEL_FEATURES: libs::lazy::Lazy = libs::lazy::Lazy::new(parse_kernel_cmdline); @@ -86,24 +95,15 @@ fn parse_kernel_cmdline() -> KernelFeatures { .split_whitespace() .collect::>(); - for &arg in kernel_arguments.iter() { - let arg_parts = arg.split("=").collect::>(); - let mut arg_parts = arg_parts.iter().peekable(); + crate::println!("{kernel_arguments:?}"); - for _ in 0..arg_parts.len() { - let part = arg_parts.next(); - if part.is_none() { - break; - } + for item in kernel_arguments { + let parts: Vec<&str> = item.split('=').collect(); - match part { - Some(&"fat_in_mem") => { - if arg_parts.peek() == Some(&&"false") { - kernel_features.fat_in_mem = false; - } - } - _ => {} - } + if parts.len() == 2 { + let (option, value) = (parts[0], parts[1]); + + kernel_features.update_option(option, value); } } diff --git a/src/mem/allocator.rs b/src/mem/allocator.rs index be9c372..260d029 100644 --- a/src/mem/allocator.rs +++ b/src/mem/allocator.rs @@ -59,7 +59,7 @@ impl BuddyAllocator { let free_lists: Mutex<[*mut FreeBlock; HEAP_BLOCKS]> = Mutex::new(free_lists_buf); - let heap_start = AtomicPtr::new(heap_start as *mut u8); + let heap_start = AtomicPtr::new(heap_start); let heap_size = AtomicUsize::new(heap_size); Self { diff --git a/src/mem/mod.rs b/src/mem/mod.rs index ce50587..9fdd813 100755 --- a/src/mem/mod.rs +++ b/src/mem/mod.rs @@ -34,7 +34,7 @@ pub static HHDM_OFFSET: Lazy = Lazy::new(|| { }); pub static PHYSICAL_MEMORY_MANAGER: Lazy = - Lazy::new(|| PhysicalMemoryManager::new()); + Lazy::new(PhysicalMemoryManager::new); pub struct Allocator { pub inner: Lazy, @@ -134,7 +134,7 @@ pub trait LabelBytes { impl LabelBytes for usize { fn label_bytes(&self) -> Label { - let bytes = self.clone(); + let bytes = *self; if bytes >> 30 > 0 { return Label { diff --git a/src/mem/pmm.rs b/src/mem/pmm.rs index 140166a..867918d 100644 --- a/src/mem/pmm.rs +++ b/src/mem/pmm.rs @@ -28,15 +28,12 @@ impl PhysicalMemoryManager { let mut highest_addr: usize = 0; for entry in super::MEMMAP.lock().read().iter() { - match entry.typ { - limine::MemoryMapEntryType::Usable => { - pmm.usable_pages - .fetch_add(entry.len as usize / PAGE_SIZE, Ordering::SeqCst); - if highest_addr < (entry.base + entry.len) as usize { - highest_addr = (entry.base + entry.len) as usize; - } + if entry.typ == limine::MemoryMapEntryType::Usable { + pmm.usable_pages + .fetch_add(entry.len as usize / PAGE_SIZE, Ordering::SeqCst); + if highest_addr < (entry.base + entry.len) as usize { + highest_addr = (entry.base + entry.len) as usize; } - _ => {} } } @@ -83,7 +80,7 @@ impl PhysicalMemoryManager { let mut p: usize = 0; while self.last_used_page_idx.load(Ordering::SeqCst) < limit { - if self.bitmap_test(self.last_used_page_idx.fetch_add(1, Ordering::SeqCst)) == true { + if self.bitmap_test(self.last_used_page_idx.fetch_add(1, Ordering::SeqCst)) { p = 0; continue; } diff --git a/src/usr/shell.rs b/src/usr/shell.rs index c567fe0..47e4f77 100755 --- a/src/usr/shell.rs +++ b/src/usr/shell.rs @@ -60,7 +60,7 @@ impl ModStatusBits { let status = self.status.load(Ordering::SeqCst); return ModStatus { - win: ((status >> 0) & 1) != 0, + win: (status & 1) != 0, ctrl: ((status >> 1) & 1) != 0, alt: ((status >> 2) & 1) != 0, shift: ((status >> 3) & 1) != 0, diff --git a/src/usr/tty.rs b/src/usr/tty.rs index 5d7b792..2c5be90 100755 --- a/src/usr/tty.rs +++ b/src/usr/tty.rs @@ -51,7 +51,7 @@ impl Console { let framebuffer = crate::drivers::video::get_framebuffer(); // Enable serial if it initialized correctly - if crate::drivers::serial::POISONED.load(Ordering::SeqCst) == false { + if !crate::drivers::serial::POISONED.load(Ordering::SeqCst) { self.feature_bits.store( self.feature_bits.load(Ordering::SeqCst) | 1 << 1, Ordering::SeqCst, @@ -121,7 +121,7 @@ impl Console { let mut in_escape_sequence = false; let mut color_code_buffer = String::new(); - for (_i, character) in string.chars().enumerate() { + for character in string.chars() { if in_escape_sequence { if character == 'm' { in_escape_sequence = false; @@ -251,11 +251,7 @@ impl Console { screen_size - skip, ); - crate::libs::util::memset32( - second_buffer.add(screen_size - skip) as *mut u32, - 0x000000, - skip, - ); + crate::libs::util::memset32(second_buffer.add(screen_size - skip), 0x000000, skip); core::ptr::copy_nonoverlapping(second_buffer, framebuffer, screen_size); } @@ -267,11 +263,7 @@ impl Console { screen_size - skip, ); - crate::libs::util::memset32( - framebuffer.add(screen_size - skip) as *mut u32, - 0x000000, - skip, - ); + crate::libs::util::memset32(framebuffer.add(screen_size - skip), 0x000000, skip); } } } @@ -416,14 +408,14 @@ fn color_to_hex(color: u8) -> u32 { #[macro_export] macro_rules! println { - () => (crate::print!("\n")); - ($($arg:tt)*) => (crate::print!("{}\n", &alloc::format!($($arg)*))); + () => ($crate::print!("\n")); + ($($arg:tt)*) => ($crate::print!("{}\n", &alloc::format!($($arg)*))); } #[macro_export] macro_rules! print { ($($arg:tt)*) => ( - crate::usr::tty::CONSOLE.puts(&alloc::format!($($arg)*)) + $crate::usr::tty::CONSOLE.puts(&alloc::format!($($arg)*)) ) } @@ -441,7 +433,7 @@ impl InputBuffer { } pub fn pop(&mut self) { - if self.buffer.len() > 0 { + if !self.buffer.is_empty() { self.buffer.pop(); } } @@ -495,7 +487,7 @@ pub fn handle_key(key: crate::drivers::keyboard::Key) { } if key.character.unwrap() == '\u{0008}' { - if input_buffer.buffer.len() == 0 { + if input_buffer.buffer.is_empty() { return; } @@ -513,7 +505,7 @@ pub fn handle_key(key: crate::drivers::keyboard::Key) { pub fn exec(command: &str) { let (command, args) = parse_input(command.trim()); - if command == "" { + if command.is_empty() { return; } @@ -531,7 +523,7 @@ pub fn exec(command: &str) { } if command == "memalloc" { - if args.len() == 0 { + if args.is_empty() { println!("Allocation size is required. See --help for detailed instructions."); return; } @@ -556,7 +548,7 @@ pub fn exec(command: &str) { let layout = core::alloc::Layout::from_size_align(size.unwrap(), 16).unwrap(); let mem = unsafe { alloc(layout) as *mut u16 }; - unsafe { *(mem as *mut u16) = 42 }; + unsafe { *(mem) = 42 }; println!("{mem:p} val: {}", unsafe { *(mem) }); } else { // deallocate @@ -569,7 +561,7 @@ pub fn exec(command: &str) { let mut size = 0; for arg in args { - if arg.starts_with("-") { + if arg.starts_with('-') { continue; } @@ -604,7 +596,7 @@ pub fn exec(command: &str) { } if command == "memtest" { - if args.len() == 0 { + if args.is_empty() { println!("Memory address to test is required."); return; } @@ -643,7 +635,7 @@ pub fn exec(command: &str) { if command == "echo" { let mut input = ""; - if args.len() != 0 { + if !args.is_empty() { input = args[0].as_str(); } @@ -683,7 +675,7 @@ pub fn exec(command: &str) { } if command == "read" { - if args.len() < 1 { + if args.is_empty() { println!("read: usage error: at least one argument is required!"); return; } @@ -809,9 +801,9 @@ fn parse_escaped_char(next_char: char) -> char { } fn parse_memory_address(input: &str) -> Option { - if input.starts_with("0x") { - u64::from_str_radix(&input[2..], 16).ok() + if let Some(stripped) = input.strip_prefix("0x") { + return u64::from_str_radix(stripped, 16).ok(); } else { - None + return None; } }