diff --git a/loader/build.rs b/loader/build.rs index 20d800865..19d75180d 100644 --- a/loader/build.rs +++ b/loader/build.rs @@ -17,21 +17,15 @@ fn main() { #[cfg(not(any(feature = "cramium-soc", feature = "cramium-fpga")))] let p = PathBuf::from("src/platform/precursor/link.x"); - println!( - "cargo:rerun-if-changed={}", - p.clone().into_os_string().into_string().unwrap() - ); + println!("cargo:rerun-if-changed={}", p.clone().into_os_string().into_string().unwrap()); println!("cargo:rustc-link-arg=-Tlink.x"); p } else if target.starts_with("armv7a") { let name = env::var("CARGO_PKG_NAME").unwrap(); - fs::copy( - format!("bin/{}.a", target), - out_dir.join(format!("lib{}.a", name)), - ) - .expect("copy arm assembly binary"); + fs::copy(format!("bin/{}.a", target), out_dir.join(format!("lib{}.a", name))) + .expect("copy arm assembly binary"); println!("cargo:rustc-link-lib=static={}", name); println!("cargo:rustc-link-search={}", out_dir.display()); @@ -51,11 +45,7 @@ fn main() { .truncate(true) .open(out_dir.join("link.x")) .unwrap() - .write_all( - fs::read_to_string(linker_file_path) - .expect("linker file read") - .as_bytes(), - ) + .write_all(fs::read_to_string(linker_file_path).expect("linker file read").as_bytes()) .unwrap(); println!("cargo:rustc-link-search={}", out_dir.display()); diff --git a/loader/src/args.rs b/loader/src/args.rs index ceb531412..dd3dd8486 100644 --- a/loader/src/args.rs +++ b/loader/src/args.rs @@ -20,18 +20,10 @@ pub struct KernelArgumentsIterator { } impl KernelArguments { - pub fn new(base: *const usize) -> KernelArguments { - KernelArguments { - base: base as *const u32, - } - } + pub fn new(base: *const usize) -> KernelArguments { KernelArguments { base: base as *const u32 } } pub fn iter(self) -> KernelArgumentsIterator { - KernelArgumentsIterator { - base: self.base, - size: self.size(), - offset: 0, - } + KernelArgumentsIterator { base: self.base, size: self.size(), offset: 0 } } pub fn size(self) -> usize { @@ -53,24 +45,15 @@ pub struct KernelArgument { impl KernelArgument { pub fn new(base: *const u32, offset: u32) -> Self { let name = unsafe { base.add(offset as usize / 4).read() }; - let size = unsafe { - (base.add(offset as usize / 4 + 1) as *const u16) - .add(1) - .read() - } as u32; - let data = unsafe { - core::slice::from_raw_parts(base.add(offset as usize / 4 + 2), size as usize) - }; - KernelArgument { - name, - size: size * 4, - data, - } + let size = unsafe { (base.add(offset as usize / 4 + 1) as *const u16).add(1).read() } as u32; + let data = unsafe { core::slice::from_raw_parts(base.add(offset as usize / 4 + 2), size as usize) }; + KernelArgument { name, size: size * 4, data } } } impl Iterator for KernelArgumentsIterator { type Item = KernelArgument; + fn next(&mut self) -> Option { if self.offset as usize >= self.size { None diff --git a/loader/src/bootconfig.rs b/loader/src/bootconfig.rs index b3585e16a..847372055 100644 --- a/loader/src/bootconfig.rs +++ b/loader/src/bootconfig.rs @@ -78,8 +78,7 @@ impl BootConfig { pub fn get_top(&self) -> *mut usize { let val = unsafe { self.sram_start.add( - (self.sram_size - self.init_size - self.extra_pages * PAGE_SIZE) - / mem::size_of::(), + (self.sram_size - self.init_size - self.extra_pages * PAGE_SIZE) / mem::size_of::(), ) }; assert!((val as usize) >= (self.sram_start as usize)); @@ -103,15 +102,11 @@ impl BootConfig { let pg = self.get_top(); unsafe { // Grab the page address and zero it out - bzero( - pg as *mut usize, - pg.add(PAGE_SIZE / mem::size_of::()) as *mut usize, - ); + bzero(pg as *mut usize, pg.add(PAGE_SIZE / mem::size_of::()) as *mut usize); } // Mark this page as in-use by the kernel let extra_bytes = self.extra_pages * PAGE_SIZE; - self.runtime_page_tracker[(self.sram_size - (extra_bytes + self.init_size)) / PAGE_SIZE] = - 1; + self.runtime_page_tracker[(self.sram_size - (extra_bytes + self.init_size)) / PAGE_SIZE] = 1; // Return the address pg as *mut usize @@ -136,10 +131,7 @@ impl BootConfig { } rpt_offset += rlen / PAGE_SIZE; } - panic!( - "Tried to change region {:08x} that isn't in defined memory!", - addr - ); + panic!("Tried to change region {:08x} that isn't in defined memory!", addr); } /// Map the given page to the specified process table. If necessary, @@ -148,24 +140,11 @@ impl BootConfig { /// # Panics /// /// * If you try to map a page twice - pub fn map_page( - &mut self, - root: &mut PageTable, - phys: usize, - virt: usize, - flags: usize, - owner: XousPid, - ) { + pub fn map_page(&mut self, root: &mut PageTable, phys: usize, virt: usize, flags: usize, owner: XousPid) { if VDBG { - println!( - " map pa {:x} -> va {:x} (satp {:x})", - phys, virt, root as *mut PageTable as u32 - ); + println!(" map pa {:x} -> va {:x} (satp {:x})", phys, virt, root as *mut PageTable as u32); } - assert!( - !(phys == 0 && flags & FLG_VALID != 0), - "cannot map zero page" - ); + assert!(!(phys == 0 && flags & FLG_VALID != 0), "cannot map zero page"); if flags & FLG_VALID != 0 { self.change_owner(owner, phys); } @@ -206,8 +185,12 @@ impl BootConfig { if l1_pt[vpn1] & FLG_VALID == 0 { let na = self.alloc() as usize; if VDBG { - println!("The Level 1 page table is invalid ({:08x}) @ {:08x} -- allocating a new one @ {:08x}", - unsafe { l1_pt.as_ptr().add(vpn1) } as usize, l1_pt[vpn1], na); + println!( + "The Level 1 page table is invalid ({:08x}) @ {:08x} -- allocating a new one @ {:08x}", + unsafe { l1_pt.as_ptr().add(vpn1) } as usize, + l1_pt[vpn1], + na + ); } // Mark this entry as a leaf node (WRX as 0), and indicate // it is a valid page by setting "V". @@ -215,8 +198,7 @@ impl BootConfig { new_addr = Some(NonZeroUsize::new(na).unwrap()); } - let l0_pt_idx = - unsafe { &mut (*(((l1_pt[vpn1] << 2) & !((1 << 12) - 1)) as *mut PageTable)) }; + let l0_pt_idx = unsafe { &mut (*(((l1_pt[vpn1] << 2) & !((1 << 12) - 1)) as *mut PageTable)) }; let l0_pt = &mut l0_pt_idx.entries; // Ensure the entry hasn't already been mapped to a different address. diff --git a/loader/src/debug.rs b/loader/src/debug.rs index b7ff6a574..3b302e67f 100644 --- a/loader/src/debug.rs +++ b/loader/src/debug.rs @@ -12,6 +12,7 @@ impl Uart { while uart.r(utra::uart::TXFULL) != 0 {} uart.wo(utra::uart::RXTX, c as u32) } + #[cfg(any(feature = "cramium-soc", feature = "cramium-fpga"))] pub fn putc(&self, c: u8) { let base = utra::duart::HW_DUART_BASE as *mut u32; @@ -82,11 +83,7 @@ macro_rules! println pub fn print_pagetable(root: usize) { use crate::PageTable; - println!( - "Memory Maps (SATP: {:08x} Root: {:08x}):", - root, - root << 12 - ); + println!("Memory Maps (SATP: {:08x} Root: {:08x}):", root, root << 12); let l1_pt = unsafe { &mut (*((root << 12) as *mut PageTable)) }; for (i, l1_entry) in l1_pt.entries.iter().enumerate() { if *l1_entry == 0 { diff --git a/loader/src/main.rs b/loader/src/main.rs index 90f8c7706..71f71035b 100644 --- a/loader/src/main.rs +++ b/loader/src/main.rs @@ -23,6 +23,8 @@ mod phase1; mod phase2; mod platform; +use core::{mem, ptr, slice}; + use asm::*; use bootconfig::BootConfig; use consts::*; @@ -30,8 +32,6 @@ use minielf::*; use phase1::{phase_1, InitialProcess}; use phase2::{phase_2, ProgramDescription}; -use core::{mem, ptr, slice}; - pub type XousPid = u8; pub const PAGE_SIZE: usize = 4096; const WORD_SIZE: usize = mem::size_of::(); @@ -109,11 +109,7 @@ fn boot_sequence(args: KernelArguments, _signature: u32, fs_prehash: [u8; 64]) - #[cfg(feature = "platform-tests")] platform::platform_tests(); - let mut cfg = BootConfig { - base_addr: args.base as *const usize, - args, - ..Default::default() - }; + let mut cfg = BootConfig { base_addr: args.base as *const usize, args, ..Default::default() }; read_initial_config(&mut cfg); // check to see if we are recovering from a clean suspend or not @@ -184,7 +180,8 @@ fn boot_sequence(args: KernelArguments, _signature: u32, fs_prehash: [u8; 64]) - resume_csr.wfo(utra::susres::EV_ENABLE_SOFT_INT, 1); // ensure that the soft interrupt is enabled for the kernel to kick println!("clean suspend marker found, doing a resume!"); - // trigger the interrupt; it's not immediately handled, but rather checked later on by the kernel on clean resume + // trigger the interrupt; it's not immediately handled, but rather checked later on by the kernel on + // clean resume resume_csr.wfo(utra::susres::INTERRUPT_INTERRUPT, 1); } @@ -202,8 +199,7 @@ fn boot_sequence(args: KernelArguments, _signature: u32, fs_prehash: [u8; 64]) - let _tt_addr = { cfg.processes[0].ttbr0 }; println!( "Jumping to kernel @ {:08x} with map @ {:08x} and stack @ {:08x} (kargs: {:08x}, ip: {:08x}, rpt: {:08x})", - cfg.processes[0].entrypoint, _tt_addr, cfg.processes[0].sp, - arg_offset, ip_offset, rpt_offset, + cfg.processes[0].entrypoint, _tt_addr, cfg.processes[0].sp, arg_offset, ip_offset, rpt_offset, ); // save a copy of the computed kernel registers at the bottom of the page reserved @@ -281,8 +277,7 @@ fn boot_sequence(args: KernelArguments, _signature: u32, fs_prehash: [u8; 64]) - println!("0x{:08x}", (*backup_args)[i]); } } - let satp = ((*backup_args)[3] as usize) & 0x803F_FFFF - | (((susres_pid as usize) & 0x1FF) << 22); + let satp = ((*backup_args)[3] as usize) & 0x803F_FFFF | (((susres_pid as usize) & 0x1FF) << 22); //let satp = (*backup_args)[3]; println!( "Adjusting SATP to the sures process. Was: 0x{:08x} now: 0x{:08x}", @@ -347,14 +342,9 @@ pub fn read_initial_config(cfg: &mut BootConfig) { } } else if tag.name == u32::from_le_bytes(*b"XKrn") { assert!(!kernel_seen, "kernel appears twice"); - assert!( - tag.size as usize == mem::size_of::(), - "invalid XKrn size" - ); + assert!(tag.size as usize == mem::size_of::(), "invalid XKrn size"); kernel_seen = true; - } else if tag.name == u32::from_le_bytes(*b"IniE") - || tag.name == u32::from_le_bytes(*b"IniF") - { + } else if tag.name == u32::from_le_bytes(*b"IniE") || tag.name == u32::from_le_bytes(*b"IniF") { assert!(tag.size >= 4, "invalid Init size"); init_seen = true; cfg.init_process_count += 1; @@ -381,11 +371,7 @@ fn check_resume(cfg: &mut BootConfig) -> (bool, bool, u32) { let boot_seed = CSR::new(utra::seed::HW_SEED_BASE as *mut u32); let seed0 = boot_seed.r(utra::seed::SEED0); let seed1 = boot_seed.r(utra::seed::SEED1); - let was_forced_suspend: bool = if unsafe { (*marker)[0] } != 0 { - true - } else { - false - }; + let was_forced_suspend: bool = if unsafe { (*marker)[0] } != 0 { true } else { false }; let mut clean = true; let mut hashbuf: [u32; WORDS_PER_SECTOR - 1] = [0; WORDS_PER_SECTOR - 1]; @@ -395,8 +381,9 @@ fn check_resume(cfg: &mut BootConfig) -> (bool, bool, u32) { for i in 0..hashbuf.len() { hashbuf[i] = unsafe { (*marker)[index * WORDS_PER_SECTOR + i] }; } - // sector 0 contains the boot seeds, which we replace with our own as read out from our FPGA before computing the hash - // it also contains the PID of the suspend/resume process manager, which we need to inject into the SATP + // sector 0 contains the boot seeds, which we replace with our own as read out from our FPGA before + // computing the hash it also contains the PID of the suspend/resume process manager, which we + // need to inject into the SATP if sector == 0 { hashbuf[1] = seed0; hashbuf[2] = seed1; @@ -413,7 +400,8 @@ fn check_resume(cfg: &mut BootConfig) -> (bool, bool, u32) { } index += 1; } - // zero out the clean suspend marker, so if something goes wrong during resume we don't try to resume again + // zero out the clean suspend marker, so if something goes wrong during resume we don't try to resume + // again for i in 0..WORDS_PER_PAGE { unsafe { (*marker)[i] = 0; diff --git a/loader/src/minielf.rs b/loader/src/minielf.rs index 5ce806f87..4defe972f 100644 --- a/loader/src/minielf.rs +++ b/loader/src/minielf.rs @@ -2,12 +2,11 @@ use core::{mem, slice}; #[cfg(feature = "atsama5d27")] use armv7::structures::paging::TranslationTableMemory; - #[cfg(all(feature = "atsama5d27", feature = "debug-print"))] use armv7::{ structures::paging::{ - InMemoryRegister, PageTableDescriptor, Readable, TranslationTableDescriptor, - TranslationTableType, SMALL_PAGE_FLAGS, + InMemoryRegister, PageTableDescriptor, Readable, TranslationTableDescriptor, TranslationTableType, + SMALL_PAGE_FLAGS, }, VirtualAddress, }; @@ -55,9 +54,7 @@ impl MiniElfSection { le_bytes as usize } - pub fn no_copy(&self) -> bool { - self.size_and_flags & (1 << 25) != 0 - } + pub fn no_copy(&self) -> bool { self.size_and_flags & (1 << 25) != 0 } } /// Describes a Mini ELF file, suitable for loading into RAM @@ -109,8 +106,7 @@ impl MiniElf { // the page offsets line up for XIP sections. This assert confirms this necessary pre-condition. if xip { assert!( - (image_phys_base & (PAGE_SIZE - 1)) - == self.sections[0].virt as usize & (PAGE_SIZE - 1), + (image_phys_base & (PAGE_SIZE - 1)) == self.sections[0].virt as usize & (PAGE_SIZE - 1), "Image generator did not align load offsets to page offsets!" ); } @@ -170,13 +166,7 @@ impl MiniElf { // Allocate thread 1 for this process let thread_address = allocator.alloc() as usize; println!(" Thread 1 @ {:08x}", thread_address); - allocator.map_page( - tt, - thread_address, - CONTEXT_OFFSET, - FLG_R | FLG_W | FLG_VALID, - pid, - ); + allocator.map_page(tt, thread_address, CONTEXT_OFFSET, FLG_R | FLG_W | FLG_VALID, pid); // Allocate stack pages. println!(" Stack"); @@ -257,8 +247,7 @@ impl MiniElf { this_page += PAGE_SIZE; // Part 1: Copy the first chunk over. - let mut first_chunk_size = - PAGE_SIZE - (section.virt as usize & (PAGE_SIZE - 1)); + let mut first_chunk_size = PAGE_SIZE - (section.virt as usize & (PAGE_SIZE - 1)); if first_chunk_size > section.len() { first_chunk_size = section.len(); } @@ -357,17 +346,12 @@ impl MiniElf { pages_to_map -= 1; } if VDBG { - println!( - "section is 0x{:x} bytes long; mapping {} pages", - section.len(), - pages_to_map - ); + println!("section is 0x{:x} bytes long; mapping {} pages", section.len(), pages_to_map); } // --- map FLASH pages to virtual memory --- while pages_to_map > 0 { - let map_phys_addr = - (image_phys_base + section_map_phys_offset) & !(PAGE_SIZE - 1); + let map_phys_addr = (image_phys_base + section_map_phys_offset) & !(PAGE_SIZE - 1); allocator.map_page(tt, map_phys_addr, virt_page, flag_defaults, pid as XousPid); last_mapped_xip = virt_page; @@ -418,12 +402,14 @@ impl MiniElf { let mut section_offset = 0; for (index, section) in self.sections.iter().enumerate() { if let Some(dest_offset) = pt_walk(tt, section.virt as usize) { - println!(" Section {} start 0x{:x}(PA src), 0x{:x}(VA dst), 0x{:x}(PA dst) len {}/0x{:x}", + println!( + " Section {} start 0x{:x}(PA src), 0x{:x}(VA dst), 0x{:x}(PA dst) len {}/0x{:x}", index, section_offset + image_phys_base, section.virt as usize, dest_offset, - section.len(), section.len() + section.len(), + section.len() ); // dumping routines let dump_pa_src = section_offset + image_phys_base; @@ -432,7 +418,8 @@ impl MiniElf { dump_addr(dump_pa_src, " Src [:20] "); dump_addr(dump_pa_dst, " Dst [:20] "); dump_addr(dump_pa_src + section.len() - 20, " Src [-20:] "); - // recompute the end section mapping, because PA/VA mappings don't have to be linear (in fact they go in the opposite direction) + // recompute the end section mapping, because PA/VA mappings don't have to be linear (in fact + // they go in the opposite direction) if let Some(pa_dst_end) = dump_pa_end_dst { dump_addr(pa_dst_end, " Dst [-20:] "); } else { @@ -493,15 +480,13 @@ pub fn pt_walk(root: usize, va: usize) -> Option { assert!(vpn1 < 4096); assert!(vpn2 < 256); - let existing_l1_entry = unsafe { - ((root as *mut u32).add(vpn1) as *mut TranslationTableDescriptor).read_volatile() - }; + let existing_l1_entry = + unsafe { ((root as *mut u32).add(vpn1) as *mut TranslationTableDescriptor).read_volatile() }; if existing_l1_entry.get_type() == TranslationTableType::Invalid { return None; } let l2_pt_addr = (existing_l1_entry.as_u32() & 0xfff) + vpn1 as u32 * PAGE_SIZE as u32; - let existing_l2_entry_addr = - unsafe { (l2_pt_addr as *mut u32).add(vpn2) as *mut PageTableDescriptor }; + let existing_l2_entry_addr = unsafe { (l2_pt_addr as *mut u32).add(vpn2) as *mut PageTableDescriptor }; let current_entry: PageTableDescriptor = unsafe { existing_l2_entry_addr.read_volatile() }; let flags_u32 = current_entry.get_flags().expect("flags"); let flags: InMemoryRegister = InMemoryRegister::new(flags_u32); diff --git a/loader/src/murmur3.rs b/loader/src/murmur3.rs index d7842f165..1e602ef9b 100644 --- a/loader/src/murmur3.rs +++ b/loader/src/murmur3.rs @@ -68,19 +68,11 @@ mod tests { slice: &[0x34333231, 0x38373635], // "12345678", hash_32: 0x91b313ce, }, - Result { - slice: &[], - hash_32: 0, - }, + Result { slice: &[], hash_32: 0 }, ]; for test in &tests { - assert_eq!( - murmur3_32(test.slice, 0), - test.hash_32, - "Failed on slice {:x?}", - test.slice - ); + assert_eq!(murmur3_32(test.slice, 0), test.hash_32, "Failed on slice {:x?}", test.slice); } } } diff --git a/loader/src/phase1.rs b/loader/src/phase1.rs index 14bc23c12..00b428af3 100644 --- a/loader/src/phase1.rs +++ b/loader/src/phase1.rs @@ -1,9 +1,8 @@ use core::{mem, slice}; -use crate::*; - #[cfg(feature = "atsama5d27")] pub use crate::platform::atsama5d27::load::InitialProcess; +use crate::*; #[repr(C)] #[cfg(not(feature = "atsama5d27"))] @@ -113,10 +112,7 @@ pub fn allocate_regions(cfg: &mut BootConfig) { let runtime_page_tracker = cfg.get_top(); assert!((runtime_page_tracker as usize) < (cfg.sram_start as usize) + cfg.sram_size); unsafe { - bzero( - runtime_page_tracker, - runtime_page_tracker.add(rpt_pages / mem::size_of::()), - ); + bzero(runtime_page_tracker, runtime_page_tracker.add(rpt_pages / mem::size_of::())); } cfg.runtime_page_tracker = @@ -130,14 +126,10 @@ pub fn allocate_processes(cfg: &mut BootConfig) { cfg.init_size += table_size; let processes = cfg.get_top(); unsafe { - bzero( - processes, - processes.add((table_size / mem::size_of::()) as usize), - ); + bzero(processes, processes.add((table_size / mem::size_of::()) as usize)); } - cfg.processes = unsafe { - slice::from_raw_parts_mut(processes as *mut InitialProcess, process_count as usize) - }; + cfg.processes = + unsafe { slice::from_raw_parts_mut(processes as *mut InitialProcess, process_count as usize) }; } pub fn copy_args(cfg: &mut BootConfig) { @@ -146,11 +138,7 @@ pub fn copy_args(cfg: &mut BootConfig) { let runtime_arg_buffer = cfg.get_top(); unsafe { #[allow(clippy::cast_ptr_alignment)] - memcpy( - runtime_arg_buffer, - cfg.args.base as *const usize, - cfg.args.size() as usize, - ) + memcpy(runtime_arg_buffer, cfg.args.base as *const usize, cfg.args.size() as usize) }; cfg.args = KernelArguments::new(runtime_arg_buffer); } @@ -199,17 +187,11 @@ fn copy_processes(cfg: &mut BootConfig) { let mut top = core::ptr::null_mut::(); let inie = MiniElf::new(&tag); - let mut src_paddr = unsafe { - cfg.base_addr - .add(inie.load_offset as usize / mem::size_of::()) - } as *const u8; + let mut src_paddr = + unsafe { cfg.base_addr.add(inie.load_offset as usize / mem::size_of::()) } + as *const u8; - println!( - "\n\n{} {} has {} sections", - tag_type.to_str(), - _pid, - inie.sections.len() - ); + println!("\n\n{} {} has {} sections", tag_type.to_str(), _pid, inie.sections.len()); println!( "Initial top: {:x}, extra_pages: {:x}, init_size: {:x}, base_addr: {:x}", cfg.get_top() as *mut u8 as u32, @@ -231,36 +213,41 @@ fn copy_processes(cfg: &mut BootConfig) { let copy_to_ram = (flags & MINIELF_FLG_W != 0) || (tag_type == TagType::IniE); if (section.virt as usize) < last_page_vaddr { - panic!("init section addresses are not strictly increasing (new virt: {:08x}, last virt: {:08x})", - section.virt, last_page_vaddr); + panic!( + "init section addresses are not strictly increasing (new virt: {:08x}, last virt: {:08x})", + section.virt, last_page_vaddr + ); } // cfg.extra_pages tracks how many pages of RAM we've allocated so far // cfg.top() points to the bottom of the most recently allocated page - // - so if cfg.extra_pages is 0, nothing is allocated, and cfg.top() points to previously reserved space + // - so if cfg.extra_pages is 0, nothing is allocated, and cfg.top() points to + // previously reserved space // // The section length always matches the stride between sections in physical memory. // - // However, the section length has nothing to do with the distance between sections in virtual memory; - // the virtual start address is allowed to be an arbitrary number of bytes higher than the previous section - // end, for alignment and padding reasons. + // However, the section length has nothing to do with the distance between sections in + // virtual memory; the virtual start address is allowed to be an + // arbitrary number of bytes higher than the previous section end, for + // alignment and padding reasons. if copy_to_ram { let mut dst_page_vaddr = section.virt as usize; let mut bytes_to_copy = section.len(); - if (last_page_vaddr & !(PAGE_SIZE - 1)) - != (dst_page_vaddr & !(PAGE_SIZE - 1)) + if (last_page_vaddr & !(PAGE_SIZE - 1)) != (dst_page_vaddr & !(PAGE_SIZE - 1)) || last_section_perfect_fit { // this condition is always true for the first section's first iteration, because // current_vpage_addr starts as NULL; thus we are guaranteed to always // trigger the page allocate/zero mechanism the first time through the loop // - // `last_section_perfect_fit` triggers a page allocation as well, because in this case - // we had exactly enough data to fill out the previous section, so we have no more - // space left in the current page. We don't automatically allocate a new page because - // if it was actually the very last section we *shouldn't* allocate another page; and - // we can only know if there's another section available by dropping off the end of the + // `last_section_perfect_fit` triggers a page allocation as well, because in this + // case we had exactly enough data to fill out the + // previous section, so we have no more space left in + // the current page. We don't automatically allocate a new page because + // if it was actually the very last section we *shouldn't* allocate another page; + // and we can only know if there's another section + // available by dropping off the end of the // loop and coming back to the surrounding for-loop iterator. cfg.extra_pages += 1; top = cfg.get_top() as *mut u8; @@ -272,8 +259,7 @@ fn copy_processes(cfg: &mut BootConfig) { // Copy the start copying the source data into virtual memory, until the current // page is exhausted. while bytes_to_copy > 0 { - let bytes_remaining_in_vpage = - PAGE_SIZE - (dst_page_vaddr & (PAGE_SIZE - 1)); + let bytes_remaining_in_vpage = PAGE_SIZE - (dst_page_vaddr & (PAGE_SIZE - 1)); let copyable_bytes = bytes_remaining_in_vpage.min(bytes_to_copy); last_section_perfect_fit = bytes_remaining_in_vpage == bytes_to_copy; if !section.no_copy() { @@ -333,19 +319,13 @@ fn copy_processes(cfg: &mut BootConfig) { // TEXT SECTION // Round it off to a page boundary - let load_size_rounded = - (prog.text_size as usize + PAGE_SIZE - 1) & !(PAGE_SIZE - 1); + let load_size_rounded = (prog.text_size as usize + PAGE_SIZE - 1) & !(PAGE_SIZE - 1); cfg.extra_pages += load_size_rounded / PAGE_SIZE; let top = cfg.get_top(); - println!( - "\n\nKernel top: {:x}, extra_pages: {:x}", - top as u32, cfg.extra_pages - ); + println!("\n\nKernel top: {:x}, extra_pages: {:x}", top as u32, cfg.extra_pages); unsafe { // Copy the program to the target address, rounding it off to the load size. - let src_addr = cfg - .base_addr - .add(prog.load_offset as usize / mem::size_of::()); + let src_addr = cfg.base_addr.add(prog.load_offset as usize / mem::size_of::()); println!( " Copying TEXT from {:08x}-{:08x} to {:08x}-{:08x} ({} bytes long)", src_addr as usize, @@ -377,10 +357,9 @@ fn copy_processes(cfg: &mut BootConfig) { let top = cfg.get_top(); unsafe { // Copy the program to the target address, rounding it off to the load size. - let src_addr = cfg.base_addr.add( - (prog.load_offset + prog.text_size + 4) as usize / mem::size_of::() - - 1, - ); + let src_addr = cfg + .base_addr + .add((prog.load_offset + prog.text_size + 4) as usize / mem::size_of::() - 1); println!( " Copying DATA from {:08x}-{:08x} to {:08x}-{:08x} ({} bytes long)", src_addr as usize, diff --git a/loader/src/phase2.rs b/loader/src/phase2.rs index 2855ca7e0..83f7808bd 100644 --- a/loader/src/phase2.rs +++ b/loader/src/phase2.rs @@ -102,16 +102,11 @@ pub fn phase_2(cfg: &mut BootConfig, fs_prehash: &[u8; 64]) { } #[cfg(feature = "atsama5d27")] { - ( - ktext_offset, - kdata_offset, - kernel_exception_sp, - kernel_irq_sp, - ) = xkrn.load(cfg, process_offset - load_size_rounded, 1); + (ktext_offset, kdata_offset, kernel_exception_sp, kernel_irq_sp) = + xkrn.load(cfg, process_offset - load_size_rounded, 1); (ktext_size, kdata_size, ktext_virt_offset, kdata_virt_offset) = ( (xkrn.text_size as usize + PAGE_SIZE - 1) & !(PAGE_SIZE - 1), - (((xkrn.data_size + xkrn.bss_size) as usize + PAGE_SIZE - 1) - & !(PAGE_SIZE - 1)), + (((xkrn.data_size + xkrn.bss_size) as usize + PAGE_SIZE - 1) & !(PAGE_SIZE - 1)), xkrn.text_offset as usize, xkrn.data_offset as usize, ); @@ -161,11 +156,7 @@ pub fn phase_2(cfg: &mut BootConfig, fs_prehash: &[u8; 64]) { #[cfg(feature = "atsama5d27")] { // Map boot-generated kernel structures into the kernel - crate::platform::atsama5d27::boot::map_structs_to_kernel( - cfg, - krn_l1_pt_addr, - krn_struct_start, - ); + crate::platform::atsama5d27::boot::map_structs_to_kernel(cfg, krn_l1_pt_addr, krn_struct_start); crate::platform::atsama5d27::boot::map_kernel_to_processes( cfg, ktext_offset, @@ -198,10 +189,7 @@ pub fn phase_2(cfg: &mut BootConfig, fs_prehash: &[u8; 64]) { println!(); } } - println!( - "Runtime Page Tracker: {} bytes", - cfg.runtime_page_tracker.len() - ); + println!("Runtime Page Tracker: {} bytes", cfg.runtime_page_tracker.len()); // mark pages used by suspend/resume according to their needs cfg.runtime_page_tracker[cfg.sram_size / PAGE_SIZE - 1] = 1; // claim the loader stack -- do not allow tampering, as it contains backup kernel args cfg.runtime_page_tracker[cfg.sram_size / PAGE_SIZE - 2] = 1; // 8k in total (to allow for digital signatures to be computed) @@ -252,17 +240,12 @@ impl ProgramDescription { let pid_idx = (pid - 1) as usize; let is_kernel = pid == 1; let flag_defaults = FLG_R | FLG_W | FLG_VALID | if is_kernel { 0 } else { FLG_U }; - let stack_addr = if is_kernel { - KERNEL_STACK_TOP - } else { - USER_STACK_TOP - } - 16; + let stack_addr = if is_kernel { KERNEL_STACK_TOP } else { USER_STACK_TOP } - 16; if is_kernel { assert!(self.text_offset as usize == KERNEL_LOAD_OFFSET); assert!(((self.text_offset + self.text_size) as usize) < EXCEPTION_STACK_TOP); assert!( - ((self.data_offset + self.data_size + self.bss_size) as usize) - < EXCEPTION_STACK_TOP - 16 + ((self.data_offset + self.data_size + self.bss_size) as usize) < EXCEPTION_STACK_TOP - 16 ); assert!(self.data_offset as usize >= KERNEL_LOAD_OFFSET); } else { @@ -291,20 +274,10 @@ impl ProgramDescription { // Allocate context for this process let thread_address = allocator.alloc() as usize; - allocator.map_page( - satp, - thread_address, - CONTEXT_OFFSET, - FLG_R | FLG_W | FLG_VALID, - pid as XousPid, - ); + allocator.map_page(satp, thread_address, CONTEXT_OFFSET, FLG_R | FLG_W | FLG_VALID, pid as XousPid); // Allocate stack pages. - for i in 0..if is_kernel { - KERNEL_STACK_PAGE_COUNT - } else { - STACK_PAGE_COUNT - } { + for i in 0..if is_kernel { KERNEL_STACK_PAGE_COUNT } else { STACK_PAGE_COUNT } { if i == 0 { // Pre-allocate the first stack offset, since it // will definitely be used @@ -350,8 +323,7 @@ impl ProgramDescription { // Either this is on SPI flash at an aligned address, or it // has been copied into RAM already. This is why we ignore `self.load_offset` // and use the `load_offset` parameter instead. - let rounded_data_bss = - ((self.data_size + self.bss_size) as usize + PAGE_SIZE - 1) & !(PAGE_SIZE - 1); + let rounded_data_bss = ((self.data_size + self.bss_size) as usize + PAGE_SIZE - 1) & !(PAGE_SIZE - 1); // let load_size_rounded = (self.text_size as usize + PAGE_SIZE - 1) & !(PAGE_SIZE - 1); for offset in (0..self.text_size as usize).step_by(PAGE_SIZE) { @@ -394,13 +366,7 @@ impl ProgramDescription { // Our "earlyprintk" equivalent if cfg!(feature = "earlyprintk") && is_kernel { - allocator.map_page( - satp, - 0xF000_2000, - 0xffcf_0000, - FLG_R | FLG_W | FLG_VALID, - pid as XousPid, - ); + allocator.map_page(satp, 0xF000_2000, 0xffcf_0000, FLG_R | FLG_W | FLG_VALID, pid as XousPid); } let process = &mut allocator.processes[pid_idx]; diff --git a/loader/src/platform/atsama5d27/boot.rs b/loader/src/platform/atsama5d27/boot.rs index dc89aea92..afbee2624 100644 --- a/loader/src/platform/atsama5d27/boot.rs +++ b/loader/src/platform/atsama5d27/boot.rs @@ -5,18 +5,19 @@ use core::mem; use core::num::NonZeroUsize; +use armv7::structures::paging::{ + PageTable as L2PageTable, PageTableDescriptor, PageTableMemory, PageTableType, TranslationTable, + TranslationTableDescriptor, TranslationTableMemory, TranslationTableType, PAGE_TABLE_FLAGS, + SMALL_PAGE_FLAGS, +}; +use armv7::{PhysicalAddress, VirtualAddress}; + use crate::consts::{ EXCEPTION_STACK_TOP, FLG_R, FLG_U, FLG_VALID, FLG_W, FLG_X, GUARD_MEMORY_BYTES, IRQ_STACK_TOP, KERNEL_ARGUMENT_OFFSET, KERNEL_STACK_PAGE_COUNT, LOADER_CODE_ADDRESS, PAGE_TABLE_OFFSET, }; use crate::platform::atsama5d27::load::InitialProcess; use crate::{bzero, println, BootConfig, XousPid, PAGE_SIZE, WORD_SIZE}; -use armv7::structures::paging::{ - PageTable as L2PageTable, PageTableDescriptor, PageTableMemory, PageTableType, - TranslationTable, TranslationTableDescriptor, TranslationTableMemory, TranslationTableType, - PAGE_TABLE_FLAGS, SMALL_PAGE_FLAGS, -}; -use armv7::{PhysicalAddress, VirtualAddress}; const DEBUG_PAGE_MAPPING: bool = false; macro_rules! dprint { @@ -38,8 +39,7 @@ impl BootConfig { pub fn get_top(&self) -> *mut usize { let val = unsafe { self.sram_start.add( - (self.sram_size - self.init_size - self.extra_pages * PAGE_SIZE) - / mem::size_of::(), + (self.sram_size - self.init_size - self.extra_pages * PAGE_SIZE) / mem::size_of::(), ) }; assert!((val as usize) >= (self.sram_start as usize)); @@ -61,15 +61,11 @@ impl BootConfig { let pg = self.get_top(); unsafe { // Grab the page address and zero it out - bzero( - pg as *mut usize, - pg.add(PAGE_SIZE / mem::size_of::()) as *mut usize, - ); + bzero(pg as *mut usize, pg.add(PAGE_SIZE / mem::size_of::()) as *mut usize); } // Mark this page as in-use by the kernel let extra_bytes = self.extra_pages * PAGE_SIZE; - self.runtime_page_tracker[(self.sram_size - (extra_bytes + self.init_size)) / PAGE_SIZE] = - 1; + self.runtime_page_tracker[(self.sram_size - (extra_bytes + self.init_size)) / PAGE_SIZE] = 1; dprintln!("Allocated a physical page: {:08x}", pg as usize); @@ -94,7 +90,10 @@ impl BootConfig { if is_aligned { return if num_alloc_pages != 4 { - dprintln!("Allocated a dummy page (aligned but not enough pages allocated yet): {:08x}", allocated_page_ptr as usize); + dprintln!( + "Allocated a dummy page (aligned but not enough pages allocated yet): {:08x}", + allocated_page_ptr as usize + ); // Allocate 4 more pages for a whole L1 translation table for _ in 0..4 { @@ -107,20 +106,14 @@ impl BootConfig { self.change_owner(pid, allocated_page_ptr as usize); } - dprintln!( - "Allocated a L1 page table at {:08x}", - allocated_page_ptr as usize - ); + dprintln!("Allocated a L1 page table at {:08x}", allocated_page_ptr as usize); allocated_page_ptr } else { allocated_page_ptr }; } else { - dprintln!( - "Allocated a dummy page for alignment: {:08x}", - allocated_page_ptr as usize - ); + dprintln!("Allocated a dummy page for alignment: {:08x}", allocated_page_ptr as usize); } } @@ -148,10 +141,7 @@ impl BootConfig { } rpt_offset += rlen / PAGE_SIZE; } - panic!( - "Tried to change region {:08x} that isn't in defined memory!", - addr - ); + panic!("Tried to change region {:08x} that isn't in defined memory!", addr); } /// Map the given page to the specified process table. If necessary, @@ -168,10 +158,7 @@ impl BootConfig { flags: usize, pid: XousPid, ) { - assert!( - !(phys == 0 && flags & FLG_VALID != 0), - "cannot map zero page" - ); + assert!(!(phys == 0 && flags & FLG_VALID != 0), "cannot map zero page"); if flags & FLG_VALID != 0 { self.change_owner(owner, phys); } @@ -190,11 +177,7 @@ impl BootConfig { flags: usize, pid: XousPid, ) { - dprintln!( - "PageTable: {:p} {:08x}", - translation_table, - translation_table as usize - ); + dprintln!("PageTable: {:p} {:08x}", translation_table, translation_table as usize); dprint!("MAP: p0x{:08x} -> v0x{:08x} ", phys, virt); print_flags(flags); dprintln!(); @@ -210,13 +193,7 @@ impl BootConfig { assert!(vpn2 < 256); assert!(ppn2 < 256); - dprintln!( - "vpn1: {:04x}, vpn2: {:02x}, ppn2: {:08x}, phys frame addr: {:08x}", - vpn1, - vpn2, - ppn2, - p - ); + dprintln!("vpn1: {:04x}, vpn2: {:02x}, ppn2: {:08x}, phys frame addr: {:08x}", vpn1, vpn2, ppn2, p); let mut tt = TranslationTable::new(translation_table); let tt = unsafe { tt.table_mut() }; @@ -230,11 +207,10 @@ impl BootConfig { let na = self.alloc(); let phys = PhysicalAddress::from_ptr(na); - let entry_flags = u32::from(PAGE_TABLE_FLAGS::VALID::Enable) - | u32::from(PAGE_TABLE_FLAGS::DOMAIN.val(0xf)); - let descriptor = - TranslationTableDescriptor::new(TranslationTableType::Page, phys, entry_flags) - .expect("tt descriptor"); + let entry_flags = + u32::from(PAGE_TABLE_FLAGS::VALID::Enable) | u32::from(PAGE_TABLE_FLAGS::DOMAIN.val(0xf)); + let descriptor = TranslationTableDescriptor::new(TranslationTableType::Page, phys, entry_flags) + .expect("tt descriptor"); dprintln!("New TT descriptor: {:032b}", descriptor); tt[vpn1] = descriptor; @@ -255,24 +231,13 @@ impl BootConfig { let existing_l2_entry = l2_pt[vpn2]; - dprintln!( - "({:08x}) l2_pt[{:08x}] = {:032b}", - l2_phys_addr, - vpn2, - existing_l2_entry - ); + dprintln!("({:08x}) l2_pt[{:08x}] = {:032b}", l2_phys_addr, vpn2, existing_l2_entry); if existing_l2_entry.get_type() == PageTableType::SmallPage { - let mapped_addr = existing_l2_entry - .get_addr() - .expect("invalid l2 entry") - .as_u32() as usize; + let mapped_addr = + existing_l2_entry.get_addr().expect("invalid l2 entry").as_u32() as usize; - dprintln!( - "L2 entry {:02x} already mapped to {:08x}", - vpn2, - mapped_addr - ); + dprintln!("L2 entry {:02x} already mapped to {:08x}", vpn2, mapped_addr); // Ensure the entry hasn't already been mapped to a different address. if mapped_addr != p { @@ -308,12 +273,7 @@ impl BootConfig { ) .expect("new l2 entry"); l2_pt[vpn2] = new_entry; - dprintln!( - "new ({:08x}) l2_pt[{:08x}] = {:032b}", - l2_phys_addr, - vpn2, - l2_pt[vpn2] - ); + dprintln!("new ({:08x}) l2_pt[{:08x}] = {:032b}", l2_phys_addr, vpn2, l2_pt[vpn2]); // If we had to allocate a translation table (L1) entry, ensure that it's // mapped into our address space, owned by PID 1. @@ -335,10 +295,7 @@ impl BootConfig { } } - _ => panic!( - "Invalid translation table entry type: {:?}", - existing_entry.get_type() - ), + _ => panic!("Invalid translation table entry type: {:?}", existing_entry.get_type()), } } } @@ -363,23 +320,11 @@ pub fn map_structs_to_kernel(cfg: &mut BootConfig, table_addr: usize, krn_struct // Map the last stack page (4K) to the kernel to make it visible from the trampoline code // Otherwise some arguments passed via stack won't be available after the MMU is turned on dprintln!("Making the loader stack visible"); - cfg.map_page( - translation_table, - 0x200ff000, - 0x200ff000, - FLG_R | FLG_X | FLG_VALID, - 1 as XousPid, - ); + cfg.map_page(translation_table, 0x200ff000, 0x200ff000, FLG_R | FLG_X | FLG_VALID, 1 as XousPid); // Identity map the page that contains kernel arguments dprintln!("Making the kernel arguments visible"); - cfg.map_page( - translation_table, - 0x20100000, - 0x20100000, - FLG_R | FLG_X | FLG_VALID, - 1 as XousPid, - ); + cfg.map_page(translation_table, 0x20100000, 0x20100000, FLG_R | FLG_X | FLG_VALID, 1 as XousPid); for addr in (0..cfg.init_size - GUARD_MEMORY_BYTES).step_by(PAGE_SIZE) { cfg.map_page( @@ -407,10 +352,7 @@ pub fn map_kernel_to_processes( ) { let processes = unsafe { core::mem::transmute::<_, &[InitialProcess]>(&*cfg.processes) }; - assert_ne!( - kernel_exception_sp, 0, - "No exception stack allocated for the kernel!" - ); + assert_ne!(kernel_exception_sp, 0, "No exception stack allocated for the kernel!"); for process in processes[1..].iter() { println!("Mapping kernel (PID1) text to process PID{}", process.asid); @@ -419,74 +361,33 @@ pub fn map_kernel_to_processes( for addr in (0..ktext_size).step_by(PAGE_SIZE) { let phys = ktext_offset + addr; let virt = ktext_virt_offset + addr; - println!( - "MAP ({:08x}): {:08x} -> {:08x}", - translation_table as usize, virt, phys - ); + println!("MAP ({:08x}): {:08x} -> {:08x}", translation_table as usize, virt, phys); - cfg.map_page( - translation_table, - phys, - virt, - FLG_VALID | FLG_R | FLG_X, - 1 as XousPid, - ); + cfg.map_page(translation_table, phys, virt, FLG_VALID | FLG_R | FLG_X, 1 as XousPid); } println!("Mapping kernel (PID1) data to process PID{}", process.asid); println!("Offset: {:08x}, size: {:08x}", kdata_offset, kdata_size); for addr in (0..kdata_size).step_by(PAGE_SIZE) { let phys = kdata_offset + addr; let virt = kdata_virt_offset + addr; - println!( - "MAP ({:08x}): {:08x} -> {:08x}", - translation_table as usize, virt, phys - ); + println!("MAP ({:08x}): {:08x} -> {:08x}", translation_table as usize, virt, phys); - cfg.map_page( - translation_table, - phys, - virt, - FLG_VALID | FLG_R | FLG_W, - 1 as XousPid, - ); + cfg.map_page(translation_table, phys, virt, FLG_VALID | FLG_R | FLG_W, 1 as XousPid); } - println!( - "Mapping kernel exception stack pages to the process PID{}", - process.asid - ); + println!("Mapping kernel exception stack pages to the process PID{}", process.asid); for i in 0..KERNEL_STACK_PAGE_COUNT { - let virt = - EXCEPTION_STACK_TOP - (PAGE_SIZE * KERNEL_STACK_PAGE_COUNT) + (PAGE_SIZE * i); - let phys = - kernel_exception_sp - (PAGE_SIZE * KERNEL_STACK_PAGE_COUNT) + (PAGE_SIZE * (i + 1)); - println!( - "MAP ({:08x}): {:08x} -> {:08x}", - translation_table as usize, virt, phys - ); - cfg.map_page( - translation_table, - phys, - virt, - FLG_VALID | FLG_R | FLG_W, - 1 as XousPid, - ); + let virt = EXCEPTION_STACK_TOP - (PAGE_SIZE * KERNEL_STACK_PAGE_COUNT) + (PAGE_SIZE * i); + let phys = kernel_exception_sp - (PAGE_SIZE * KERNEL_STACK_PAGE_COUNT) + (PAGE_SIZE * (i + 1)); + println!("MAP ({:08x}): {:08x} -> {:08x}", translation_table as usize, virt, phys); + cfg.map_page(translation_table, phys, virt, FLG_VALID | FLG_R | FLG_W, 1 as XousPid); } println!("Mapping irq stack page to the process PID{}", process.asid); let virt = IRQ_STACK_TOP; let phys = kernel_irq_sp; - println!( - "MAP ({:08x}): {:08x} -> {:08x}", - translation_table as usize, virt, phys - ); - cfg.map_page( - translation_table, - phys, - virt, - FLG_VALID | FLG_R | FLG_W, - 1 as XousPid, - ); + println!("MAP ({:08x}): {:08x} -> {:08x}", translation_table as usize, virt, phys); + cfg.map_page(translation_table, phys, virt, FLG_VALID | FLG_R | FLG_W, 1 as XousPid); // TODO: For now, make the UART visible for all the processes. // Later on we may reuse the mapping made by the kernel. @@ -494,17 +395,8 @@ pub fn map_kernel_to_processes( for i in 0..4 { let virt = 0xffcf_0000 + (i * PAGE_SIZE); let phys = 0xf802_0000 + (i * PAGE_SIZE); - println!( - "MAP ({:08x}): {:08x} -> {:08x}", - translation_table as usize, virt, phys - ); - cfg.map_page( - translation_table, - phys, - virt, - FLG_VALID | FLG_R | FLG_W | FLG_X, - 1 as XousPid, - ); + println!("MAP ({:08x}): {:08x} -> {:08x}", translation_table as usize, virt, phys); + cfg.map_page(translation_table, phys, virt, FLG_VALID | FLG_R | FLG_W | FLG_X, 1 as XousPid); } println!("Mapping kernel structures to PID{}", process.asid); diff --git a/loader/src/platform/atsama5d27/debug.rs b/loader/src/platform/atsama5d27/debug.rs index bedda1a9c..2b4ed8fbd 100644 --- a/loader/src/platform/atsama5d27/debug.rs +++ b/loader/src/platform/atsama5d27/debug.rs @@ -3,8 +3,8 @@ // SPDX-License-Identifier: Apache-2.0 use armv7::structures::paging::{ - PageTable as L2PageTable, PageTableMemory, PageTableType, TranslationTable, - TranslationTableMemory, TranslationTableType, + PageTable as L2PageTable, PageTableMemory, PageTableType, TranslationTable, TranslationTableMemory, + TranslationTableType, }; use armv7::PhysicalAddress; use atsama5d27::uart::{Uart as UartHw, Uart1}; @@ -17,11 +17,7 @@ pub struct Uart { impl Uart { #[allow(dead_code)] - pub fn new() -> Self { - Self { - inner: UartType::new(), - } - } + pub fn new() -> Self { Self { inner: UartType::new() } } } use core::fmt::{Error, Write}; @@ -100,14 +96,12 @@ fn print_l2_pagetable(vpn1: usize, phys_addr: PhysicalAddress) { let _phys_addr = pt_desc.get_addr().expect("addr"); match pt_desc.get_type() { - PageTableType::LargePage => println!( - " - {:02x} (64K) Large Page {:08x} -> {:08x}", - i, _virt_addr, _phys_addr - ), - PageTableType::SmallPage => println!( - " - {:02x} (4K) Small Page {:08x} -> {:08x}", - i, _virt_addr, _phys_addr - ), + PageTableType::LargePage => { + println!(" - {:02x} (64K) Large Page {:08x} -> {:08x}", i, _virt_addr, _phys_addr) + } + PageTableType::SmallPage => { + println!(" - {:02x} (4K) Small Page {:08x} -> {:08x}", i, _virt_addr, _phys_addr) + } _ => (), } } @@ -133,25 +127,16 @@ pub fn print_pagetable(root: usize) { match tt_desc.get_type() { TranslationTableType::Page => { let _virt_addr = i << 20; - println!( - " - {:03x} (1MB) {:08x} L2 page table @ {:08x}", - i, _virt_addr, phys_addr - ); + println!(" - {:03x} (1MB) {:08x} L2 page table @ {:08x}", i, _virt_addr, phys_addr); print_l2_pagetable(i, phys_addr); } TranslationTableType::Section => { let _virt_addr = i * 1024; // 1 MB - println!( - " - {:03x} (1MB) section {:08x} -> {:08x}", - i, _virt_addr, phys_addr - ); + println!(" - {:03x} (1MB) section {:08x} -> {:08x}", i, _virt_addr, phys_addr); } TranslationTableType::Supersection => { let _virt_addr = i * (1024 * 16); // 16 MB - println!( - " - {:03x} (16MB) supersection {:08x} -> {:08x}", - i, _virt_addr, phys_addr - ); + println!(" - {:03x} (16MB) supersection {:08x} -> {:08x}", i, _virt_addr, phys_addr); } _ => (), diff --git a/loader/src/platform/atsama5d27/load.rs b/loader/src/platform/atsama5d27/load.rs index a28a1f319..5e1c4cb71 100644 --- a/loader/src/platform/atsama5d27/load.rs +++ b/loader/src/platform/atsama5d27/load.rs @@ -2,13 +2,14 @@ // SPDX-FileCopyrightText: 2023 Foundation Devices, Inc // SPDX-License-Identifier: Apache-2.0 +use armv7::structures::paging::TranslationTableMemory; + use crate::consts::{ - CONTEXT_OFFSET, EXCEPTION_STACK_TOP, FLG_R, FLG_U, FLG_VALID, FLG_W, FLG_X, - IRQ_STACK_PAGE_COUNT, IRQ_STACK_TOP, KERNEL_LOAD_OFFSET, KERNEL_STACK_PAGE_COUNT, - KERNEL_STACK_TOP, PAGE_TABLE_ROOT_OFFSET, USER_AREA_END, USER_STACK_TOP, + CONTEXT_OFFSET, EXCEPTION_STACK_TOP, FLG_R, FLG_U, FLG_VALID, FLG_W, FLG_X, IRQ_STACK_PAGE_COUNT, + IRQ_STACK_TOP, KERNEL_LOAD_OFFSET, KERNEL_STACK_PAGE_COUNT, KERNEL_STACK_TOP, PAGE_TABLE_ROOT_OFFSET, + USER_AREA_END, USER_STACK_TOP, }; use crate::{println, BootConfig, ProgramDescription, XousPid, PAGE_SIZE, STACK_PAGE_COUNT, VDBG}; -use armv7::structures::paging::TranslationTableMemory; #[repr(C)] #[derive(Debug, Copy, Clone)] @@ -45,11 +46,7 @@ impl ProgramDescription { let pid_idx = (pid - 1) as usize; let is_kernel = pid == 1; let flag_defaults = FLG_R | FLG_W | FLG_VALID | if is_kernel { 0 } else { FLG_U }; - let stack_addr = if is_kernel { - KERNEL_STACK_TOP - } else { - USER_STACK_TOP - } - 16; + let stack_addr = if is_kernel { KERNEL_STACK_TOP } else { USER_STACK_TOP } - 16; if is_kernel { println!( "self.text_offset: {:08x}, KERNEL_LOAD_OFFSET: {:08x}", @@ -58,8 +55,7 @@ impl ProgramDescription { assert_eq!(self.text_offset as usize, KERNEL_LOAD_OFFSET); assert!(((self.text_offset + self.text_size) as usize) < EXCEPTION_STACK_TOP); assert!( - ((self.data_offset + self.data_size + self.bss_size) as usize) - < EXCEPTION_STACK_TOP - 16 + ((self.data_offset + self.data_size + self.bss_size) as usize) < EXCEPTION_STACK_TOP - 16 ); assert!(self.data_offset as usize >= KERNEL_LOAD_OFFSET); } else { @@ -75,10 +71,7 @@ impl ProgramDescription { // Allocate physical pages for L1 translation table let tt_address = allocator.alloc_l1_page_table(pid) as usize; if VDBG { - println!( - "Setting {:08x} as translation table address for PID {}", - tt_address, pid - ); + println!("Setting {:08x} as translation table address for PID {}", tt_address, pid); } allocator.processes[pid_idx].ttbr0 = tt_address; @@ -87,11 +80,7 @@ impl ProgramDescription { // Map all four pages of the translation table to the kernel address space for offset in 0..4 { let offset = offset * PAGE_SIZE; - println!( - "Map L1 pages: {:08x} -> {:08x}", - tt_address + offset, - PAGE_TABLE_ROOT_OFFSET + offset - ); + println!("Map L1 pages: {:08x} -> {:08x}", tt_address + offset, PAGE_TABLE_ROOT_OFFSET + offset); allocator.map_page( translation_table, tt_address + offset, @@ -116,11 +105,7 @@ impl ProgramDescription { ); // Allocate stack pages. - let total_stack_pages = if is_kernel { - KERNEL_STACK_PAGE_COUNT - } else { - STACK_PAGE_COUNT - }; + let total_stack_pages = if is_kernel { KERNEL_STACK_PAGE_COUNT } else { STACK_PAGE_COUNT }; if VDBG { println!("Mapping {} stack pages for PID {}", total_stack_pages, pid); @@ -199,8 +184,7 @@ impl ProgramDescription { // Either this is on SPI flash at an aligned address, or it // has been copied into RAM already. This is why we ignore `self.load_offset` // and use the `load_offset` parameter instead. - let rounded_data_bss = - ((self.data_size + self.bss_size) as usize + PAGE_SIZE - 1) & !(PAGE_SIZE - 1); + let rounded_data_bss = ((self.data_size + self.bss_size) as usize + PAGE_SIZE - 1) & !(PAGE_SIZE - 1); // let load_size_rounded = (self.text_size as usize + PAGE_SIZE - 1) & !(PAGE_SIZE - 1); let text_phys_offset = load_offset + rounded_data_bss; diff --git a/loader/src/platform/atsama5d27/memtest.rs b/loader/src/platform/atsama5d27/memtest.rs index 565f69865..a4a4a3c0c 100644 --- a/loader/src/platform/atsama5d27/memtest.rs +++ b/loader/src/platform/atsama5d27/memtest.rs @@ -3,6 +3,4 @@ // SPDX-License-Identifier: Apache-2.0 #[allow(dead_code)] -pub fn memtest() { - todo!() -} +pub fn memtest() { todo!() } diff --git a/loader/src/platform/atsama5d27/panic.rs b/loader/src/platform/atsama5d27/panic.rs index 821912f1a..dcab0e801 100644 --- a/loader/src/platform/atsama5d27/panic.rs +++ b/loader/src/platform/atsama5d27/panic.rs @@ -2,9 +2,10 @@ // SPDX-FileCopyrightText: 2023 Foundation Devices, Inc // SPDX-License-Identifier: Apache-2.0 -use armv7; use core::panic::PanicInfo; +use armv7; + #[cfg(feature = "atsama5d27")] #[panic_handler] fn handle_panic(_arg: &PanicInfo) -> ! { diff --git a/loader/src/platform/cramium/cramium.rs b/loader/src/platform/cramium/cramium.rs index 8f96dce5b..3a65b94a4 100644 --- a/loader/src/platform/cramium/cramium.rs +++ b/loader/src/platform/cramium/cramium.rs @@ -26,18 +26,21 @@ impl Duart { duart_csr.wfo(duart::UART_CTL_EN, 1); Duart { csr: duart_csr } } + pub fn putc(&mut self, ch: char) { while self.csr.rf(duart::UART_BUSY_BUSY) != 0 { // spin wait } // the code here bypasses a lot of checks to simulate very fast write cycles so // that the read waitback actually returns something other than not busy. - // unsafe {(duart::HW_DUART_BASE as *mut u32).write_volatile(ch as u32) }; // this line really ensures we have to readback something, but it causes double-printing + // unsafe {(duart::HW_DUART_BASE as *mut u32).write_volatile(ch as u32) }; // this line really ensures + // we have to readback something, but it causes double-printing while unsafe { (duart::HW_DUART_BASE as *mut u32).add(2).read_volatile() } != 0 { // wait } unsafe { (duart::HW_DUART_BASE as *mut u32).write_volatile(ch as u32) }; } + pub fn puts(&mut self, s: &str) { for c in s.as_bytes() { self.putc(*c as char); @@ -54,9 +57,7 @@ fn test_duart() { } #[cfg(feature = "platform-tests")] -pub fn platform_tests() { - test_duart(); -} +pub fn platform_tests() { test_duart(); } #[cfg(feature = "cramium-soc")] pub fn early_init() { @@ -131,18 +132,10 @@ pub fn early_init() { let iox_csr = utra::iox::HW_IOX_BASE as *mut u32; unsafe { iox_csr.add(0).write_volatile(0b00_00_00_01_01_00_00_00); // PAL AF1 on PA3/PA4 - iox_csr - .add(0x1c / core::mem::size_of::()) - .write_volatile(0x1400); // PDH - iox_csr - .add(0x148 / core::mem::size_of::()) - .write_volatile(0x10); // PA4 output - iox_csr - .add(0x148 / core::mem::size_of::() + 3) - .write_volatile(0xffff); // PD - iox_csr - .add(0x160 / core::mem::size_of::()) - .write_volatile(0x8); // PA3 pullup + iox_csr.add(0x1c / core::mem::size_of::()).write_volatile(0x1400); // PDH + iox_csr.add(0x148 / core::mem::size_of::()).write_volatile(0x10); // PA4 output + iox_csr.add(0x148 / core::mem::size_of::() + 3).write_volatile(0xffff); // PD + iox_csr.add(0x160 / core::mem::size_of::()).write_volatile(0x8); // PA3 pullup } udma_ctrl.wo(utra::udma_ctrl::REG_CG, 1); @@ -150,10 +143,7 @@ pub fn early_init() { let freq: u32 = 100_000_000; let clk_counter: u32 = (freq + baudrate / 2) / baudrate; let mut udma_uart = CSR::new(utra::udma_uart_0::HW_UDMA_UART_0_BASE as *mut u32); - udma_uart.wo( - utra::udma_uart_0::REG_UART_SETUP, - 0x0306 | (clk_counter << 16), - ); + udma_uart.wo(utra::udma_uart_0::REG_UART_SETUP, 0x0306 | (clk_counter << 16)); /* // send a test string to confirm the UART is configured diff --git a/loader/src/platform/precursor.rs b/loader/src/platform/precursor.rs index 62e8c54b9..dd1c1980c 100644 --- a/loader/src/platform/precursor.rs +++ b/loader/src/platform/precursor.rs @@ -33,21 +33,11 @@ pub fn platform_tests() { let rd = ram_ptr.add(i).read_volatile(); if rd != (0xACE0_0000 + i) as u32 { if errcnt < 16 || ((errcnt % 256) == 0) { - println!( - "* 0x{:08x}: e:0x{:08x} o:0x{:08x}", - i * 4, - 0xACE0_0000 + i, - rd - ); + println!("* 0x{:08x}: e:0x{:08x} o:0x{:08x}", i * 4, 0xACE0_0000 + i, rd); } errcnt += 1; } else if (i & 0x1FFF) == 8 { - println!( - " 0x{:08x}: e:0x{:08x} o:0x{:08x}", - i * 4, - 0xACE0_0000 + i, - rd - ); + println!(" 0x{:08x}: e:0x{:08x} o:0x{:08x}", i * 4, 0xACE0_0000 + i, rd); }; } } @@ -62,9 +52,7 @@ pub fn platform_tests() { for i in START_ADDR + TESTLEN / 2..START_ADDR + TESTLEN { while trng_csr.rf(utra::trng_kernel::URANDOM_VALID_URANDOM_VALID) == 0 {} unsafe { - ram_ptr - .add(i) - .write_volatile(trng_csr.rf(utra::trng_kernel::URANDOM_URANDOM)); + ram_ptr.add(i).write_volatile(trng_csr.rf(utra::trng_kernel::URANDOM_URANDOM)); } /* seed = crate::murmur3::murmur3_32(&[0], seed); @@ -76,9 +64,7 @@ pub fn platform_tests() { // copy one half to another for i in START_ADDR..START_ADDR + TESTLEN / 2 { unsafe { - ram_ptr - .add(i) - .write_volatile(ram_ptr.add(i + TESTLEN / 2).read_volatile()); + ram_ptr.add(i).write_volatile(ram_ptr.add(i + TESTLEN / 2).read_volatile()); } } // check for copy (write) errors @@ -115,18 +101,10 @@ pub fn platform_tests() { if errcnt != 0 { println!("error count: {}", errcnt); - println!("0x01000: {:08x}", unsafe { - ram_ptr.add(0x1000 / 4).read_volatile() - }); - println!("0x00000: {:08x}", unsafe { - ram_ptr.add(0x0).read_volatile() - }); - println!("0x0FFFC: {:08x}", unsafe { - ram_ptr.add(0xFFFC / 4).read_volatile() - }); - println!("0xfdff04: {:08x}", unsafe { - ram_ptr.add(0xfdff04 / 4).read_volatile() - }); + println!("0x01000: {:08x}", unsafe { ram_ptr.add(0x1000 / 4).read_volatile() }); + println!("0x00000: {:08x}", unsafe { ram_ptr.add(0x0).read_volatile() }); + println!("0x0FFFC: {:08x}", unsafe { ram_ptr.add(0xFFFC / 4).read_volatile() }); + println!("0xfdff04: {:08x}", unsafe { ram_ptr.add(0xfdff04 / 4).read_volatile() }); } else { println!("No errors detected by memory test."); } diff --git a/loader/src/secboot.rs b/loader/src/secboot.rs index dbcbd1c72..c19ba4306 100644 --- a/loader/src/secboot.rs +++ b/loader/src/secboot.rs @@ -1,7 +1,7 @@ -use crate::println; -use sha2_loader::Sha512; use ed25519_dalek_loader::Digest; +use sha2_loader::Sha512; +use crate::println; use crate::SIGBLOCK_SIZE; const VERSION_STR: &'static str = "Xous OS Loader v0.9.6\n\r"; @@ -38,7 +38,7 @@ const FB_WIDTH_WORDS: usize = 11; const FB_WIDTH_PIXELS: usize = 336; const FB_LINES: usize = 536; const FB_SIZE: usize = FB_WIDTH_WORDS * FB_LINES; // 44 bytes by 536 lines - // this font is from the embedded graphics crate https://docs.rs/embedded-graphics/0.7.1/embedded_graphics/ +// this font is from the embedded graphics crate https://docs.rs/embedded-graphics/0.7.1/embedded_graphics/ const FONT_IMAGE: &'static [u8] = include_bytes!("font6x12_1bpp.raw"); const CHAR_HEIGHT: u32 = 12; const CHAR_WIDTH: u32 = 6; @@ -51,23 +51,16 @@ struct Gfx { } impl<'a> Gfx { pub fn init(&mut self, clk_mhz: u32) { - self.csr - .wfo(utra::memlcd::PRESCALER_PRESCALER, (clk_mhz / 2_000_000) - 1); + self.csr.wfo(utra::memlcd::PRESCALER_PRESCALER, (clk_mhz / 2_000_000) - 1); } + #[allow(dead_code)] - pub fn update_all(&mut self) { - self.csr.wfo(utra::memlcd::COMMAND_UPDATEALL, 1); - } - pub fn update_dirty(&mut self) { - self.csr.wfo(utra::memlcd::COMMAND_UPDATEDIRTY, 1); - } - pub fn busy(&self) -> bool { - if self.csr.rf(utra::memlcd::BUSY_BUSY) == 1 { - true - } else { - false - } - } + pub fn update_all(&mut self) { self.csr.wfo(utra::memlcd::COMMAND_UPDATEALL, 1); } + + pub fn update_dirty(&mut self) { self.csr.wfo(utra::memlcd::COMMAND_UPDATEDIRTY, 1); } + + pub fn busy(&self) -> bool { if self.csr.rf(utra::memlcd::BUSY_BUSY) == 1 { true } else { false } } + pub fn flush(&mut self) { self.update_dirty(); while self.busy() {} @@ -76,9 +69,8 @@ impl<'a> Gfx { self.fb[lines * FB_WIDTH_WORDS + (FB_WIDTH_WORDS - 1)] &= 0x0000_FFFF; } } - pub fn set_devboot(&mut self) { - self.csr.wfo(utra::memlcd::DEVBOOT_DEVBOOT, 1); - } + + pub fn set_devboot(&mut self) { self.csr.wfo(utra::memlcd::DEVBOOT_DEVBOOT, 1); } fn char_offset(&self, c: char) -> u32 { let fallback = ' ' as u32 - ' ' as u32; @@ -90,6 +82,7 @@ impl<'a> Gfx { } fallback } + fn put_digit(&mut self, d: u8, pos: &mut Point) { let mut buf: [u8; 4] = [0; 4]; // stack buffer for the character encoding let nyb = d & 0xF; @@ -99,15 +92,18 @@ impl<'a> Gfx { self.msg(((nyb + 0x61 - 10) as char).encode_utf8(&mut buf), pos); } } + fn put_hex(&mut self, c: u8, pos: &mut Point) { self.put_digit(c >> 4, pos); self.put_digit(c & 0xF, pos); } + pub fn hex_word(&mut self, word: u32, pos: &mut Point) { for &byte in word.to_be_bytes().iter() { self.put_hex(byte, pos); } } + pub fn msg(&mut self, text: &'a str, pos: &mut Point) { // this routine is adapted from the embedded graphics crate https://docs.rs/embedded-graphics/0.7.1/embedded_graphics/ let char_per_row = FONT_IMAGE_WIDTH / CHAR_WIDTH; @@ -132,10 +128,8 @@ impl<'a> Gfx { // + Character row offset (row 0 = 0, row 1 = (192 * 8) = 1536) // + X offset for the pixel block that comprises this char // + Y offset for pixel block - let bitmap_bit_index = char_x - + (FONT_IMAGE_WIDTH * char_y) - + char_walk_x - + (char_walk_y * FONT_IMAGE_WIDTH); + let bitmap_bit_index = + char_x + (FONT_IMAGE_WIDTH * char_y) + char_walk_x + (char_walk_y * FONT_IMAGE_WIDTH); let bitmap_byte = bitmap_bit_index / 8; let bitmap_bit = 7 - (bitmap_bit_index % 8); @@ -183,6 +177,7 @@ impl<'a> Gfx { pos.x += x_update; self.flush(); } + pub fn draw_pixel(&mut self, pix: Point, color: Color) { let mut clip_y: usize = pix.y as usize; if clip_y >= FB_LINES { @@ -212,11 +207,8 @@ enum KeyLoc { ThirdPartyPub = 0x20, } impl Keyrom { - pub fn new() -> Self { - Keyrom { - csr: CSR::new(utra::keyrom::HW_KEYROM_BASE as *mut u32), - } - } + pub fn new() -> Self { Keyrom { csr: CSR::new(utra::keyrom::HW_KEYROM_BASE as *mut u32) } } + fn key_is_zero(&mut self, key_base: KeyLoc) -> bool { for offset in key_base as u32..key_base as u32 + 8 { self.csr.wfo(utra::keyrom::ADDRESS_ADDRESS, offset as u32); @@ -226,17 +218,12 @@ impl Keyrom { } true } + fn key_is_dev(&mut self, key_base: KeyLoc) -> bool { for offset in 0..8 { - self.csr.wfo( - utra::keyrom::ADDRESS_ADDRESS, - offset as u32 + key_base as u32, - ); + self.csr.wfo(utra::keyrom::ADDRESS_ADDRESS, offset as u32 + key_base as u32); let kval = self.csr.rf(utra::keyrom::DATA_DATA); - self.csr.wfo( - utra::keyrom::ADDRESS_ADDRESS, - offset as u32 + KeyLoc::DevPub as u32, - ); + self.csr.wfo(utra::keyrom::ADDRESS_ADDRESS, offset as u32 + KeyLoc::DevPub as u32); let dkval = self.csr.rf(utra::keyrom::DATA_DATA); if kval != dkval { return false; @@ -244,16 +231,11 @@ impl Keyrom { } true } - fn read_ed25519( - &mut self, - key_base: KeyLoc, - ) -> Result { + + fn read_ed25519(&mut self, key_base: KeyLoc) -> Result { let mut pk_bytes: [u8; 32] = [0; 32]; for (offset, pk_word) in pk_bytes.chunks_exact_mut(4).enumerate() { - self.csr.wfo( - utra::keyrom::ADDRESS_ADDRESS, - key_base as u32 + offset as u32, - ); + self.csr.wfo(utra::keyrom::ADDRESS_ADDRESS, key_base as u32 + offset as u32); let word = self.csr.rf(utra::keyrom::DATA_DATA); for (&src_byte, dst_byte) in word.to_be_bytes().iter().zip(pk_word.iter_mut()) { *dst_byte = src_byte; @@ -261,6 +243,7 @@ impl Keyrom { } ed25519_dalek_loader::PublicKey::from_bytes(&pk_bytes).or(Err("invalid public key")) } + /// locks all the keys from future read-out pub fn lock(&mut self) { for i in 0..256 { @@ -280,10 +263,7 @@ pub fn validate_xous_img(xous_img_offset: *const u32, fs_prehash: &mut [u8; 64]) // conjure the signature struct directly out of memory. super unsafe. let sig_ptr = xous_img_offset as *const SignatureInFlash; let sig: &SignatureInFlash = unsafe { sig_ptr.as_ref().unwrap() }; - let mut cursor = Point { - x: LEFT_MARGIN, - y: (FB_LINES as i16 / 2) + 10, - }; // draw on bottom half + let mut cursor = Point { x: LEFT_MARGIN, y: (FB_LINES as i16 / 2) + 10 }; // draw on bottom half // clear screen to all black let mut gfx = Gfx { @@ -310,7 +290,8 @@ pub fn validate_xous_img(xous_img_offset: *const u32, fs_prehash: &mut [u8; 64]) // this will emit a warning -- we want that. this is not a natural or intended normal code exit! } // insert a pattern of alternating 0101/1010 to create a "gray effect" on the bottom half of the fb - // note that the gray has "stripes" every 32 bits but it's visually easier to look at than stripes every other bit + // note that the gray has "stripes" every 32 bits but it's visually easier to look at than stripes every + // other bit let (_top, bottom) = gfx.fb.split_at_mut(gfx.fb.len() / 2); for (i, word) in bottom.iter_mut().enumerate() { if i % 2 == 0 { @@ -341,7 +322,8 @@ pub fn validate_xous_img(xous_img_offset: *const u32, fs_prehash: &mut [u8; 64]) // self-signing key takes priority if keyrom.key_is_dev(KeyLoc::SelfSignPub) { println!("Self-signed key slot, but with developer public key."); - // mainly to protect against devs who were debugging and just stuck a dev key in the secure slot, and forgot to remove it. + // mainly to protect against devs who were debugging and just stuck a dev key in the + // secure slot, and forgot to remove it. gfx.msg("DEVELOPER KEY DETECTED\n\r", &mut cursor); gfx.set_devboot(); } @@ -398,13 +380,9 @@ pub fn validate_xous_img(xous_img_offset: *const u32, fs_prehash: &mut [u8; 64]) // extract the version and length from the signed region use core::convert::TryInto; - let protected_version = u32::from_le_bytes( - image[signed_len as usize - 8..signed_len as usize - 4] - .try_into() - .unwrap(), - ); - let protected_len = - u32::from_le_bytes(image[signed_len as usize - 4..].try_into().unwrap()); + let protected_version = + u32::from_le_bytes(image[signed_len as usize - 8..signed_len as usize - 4].try_into().unwrap()); + let protected_len = u32::from_le_bytes(image[signed_len as usize - 4..].try_into().unwrap()); // check that the signed versions match the version reported in the header if sig.version != 2 || (sig.version != protected_version) { if sig.version == 1 { @@ -413,10 +391,7 @@ pub fn validate_xous_img(xous_img_offset: *const u32, fs_prehash: &mut [u8; 64]) &mut cursor, ); } else { - gfx.msg( - "Check fail: mismatch on signature record version numbering.\n\r", - &mut cursor, - ); + gfx.msg("Check fail: mismatch on signature record version numbering.\n\r", &mut cursor); } println!("Check fail: mismatch on signature record version numbering.\n\r"); println!("sig.version: {}", sig.version); @@ -429,10 +404,7 @@ pub fn validate_xous_img(xous_img_offset: *const u32, fs_prehash: &mut [u8; 64]) die(); } if protected_len != signed_len - 4 { - gfx.msg( - "Check fail: mismatch on header length vs protected length.\n\r", - &mut cursor, - ); + gfx.msg("Check fail: mismatch on header length vs protected length.\n\r", &mut cursor); println!("Check fail: mismatch on header length vs protected length.\n\r"); println!("signed_len - 4: {}", signed_len - 4); println!("protected_len: {}", protected_len); @@ -494,10 +466,7 @@ pub fn validate_xous_img(xous_img_offset: *const u32, fs_prehash: &mut [u8; 64]) } unused_stack_words += 1; } - println!( - "Free stack after signature check: {} bytes", - unused_stack_words * 4 - ); + println!("Free stack after signature check: {} bytes", unused_stack_words * 4); gfx.msg("Free stack after sigcheck: 0x", &mut cursor); gfx.hex_word(unused_stack_words * 4, &mut cursor); @@ -508,8 +477,9 @@ pub fn validate_xous_img(xous_img_offset: *const u32, fs_prehash: &mut [u8; 64]) sha_csr.wfo(utra::sha512::POWER_ON, 0); // cut power to the SHA block; this is the expected default state after the bootloader is done. let mut engine_csr = CSR::new(utra::engine::HW_ENGINE_BASE as *mut u32); engine_csr.wfo(utra::engine::POWER_ON, 0); // cut power to the engine block; this is the expected default state after the bootloader is done. - // note that removing power does *not* clear the RF or microcode state -- data can leak from the bootloader - // into other areas because of this! (but I think it's OK because we just mess around with public keys here) + // note that removing power does *not* clear the RF or microcode state -- data can leak from the + // bootloader into other areas because of this! (but I think it's OK because we just mess around with + // public keys here) true } @@ -530,10 +500,7 @@ fn die() { power.rmwf(utra::power::POWER_SELF, 0); // ship mode is the safest mode -- suitable for long-term storage (~years) - com.wfo( - utra::com::TX_TX, - com_rs::ComState::POWER_SHIPMODE.verb as u32, - ); + com.wfo(utra::com::TX_TX, com_rs::ComState::POWER_SHIPMODE.verb as u32); while com.rf(utra::com::STATUS_TIP) == 1 {} let _ = com.rf(utra::com::RX_RX); // discard the RX result start = ticktimer.rf(utra::ticktimer::TIME0_TIME); diff --git a/loader/src/test.rs b/loader/src/test.rs index 42809ceb5..7888abf44 100644 --- a/loader/src/test.rs +++ b/loader/src/test.rs @@ -1,7 +1,8 @@ +use std::sync::Mutex; + use lazy_static::lazy_static; use crate::BootConfig; -use std::sync::Mutex; fn get_args_bin(idx: usize) -> &'static [u8] { match idx { @@ -12,8 +13,7 @@ fn get_args_bin(idx: usize) -> &'static [u8] { } const REGION_COUNT: usize = 8; -static mut MEMORY_REGIONS: [[usize; 1024 * 1024]; REGION_COUNT] = - [[0usize; 1024 * 1024]; REGION_COUNT]; +static mut MEMORY_REGIONS: [[usize; 1024 * 1024]; REGION_COUNT] = [[0usize; 1024 * 1024]; REGION_COUNT]; lazy_static! { static ref REGIONS_CHECKED_OUT: Mutex<[bool; REGION_COUNT]> = Mutex::new([false; REGION_COUNT]); } @@ -37,10 +37,7 @@ impl FakeMemory { let found_idx = found_idx.expect("no available memory regions found"); println!("Checking out region {}", found_idx); store[found_idx] = true; - FakeMemory { - region: &mut MEMORY_REGIONS[found_idx], - index: found_idx, - } + FakeMemory { region: &mut MEMORY_REGIONS[found_idx], index: found_idx } } } } @@ -75,11 +72,7 @@ impl TestEnvironment { #[allow(clippy::cast_ptr_alignment)] // This test only works on 32-bit systems let ka = KernelArguments::new(args.as_ptr() as *const usize); #[allow(clippy::cast_ptr_alignment)] // This test only works on 32-bit systems - let mut cfg = BootConfig { - args: ka, - base_addr: ka.base as *const usize, - ..Default::default() - }; + let mut cfg = BootConfig { args: ka, base_addr: ka.base as *const usize, ..Default::default() }; crate::read_initial_config(&mut cfg); // Patch up the config memory address. Ensure the range is on a "page" boundary. @@ -95,10 +88,7 @@ impl TestEnvironment { fake_memory.region.len() * core::mem::size_of::() ); - TestEnvironment { - cfg, - _mem: fake_memory, - } + TestEnvironment { cfg, _mem: fake_memory } } } @@ -132,11 +122,7 @@ fn parse_args_bin() { let mut ka_iter = ka.iter(); let ka_first = ka_iter.next().expect("kernel args has no first tag"); - assert_eq!( - ka_first.name, - u32::from_le_bytes(*b"XArg"), - "first tag was not valid" - ); + assert_eq!(ka_first.name, u32::from_le_bytes(*b"XArg"), "first tag was not valid"); assert_eq!(ka_first.size, 20, "first tag had invalid size"); assert_eq!(ka_first.data[1], 1, "tag version number unexpected"); @@ -167,11 +153,7 @@ fn read_initial_config() { #[allow(clippy::cast_ptr_alignment)] // This test only works on 32-bit systems let ka = KernelArguments::new(args.as_ptr() as *const usize); #[allow(clippy::cast_ptr_alignment)] // This test only works on 32-bit systems - let mut cfg = BootConfig { - args: ka, - base_addr: ka.base as *const usize, - ..Default::default() - }; + let mut cfg = BootConfig { args: ka, base_addr: ka.base as *const usize, ..Default::default() }; crate::read_initial_config(&mut cfg); } @@ -216,19 +198,13 @@ fn verify_kernel(cfg: &BootConfig, pid: usize, arg: &crate::args::KernelArgument let mut src_data = vec![]; { for i in 0..(prog.text_size as usize) { - let word = unsafe { - (cfg.base_addr as *mut u32) - .add((program_offset + i) / 4) - .read() - }; + let word = unsafe { (cfg.base_addr as *mut u32).add((program_offset + i) / 4).read() }; src_text.push(word); } for i in 0..(prog.data_size as usize) { let word = unsafe { - (cfg.base_addr as *mut u32) - .add((program_offset + prog.text_size as usize + i) / 4) - .read() + (cfg.base_addr as *mut u32).add((program_offset + prog.text_size as usize + i) / 4).read() }; src_data.push(word); } @@ -244,11 +220,7 @@ fn verify_kernel(cfg: &BootConfig, pid: usize, arg: &crate::args::KernelArgument for addr in (0..(prog.text_size as usize)).step_by(4) { assert_eq!( src_text[addr], - read_word( - cfg.processes[pid].satp as usize, - addr + prog.text_offset as usize - ) - .unwrap(), + read_word(cfg.processes[pid].satp as usize, addr + prog.text_offset as usize).unwrap(), "program text doesn't match @ offset {:08x}", addr + prog.text_offset as usize ); @@ -257,29 +229,17 @@ fn verify_kernel(cfg: &BootConfig, pid: usize, arg: &crate::args::KernelArgument for addr in (0..(prog.data_size as usize)).step_by(4) { assert_eq!( src_data[addr], - read_word( - cfg.processes[pid].satp as usize, - addr + prog.data_offset as usize - ) - .unwrap(), + read_word(cfg.processes[pid].satp as usize, addr + prog.data_offset as usize).unwrap(), "program data doesn't match @ offset {:08x}", addr + prog.data_offset as usize ); } - for addr in ((prog.data_size as usize)..((prog.data_size + prog.bss_size) as usize)).step_by(4) - { - println!( - "Verifying BSS @ {:08x} is 0", - addr + prog.data_offset as usize - ); + for addr in ((prog.data_size as usize)..((prog.data_size + prog.bss_size) as usize)).step_by(4) { + println!("Verifying BSS @ {:08x} is 0", addr + prog.data_offset as usize); assert_eq!( 0, - read_word( - cfg.processes[pid].satp as usize, - addr + prog.data_offset as usize - ) - .unwrap(), + read_word(cfg.processes[pid].satp as usize, addr + prog.data_offset as usize).unwrap(), "bss is not zero @ offset {:08x}", addr + prog.data_offset as usize );