enable trng server in dabao mode

this allows the rand core crates to work
This commit is contained in:
bunnie 2025-11-02 10:37:47 +08:00
parent 9d3da626f2
commit ed94245a5c
5 changed files with 149 additions and 74 deletions

View file

@ -265,6 +265,8 @@ fn main() {
// 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();
let mut msg_opt = None;
log::debug!("Starting main loop");

View file

@ -3,5 +3,4 @@ pub mod keyboard;
// TRNG server is only needed for baosec; dabao can cheat and use the kernel TRNG port
#[cfg(feature = "board-baosec")]
mod baosec_hw;
#[cfg(feature = "board-baosec")]
pub mod trng; // not public - for internal use only

View file

@ -1,22 +1,29 @@
#[cfg(feature = "board-baosec")]
use std::sync::{Arc, Mutex};
#[cfg(feature = "board-dabao")]
use bao1x_hal_service::trng::Trng;
use bao1x_hal_service::trng::api;
use flatipc::Ipc;
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 {
server_to_cb_cid: CID,
cb_to_client_cid: CID,
cb_to_client_id: u32,
}
#[cfg(feature = "board-baosec")]
pub fn start_trng_service(bio_ss: &Arc<Mutex<BioSharedState>>) {
std::thread::spawn({
let bio_ss = bio_ss.clone();
@ -25,7 +32,7 @@ pub fn start_trng_service(bio_ss: &Arc<Mutex<BioSharedState>>) {
}
});
}
#[cfg(feature = "board-baosec")]
fn trng_service(bio_ss: Arc<Mutex<BioSharedState>>) -> ! {
let xns = xous_names::XousNames::new().unwrap();
// unlimited connections allowed, anyone including less-trusted processes can get a random number
@ -83,6 +90,70 @@ fn trng_service(bio_ss: Arc<Mutex<BioSharedState>>) -> ! {
}
}
#[cfg(feature = "board-dabao")]
pub fn start_trng_service() {
std::thread::spawn({
move || {
trng_service();
}
});
}
#[cfg(feature = "board-dabao")]
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 trng = Trng::new(&xns).unwrap();
let mut error_cb_conns = Vec::<ScalarCallback>::new();
loop {
let mut msg = xous::receive_message(trng_sid).unwrap();
let op: Option<api::Opcode> = FromPrimitive::from_usize(msg.body.id());
log::debug!("{:?}", op);
match op {
Some(api::Opcode::GetTrng) => xous::msg_blocking_scalar_unpack!(msg, count, _, _, _, {
if count == 1 {
xous::return_scalar2(msg.sender, trng.get_u32().unwrap() as usize, 0xdead_beef)
.expect("couldn't return GetTrng request");
} else {
xous::return_scalar2(
msg.sender,
trng.get_u32().unwrap() as usize,
trng.get_u32().unwrap() as usize,
)
.expect("couldn't return GetTrng request");
}
}),
Some(api::Opcode::ErrorSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<api::ScalarHook, _>().unwrap();
do_hook(hookdata, &mut error_cb_conns);
}
Some(api::Opcode::ErrorNotification) => {
unimplemented!()
}
Some(api::Opcode::HealthStats) => {
unimplemented!()
}
Some(api::Opcode::ErrorStats) => {
unimplemented!()
}
Some(api::Opcode::FillTrng) => {
let mm = msg.body.memory_message_mut().unwrap();
let buffer =
api::IpcTrngBuf::from_memory_message_mut(mm).expect("couldn't unpack FillTrng buffer");
let len = buffer.len as usize;
trng.fill_buf(&mut buffer.data[..len]).expect("couldn't fill TRNG buffer");
}
None => {
log::error!("couldn't convert opcode, ignoring");
}
}
}
}
fn do_hook(hookdata: api::ScalarHook, cb_conns: &mut Vec<ScalarCallback>) {
let (s0, s1, s2, s3) = hookdata.sid;
let sid = xous::SID::from_u32(s0, s1, s2, s3);
@ -106,6 +177,7 @@ fn unhook(cb_conns: &mut Vec<ScalarCallback>) {
}
}
}
#[allow(dead_code)]
fn send_event(cb_conns: &Vec<ScalarCallback>) {
for scb in cb_conns.iter() {
// note that the "which" argument is only used for GPIO events, to indicate which pin had the

View file

@ -19,6 +19,8 @@ use rand_core::{CryptoRng, RngCore};
use xous::{CID, send_message};
use xous_ipc::Buffer;
use crate::trng::api;
pub struct Trng {
conn: CID,
error_sid: Option<xous::SID>,
@ -240,74 +242,3 @@ fn error_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
}
xous::destroy_server(sid).unwrap();
}
pub mod api {
pub const SERVER_NAME_TRNG: &str = "_TRNG manager_"; // depended upon by getrandom, do not change
/// These opcode numbers are partially baked into the `getrandom` library --
/// which kind of acts as a `std`-lib-ish style interface for the trng, so,
/// by design it can't have a dependency on this crate :-/
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
pub enum Opcode {
/// Get one or two 32-bit words of TRNG data
GetTrng = 0,
/// Fill a buffer with random data
FillTrng = 1,
/// Notification of an error from the interrupt handler
ErrorNotification = 3,
/// Subscribe to error notifications
ErrorSubscribe = 4,
/// Get TRNG health stats
HealthStats = 5,
/// Get Error stats
ErrorStats = 6,
}
#[derive(Debug, flatipc::Ipc)]
#[allow(dead_code)]
/// Note that this structure is mirrored in imports/getrandom/src/xous.rs
#[repr(C)]
pub struct TrngBuf {
pub data: [u32; 1020],
pub len: u16,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub enum EventCallback {
Event,
Drop,
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub struct ScalarHook {
pub sid: (u32, u32, u32, u32),
pub id: u32, /* ID of the scalar message to send through (e.g. the discriminant of the Enum on the
* caller's side API) */
pub cid: xous::CID, /* caller-side connection ID for the scalar message to route to. Created by
* the caller before hooking. */
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Default)]
pub struct NistTests {
pub adaptive_b: u16,
pub repcount_b: u16,
pub fresh: bool,
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Default)]
pub struct HealthTests {
pub av_nist: NistTests,
pub ro_nist: NistTests,
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Default)]
pub struct TrngErrors {
pub nist_errs: u32,
pub pending_mask: u32,
}
}

View file

@ -6,3 +6,74 @@ pub use baosec::*;
pub mod dabao;
#[cfg(feature = "board-dabao")]
pub use dabao::*;
pub mod api {
pub const SERVER_NAME_TRNG: &str = "_TRNG manager_"; // depended upon by getrandom, do not change
/// These opcode numbers are partially baked into the `getrandom` library --
/// which kind of acts as a `std`-lib-ish style interface for the trng, so,
/// by design it can't have a dependency on this crate :-/
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
pub enum Opcode {
/// Get one or two 32-bit words of TRNG data
GetTrng = 0,
/// Fill a buffer with random data
FillTrng = 1,
/// Notification of an error from the interrupt handler
ErrorNotification = 3,
/// Subscribe to error notifications
ErrorSubscribe = 4,
/// Get TRNG health stats
HealthStats = 5,
/// Get Error stats
ErrorStats = 6,
}
#[derive(Debug, flatipc::Ipc)]
#[allow(dead_code)]
/// Note that this structure is mirrored in imports/getrandom/src/xous.rs
#[repr(C)]
pub struct TrngBuf {
pub data: [u32; 1020],
pub len: u16,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub enum EventCallback {
Event,
Drop,
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub struct ScalarHook {
pub sid: (u32, u32, u32, u32),
pub id: u32, /* ID of the scalar message to send through (e.g. the discriminant of the Enum on the
* caller's side API) */
pub cid: xous::CID, /* caller-side connection ID for the scalar message to route to. Created by
* the caller before hooking. */
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Default)]
pub struct NistTests {
pub adaptive_b: u16,
pub repcount_b: u16,
pub fresh: bool,
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Default)]
pub struct HealthTests {
pub av_nist: NistTests,
pub ro_nist: NistTests,
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Default)]
pub struct TrngErrors {
pub nist_errs: u32,
pub pending_mask: u32,
}
}