From 399742a3d408d7a806ad2cad031a76561d491079 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 7 May 2025 23:10:04 +0800 Subject: [PATCH 01/10] feature-out some battery testing code in hosted mode --- services/bao-console/src/main.rs | 33 +++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/services/bao-console/src/main.rs b/services/bao-console/src/main.rs index 5445cfd72..8185cf467 100644 --- a/services/bao-console/src/main.rs +++ b/services/bao-console/src/main.rs @@ -70,19 +70,26 @@ fn main() { log::set_max_level(log::LevelFilter::Debug); modals::tests::spawn_test(); } - use cramium_api::I2cApi; - let mut i2c = cram_hal_service::I2c::new(); - use cramium_hal::axp2101::*; - let measurements = [("VBAT", REG_VBAT_H), ("VBUS", REG_VBUS_H), ("VSYS", REG_VSYS_H)]; - let mut buf = [0u8, 0u8]; - loop { - tt.sleep_ms(2_000).ok(); - for (name, offset) in measurements { - i2c.i2c_read(AXP2101_DEV, offset, &mut buf, false).unwrap(); - let v: u32 = (((buf[0] as u32) & 0x3F) << 8) | buf[1] as u32; - log::info!("{}: {:0.3}V", name, v as f32 / 1000.0); - i2c.i2c_read(AXP2101_DEV, REG_SOC, &mut buf[0..1], false).unwrap(); - log::info!("SOC: {}%", buf[0]); + #[cfg(not(feature = "hosted-baosec"))] + { + use cramium_api::I2cApi; + let mut i2c = cram_hal_service::I2c::new(); + use cramium_hal::axp2101::*; + let measurements = [("VBAT", REG_VBAT_H), ("VBUS", REG_VBUS_H), ("VSYS", REG_VSYS_H)]; + let mut buf = [0u8, 0u8]; + loop { + tt.sleep_ms(2_000).ok(); + for (name, offset) in measurements { + i2c.i2c_read(AXP2101_DEV, offset, &mut buf, false).unwrap(); + let v: u32 = (((buf[0] as u32) & 0x3F) << 8) | buf[1] as u32; + log::info!("{}: {:0.3}V", name, v as f32 / 1000.0); + i2c.i2c_read(AXP2101_DEV, REG_SOC, &mut buf[0..1], false).unwrap(); + log::info!("SOC: {}%", buf[0]); + } } } + #[cfg(feature = "hosted-baosec")] + loop { + tt.sleep_ms(2_000).ok(); + } } From 645846e32ef72a809dc394bf24c99c4f60426bd9 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 8 May 2025 15:59:31 +0800 Subject: [PATCH 02/10] move pddb, spinor params into the board section of the HAL for hosted this makes code a little cleaner when porting to new targets --- libs/cramium-hal/src/board/hosted.rs | 6 ++++++ libs/cramium-hal/src/board/mod.rs | 4 ++++ libs/cramium-hal/src/lib.rs | 9 +++++++++ 3 files changed, 19 insertions(+) create mode 100644 libs/cramium-hal/src/board/hosted.rs diff --git a/libs/cramium-hal/src/board/hosted.rs b/libs/cramium-hal/src/board/hosted.rs new file mode 100644 index 000000000..ac3aed50e --- /dev/null +++ b/libs/cramium-hal/src/board/hosted.rs @@ -0,0 +1,6 @@ +pub const SPINOR_PAGE_LEN: u32 = 0x100; +pub const SPINOR_ERASE_SIZE: u32 = 0x1000; // this is the smallest sector size. +pub const SPINOR_BULK_ERASE_SIZE: u32 = 0x1_0000; // this is the bulk erase size. +pub const SPINOR_LEN: u32 = 16384 * 1024; +pub const PDDB_LOC: u32 = 0; +pub const PDDB_LEN: u32 = 4096 * 1024; // 4MiB data for the PDDB total diff --git a/libs/cramium-hal/src/board/mod.rs b/libs/cramium-hal/src/board/mod.rs index 9011308ff..aae709edc 100644 --- a/libs/cramium-hal/src/board/mod.rs +++ b/libs/cramium-hal/src/board/mod.rs @@ -20,3 +20,7 @@ pub use baosor::*; pub mod dabao; #[cfg(any(feature = "board-dabao", feature = "loader-dabao"))] pub use dabao::*; +#[cfg(feature = "hosted-baosec")] +pub mod hosted; +#[cfg(feature = "hosted-baosec")] +pub use hosted::*; diff --git a/libs/cramium-hal/src/lib.rs b/libs/cramium-hal/src/lib.rs index af4395209..f3a4e7fef 100644 --- a/libs/cramium-hal/src/lib.rs +++ b/libs/cramium-hal/src/lib.rs @@ -1,21 +1,30 @@ #![cfg_attr(not(feature = "std"), no_std)] #[macro_use] +#[cfg(not(feature = "hosted-baosec"))] pub mod debug; #[cfg(feature = "axp2101")] pub mod axp2101; pub mod board; #[cfg(feature = "camera-gc2145")] pub mod gc2145; +#[cfg(not(feature = "hosted-baosec"))] pub mod ifram; +#[cfg(not(feature = "hosted-baosec"))] pub mod iox; #[cfg(feature = "camera-ov2640")] pub mod ov2640; +#[cfg(not(feature = "hosted-baosec"))] pub mod sce; #[cfg(feature = "display-sh1107")] pub mod sh1107; +#[cfg(not(feature = "hosted-baosec"))] pub mod shared_csr; +#[cfg(not(feature = "hosted-baosec"))] pub mod udma; +#[cfg(not(feature = "hosted-baosec"))] pub mod usb; +#[cfg(not(feature = "hosted-baosec"))] pub use shared_csr::*; +#[cfg(not(feature = "hosted-baosec"))] pub mod mbox; From 5417c2bd870654826bd8e96499b9d36b71188a9e Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 8 May 2025 16:00:28 +0800 Subject: [PATCH 03/10] add more test features to the console; absorb board:: api for sizes --- services/bao-console/Cargo.toml | 9 ++++- services/bao-console/src/cmds/pddb.rs | 54 ++++++++++++++++++++++++++- 2 files changed, 59 insertions(+), 4 deletions(-) diff --git a/services/bao-console/Cargo.toml b/services/bao-console/Cargo.toml index 47de6f88f..5521d7c8f 100644 --- a/services/bao-console/Cargo.toml +++ b/services/bao-console/Cargo.toml @@ -23,6 +23,10 @@ modals = { path = "../modals", default-features = false } ux-api = { path = "../../libs/ux-api", optional = true } pddb = { path = "../pddb", features = ["gen2"] } +# pddb testing +rand = { version = "0.8.5", features = ["getrandom"], optional = true } +rand_chacha = { version = "0.3.1", optional = true } + [features] cramium-soc = [ "utralib/cramium-soc", @@ -41,11 +45,12 @@ hosted-baosec = [ "usb-cramium/hosted-baosec", "cramium-emu", "pddb/hosted-baosec", + "cramium-hal/hosted-baosec", ] usb = [] pddbtest = [] test-rekey = [] -autobasis = [] +autobasis = ["rand_chacha", "rand"] modal-testing = ["ux-api", "modals/modal-testing"] test-scrollbars = [] -default = [] +default = ["pddbtest"] diff --git a/services/bao-console/src/cmds/pddb.rs b/services/bao-console/src/cmds/pddb.rs index 9c4398830..8f969c0ef 100644 --- a/services/bao-console/src/cmds/pddb.rs +++ b/services/bao-console/src/cmds/pddb.rs @@ -6,7 +6,7 @@ use std::path::PathBuf; use String; #[cfg(all(feature = "pddbtest", feature = "autobasis"))] -const PDDB_A_LEN: usize = cramium_emu::PDDB_LEN as usize; +const PDDB_A_LEN: usize = cramium_hal::board::PDDB_LEN as usize; use crate::{CommonEnv, ShellCmdApi}; @@ -1184,7 +1184,7 @@ impl<'a> ShellCmdApi<'a> for PddbCmd { for i in 0..20 { let mut testkey = self .pddb - .get("wlan.networks", "testkey", None, false, true, None, None::) + .get("wlan.networks", "testkey", None, true, true, None, None::) .expect("couldn't make test key"); testdata.push_str(&i.to_string()); // testkey.seek(SeekFrom::Start(0)).ok(); @@ -1249,3 +1249,53 @@ fn join_tokens<'a>(buf: &mut String, tokens: impl Iterator) { } } } + +#[cfg(all(feature = "pddbtest", feature = "autobasis"))] +enum VectorType { + Small(usize), + Large(usize), + Junk, +} +#[cfg(all(feature = "pddbtest", feature = "autobasis"))] +const SMALL_SIZE: usize = 2011; +#[cfg(all(feature = "pddbtest", feature = "autobasis"))] +const LARGE_SIZE: usize = 28813; +#[cfg(all(feature = "pddbtest", feature = "autobasis"))] +const JUNK_SIZE: usize = 128 * 1024 - 2; +#[cfg(all(feature = "pddbtest", feature = "autobasis"))] +fn make_vector(basis_number: usize, vtype: VectorType) -> Vec { + use rand::prelude::*; + use rand_chacha::ChaCha8Rng; + + let mut vector = Vec::::new(); + // seed format: + // bottom 0xFFFF is reserved for the basis_number + // next 0xFFF is resrved for the vector number + // 0x8000_0000 when set means small, not set means large + let typemod = match vtype { + VectorType::Small(n) => 0x1_0000 * (n as u64) + 0x8000_0000, + VectorType::Large(n) => 0x1_0000 * (n as u64) + 0x0000_0000, + VectorType::Junk => 0x1_0000_000, + }; + let mut rng = ChaCha8Rng::seed_from_u64(basis_number as u64 + typemod); + match vtype { + VectorType::Small(n) => { + // multiply the vector number by some odd value so the vectors are not same-sized + for _ in 0..SMALL_SIZE + 7 * n + basis_number { + vector.push(rng.gen()); + } + } + VectorType::Large(n) => { + // multiply the vector number by some odd value so the vectors are not same-sized + for _ in 0..LARGE_SIZE + 1117 * n + basis_number { + vector.push(rng.gen()); + } + } + VectorType::Junk => { + for _ in 0..JUNK_SIZE + basis_number { + vector.push(rng.gen()); + } + } + } + vector +} From 0cb80c2afb913c7ba71e80294fb02f06121f1825 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 8 May 2025 16:01:11 +0800 Subject: [PATCH 04/10] remove sizes from the emu lib, so it can live in board:: --- services/cramium-emu/src/lib.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/services/cramium-emu/src/lib.rs b/services/cramium-emu/src/lib.rs index 54c9d3d7f..7c97f57da 100644 --- a/services/cramium-emu/src/lib.rs +++ b/services/cramium-emu/src/lib.rs @@ -4,10 +4,3 @@ pub mod i2c; pub mod keyboard; pub mod trng; pub mod udma; - -pub const SPINOR_PAGE_LEN: u32 = 0x100; -pub const SPINOR_ERASE_SIZE: u32 = 0x1000; // this is the smallest sector size. -pub const SPINOR_BULK_ERASE_SIZE: u32 = 0x1_0000; // this is the bulk erase size. -pub const SPINOR_LEN: u32 = 16384 * 1024; -pub const PDDB_LOC: u32 = 4096 * 1024; // located 4MiB in, after the swap image -pub const PDDB_LEN: u32 = 4096 * 1024; // 4MiB data for the PDDB total From 34a1a331659e8efd89fb72079b3fb152ceff8149 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 8 May 2025 16:01:46 +0800 Subject: [PATCH 05/10] fix off-by-one arg error on Dna routine this is a common api problem because yes, while arg1 is strictly the second item, previously arg0 was hidden and in the argument list arg1 took the first place not the second. so i make this mistake a lot... --- services/keystore/src/lib.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/services/keystore/src/lib.rs b/services/keystore/src/lib.rs index d64b9c2cc..fdf2d5aac 100644 --- a/services/keystore/src/lib.rs +++ b/services/keystore/src/lib.rs @@ -46,7 +46,7 @@ impl Keystore { Message::new_blocking_scalar(Opcode::GetDna.to_usize().unwrap(), 0, 0, 0, 0), ) .unwrap(); - if let xous::Result::Scalar5(val1, val2, _, _, _) = response { + if let xous::Result::Scalar5(_, val1, val2, _, _) = response { (val1 as u64) | ((val2 as u64) << 32) } else { panic!("get_dna() failed with internal error"); @@ -71,7 +71,10 @@ impl Keystore { self.conn, Message::new_blocking_scalar(Opcode::EnsurePassword.to_usize().unwrap(), 0, 0, 0, 0), ) { - Ok(xous::Result::Scalar5(arg1, arg2, arg3, _arg4, _arg5)) => (arg1, arg2, arg3).into(), + Ok(xous::Result::Scalar5(_arg0, arg1, arg2, arg3, _arg4)) => { + log::info!("got {:x}, {:x}, {:x}", arg1, arg2, arg3); + (arg1, arg2, arg3).into() + } _ => panic!("ensure_password() failed with internal error"), } } From 2ea777e04fb8f5d58e188332f0392b95367b169d Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 8 May 2025 16:02:52 +0800 Subject: [PATCH 06/10] fix key encoding bug; set DNA to "0" in emulation mode this matches what's done in hosted mode, allowing the analysis scripts to work on the images generated by this version --- services/keystore/src/platform/hosted.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/keystore/src/platform/hosted.rs b/services/keystore/src/platform/hosted.rs index a586fa537..428bef578 100644 --- a/services/keystore/src/platform/hosted.rs +++ b/services/keystore/src/platform/hosted.rs @@ -32,7 +32,7 @@ pub fn keystore(sid: SID) -> ! { AesOpType::Encrypt => AesOpType::Encrypt, }; let mut ikm = [0u8; 32]; - hex::encode_to_slice(WELL_KNOWN_KEY, &mut ikm).unwrap(); + ikm.copy_from_slice(&hex::decode(WELL_KNOWN_KEY).unwrap()); let hk = Hkdf::::new(None, &ikm); let mut okm = [0u8; 32]; hk.expand(&aes_op.domain.as_bytes(), &mut okm) @@ -68,7 +68,7 @@ pub fn keystore(sid: SID) -> ! { } Opcode::AesKwp => { let mut ikm = [0u8; 32]; - hex::encode_to_slice(WELL_KNOWN_KEY, &mut ikm).unwrap(); + ikm.copy_from_slice(&hex::decode(WELL_KNOWN_KEY).unwrap()); let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut kwp = buffer.to_original::().unwrap(); @@ -149,8 +149,8 @@ pub fn keystore(sid: SID) -> ! { Opcode::GetDna => { // dummy DNA value if let Some(scalar) = msg.body.scalar_message_mut() { - scalar.arg1 = 0x1234_5678; - scalar.arg2 = 0xface_cafe; + scalar.arg1 = 0; + scalar.arg2 = 0; } } Opcode::InvalidCall => { From fe599c2fe0f45a7fb3f1866026bafcdaf9ed142c Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 8 May 2025 16:03:48 +0800 Subject: [PATCH 07/10] migrate lengths to board:: for gen2; fix opcode numbering bug opcode numbering bug only affects test mode, fortunately. just bit-rot from tests long not run... --- services/pddb/src/api.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/services/pddb/src/api.rs b/services/pddb/src/api.rs index 0d24dbc80..f31b02f60 100644 --- a/services/pddb/src/api.rs +++ b/services/pddb/src/api.rs @@ -44,11 +44,23 @@ pub(crate) const PDDB_VERSION: u32 = 0x00_00_02_01; #[allow(dead_code)] // PDDB_A_LEN may be shorter than xous::PDDB_LEN, to speed up testing. #[allow(dead_code)] -#[cfg(not(any(feature = "pddbtest", feature = "autobasis", feature = "ci", feature = "smalldb")))] +#[cfg(all( + not(any(feature = "pddbtest", feature = "autobasis", feature = "ci", feature = "smalldb")), + not(feature = "gen2") +))] pub(crate) const PDDB_A_LEN: usize = xous::PDDB_LEN as usize; #[allow(dead_code)] -#[cfg(any(feature = "pddbtest", feature = "autobasis", feature = "ci", feature = "smalldb"))] +#[cfg(all( + any(feature = "pddbtest", feature = "autobasis", feature = "ci", feature = "smalldb"), + not(feature = "gen2") +))] pub const PDDB_A_LEN: usize = 4 * 1024 * 1024; +#[cfg(feature = "gen2")] +pub const PDDB_A_LEN: usize = cramium_hal::board::PDDB_LEN as usize; +#[cfg(feature = "gen1")] +pub const PDDB_A_LOC: u32 = xous::PDDB_LOC as u32; +#[cfg(feature = "gen2")] +pub const PDDB_A_LOC: u32 = cramium_hal::board::PDDB_LOC as u32; /// range for the starting point of a journal number, picked from a random seed /// the goal is to reduce info leakage about the age of structures relative to each other @@ -163,7 +175,7 @@ pub(crate) enum Opcode { #[cfg(not(target_os = "xous"))] DangerousDebug = 25, #[cfg(all(feature = "pddbtest", feature = "autobasis"))] - BasisTesting = 26, + BasisTesting = 65536, ListBasisStd = 26, CreateBasisStd = 27, From f92839602ec5cb33799d206adf32f7e964344d40 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 8 May 2025 16:04:36 +0800 Subject: [PATCH 08/10] feature flag fixes for moving sizes to board:: --- Cargo.lock | 2 ++ services/pddb/Cargo.toml | 1 + 2 files changed, 3 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 1bf188cf0..30f311eb5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -343,6 +343,8 @@ dependencies = [ "num-derive 0.4.2", "num-traits", "pddb", + "rand 0.8.5", + "rand_chacha 0.3.1", "usb-cramium", "utralib 0.1.25", "ux-api", diff --git a/services/pddb/Cargo.toml b/services/pddb/Cargo.toml index ae5dd1aa2..c405f7e31 100644 --- a/services/pddb/Cargo.toml +++ b/services/pddb/Cargo.toml @@ -106,6 +106,7 @@ hosted-baosec = [ "gen2", "cramium-emu", "modals/hosted-baosec", + "cramium-hal/hosted-baosec", ] # emulated hardware on x86 platform board-baosor = [ "gen2", From c7225d227dba78fc9fea2ddb32a87af983cfcf69 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 8 May 2025 16:06:42 +0800 Subject: [PATCH 09/10] migrate pddb size to board:: and fix boot init the policy is to format the PDDB automatically on boot if it can't be mounted. Need to think about whether this is the right thing to do or not for the product: if there is any sort of error, it will just wipe the PDDB entirely, making it unrecoverable. That being said, why would there be an error? if that happens, something bad probably happened to the hardware. I feel like if the SPI interface is reliable this shouldn't be a problem. So the solution is to make sure the hardware is reliable... on the other hand, fundamentally, SPI flash can wear out, so this could aggravate problems at EOL for the device (i.e. it will take small problems and "amplify them up" into a huge problem). The trade-off is...the auto-format makes the token "just work" on boot. Maybe the right thing to do is to add some code that checks to see if we're in a true blank state, and if so, autoformat; and if it looks like something was there before, prompt for a format? tbd. --- services/pddb/src/backend/hosted.rs | 2 +- services/pddb/src/backend/hw.rs | 62 +++++++++++--------------- services/pddb/src/backend/pagetable.rs | 2 +- services/pddb/src/backend/trngpool.rs | 2 +- 4 files changed, 29 insertions(+), 39 deletions(-) diff --git a/services/pddb/src/backend/hosted.rs b/services/pddb/src/backend/hosted.rs index 7aa783768..b4b6afbc1 100644 --- a/services/pddb/src/backend/hosted.rs +++ b/services/pddb/src/backend/hosted.rs @@ -138,7 +138,7 @@ impl HostedSpinor { pub fn bulk_erase(&self, start: u32, len: u32) -> Result<(), xous::Error> { for b in flashmem().memory.as_mut_slice() - [(start - xous::PDDB_LOC) as usize..(start - xous::PDDB_LOC + len) as usize] + [(start - PDDB_A_LOC) as usize..(start - PDDB_A_LOC + len) as usize] .iter_mut() { *b = 0xFF; diff --git a/services/pddb/src/backend/hw.rs b/services/pddb/src/backend/hw.rs index 64692fa01..eb5aea7c9 100644 --- a/services/pddb/src/backend/hw.rs +++ b/services/pddb/src/backend/hw.rs @@ -15,9 +15,7 @@ use aes::{Aes256, BLOCK_SIZE, Block}; use aes_gcm_siv::aead::{Aead, Payload}; use aes_gcm_siv::{Aes256GcmSiv, Nonce, Tag}; use backend::bcrypt::*; -#[cfg(all(feature = "gen2", feature = "cramium-emu"))] -use cramium_emu::{SPINOR_BULK_ERASE_SIZE, SPINOR_ERASE_SIZE}; -#[cfg(all(feature = "gen2", not(feature = "cramium-emu")))] +#[cfg(all(feature = "gen2"))] use cramium_hal::board::{SPINOR_BULK_ERASE_SIZE, SPINOR_ERASE_SIZE}; #[cfg(feature = "gen1")] use keystore_api::AesRootkeyType; @@ -28,6 +26,7 @@ use sha2::{Digest, Sha512_256Hw, Sha512_256Sw}; use spinor::{SPINOR_BULK_ERASE_SIZE, SPINOR_ERASE_SIZE}; use subtle::ConstantTimeEq; +use crate::api::PDDB_A_LOC; use crate::*; #[cfg(not(feature = "deterministic"))] @@ -208,7 +207,7 @@ impl PddbOs { let xns = xous_names::XousNames::new().unwrap(); #[cfg(any(feature = "precursor", feature = "renode"))] let pddb = xous::syscall::map_memory( - xous::MemoryAddress::new(xous::PDDB_LOC as usize + xous::FLASH_PHYS_BASE as usize), + xous::MemoryAddress::new(PDDB_A_LOC as usize + xous::FLASH_PHYS_BASE as usize), None, PDDB_A_LEN as usize, xous::MemoryFlags::R | xous::MemoryFlags::RESERVE, @@ -428,7 +427,7 @@ impl PddbOs { self.spinor .patch( unsafe { self.pddb_mr.as_slice() }, - xous::PDDB_LOC, + PDDB_A_LOC, &data, offset + self.data_phys_base.as_u32(), ) @@ -452,7 +451,7 @@ impl PddbOs { self.spinor .patch( unsafe { self.pddb_mr.as_slice() }, - xous::PDDB_LOC, + PDDB_A_LOC, &mbbb, self.pt_phys_base.as_u32() + erased_offset, ) @@ -490,7 +489,7 @@ impl PddbOs { self.spinor .patch( unsafe { self.pddb_mr.as_slice() }, - xous::PDDB_LOC, + PDDB_A_LOC, &blank, self.pt_phys_base.as_u32() + base_page as u32, ) @@ -507,12 +506,7 @@ impl PddbOs { "attempt to patch past page table end" ); self.spinor - .patch( - unsafe { self.pddb_mr.as_slice() }, - xous::PDDB_LOC, - &data, - self.pt_phys_base.as_u32() + offset, - ) + .patch(unsafe { self.pddb_mr.as_slice() }, PDDB_A_LOC, &data, self.pt_phys_base.as_u32() + offset) .expect("couldn't write to page table"); } @@ -523,12 +517,7 @@ impl PddbOs { ); log::info!("patching keys area with {} bytes", data.len()); self.spinor - .patch( - unsafe { self.pddb_mr.as_slice() }, - xous::PDDB_LOC, - data, - self.key_phys_base.as_u32() + offset, - ) + .patch(unsafe { self.pddb_mr.as_slice() }, PDDB_A_LOC, data, self.key_phys_base.as_u32() + offset) .expect("couldn't burn keys"); } @@ -537,7 +526,7 @@ impl PddbOs { self.spinor .patch( unsafe { self.pddb_mr.as_slice() }, - xous::PDDB_LOC, + PDDB_A_LOC, data, self.mbbb_phys_base.as_u32() + offset, ) @@ -551,7 +540,7 @@ impl PddbOs { self.spinor .patch( unsafe { self.pddb_mr.as_slice() }, - xous::PDDB_LOC, + PDDB_A_LOC, data, self.fscb_phys_base.as_u32() + offset, ) @@ -807,7 +796,10 @@ impl PddbOs { } #[cfg(feature = "gen2")] - pub(crate) fn ensure_password(&self) -> PasswordState { self.rootkeys.ensure_password() } + pub(crate) fn ensure_password(&mut self) -> PasswordState { + self.rootkeys.ensure_password(); + self.try_login() + } pub(crate) fn try_login(&mut self) -> PasswordState { use aes::cipher::KeyInit; @@ -2098,27 +2090,27 @@ impl PddbOs { modals .start_progress( t!("pddb.erase", locales::LANG), - xous::PDDB_LOC, - xous::PDDB_LOC + PDDB_A_LEN as u32, - xous::PDDB_LOC, + PDDB_A_LOC, + PDDB_A_LOC + PDDB_A_LEN as u32, + PDDB_A_LOC, ) .expect("couldn't raise progress bar"); // retain this delay, because the next section is so compute-intensive, it may take a // while for the GAM to catch up. self.tt.sleep_ms(100).unwrap(); } - for offset in (xous::PDDB_LOC..(xous::PDDB_LOC + PDDB_A_LEN as u32)) - .step_by(SPINOR_BULK_ERASE_SIZE as usize) + for offset in + (PDDB_A_LOC..(PDDB_A_LOC + PDDB_A_LEN as u32)).step_by(SPINOR_BULK_ERASE_SIZE as usize) { if (offset / SPINOR_BULK_ERASE_SIZE) % 4 == 0 { - log::info!("Initial erase: {}/{}", offset - xous::PDDB_LOC, PDDB_A_LEN as u32); + log::info!("Initial erase: {}/{}", offset - PDDB_A_LOC, PDDB_A_LEN as u32); if let Some(modals) = progress { modals.update_progress(offset as u32).expect("couldn't update progress bar"); } } // do a blank check first to see if the sector really needs erasing let mut blank = true; - let slice_start = (offset - xous::PDDB_LOC) as usize / size_of::(); + let slice_start = (offset - PDDB_A_LOC) as usize / size_of::(); for word in unsafe { self.pddb_mr.as_slice::() [slice_start..slice_start + SPINOR_BULK_ERASE_SIZE as usize / size_of::()] @@ -2134,9 +2126,7 @@ impl PddbOs { } } if let Some(modals) = progress { - modals - .update_progress(xous::PDDB_LOC + PDDB_A_LEN as u32) - .expect("couldn't update progress bar"); + modals.update_progress(PDDB_A_LOC + PDDB_A_LEN as u32).expect("couldn't update progress bar"); modals.finish_progress().expect("couldn't dismiss progress bar"); #[cfg(feature = "ux-swap-delay")] self.tt.sleep_ms(100).unwrap(); @@ -2332,7 +2322,7 @@ impl PddbOs { } } self.spinor - .patch(unsafe { self.pddb_mr.as_slice() }, xous::PDDB_LOC, &temp, offset as u32) + .patch(unsafe { self.pddb_mr.as_slice() }, PDDB_A_LOC, &temp, offset as u32) .expect("couldn't fill in disk with random datax"); } if let Some(modals) = progress { @@ -2503,7 +2493,7 @@ impl PddbOs { self.spinor .patch( unsafe { self.pddb_mr.as_slice() }, - xous::PDDB_LOC, + PDDB_A_LOC, &mbbb, self.pt_phys_base.as_u32() + erased_offset, ) @@ -3087,7 +3077,7 @@ impl PddbOs { pub(crate) fn pddb_get_all_keys<'a>( &'a self, cache: &'a Vec, - _op: GetKeyOp, + // _op: GetKeyOp, ) -> Option> { // populate the "known" entries let mut ret = Vec::<(BasisKeys, String)>::new(); @@ -3240,7 +3230,7 @@ impl PddbOs { self.spinor .patch( self.pddb_mr.as_slice(), - xous::PDDB_LOC, + PDDB_A_LOC, &page, self.pt_phys_base.as_u32() + (page_index * PAGE_SIZE) as u32, ) diff --git a/services/pddb/src/backend/pagetable.rs b/services/pddb/src/backend/pagetable.rs index c8294d896..0c954e435 100644 --- a/services/pddb/src/backend/pagetable.rs +++ b/services/pddb/src/backend/pagetable.rs @@ -150,7 +150,7 @@ impl DerefMut for Pte { pub const PDDB_SIZE_PAGES: usize = crate::PDDB_A_LEN as usize / PAGE_SIZE; /// This structure is mapped into the top of FLASH memory, starting at -/// xous::PDDB_LOC. This actually slightly over-sizes the page table, +/// PDDB_A_LOC. This actually slightly over-sizes the page table, /// because the page table does not map the locations for the page table /// itself, the MBBB, or the FSCB. However, the 0th entry of the page table /// always corresponds to the base of data in FLASH, which means the excess diff --git a/services/pddb/src/backend/trngpool.rs b/services/pddb/src/backend/trngpool.rs index 8ccf1499a..74a9d4830 100644 --- a/services/pddb/src/backend/trngpool.rs +++ b/services/pddb/src/backend/trngpool.rs @@ -3,7 +3,7 @@ use core::mem::size_of; use std::convert::TryInto; use aes_gcm_siv::Nonce; -#[cfg(feature = "cramium-hal")] +#[cfg(all(feature = "cramium-hal", not(feature = "hosted-baosec")))] use cram_hal_service::trng::Trng; #[cfg(feature = "hosted-baosec")] use cramium_emu::trng::Trng; From 58f20057b4b163752ceeed7ba1c8604b5dd61146 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 10 May 2025 08:22:38 +0800 Subject: [PATCH 10/10] update strategy --- services/pddb/src/main.rs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index 818a7a66e..8247604dc 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -371,7 +371,7 @@ extern crate bitfield; -[x] Rewrite pddb to use 'keystore' server instead of rootkeys/modals/ux integrations. -[x] Fill in 'keystore' server for hosted mode emulation -[x] Make a simple PDDB test in the baosec console app - -[ ] Fix the bugs in hosted mode + -[x] Fix the bugs in hosted mode -[ ] Rewrite xous-swapper/swap layer to understand virtual pages mapped to SPI flash (see notes below) -[ ] Fix the bugs in real hardware @@ -395,7 +395,7 @@ extern crate bitfield; If the virtual address is in the magic range for SPINOR, the contents are fetched using the SPINOR interface based on the linear mapping of the lower bits of the address onto the SPINOR memory space. - - WHnever a write happens inside Xous-Swapper to a location in FLASH, the page table entry for + - Whenever a write happens inside Xous-Swapper to a location in FLASH, the page table entry for the mapped FLASH location needs to be marked as invalid and returned to the free pool. This uses the swap system to keep the read-view of FLASH in sync with hte write-view. This also means that Xous-Swapper's SPINOR map has to keep a scoreboard of what pages are mapped to @@ -405,6 +405,29 @@ extern crate bitfield; tries to map the SPINOR and read some contents out, and perhaps update a sector. This will exercise the path in isolation and allow us to test this routine as a separate primitive from the PDDB. + + - Development takes an incremental strategy: + 1. Write the code that maps the proposed space with the proposed flags; need to implement + (a) "swap" flag which indicates the page is allocated in VM but not physically; and + (b) also make sure that the "dirty" flag is implemented correctly as it will actually + take on meaning for flushing pages to SPINOR + 2. implement the kernel hooks to catch it, and test that + 3. Attempt a read on the space, show the page fault, and hand-off to the swapper + 4. implement the swapper hardware read interface + 5. test reading to a range of data + 6. implement the swapper *write* interface (with "patching" of unaligned writes) + 7. add SwapOp to sync an in-memory page to FLASH + 8. implement flush-on-release semantics for in-memory flash pages + 9. test writing to a ranges of data (aligned, unaligned) + 10. redo the 10 instances of spinor.patch() in pddb/backend/hw.rs to use straight-up + page writes as the method for writing. If we always sync after write, we can skip 11. + 11. add swap flush call to the sync() method in PDDB + + The merit of sync after write is we reduce the chance of inconsistent device state + on power loss. The downside is we end up writing a lot more? on the other hand, + writes aren't *that* common in this implementation, we may update a key record with + a timestamp every time it's accessed. Anyways, keep it flexible, I think this is + something we can tune later. */ extern crate bitflags;