From 39eb15003da688a45fe3a553eede152a0e9e70de Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 22 Dec 2025 02:04:31 +0800 Subject: [PATCH 1/7] work around buram erratum; convert reserved field to flags - backup RAM has an erratum where two locations are corruptable and should not be used between soft resets to store data - the reserved 32 bits in the bureg are now accessible as flags. these flag bits are used between boots to coordinate system state information. --- libs/bao1x-hal/src/buram.rs | 41 ++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/libs/bao1x-hal/src/buram.rs b/libs/bao1x-hal/src/buram.rs index 917aeaa74..8e045a284 100644 --- a/libs/bao1x-hal/src/buram.rs +++ b/libs/bao1x-hal/src/buram.rs @@ -3,15 +3,21 @@ use core::ops::Range; const KEY_RANGE: Range = 2..8; const KEY_LEN: usize = range_len(KEY_RANGE) * size_of::(); const HASH_LOC: usize = 0; -#[allow(dead_code)] -const RESERVED_LOC: usize = 1; +const FLAGS_LOC: usize = 1; pub const ERASURE_PROOF_RANGE_BYTES: Range = 0..32; // special case: don't hash in the erasure_proof range, because this // value is passed between boot0 all the way to the loader for checking, // *but* the consistency check on backup regs is done in boot1! +// +// Conveniently, due to an errata, this location of RAM is not preserved +// on soft reset, and thus it's perfect for this application. pub const HASH_REGION_START: usize = ERASURE_PROOF_RANGE_BYTES.end; +// This is an additional range in backup RAM that is not preserved +// across soft resets - and thus this value cannot be used in the hash. +pub const ERRATUM_RANGE_BYTES: Range = 0x2000..0x2020; + use crate::buram::murmur3::murmur3_32; const fn range_len(r: Range) -> usize { r.end - r.start } @@ -56,12 +62,26 @@ impl BackupManager { BackupManager { bu_reg, bu_ram } } + /// The RAM hash is complicated by an erratum where the first word of each bank of the BURAM + /// can be corrupted on a reset (the banking is an internal implementation detail that was + /// meant to be transparent to software). + fn hash_ram(&self) -> u32 { + // hash from the start of the hash region to the beginning of the erratum range + let bu_ram_front_u32: &[u32] = &unsafe { self.bu_ram.as_slice() } + [HASH_REGION_START / size_of::()..ERRATUM_RANGE_BYTES.start / size_of::()]; + let hash_front = murmur3_32(bu_ram_front_u32, 0x0); + + // hash from the end of the erratum range to the end of memory. Use the hash of the + // first half as the seed. + let bu_ram_back_u32: &[u32] = + &unsafe { self.bu_ram.as_slice() }[ERRATUM_RANGE_BYTES.end / size_of::()..]; + murmur3_32(bu_ram_back_u32, hash_front) + } + /// Validity is computed using a hash of the backup RAM region less the "erase proof" slice. pub fn is_backup_valid(&self) -> bool { - let bu_ram_u32: &[u32] = &unsafe { self.bu_ram.as_slice() }[HASH_REGION_START..]; - let hash = murmur3_32(bu_ram_u32, 0x0); let bu_reg: &[u32] = &unsafe { self.bu_reg.as_slice() }[..utralib::utra::aobureg::AOBUREG_NUMREGS]; - hash == bu_reg[HASH_LOC] + self.hash_ram() == bu_reg[HASH_LOC] } pub fn is_zero(&self) -> bool { @@ -69,9 +89,16 @@ impl BackupManager { bu_reg.iter().all(|&x| x == 0) } + pub fn get_flags(&self) -> bao1x_api::BackupFlags { + bao1x_api::BackupFlags::new_with_raw_value(unsafe { self.bu_reg.as_slice()[FLAGS_LOC] }) + } + + pub fn set_flags(&mut self, flag: bao1x_api::BackupFlags) { + unsafe { self.bu_reg.as_slice_mut()[FLAGS_LOC] = flag.raw_value() }; + } + pub fn make_valid(&mut self) { - let bu_ram_u32: &[u32] = &unsafe { self.bu_ram.as_slice() }[HASH_REGION_START..]; - let hash = murmur3_32(bu_ram_u32, 0x0); + let hash = self.hash_ram(); unsafe { (self.bu_reg.as_mut_ptr() as *mut u32).add(HASH_LOC).write_volatile(hash); } From a5303a707f29a754c5576d63d9b2b7d91c5b687e Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 22 Dec 2025 02:05:46 +0800 Subject: [PATCH 2/7] define backup flags --- libs/bao1x-api/src/lib.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/libs/bao1x-api/src/lib.rs b/libs/bao1x-api/src/lib.rs index 4ea4293d0..241d3efb0 100644 --- a/libs/bao1x-api/src/lib.rs +++ b/libs/bao1x-api/src/lib.rs @@ -18,6 +18,8 @@ pub mod signatures; pub use offsets::*; pub mod clocks; pub mod pubkeys; +use arbitrary_int::u31; +use bitbybit::bitfield; pub use clocks::*; /// UF2 Family ID. Randomly generated, no collisions with the known list, still to be merged @@ -44,6 +46,19 @@ pub const SERVER_NAME_KBD: &str = "_Matrix keyboard driver_"; /// circular dependencies on the IFRAM block. pub const SERVER_NAME_BAO1X_HAL: &str = "_bao1x-SoC HAL_"; +/// Flags register in the backup register bank. Used to track system state between soft resets. +#[bitfield(u32)] +#[derive(PartialEq, Eq, Debug)] +pub struct BackupFlags { + #[bits(1..=31, rw)] + reserved: u31, + /// When `false`, indicates that the time in the RTC register is not synchronized to the offset + /// that is read from disk. Upon first encounter with an external time source, the offset should + /// be captured and recorded to disk. + #[bit(0, rw)] + rtc_synchronized: bool, +} + pub mod camera { #[derive(Clone, Copy)] pub enum Resolution { From 00fe25b28c2ecfca015ce308f66e8467738b2ea4 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 22 Dec 2025 02:06:22 +0800 Subject: [PATCH 3/7] fix RTC setting bug - don't reset if it's already set the backup RAM region is being used as a way to check if the system is coming out of a cold power-on. Deep sleep is indistinguishable from a power-on from the hashing perspective. Check if the RTC is *enabled* and if not, enable it and reset the time; don't always reset it if the backup ram is scrambled. --- bao1x-boot/boot1/src/platform/bao1x/bao1x.rs | 38 +++++++++++++------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs b/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs index 81fa21c6d..0ea6ac616 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs @@ -110,21 +110,27 @@ pub fn setup_backup_region() -> u32 { acc += i as u32; } - // enable the RTC if it isn't already - on a cold boot, it would be off let mut ao_sysctrl = CSR::new(utralib::HW_AO_SYSCTRL_BASE as *mut u32); - // set effective tick to 1/1024th of a second - // this causes the RTC to roll over every 48 days - the code before had some deniability about - // RTC offset because it would roll over every 168 years, but I think once every 48 days is within - // a reasonable window of deniability (previously it was a random number from 0-6 months) and - // also the system has to be powered on at least once every rollover window to capture the rollover. - // The device won't last 48 days on RTC battery alone - and every time a QR code is scanned you - // update the RTC offset. So I think this is a reasonable window to just leave "as so". The - // initial value is set to within minutes of a roll-over, so that an error in rollover handling - // would be detected quickly. - ao_sysctrl.wo(utra::ao_sysctrl::CR_CLK1HZFD, 15); let mut rtc = CSR::new(bao1x_hal::rtc::HW_RTC_BASE as *mut u32); - rtc.wo(bao1x_hal::rtc::LR, 0xFFFE_2000); // set base to "roll over" in 2 minutes - forces an edge case in testing - rtc.wfo(bao1x_hal::rtc::CR_EN, 1); + // enable the RTC if it isn't already - on a cold boot, it would be off + if rtc.rf(bao1x_hal::rtc::CR_EN) != 1 { + // set effective tick to 1/1024th of a second + // this causes the RTC to roll over every 48 days - the code before had some deniability about + // RTC offset because it would roll over every 168 years, but I think once every 48 days is within + // a reasonable window of deniability (previously it was a random number from 0-6 months) and + // also the system has to be powered on at least once every rollover window to capture the + // rollover. The device won't last 48 days on RTC battery alone - and every time a QR + // code is scanned you update the RTC offset. So I think this is a reasonable window + // to just leave "as so". The initial value is set to within minutes of a roll-over, + // so that an error in rollover handling would be detected quickly. + ao_sysctrl.wo(utra::ao_sysctrl::CR_CLK1HZFD, 15); + rtc.wo(bao1x_hal::rtc::LR, 0xFFFE_2000); // set base to "roll over" in 2 minutes - forces an edge case in testing + rtc.wfo(bao1x_hal::rtc::CR_EN, 1); + + let mut backup_flags = bu_mgr.get_flags(); + backup_flags.set_rtc_synchronized(false); + bu_mgr.set_flags(backup_flags); + } // soft-reset the system let mut rcurst = CSR::new(utra::sysctrl::HW_SYSCTRL_BASE as *mut u32); @@ -162,6 +168,12 @@ pub fn early_init(mut board_type: bao1x_api::BoardTypeCoding) -> (bao1x_api::Boa if setup_backup_region() == 0 { crate::println!("backup region is clean!"); } + /* // debug RTC setting - remove once confident + let rtc = CSR::new(bao1x_hal::rtc::HW_RTC_BASE as *mut u32); + for i in 0..8 { + crate::println_d!("rtc {}: {:x}", i, unsafe { rtc.base().add(i).read_volatile() }); + } + */ // setup board-specific I/Os - early boot set. These are items that have to be // done in a time-sensitive fashion. From 30725c5169171698be1b043e1969b21bbb982cc8 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 22 Dec 2025 02:10:09 +0800 Subject: [PATCH 4/7] add deep sleep mode --- libs/bao1x-hal/src/clocks.rs | 49 ++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/libs/bao1x-hal/src/clocks.rs b/libs/bao1x-hal/src/clocks.rs index c1dcf1772..931fe4422 100644 --- a/libs/bao1x-hal/src/clocks.rs +++ b/libs/bao1x-hal/src/clocks.rs @@ -438,6 +438,52 @@ impl ClockManager { } } + pub fn deep_sleep(&mut self) { + // setup wakeup mask + self.ao_sysctrl.wo(utra::ao_sysctrl::CR_WKUPMASK, 0x0001_003F); + self.ao_sysctrl.wo(utra::ao_sysctrl::CR_RSTCRMASK, 0x00); + self.ao_sysctrl.wo(utra::ao_sysctrl::SFR_PMUDFTSR, 0); + + wfi_debug("entering deep sleep"); + // switch to internal osc only + self.sysctrl.wo(utra::sysctrl::SFR_CGUSEL0, 0); + self.sysctrl.wo(utra::sysctrl::SFR_CGUSEL1, 1); + self.sysctrl.wo(utra::sysctrl::SFR_CGUSET, 0x32); + wfi_debug("internal osc"); + + #[cfg(feature = "board-baosec")] + { + wfi_debug("disconnect dcdc2"); + self.iox.set_gpio_pin_value(self.dcdc2_io.0, self.dcdc2_io.1, bao1x_api::IoxValue::High); + + self.pmic.set_dcdc(&mut self.i2c, None, crate::axp2101::WhichDcDc::Dcdc2).unwrap(); + wfi_debug("DCDC2 off"); + + self.pmic.set_dcdc(&mut self.i2c, None, crate::axp2101::WhichDcDc::Dcdc5).unwrap(); + self.pmic.set_ldo(&mut self.i2c, None, crate::axp2101::WhichLdo::Bldo2).unwrap(); + wfi_debug("camera off"); + + // Turning this off probably requires disabling a bunch of interrupt handlers: it seems + // like the system gets "activated" into some sort of .. interrupt loop? either that, or + // there is significant leakage into an I/O from something being held up, because we see + // *more* power rather than less when this is turned off. + // self.pmic.set_dcdc(&mut self.i2c, None, crate::axp2101::WhichDcDc::Dcdc4).unwrap(); + // wfi_debug("DCDC4 off"); + } + + // enter PD mode - cuts VDDCORE power - requires full reset to come out of this + // only RTC & backup regsiters are kept. ~1.2mA @ 4.2V consumption in this mode. + + // ensure use of 32k external crystal + self.ao_sysctrl.wo(utra::ao_sysctrl::CR_CR, 7); + + self.ao_sysctrl.wo(utra::ao_sysctrl::SFR_PMUCRPD, 0x0c); // immediate shutdown -- 0x0c will also turn off 2.5V domain + self.ao_sysctrl.wo(utra::ao_sysctrl::SFR_PMUTRMLP0, 0x08420002); // 0.7v + self.ao_sysctrl.wo(utra::ao_sysctrl::SFR_PMUPDAR, 0x5a); + + // deep sleep recovery by touching any button + } + pub fn wfi(&mut self) { wfi_debug("entering wfi"); @@ -480,8 +526,7 @@ impl ClockManager { // We'll just mark this as "thar be dragons" and leave the dungeon crawl to another day. self.sysctrl.wo(utra::sysctrl::SFR_CGULP, 0x3); wfi_debug("ULP"); - // enter PD mode - cuts VDDCORE power - requires full reset to come out of this - // only RTC is kept (check this!). ~1.5-2mA @ 4.2V consumption in this mode. + // ensure use of 32k extenal crystal self.ao_sysctrl.wo(utra::ao_sysctrl::CR_CR, 7); wfi_debug("CR"); // setup wakeup mask From 0487d5a2a30764cfb8a72ea9644d4ad6bbca302f Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 22 Dec 2025 02:10:26 +0800 Subject: [PATCH 5/7] add shipmode and deepsleep mode tests - shipmode is for long-term storage. it disconnects the battery from the system so that the shelf life can be ~years - deep sleep effectively shuts down the system but leaves the real time clock running. Requires a full reboot to recover from deep sleep. --- services/bao-console/src/cmds/test.rs | 74 ++++++++++++++------------- 1 file changed, 39 insertions(+), 35 deletions(-) diff --git a/services/bao-console/src/cmds/test.rs b/services/bao-console/src/cmds/test.rs index 6c8c08358..25c966f8a 100644 --- a/services/bao-console/src/cmds/test.rs +++ b/services/bao-console/src/cmds/test.rs @@ -81,53 +81,57 @@ impl<'a> ShellCmdApi<'a> for Test { } } #[cfg(not(feature = "hosted-baosec"))] - "shutdown" => { - use bao1x_api::*; + "shipmode" => { use bao1x_hal::i2c::I2c; - let iox = bao1x_api::IoxHal::new(); let mut i2c = I2c::new(); - iox.setup_pin( - IoxPort::PF, - 0, - Some(IoxDir::Output), - Some(IoxFunction::Gpio), - None, - Some(IoxEnable::Disable), - None, - Some(IoxDriveStrength::Drive8mA), - ); - iox.set_gpio_pin_value(IoxPort::PF, 0, IoxValue::Low); - log::info!( - "shutdown got {:x?}, {:x?}", - iox.get_gpio_pin_value(IoxPort::PF, 0), - iox.get_gpio_bank_value(IoxPort::PF) - ); - let axp2101 = bao1x_hal::axp2101::Axp2101::new(&mut i2c).expect("couldn't get AXP2101"); - log::info!("sending shutdown to axp2101 pmic...in four seconds"); + let mut axp2101 = + bao1x_hal::axp2101::Axp2101::new(&mut i2c).expect("couldn't get AXP2101"); + log::info!("sending shipmode to axp2101 pmic...in four seconds"); let tt = ticktimer::Ticktimer::new().unwrap(); tt.sleep_ms(4000).ok(); + // shut down BLDO1 - this should disconnect the battery + axp2101.set_ldo(&mut i2c, None, bao1x_hal::axp2101::WhichLdo::Bldo1).ok(); + // shut down PMIC axp2101.powerdown(&mut i2c).ok(); - iox.setup_pin( - IoxPort::PF, - 6, - Some(IoxDir::Output), - Some(IoxFunction::Gpio), - None, - Some(IoxEnable::Disable), - None, - Some(IoxDriveStrength::Drive8mA), - ); - iox.set_gpio_pin_value(IoxPort::PF, 6, IoxValue::Low); log::info!("sent shutdown to axp2101"); } + #[cfg(not(feature = "hosted-baosec"))] + "deepsleep" => { + let gfx = ux_api::service::gfx::Gfx::new(&_env.xns).unwrap(); + log::info!("turn off display"); + gfx.set_power(false).unwrap(); + log::info!("display off"); + use num_traits::*; + // monkey patch over the standard xous IP + let conn = _env + .xns + .request_connection_blocking(susres::api::SERVER_NAME_SUSRES) + .expect("Can't connect to SUSRES"); + match xous::send_message( + conn, + xous::Message::new_blocking_scalar( + susres::api::Opcode::SuspendRequest.to_usize().unwrap(), + 1, // this is a monkeypatch + 0, + 0, + 0, + ), + ) { + Ok(xous::Result::Scalar1(result)) => { + if result == 1 { + log::info!("Should be in deep sleep!"); + } else { + log::error!("Couldn't initiate deep sleep") + } + } + _ => panic!("Couldn't send deep sleep message to susres"), + } + } "seed" => { let (_, value) = std::env::vars().find(|(key, _value)| key == "SEED").unwrap(); log::info!("Seed: {:?}", value); } - "keepon" => { - todo!("Fix this to use DCDC2 for keepon (as per baosec v2)"); - } #[cfg(not(feature = "hosted-baosec"))] "wfi" => { let gfx = ux_api::service::gfx::Gfx::new(&_env.xns).unwrap(); From 3427c4965e8d5186b165d74d76c175008bc1d338 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 22 Dec 2025 02:11:29 +0800 Subject: [PATCH 6/7] note RTC todo's --- services/bao1x-hal-service/src/servers/rtc.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/services/bao1x-hal-service/src/servers/rtc.rs b/services/bao1x-hal-service/src/servers/rtc.rs index 600d66a7a..f430cdcd4 100644 --- a/services/bao1x-hal-service/src/servers/rtc.rs +++ b/services/bao1x-hal-service/src/servers/rtc.rs @@ -37,6 +37,9 @@ fn rtc_service() -> ! { let mut rtc_rollovers: u32 = 0; // gives us up to 168 years let mut last_rtc_val = rtc.r(DR); // use this to detect rollovers + // TODO: + // - check backup register: is the RTC synchronized to the value on disk? + // - if yes, read the value and use it to initialize the time offset, instead of using 0. let mut utc_offset_ms = 0; let mut tz_offset_ms = 0; @@ -103,6 +106,9 @@ fn rtc_service() -> ! { log::info!("rtc_secs: {}", rtc_offset_ms / 1000); let offset = utc_time_ms - rtc_offset_ms; utc_offset_ms = offset; + // TODO: + // - commit the UTC offset to disk + // - set the flag on the backup register for time sync to `true` } } Some(TimeOp::SetTzOffsetMs) => { From 192a9148dc062881f0b8fcef8e384dbc88a1ca99 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 22 Dec 2025 02:11:54 +0800 Subject: [PATCH 7/7] catch the deep sleep request --- services/bao1x-hal-service/src/servers/susres.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/services/bao1x-hal-service/src/servers/susres.rs b/services/bao1x-hal-service/src/servers/susres.rs index 8bd63b8a2..f3b91b67c 100644 --- a/services/bao1x-hal-service/src/servers/susres.rs +++ b/services/bao1x-hal-service/src/servers/susres.rs @@ -219,7 +219,14 @@ fn susres_service() { log::trace!("still waiting on callbacks, returning to main loop"); } }), - Some(Opcode::SuspendRequest) => { + Some(Opcode::SuspendRequest) => msg_blocking_scalar_unpack!(msg, deepsleep, 0, 0, 0, { + // catch the case of deepsleep request + if deepsleep == 1 { + log::info!("entering deep sleep"); + clk_mgr.deep_sleep(); + xous::return_scalar(msg.sender, 1).ok(); + // system is shut down after this point, no code runs + } log::info!("registered suspend listeners:"); for sub in suspend_subscribers.iter() { log::info!("{:?}", sub); @@ -258,7 +265,7 @@ fn susres_service() { ); xous::return_scalar(msg.sender, 0).ok(); } - } + }), Some(Opcode::SuspendTimeout) => { if timeout_pending { // record which tokens had not reported in