move the AV trng into the BIO subsystem

this also removes the board-specific hacks that track BIO usage
for the TRNG as set up by the loader
This commit is contained in:
bunnie 2026-01-05 21:54:30 +08:00
parent dd18ddf97c
commit 92180af349
5 changed files with 25 additions and 115 deletions

View file

@ -18,12 +18,7 @@ log = "0.4.14"
xous-api-susres = "0.9.67"
bao1x-hal = { path = "../../libs/bao1x-hal", default-features = false }
bao1x-api = { path = "../../libs/bao1x-api", features = ["derive-rkyv", "std"] }
# xous-pl230 = { path = "../../libs/xous-pl230", features = ["bao1x"] }
xous-bio-bdma = { path = "../../libs/xous-bio-bdma", default-features = false, features = [
"bao1x",
"bio-mul",
"std",
] }
bio-lib = { path = "../../libs/bio-lib" }
# I'm not entirely in love with the aborted attempt to use flatipc in Xous, but we use
# this because it makes the API backward-compatible with older Xous code.
flatipc = { path = "../../libs/flatipc" }

View file

@ -1,7 +1,5 @@
mod api;
mod servers;
#[cfg(feature = "board-baosec")]
use std::sync::{Arc, Mutex};
use bao1x_api::*;
use bao1x_hal::{iox::Iox, udma::GlobalConfig};
@ -275,21 +273,13 @@ fn main() {
servers::susres::start_susres_service();
// claim BIO
#[cfg(feature = "board-baosec")]
let bio_ss = Arc::new(Mutex::new(xous_bio_bdma::BioSharedState::new()));
#[cfg(feature = "board-baosec")]
bio_ss.lock().unwrap().init();
// setup TRNG server - baosec only because it has an external AV generator
#[cfg(feature = "board-baosec")]
servers::trng::start_trng_service(&bio_ss);
#[cfg(feature = "board-dabao")]
servers::trng::start_trng_service();
servers::rtc::start_rtc_service();
// TODO: implement a method to fetch the clock setting from susres and put it into here!
servers::bio::start_bio_service(bao1x_hal::board::DEFAULT_FCLK_FREQUENCY);
// claim BIO, based on the platform
servers::trng::start_trng_service();
servers::rtc::start_rtc_service();
let mut msg_opt = None;
log::debug!("Starting main loop");
loop {

View file

@ -1,55 +1,23 @@
use core::sync::atomic::{AtomicU32, Ordering};
use std::cell::RefCell;
use std::sync::{Arc, Mutex};
use bao1x_hal_service::trng::api;
use bio_lib::av_trng::AvTrng;
use rand_chacha::ChaCha8Rng;
// the 0.5.1 API is necessary for compatibility with curve25519-dalek crates
use rand_core::{CryptoRng, RngCore, SeedableRng};
use utralib::*;
use xous_bio_bdma::*;
const RESEED_INTERVAL: u32 = 128;
static RESEED: AtomicU32 = AtomicU32::new(0);
const BITS_PER_SAMPLE: usize = 4;
pub struct HwTrng {
csprng: RefCell<rand_chacha::ChaCha8Rng>,
bio_ss: Arc<Mutex<BioSharedState>>,
av_trng: AvTrng,
}
impl HwTrng {
pub fn new(bio_ss_guarded: Arc<Mutex<BioSharedState>>) -> Self {
pub fn new(mut av_trng: AvTrng) -> Self {
let mut seed = [0u8; 32];
{
let mut bio_ss = bio_ss_guarded.lock().unwrap();
let tt = ticktimer::Ticktimer::new().unwrap();
let iox = crate::iox::IoxHal::new();
let trng_pin = bao1x_hal::board::setup_trng_input_pin(&iox);
let trng_power = bao1x_hal::board::setup_trng_power_pin(&iox);
iox.set_gpio_pin_value(trng_power.0, trng_power.1, bao1x_api::IoxValue::High);
tt.sleep_ms(50).ok(); // wait for power to stabilize on the avalanche generator
// avalanche generator TRNG - maybe replace this with a proper API call once this has
// been baked into something a little friendlier/easier to maintain?
// stop all the machines, so that code can be loaded
bio_ss.bio.wo(utra::bio_bdma::SFR_CTRL, 0x0);
bio_ss.load_code(avtrng_bio_code(), 0, BioCore::Core0);
// don't use QDIV
bio_ss.bio.wo(utra::bio_bdma::SFR_QDIV0, 0x1_0001);
// use extclock on channel 0, tied to the trng pin
bio_ss.bio.wo(
utra::bio_bdma::SFR_EXTCLOCK,
bio_ss.bio.ms(utra::bio_bdma::SFR_EXTCLOCK_USE_EXTCLK, 0b0001)
| bio_ss.bio.ms(utra::bio_bdma::SFR_EXTCLOCK_EXTCLK_GPIO_0, trng_pin as u32),
);
// start the machine
bio_ss.set_core_run_states([true, false, false, false]);
bio_ss.bio.wo(utra::bio_bdma::SFR_TXF0, trng_pin as u32); // start the sampling
// server_id is a random number from the hardware entropy pool. Note that this
// has already been conditioned and whitened, so we can use it directly.
let seed_l = xous::create_server_id().unwrap().to_array();
@ -66,25 +34,17 @@ impl HwTrng {
}
// add AV TRNG data
let mut raw32 = 0;
for s in seed.chunks_mut(4) {
for _ in 0..(size_of::<u32>() * 8) / BITS_PER_SAMPLE {
// wait for the next interval to arrive
while bio_ss.bio.rf(utra::bio_bdma::SFR_FLEVEL_PCLK_REGFIFO_LEVEL0) == 0 {}
let raw = bio_ss.bio.r(utra::bio_bdma::SFR_RXF0);
raw32 <<= BITS_PER_SAMPLE;
// shift right by one because bit 0 always samples as 0, due to instruction timing
raw32 |= (raw >> 1) & ((1 << BITS_PER_SAMPLE) - 1)
}
let raw32 = av_trng.get_u32();
for (s_byte, &av_byte) in s.iter_mut().zip(raw32.to_le_bytes().iter()) {
*s_byte ^= av_byte;
}
}
}
HwTrng { csprng: RefCell::new(ChaCha8Rng::from_seed(seed)), bio_ss: bio_ss_guarded }
HwTrng { csprng: RefCell::new(ChaCha8Rng::from_seed(seed)), av_trng }
}
fn reseed(&self) {
fn reseed(&mut self) {
let reseed_ctr = match RESEED.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)) {
Ok(x) => x,
Err(x) => x,
@ -110,17 +70,8 @@ impl HwTrng {
}
}
// add AV TRNG data
let mut raw32 = 0;
let bio_ss = self.bio_ss.lock().unwrap();
for s in seed.chunks_mut(4) {
for _ in 0..(size_of::<u32>() * 8) / BITS_PER_SAMPLE {
// wait for the next interval to arrive
while bio_ss.bio.rf(utra::bio_bdma::SFR_FLEVEL_PCLK_REGFIFO_LEVEL0) == 0 {}
let raw = bio_ss.bio.r(utra::bio_bdma::SFR_RXF0);
raw32 <<= BITS_PER_SAMPLE;
// shift right by one because bit 0 always samples as 0, due to instruction timing
raw32 |= (raw >> 1) & ((1 << BITS_PER_SAMPLE) - 1)
}
let raw32 = self.av_trng.get_u32();
for (s_byte, &av_byte) in s.iter_mut().zip(raw32.to_ne_bytes().iter()) {
*s_byte ^= av_byte;
}
@ -129,17 +80,17 @@ impl HwTrng {
}
}
pub fn get_u32(&self) -> Result<u32, xous::Error> {
pub fn get_u32(&mut self) -> Result<u32, xous::Error> {
self.reseed();
Ok(self.csprng.borrow_mut().next_u32())
}
pub fn get_u64(&self) -> Result<u64, xous::Error> {
pub fn get_u64(&mut self) -> Result<u64, xous::Error> {
self.reseed();
Ok(self.csprng.borrow_mut().next_u64())
}
pub fn fill_buf(&self, data: &mut [u32]) -> Result<(), xous::Error> {
pub fn fill_buf(&mut self, data: &mut [u32]) -> Result<(), xous::Error> {
for d in data.iter_mut() {
*d = self.get_u32()?;
}
@ -187,16 +138,3 @@ impl RngCore for HwTrng {
}
impl CryptoRng for HwTrng {}
#[rustfmt::skip]
bio_code!(avtrng_bio_code, BM_AVTRNG_BIO_START, BM_AVTRNG_BIO_END,
"mv x1, x16", // get pin for trng input
"li x2, 1",
"sll x1, x2, x1", // shift the pin into a bitmask
"mv x25, x1", // make it an input
"10:",
"mv x20, x0", // wait for quantum: this time, the toggle from the TRNG
"mv x1, x31", // remember aclk time
"mv x16, x1", // save result to FIFO
"j 10b" // and do it again
);

View file

@ -16,16 +16,6 @@ fn bio_service(clk_freq: u32) {
let mut resource_tracker = ResourceTracker::new();
let mut bio_ss = bio_hw::BioSharedState::new(clk_freq);
// on baosec platforms, the TRNG occupies core0 and FIFO0. Mark these resources as used.
// The setup of the TRNG BIO application happened in the bootloader, so we just need to
// mark the resources as taken here.
#[cfg(feature = "board-baosec")]
{
bio_ss.handle_used = [true, false, false, false];
bio_ss.core_config =
[Some(CoreConfig { clock_mode: ClockMode::FixedDivider(1, 0) }), None, None, None];
resource_tracker.reserve_boot_resources("TRNG", Some(BioCore::Core0), Some(Fifo::Fifo0));
}
let mut msg_opt = None;
loop {
xous::reply_and_receive_next(sid, &mut msg_opt).unwrap();

View file

@ -1,6 +1,4 @@
#[cfg(feature = "board-baosec")]
use std::sync::{Arc, Mutex};
use bao1x_api::bio::IoConfigMode;
#[cfg(feature = "board-dabao")]
use bao1x_hal_service::trng::Trng;
use bao1x_hal_service::trng::api;
@ -9,12 +7,8 @@ use num_traits::*;
#[cfg(feature = "board-baosec")]
use rand::RngCore;
use xous::CID;
#[cfg(feature = "board-baosec")]
use xous_bio_bdma::BioSharedState;
use xous_ipc::Buffer;
#[cfg(feature = "board-baosec")]
use crate::servers::baosec_hw::HwTrng;
#[derive(Copy, Clone, Debug)]
#[allow(dead_code)]
struct ScalarCallback {
@ -24,21 +18,24 @@ struct ScalarCallback {
}
#[cfg(feature = "board-baosec")]
pub fn start_trng_service(bio_ss: &Arc<Mutex<BioSharedState>>) {
pub fn start_trng_service() {
std::thread::spawn({
let bio_ss = bio_ss.clone();
move || {
trng_service(bio_ss);
trng_service();
}
});
}
#[cfg(feature = "board-baosec")]
fn trng_service(bio_ss: Arc<Mutex<BioSharedState>>) -> ! {
fn trng_service() -> ! {
let xns = xous_names::XousNames::new().unwrap();
// unlimited connections allowed, anyone including less-trusted processes can get a random number
let trng_sid = xns.register_name(api::SERVER_NAME_TRNG, None).expect("can't register server");
let mut trng = Box::new(HwTrng::new(bio_ss));
let iox = bao1x_api::IoxHal::new();
let power = bao1x_hal::board::setup_trng_power_pin(&iox);
let data = bao1x_hal::board::setup_trng_input_pin(&iox);
let av_trng = bio_lib::av_trng::AvTrng::new(data, power, Some(IoConfigMode::Overwrite)).unwrap();
let mut trng = crate::servers::baosec_hw::HwTrng::new(av_trng);
let mut error_cb_conns = Vec::<ScalarCallback>::new();