From 024c8131bcd83d2ae11229f2332b59d31818f7fd Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 21 Sep 2025 21:50:31 +0800 Subject: [PATCH 1/6] extend image builder to handle baking in statics --- tools/Cargo.toml | 1 + tools/src/bin/copy-object.rs | 44 +++++++++++++++++++++++++++++++++--- tools/src/elf.rs | 44 +++++++++++------------------------- 3 files changed, 55 insertions(+), 34 deletions(-) diff --git a/tools/Cargo.toml b/tools/Cargo.toml index 51db59bab..a669c48c5 100644 --- a/tools/Cargo.toml +++ b/tools/Cargo.toml @@ -26,6 +26,7 @@ pkcs8 = { version = "0.8.0", features = ["pem"] } base64 = "0.20.0" rand = "0.8.5" aes-gcm-siv = "0.11.1" +bao1x-api = { path = "../libs/bao1x-api" } [[bin]] name = "copy-object" diff --git a/tools/src/bin/copy-object.rs b/tools/src/bin/copy-object.rs index 78b157d37..ab2ac2e29 100644 --- a/tools/src/bin/copy-object.rs +++ b/tools/src/bin/copy-object.rs @@ -1,7 +1,7 @@ use std::env; use std::fs::File; use std::io::Write; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process; use tools::elf; @@ -10,16 +10,34 @@ fn main() { env_logger::init(); let args: Vec = env::args().collect(); if args.len() < 2 { - println!("Usage: {} input.elf [output.bin]", args.get(0).unwrap_or(&"copy-object".to_owned())); + println!( + "Usage: {} input.elf [output.bin] [--bao1x]", + args.get(0).unwrap_or(&"copy-object".to_owned()) + ); return; } let input_filename = Path::new(args.get(1).unwrap()).to_path_buf(); - let output_filename = args.get(2).map(|x| Path::new(x).to_path_buf()).unwrap_or_else(|| { + + // Parse remaining arguments + let mut output_filename: Option = None; + let mut bao1x_flag = false; + + for arg in args.iter().skip(2) { + if arg == "--bao1x" { + bao1x_flag = true; + } else if output_filename.is_none() { + output_filename = Some(Path::new(arg).to_path_buf()); + } + } + + // Set default output filename if none provided + let output_filename = output_filename.unwrap_or_else(|| { let mut output_filename = input_filename.clone(); output_filename.set_extension("bin"); output_filename }); + if output_filename == input_filename { eprintln!("Input and output filename are the same: {}", output_filename.display()); eprintln!("Specify an output path, or change the suffix of your input file from \".bin\""); @@ -33,6 +51,26 @@ fn main() { eprintln!("Couldn't create output file {}: {}", output_filename.display(), e); process::exit(1); }); + if bao1x_flag { + let mut statics = bao1x_api::StaticsInRom { + jump_instruction: bao1x_api::JUMP_INSTRUCTION, + version: bao1x_api::STATICS_IN_ROM_VERSION, + valid_pokes: 0, + data_origin: 0, + data_size_bytes: 0, + poke_table: [(0u32, 0u32); 30], + }; + statics.data_origin = pd.data_offset; + statics.data_size_bytes = pd.clear_size; + statics.valid_pokes = pd.poke_table.len() as u16; + for (&entry, dest) in pd.poke_table.iter().zip(statics.poke_table.iter_mut()) { + *dest = entry; + } + f.write(statics.as_bytes()).unwrap_or_else(|e| { + eprintln!("Couldn't write data to {}: {}", output_filename.display(), e); + process::exit(1); + }); + } f.write_all(&pd.program).unwrap_or_else(|e| { eprintln!("Couldn't write data to {}: {}", output_filename.display(), e); process::exit(1); diff --git a/tools/src/elf.rs b/tools/src/elf.rs index 62a75ba67..0588df7b6 100644 --- a/tools/src/elf.rs +++ b/tools/src/elf.rs @@ -36,6 +36,13 @@ pub struct ProgramDescription { /// Size of .data section pub data_size: u32, + /// Poke table for data section; in (address, data) tuples. Addresses are in `u32` format + /// because we're packing them for a target that is 32-bits, which may be different from the host. + pub poke_table: Vec<(u32, u32)>, + + /// Size of region to be zero-ized by the loader + pub clear_size: u32, + /// Size of the .bss section pub bss_size: u32, @@ -156,6 +163,7 @@ pub fn process_program(b: &[u8], rom_only: bool) -> Result::new(); let mut size = 0; let mut data_offset = 0; @@ -328,42 +336,12 @@ pub fn process_program(b: &[u8], rom_only: bool) -> Result() == 0 { - const SPACING: &'static str = " "; - let mut non_zero_tuples = Vec::<(usize, u32)>::new(); for (i, chunk) in data_copy.chunks_exact(4).enumerate() { let word = u32::from_le_bytes(chunk.try_into().unwrap()); if word != 0 { - non_zero_tuples.push((i, word)); + poke_table.push((i as u32, word)); } } - println!("Code for loader/baremetal integration:\n"); - println!("// Define the .data region - bootstrap baremetal using these hard-coded parameters."); - println!("const DATA_ORIGIN: usize = 0x{:x};", data_offset); - println!( - "const DATA_SIZE_BYTES: usize = 0x{:x};", - // round up to the nearest u32 word. Includes .data, .bss, .stack, .heap - regions to be zero'd. - ((data_size + bss_size) as usize + size_of::() - 1) & !(size_of::() - 1) - ); - let mut init_str = String::new(); - init_str.push_str(&format!("const DATA_INIT: [(usize, u32); {}] = [\n", non_zero_tuples.len())); - for (offset, data) in non_zero_tuples { - init_str.push_str(&format!("{}(0x{:x}, 0x{:x}),\n", SPACING, offset, data)); - } - init_str.push_str(&format!("];")); - print!("{}", init_str); - let boilerplate = r#" -// Clear .data, .bss, .stack, .heap regions & setup .data values -unsafe { - let data_ptr = DATA_ORIGIN as *mut u32; - for i in 0..DATA_SIZE_BYTES / size_of::() { - data_ptr.add(i).write_volatile(0); - } - for (offset, data) in DATA_INIT { - data_ptr.add(offset).write_volatile(data); - } -} - "#; - println!("\n{}", boilerplate); } else { println!( "Data section is not word-aligned, check objdump in detail for how to initialize the section" @@ -377,6 +355,10 @@ unsafe { text_offset, text_size, bss_size, + // round up to the nearest u32 word. Includes .data, .bss, .stack, .heap - regions to be zero'd. + clear_size: (((data_size + bss_size) as usize + size_of::() - 1) & !(size_of::() - 1)) + as u32, + poke_table, }) } From a3a7bf9f3a22edcd0aa76098cba49608e1856152 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 21 Sep 2025 21:50:48 +0800 Subject: [PATCH 2/6] add a format for passing static initialized data to baremetal a small, 256-byte record is added to the top of baremetal records that is a "poke table" that incorporates what values to put where for baremetal targets, as well as a zeroization region. This is generally more efficient because most values are set to zero, and the only things that generally have a non-zero value are 'static' variables, which are used extremely sparingly. --- libs/bao1x-api/src/lib.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/libs/bao1x-api/src/lib.rs b/libs/bao1x-api/src/lib.rs index 2bb941f04..92d5f752e 100644 --- a/libs/bao1x-api/src/lib.rs +++ b/libs/bao1x-api/src/lib.rs @@ -52,3 +52,36 @@ pub mod camera { } } } + +/// Version number of the below structure +pub const STATICS_IN_ROM_VERSION: u16 = 1; +/// This encodes to jal x0, 256 - jumps 256 bytes ahead from the current PC location. +pub const JUMP_INSTRUCTION: u32 = 0x1000006f; +/// In-ROM representation of static initialization data +/// Placed by the image creation tool, and used for bootstrapping the Rust environment +/// `usize` is *not* allowed because this structure is packed on a 64-bit host. +#[repr(C, align(256))] +pub struct StaticsInRom { + // reserved for a jump-over instruction so that the structure can be located in-line in ROM. + #[allow(dead_code)] // this should never actually be used + pub jump_instruction: u32, + // version number of this structure + pub version: u16, + // total number of valid pokes in `poke_table` + pub valid_pokes: u16, + // Origin of the data segment + pub data_origin: u32, + // overall size in bytes. [origin:origin+size] will be zeroized. + pub data_size_bytes: u32, + // poke table of values to stick in the data segment. This is needed in particular + // to initialize `static` variables, such as Atomics and Mutexes, required by the + // loader environment. Presented as (address, data) tuples, up to 30 of them. + // Only entries from [0..valid_pokes] are processed. + pub poke_table: [(u32, u32); 30], +} + +impl StaticsInRom { + pub fn as_bytes(&self) -> &[u8] { + unsafe { core::slice::from_raw_parts(self as *const Self as *const u8, core::mem::size_of::()) } + } +} From 19ebb5196ca4f1f8875348f550167259a4aa0636 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 21 Sep 2025 21:52:10 +0800 Subject: [PATCH 3/6] update xtask to handle new autostatics method --- xtask/src/builder.rs | 3 +++ xtask/src/main.rs | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/xtask/src/builder.rs b/xtask/src/builder.rs index 418b65969..622b2b701 100644 --- a/xtask/src/builder.rs +++ b/xtask/src/builder.rs @@ -825,6 +825,7 @@ impl Builder { if self.change_target { std::fs::remove_file(&svd_spec_path).ok(); // don't fail if the file does not exist } + let is_bao = if self.utra_target == "bao1x" { "--bao1x" } else { "" }; // ------ build the loader ------ // stash any LTO settings applied to the kernel; proper layout of the loader @@ -875,6 +876,7 @@ impl Builder { "--", &loader[0], output_file.as_os_str().to_str().unwrap(), + is_bao, ]) .status()?; if !status.success() { @@ -947,6 +949,7 @@ impl Builder { "--", &loader[0], loader_presign.as_os_str().to_str().unwrap(), + is_bao, ]) .status()?; if !status.success() { diff --git a/xtask/src/main.rs b/xtask/src/main.rs index a7708dc25..6d534572c 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -600,13 +600,13 @@ fn main() -> Result<(), Box> { Some("baremetal-bao1x") => { builder.set_baremetal(true); - update_flash_origin("baremetal/src/platform/bao1x/link.x", 0x6000_0000)?; + update_flash_origin("baremetal/src/platform/bao1x/link.x", 0x6000_0100)?; builder.target_baremetal_bao1x(); } Some("baremetal-bao1x-evb") => { builder.set_baremetal(true); - update_flash_origin("baremetal/src/platform/bao1x/link.x", 0x6100_0000)?; + update_flash_origin("baremetal/src/platform/bao1x/link.x", 0x6100_0100)?; builder.add_loader_feature("bao1x-evb"); builder.target_baremetal_bao1x(); } From 110d39936d914fe27711c68744a97e3e4815bc63 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 21 Sep 2025 21:52:24 +0800 Subject: [PATCH 4/6] convert loader to use autostatics --- loader/src/main.rs | 4 --- loader/src/platform/bao1x/bao1x.rs | 51 +++++++++++++++++++++--------- loader/src/platform/bao1x/link.x | 3 +- 3 files changed, 37 insertions(+), 21 deletions(-) diff --git a/loader/src/main.rs b/loader/src/main.rs index 95bfc3bbe..b60e06d3d 100644 --- a/loader/src/main.rs +++ b/loader/src/main.rs @@ -142,16 +142,12 @@ pub enum IniType { /// This function is safe to call exactly once. #[export_name = "rust_entry"] pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32) -> ! { - #[cfg(all(feature = "bao1x", not(feature = "verilator-only")))] let perclk_freq = crate::platform::early_init(); // sets up PLLs so we're not running at 16MHz... // need to make this "official" for bao1x, the feature flag combo below works around some simulation // config conflicts. #[cfg(all(feature = "verilator-only", not(feature = "bao1x-mpw")))] platform::coreuser_config(); - #[cfg(not(all(feature = "bao1x", not(feature = "verilator-only"))))] - let perclk_freq = 0; - #[cfg(all(feature = "bao1x", feature = "updates"))] crate::platform::process_update(perclk_freq); diff --git a/loader/src/platform/bao1x/bao1x.rs b/loader/src/platform/bao1x/bao1x.rs index 7e53c6d37..85fc0f6d1 100644 --- a/loader/src/platform/bao1x/bao1x.rs +++ b/loader/src/platform/bao1x/bao1x.rs @@ -66,9 +66,6 @@ static ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::Loc */ // Define the .data region - bootstrap baremetal using these hard-coded parameters. -const DATA_ORIGIN: usize = 0x61000000; -const DATA_SIZE_BYTES: usize = 0x6000; -const DATA_INIT: [(usize, u32); 3] = [(0x0, 0x2), (0x558, 0x1), (0x55d, 0x1)]; pub const RAM_SIZE: usize = utralib::generated::HW_SRAM_MEM_LEN; pub const RAM_BASE: usize = utralib::generated::HW_SRAM_MEM; pub const FLASH_BASE: usize = utralib::generated::HW_RERAM_MEM; @@ -94,8 +91,43 @@ pub fn delay(quantum: usize) { } } -#[cfg(all(feature = "bao1x", not(feature = "verilator-only")))] pub fn early_init() -> u32 { + // For the loader, the statics structure is located just after the signature block + const STATICS_LOC: usize = FLASH_BASE + 0x1000; + + // safety: this data structure is pre-loaded by the image loader and is guaranteed to + // only have representable, valid values that are aligned according to the repr(C) spec + let statics_in_rom: &bao1x_api::StaticsInRom = + unsafe { (STATICS_LOC as *const bao1x_api::StaticsInRom).as_ref().unwrap() }; + assert!(statics_in_rom.version == bao1x_api::STATICS_IN_ROM_VERSION, "Can't find valid statics table"); + + // Clear .data, .bss, .stack, .heap regions & setup .data values + // Safety: only safe if the values computed by the loader are correct. + // Question: this happens before we setup any clocks, timing, etc. I think the CPU is running + // in a "slow enough" state that these writes should happen, but this may need to be re-ordered + // in particular with respect to SRAM trimming if there are boot issues discovered in the field. + unsafe { + let data_ptr = statics_in_rom.data_origin as *mut u32; + for i in 0..statics_in_rom.data_size_bytes as usize / size_of::() { + data_ptr.add(i).write_volatile(0); + } + for &(offset, data) in &statics_in_rom.poke_table[..statics_in_rom.valid_pokes as usize] { + data_ptr.add(offset as usize).write_volatile(data); + } + } + + #[cfg(not(feature = "verilator-only"))] + let ret = early_init_hw(); + + // return a fake clock result + #[cfg(feature = "verilator-only")] + let ret = 100_000_000; + + ret +} + +#[cfg(all(feature = "bao1x", not(feature = "verilator-only")))] +pub fn early_init_hw() -> u32 { let daric_cgu = sysctrl::HW_SYSCTRL_BASE as *mut u32; let mut ao_sysctrl = CSR::new(utra::ao_sysctrl::HW_AO_SYSCTRL_BASE as *mut u32); @@ -103,17 +135,6 @@ pub fn early_init() -> u32 { let fr = ao_sysctrl.r(utra::ao_sysctrl::SFR_AOFR); ao_sysctrl.wo(utra::ao_sysctrl::SFR_AOFR, fr); - // Clear .data, .bss, .stack, .heap regions & setup .data values - unsafe { - let data_ptr = DATA_ORIGIN as *mut u32; - for i in 0..DATA_SIZE_BYTES / size_of::() { - data_ptr.add(i).write_volatile(0); - } - for (offset, data) in DATA_INIT { - data_ptr.add(offset).write_volatile(data); - } - } - unsafe { // this block is mandatory in all cases to get clocks set into some consistent, expected mode { diff --git a/loader/src/platform/bao1x/link.x b/loader/src/platform/bao1x/link.x index a13eff03c..4ef2510b7 100644 --- a/loader/src/platform/bao1x/link.x +++ b/loader/src/platform/bao1x/link.x @@ -1,9 +1,8 @@ MEMORY { - /* we are using an unsigned loader, so the offset is not 1k offset */ /* if the font location is adjusted, this needs to be updated in libs/blitstr2 codegen templates.go FONT_BASE value */ FONTS : ORIGIN = 0x60040000, LENGTH = 128k - FLASH : ORIGIN = 0x60001000, LENGTH = 252k + FLASH : ORIGIN = 0x60001100, LENGTH = 252k - 256 RAM : ORIGIN = 0x61000000, LENGTH = 2M } From 6e19c4b8716732798a98ed0d9ecad33ce965c662 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 21 Sep 2025 21:52:38 +0800 Subject: [PATCH 5/6] convert baremetal to use autostatics --- baremetal/src/platform/bao1x/bao1x.rs | 65 ++++++++++----------------- baremetal/src/platform/bao1x/link.x | 3 +- 2 files changed, 25 insertions(+), 43 deletions(-) diff --git a/baremetal/src/platform/bao1x/bao1x.rs b/baremetal/src/platform/bao1x/bao1x.rs index d3215fa0a..bc5a1796e 100644 --- a/baremetal/src/platform/bao1x/bao1x.rs +++ b/baremetal/src/platform/bao1x/bao1x.rs @@ -33,22 +33,6 @@ pub const SYSTEM_CLOCK_FREQUENCY: u32 = 800_000_000; pub const SYSTEM_TICK_INTERVAL_MS: u32 = 1; pub fn early_init() { - // Define the .data region - bootstrap baremetal using these hard-coded parameters. - // Define the .data region - bootstrap baremetal using these hard-coded parameters. - const DATA_ORIGIN: usize = 0x61000000; - const DATA_INIT: [(usize, u32); 5] = [(0x0, 0x2), (0x558, 0x1), (0x55b, 0x1), (0x55e, 0x1), (0x563, 0x1)]; - - // Clear .data, .bss, .stack, .heap regions & setup .data values - unsafe { - let data_ptr = DATA_ORIGIN as *mut u32; - for i in 0..DATA_SIZE_BYTES / size_of::() { - data_ptr.add(i).write_volatile(0); - } - for (offset, data) in DATA_INIT { - data_ptr.add(offset).write_volatile(data); - } - } - let iox = Iox::new(utra::iox::HW_IOX_BASE as *mut u32); #[cfg(not(feature = "bao1x-evb"))] { @@ -178,35 +162,32 @@ pub fn early_init() { rbist.wo(utra::rbist_wrp::SFRCR_TRM, (14 << 16) | 0b001_010_00_0_0_000_0_00); rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a); } - let perclk = unsafe { init_clock_asic(SYSTEM_CLOCK_FREQUENCY) }; - // test memory - // NOTE: this smashes stack - need adjustment if this is going to be a "fixture" - /* - crate::println!("\ntest memory..."); - let base = 0x6108_5000; - let mem_range = unsafe { - core::slice::from_raw_parts_mut(base as *mut u32, (0x6120_0000 - base) / core::mem::size_of::()) - }; - let mut state = 1; - for m in mem_range.iter_mut() { - state = lfsr_next_u32(state); - *m = state; - } - state = 1; - let mut failures = 0; - for m in mem_range.iter() { - state = lfsr_next_u32(state); - if state != *m { - failures += 1; + // Now that SRAM trims are setup, initialize all the statics by writing to memory. + // For baremetal, the statics structure is just at the flash base. + const STATICS_LOC: usize = FLASH_BASE; + + // safety: this data structure is pre-loaded by the image loader and is guaranteed to + // only have representable, valid values that are aligned according to the repr(C) spec + let statics_in_rom: &bao1x_api::StaticsInRom = + unsafe { (STATICS_LOC as *const bao1x_api::StaticsInRom).as_ref().unwrap() }; + assert!(statics_in_rom.version == bao1x_api::STATICS_IN_ROM_VERSION, "Can't find valid statics table"); + + // Clear .data, .bss, .stack, .heap regions & setup .data values + // Safety: only safe if the values computed by the loader are correct. + unsafe { + let data_ptr = statics_in_rom.data_origin as *mut u32; + for i in 0..statics_in_rom.data_size_bytes as usize / size_of::() { + data_ptr.add(i).write_volatile(0); + } + for &(offset, data) in &statics_in_rom.poke_table[..statics_in_rom.valid_pokes as usize] { + data_ptr.add(offset as usize).write_volatile(data); } } - if failures != 0 { - crate::println!("fast mem test failed"); - } else { - crate::println!("fast mem test passed"); - } - */ + + // set the clock + let perclk = unsafe { init_clock_asic(SYSTEM_CLOCK_FREQUENCY) }; + crate::println!("scratch page: {:x}, heap start: {:x}", SCRATCH_PAGE, HEAP_START); // setup heap alloc diff --git a/baremetal/src/platform/bao1x/link.x b/baremetal/src/platform/bao1x/link.x index abaddb89f..d7bbb7bca 100644 --- a/baremetal/src/platform/bao1x/link.x +++ b/baremetal/src/platform/bao1x/link.x @@ -1,7 +1,8 @@ /* bottom 256k reserved for copying code into RAM for JTAG-booting targets */ MEMORY { - FLASH : ORIGIN = 0x60000000, LENGTH = 256k + /* Note: ORIGIN is updated by xtask for baremetal targets */ + FLASH : ORIGIN = 0x60000100, LENGTH = 256k - 256 RAM : ORIGIN = 0x61000000, LENGTH = 2048k } From 936be0311d6237e06a4e17b048e7f853bebc8e48 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 21 Sep 2025 21:53:01 +0800 Subject: [PATCH 6/6] update dependencies for auto-statics --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index 91e2805fc..d71b38db9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5742,6 +5742,7 @@ name = "tools" version = "0.1.0" dependencies = [ "aes-gcm-siv", + "bao1x-api", "base64 0.20.0", "bitflags 1.3.2", "clap 2.34.0",