Merge pull request #684 from betrusted-io/autostatics

Autostatics
This commit is contained in:
bunnie 2025-09-21 21:56:23 +08:00 committed by GitHub
commit 902bb23b20
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 156 additions and 100 deletions

1
Cargo.lock generated
View file

@ -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",

View file

@ -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::<u32>() {
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::<u32>())
};
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::<u32>() {
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

View file

@ -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
}

View file

@ -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::<Self>()) }
}
}

View file

@ -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);

View file

@ -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::<u32>() {
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::<u32>() {
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
{

View file

@ -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
}

View file

@ -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"

View file

@ -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<String> = 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<PathBuf> = 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);

View file

@ -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<ProgramDescription, E
let elf = ElfFile::new(&b).map_err(|x| ElfReadError::ParseElfError(x))?;
let entry_point = elf.header.pt2.entry_point() as u32;
let mut program_data = Cursor::new(Vec::new());
let mut poke_table = Vec::<(u32, u32)>::new();
let mut size = 0;
let mut data_offset = 0;
@ -328,42 +336,12 @@ pub fn process_program(b: &[u8], rom_only: bool) -> Result<ProgramDescription, E
debug!("Program size: {} bytes", observed_size);
if data_offset as usize % size_of::<u32>() == 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::<u32>() - 1) & !(size_of::<u32>() - 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::<u32>() {
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::<u32>() - 1) & !(size_of::<u32>() - 1))
as u32,
poke_table,
})
}

View file

@ -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() {

View file

@ -600,13 +600,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
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();
}