Merge pull request #743 from betrusted-io/vault-ci-fixups

Progress on vault
This commit is contained in:
bunnie 2025-11-26 15:07:57 +01:00 committed by GitHub
commit c4312f44f8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
24 changed files with 2314 additions and 904 deletions

3
Cargo.lock generated
View file

@ -499,9 +499,12 @@ dependencies = [
name = "bao1x-hal-service"
version = "0.1.0"
dependencies = [
"arbitrary-int",
"bao1x-api",
"bao1x-hal",
"bitbybit",
"bitfield",
"bytemuck",
"flatipc",
"flatipc-derive",
"log",

View file

@ -5,11 +5,19 @@ Baochip-based boards use the `bao1x` SoC. There are two boards supported out-of-
- `dabao` is a minimal SoM-style breakout board. Basically just the chip on a board.
- `baosec` is a hardware security token. It features a camera, display, external memory, buttons, and a supplemental hardware TRNG.
The build idiom is `cargo xtask <target>`, i.e. `cargo xtask dabao`. The build will generate a [`UF2`](https://makecode.com/blog/one-chip-to-flash-them-all) artifact, which can be found in `target/riscv32imac-unknown-[xous|none]-elf/release/`.
Holding down the `PROG` button while plugging the device into USB will cause it to enter a bootloader that enumerates a mass storage device. The build artifacts can then be copied onto the device. Pressing `PROG` again will cause the device to run the program. Targets also enumerate a serial port over USB, which will activate a debug console.
## Bootloaders
Regardless of the board, the `bao1x` chip comes from the factory programmed with `boot0` and `boot1` stages. The code for these can be found in `bao1x-boot/`.
- `boot0` is a permanent root of trust burned onto the chip. Its sole purpose is to validate `boot1`. See [security model](./README-baochip.md#security-model) for details on the trust chain
- `boot1` contains a USB driver, serial-over-USB driver, and serial driver capable of accepting code updates in the form of .u2f files or serial commands. It also contains a small command terminal for managing configurations, keys, and device lifecycle state.
### Applications
Three application targets are supported by Xous:
- `baremetal` is an unsecured, bare-iron environment. It is `no-std`, but comes with `alloc` pre-initialized and a USB serial console.

View file

@ -17,7 +17,7 @@ The [Xous Book](https://betrusted.io/xous-book/) covers the architecture and str
The [wiki](https://github.com/betrusted-io/betrusted-wiki/wiki) is a community resource that answers many FAQ.
The [Baochip README](./README-baochip.md) is the starting point for Baochip users.
The [Baochip README](./README-baochip.md) is the starting point for Baochip users. `vscode` users may wish to install the `baochip` extension to help manage build & test cycles.
The [Precursor README](./README-precursor.md) is the starting point for Precursor users.

View file

@ -1284,7 +1284,10 @@ impl ActionManager {
let pws = self.pddb.borrow().list_keys(VAULT_PASSWORD_DICT, None).unwrap_or(Vec::new());
if pws.len() < TARGET_ENTRIES_PW {
let extra_count = TARGET_ENTRIES_PW - pws.len();
for _index in 0..extra_count {
for index in 0..extra_count {
if index % 10 == 0 {
log::info!("Creating {}/{} passwords", index + 1, extra_count);
}
let desc = random_pick::pick_multiple_from_slice(&words, &weights, 3);
// this exposes raw unicode and symbols to the sorting list
// let description = format!("{} {} {}", desc[0], desc[1], desc[2]);
@ -1334,7 +1337,8 @@ impl ActionManager {
let totp = self.pddb.borrow().list_keys(VAULT_TOTP_DICT, None).unwrap_or(Vec::new());
if totp.len() < TARGET_ENTRIES {
let extra = TARGET_ENTRIES - totp.len();
for _index in 0..extra {
for index in 0..extra {
log::info!("Creating {}/{} TOTP records", index + 1, extra);
let names = random_pick::pick_multiple_from_slice(&words, &weights, 3);
let name = format!("{} {} {}", names[0], names[1], names[2]);
let notes = random_pick::pick_from_slice(&words, &weights).unwrap().to_string();
@ -1375,9 +1379,11 @@ impl ActionManager {
Err(e) => log::error!("PW Error: {:?}", e),
};
}
log::info!("Done creating entries, syncing DB...");
self.modals.dynamic_notification_update(Some("Syncing PDDB..."), None).ok();
self.pddb.borrow().sync().ok();
self.modals.dynamic_notification_close().ok();
log::info!("~~fin~~");
}
fn report_err<T: std::fmt::Debug>(&self, note: &str, e: Option<T>) {

View file

@ -148,6 +148,7 @@ fn main() -> ! {
log::info!("Vault2 PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap();
let tt = ticktimer_server::Ticktimer::new().unwrap();
// Register the server with xous
let sid = xns.register_name(SERVER_NAME_VAULT2, None).expect("can't register server");
@ -388,6 +389,11 @@ fn main() -> ! {
let modals = modals::Modals::new(&xns).unwrap();
vault_ui.apply_glyph_style();
// give the system a second to stabilize, then try to mount
tt.sleep_ms(1000).ok();
let pddb = pddb::Pddb::new();
pddb.try_mount();
// reload the database
xous::send_message(
actions_conn,
@ -480,7 +486,7 @@ fn main() -> ! {
vault_ui.redraw();
}
_ => {
log::info!("unhandled key {}", k);
log::debug!("unhandled key {}", k);
}
}
}

View file

@ -179,7 +179,7 @@ pub(crate) fn pumper(
{
// we really want mode.lock() to be in a different scope so...
if mode_cache == VaultMode::Totp {
tt.sleep_ms(50).unwrap();
tt.sleep_ms(250).unwrap();
send_message(
self_conn,
Message::new_scalar(PumpOp::Pump.to_usize().unwrap(), 0, 0, 0, 0),

View file

@ -100,6 +100,7 @@ impl VaultUi {
.set_margin(TotpLayout::totp_margin())
.pane_size(TotpLayout::list_box())
.style(TotpLayout::list_font());
totp_list.set_autoflush(false);
let gfx = Gfx::new(&xns).unwrap();
let style = DEFAULT_FONT;
@ -258,9 +259,10 @@ impl VaultUi {
self.totp_list.draw(TotpLayout::timer_box().br().y);
// draw the timer element
let mut object_list = ObjectList::new();
let mut timer_box = TotpLayout::timer_box();
timer_box.style = DrawStyle::new(PixelColor::Dark, PixelColor::Light, 1);
self.gfx.draw_rectangle(timer_box).ok();
object_list.push(ClipObjectType::Rect(timer_box)).unwrap();
// draw the duration bar
let current_time = std::time::SystemTime::now()
@ -281,7 +283,8 @@ impl VaultUi {
let delta_width = (delta * width * 128) / (30 * 128 * 1000);
timer_remaining.br = Point::new(width - delta_width, timer_remaining.br().y);
timer_remaining.style = DrawStyle::new(PixelColor::Light, PixelColor::Light, 1);
self.gfx.draw_rectangle(timer_remaining).ok();
object_list.push(ClipObjectType::Rect(timer_remaining)).unwrap();
self.gfx.draw_object_list(object_list).unwrap();
}
VaultMode::Password => {
/*

View file

@ -108,3 +108,18 @@ impl StaticsInRom {
unsafe { core::slice::from_raw_parts(self as *const Self as *const u8, core::mem::size_of::<Self>()) }
}
}
/// Structure for recording message formats to be passed from interrupt handlers back to userspace.
/// A specific handler may or may not use any or all of the arguments: this simply provides storage
/// for all the possible arguments.
#[derive(Copy, Clone)]
pub struct IrqNotification {
/// Specifies the bit position of the event in the irq bank
pub bit: arbitrary_int::u4,
/// Connection to send notifications to
pub conn: xous::CID,
/// Opcode argument for the notification
pub opcode: usize,
/// Up to four arguments to be passed on
pub args: [usize; 4],
}

View file

@ -21,9 +21,6 @@ pub const IFR_LEN: usize = 0x400;
/// It contains the lot ID, wafer ID, and wafer x/y position of the die.
pub const IFR_CP_ID_BASE: usize = 0x6040_00A0;
pub const AO_BU_MEM: usize = 0x5030_0000;
pub const AO_BU_MEM_LEN: usize = 0x4000;
#[bitfield(u32)]
#[derive(PartialEq, Eq, Debug)]
pub struct DataSlotAccess {

View file

@ -312,14 +312,46 @@ pub fn setup_kb_pins<T: IoSetup + IoGpio>(iox: &T) -> ([(IoxPort, u8); 2], [(Iox
)
}
pub fn setup_kpc_pins<T: IoSetup + IoGpio>(iox: &T) -> ([(IoxPort, u8); 2], [(IoxPort, u8); 3]) {
for r in R_PINS {
iox.setup_pin(
KB_PORT,
r,
Some(IoxDir::Input),
Some(IoxFunction::AF1),
None,
None,
Some(IoxEnable::Enable),
Some(IoxDriveStrength::Drive2mA),
);
}
for c in C_PINS {
iox.setup_pin(
KB_PORT,
c,
Some(IoxDir::Input),
Some(IoxFunction::AF1),
Some(IoxEnable::Enable),
None,
Some(IoxEnable::Enable),
Some(IoxDriveStrength::Drive2mA),
);
}
(
[(KB_PORT, R_PINS[0]), (KB_PORT, R_PINS[1])],
[(KB_PORT, C_PINS[0]), (KB_PORT, C_PINS[1]), (KB_PORT, C_PINS[2])],
)
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum KeyPress {
Up,
Select,
Down,
Left,
Center,
Right,
Select,
Home,
Invalid,
None,
}
@ -340,7 +372,7 @@ pub fn scan_keyboard<T: IoSetup + IoGpio>(
if key_press_index < key_presses.len() {
key_presses[key_press_index] = match (row, col) {
(1, 3) => KeyPress::Left,
(1, 2) => KeyPress::Home,
(1, 2) => KeyPress::Center,
(1, 0) => KeyPress::Right,
(0, 0) => KeyPress::Down,
(0, 2) => KeyPress::Up,
@ -356,6 +388,64 @@ pub fn scan_keyboard<T: IoSetup + IoGpio>(
key_presses
}
// key: sr1 & 0xFF | sr0 & 0xFF
// -- must read sr0 to pick up multiple key hit --
// down: 0x10 | 0xfffe 1111_1110
// select: 0x11 | 0xfffd 1111_1101 (press in on jog dial)
// up: 0x12 | 0xfffb 1111_1011
// right: 0x14 | 0xffef 1110_1111
// left: 0x15 | 0xffdf 1101_1111
// center: 0x16 | 0xffbf 1011_1111
/// SR0 will contain the current raw status of all the keys and the interrupt
/// system will continue to notify us that an event is happening until all keys
/// are released.
///
/// This maps the output of the "polled" raw event register (SR0) to `KeyPress`
/// Multiple keys can be encoded in this.
pub fn kpc_sr0_to_key(raw_event: u32) -> [KeyPress; 4] {
let mut key_presses: [KeyPress; 4] = [KeyPress::None; 4];
let mut key_press_index = 0;
let masked = raw_event & 0x7F;
for position in 0..7 {
if (masked & (1 << position)) == 0 {
let kp_candidate = match position {
0 => KeyPress::Down,
1 => KeyPress::Select,
2 => KeyPress::Up,
4 => KeyPress::Right,
5 => KeyPress::Left,
6 => KeyPress::Center,
_ => KeyPress::Invalid,
};
if kp_candidate != KeyPress::Invalid && key_press_index < key_presses.len() {
key_presses[key_press_index] = kp_candidate;
key_press_index += 1;
}
}
}
key_presses
}
/// SR1 outputs a single event every time a key is pressed. Thus it is a KeyDown
/// indicator.
///
/// This maps the output of the "keydown" event register (SR1) to `KeyPress`
/// only one keydown seems to ever be encoded in this, or at least, it can't
/// effectively differentiate multiple simultaneous keypresses due to its coding.
pub fn kpc_sr1_to_key(raw_event: u32) -> KeyPress {
let masked = raw_event & 0xFF;
match masked {
0x10 => KeyPress::Down,
0x11 => KeyPress::Select,
0x12 => KeyPress::Up,
0x14 => KeyPress::Right,
0x15 => KeyPress::Left,
0x16 => KeyPress::Center,
_ => KeyPress::Invalid,
}
}
pub fn setup_pmic_irq<T: IoIrq>(iox: &T, server: &str, opcode: usize) {
iox.set_irq_pin(IoxPort::PB, 15, IoxValue::Low, server, opcode);
}

View file

@ -25,9 +25,8 @@ impl BackupManager {
)
.unwrap()
};
let bu_ram = unsafe {
xous::MemoryRange::new(bao1x_api::offsets::AO_BU_MEM, bao1x_api::offsets::AO_BU_MEM_LEN).unwrap()
};
let bu_ram =
unsafe { xous::MemoryRange::new(utralib::HW_AORAM_MEM, utralib::HW_AORAM_MEM_LEN).unwrap() };
BackupManager { bu_reg, bu_ram }
}
@ -36,15 +35,15 @@ impl BackupManager {
let bu_reg = xous::map_memory(
xous::MemoryAddress::new(utralib::utra::aobureg::HW_AOBUREG_BASE),
None,
utralib::utra::aobureg::AOBUREG_NUMREGS * size_of::<u32>(),
4096,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map backup register range");
let bu_ram = xous::map_memory(
xous::MemoryAddress::new(bao1x_api::offsets::AO_BU_MEM),
xous::MemoryAddress::new(utralib::HW_AORAM_MEM),
None,
bao1x_api::offsets::AO_BU_MEM_LEN,
utralib::HW_AORAM_MEM_LEN,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("couldn't map backup RAM range");
@ -54,7 +53,7 @@ impl BackupManager {
pub fn is_backup_valid(&self) -> bool {
let bu_ram_u32: &[u32] = unsafe { self.bu_ram.as_slice() };
let hash = murmur3_32(bu_ram_u32, 0x0);
let bu_reg: &[u32] = unsafe { self.bu_reg.as_slice() };
let bu_reg: &[u32] = &unsafe { self.bu_reg.as_slice() }[..utralib::utra::aobureg::AOBUREG_NUMREGS];
hash == bu_reg[HASH_LOC]
}

View file

@ -0,0 +1,110 @@
use std::pin::Pin;
use arbitrary_int::u4;
use bao1x_api::IrqNotification;
use bitbybit::bitfield;
use utralib::*;
#[bitfield(u32)]
#[derive(PartialEq, Eq, Debug)]
// this is the AOFR register - ao_sysctrl::SFR_AOFR
pub struct AoIntStatus {
#[bit(6, rw)]
ao_pad_in0: bool,
#[bit(5, rw)]
ao_pad_in1: bool,
#[bit(4, rw)]
wakeup_valid: bool,
#[bit(3, rw)]
kpc_interrupt: bool,
#[bit(2, rw)]
timer_interrupt: bool,
#[bit(1, rw)]
rtc_interrupt: bool,
#[bit(0, rw)]
wdt_reset: bool,
}
// Numbers here are relative to the bit position within the IRQ2 register
#[repr(u32)]
pub enum IrqMapping {
// AoWakeup triggers based on either of PI0 or PI1 going low, plus a subset of internal wakeup sources
AoWakeup = 15,
// This is the subset of internal sources
AoInt = 14,
Watchdog = 13,
Timer1 = 12,
Timer0 = 11,
Reram = 22,
Mailbox3 = 5,
Mailbox2 = 4,
Mailbox1 = 3,
Mailbox0 = 2,
Mdma = 1,
Qfc = 0,
}
/// This structure is only available in `std` environment due to the very different
/// way in which interrupts are handled between the two environments.
pub struct KpcAoInt {
pub kpc: CSR<u32>,
pub ao: CSR<u32>,
pub irq: CSR<u32>,
pub args: Vec<IrqNotification>,
enable: u32,
}
impl KpcAoInt {
pub fn new(handler: Option<fn(usize, *mut usize)>) -> Pin<Box<Self>> {
let mem = xous::map_memory(
xous::MemoryAddress::new(utra::dkpc::HW_DKPC_BASE),
None,
4096,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map dkpc range");
let irq = xous::map_memory(
xous::MemoryAddress::new(utra::irqarray2::HW_IRQARRAY2_BASE),
None,
4096,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map irq2 range");
let ao = xous::map_memory(
xous::MemoryAddress::new(utra::ao_sysctrl::HW_AO_SYSCTRL_BASE),
None,
4096,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map ao_sysctrl range");
let mut kpc_aoint = Box::pin(KpcAoInt {
kpc: CSR::new(mem.as_ptr() as *mut u32),
irq: CSR::new(irq.as_ptr() as *mut u32),
ao: CSR::new(ao.as_ptr() as *mut u32),
args: Vec::new(),
enable: 0,
});
if let Some(handler) = handler {
xous::claim_interrupt(
utra::irqarray2::IRQARRAY2_IRQ,
handler,
Pin::as_mut(&mut kpc_aoint).get_mut() as *mut KpcAoInt as *mut usize,
)
.expect("couldn't claim ao/kpc handler interrupt");
}
kpc_aoint
}
/// Adds a notifier to the IRQ stack. Does not also enable the IRQ.
pub fn add_irq_notifier(&mut self, notification: IrqNotification) { self.args.push(notification) }
pub fn modify_irq_ena(&mut self, bit: u4, enable: bool) {
if enable {
self.enable |= 1 << bit.value() as u32;
} else {
self.enable &= !(1 << bit.value() as u32);
}
self.irq.wo(utra::irqarray2::EV_ENABLE, self.enable);
}
}

View file

@ -34,6 +34,8 @@ pub mod acram;
pub mod buram;
#[cfg(not(feature = "hosted-baosec"))]
pub mod coreuser;
#[cfg(all(not(feature = "hosted-baosec"), feature = "std"))]
pub mod kpc_aoint;
#[cfg(not(feature = "hosted-baosec"))]
pub mod mbox;
#[cfg(not(feature = "hosted-baosec"))]

View file

@ -318,7 +318,7 @@ impl Spim {
4096,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("couldn't map serial port");
.expect("couldn't map spim channel");
#[cfg(target_os = "xous")]
let csr = CSR::new(csr_range.as_mut_ptr() as *mut u32);
#[cfg(not(target_os = "xous"))]

View file

@ -60,6 +60,7 @@ pub struct ScrollableList {
/// for some global shared state to lock the UI for a given model which I haven't
/// figured out how to handle any other way.
pub gfx: Gfx,
autoflush: bool,
}
impl Clone for ScrollableList {
@ -104,9 +105,12 @@ impl ScrollableList {
text_alignment: TextAlignment::Left,
pane: RefCell::new(pane),
gfx,
autoflush: true,
}
}
pub fn set_autoflush(&mut self, autoflush: bool) { self.autoflush = autoflush; }
pub fn get_alignment(&self) -> TextAlignment { self.text_alignment }
pub fn set_alignment<'a>(&'a mut self, alignment: TextAlignment) -> &'a mut Self {
@ -507,7 +511,9 @@ impl ScrollableList {
self.gfx.draw_object_list(ol).unwrap();
}
}
self.gfx.flush().unwrap();
if self.autoflush {
self.gfx.flush().unwrap();
}
}
/// Update the scrollable list state based on a key action. Passes on

View file

@ -12,12 +12,12 @@ use crate::{CommonEnv, ShellCmdApi};
pub struct PddbCmd {
pddb: pddb::Pddb,
mounted: bool,
}
impl PddbCmd {
pub fn new() -> Self {
let pddb = pddb::Pddb::new();
log::info!("PDDB mount result: {:?}", pddb.try_mount());
PddbCmd { pddb }
PddbCmd { pddb, mounted: false }
}
}
@ -25,6 +25,11 @@ impl<'a> ShellCmdApi<'a> for PddbCmd {
cmd_api!(pddb);
fn process(&mut self, args: String, _env: &mut CommonEnv) -> Result<Option<String>, xous::Error> {
// lazy-eval this mount
if !self.mounted {
log::info!("PDDB mount result: {:?}", self.pddb.try_mount());
self.mounted = true;
}
let mut ret = String::new();
#[cfg(not(feature = "pddbtest"))]
let helpstring = "pddb [basislist] [basiscreate] [basisunlock] [basislock] [basisdelete] [default]\n[dictlist] [keylist] [write] [writeover] [query] [copy] [dictdelete] [keydelete] [churn] [flush] [sync]";

View file

@ -31,6 +31,10 @@ rand = "0.8.5"
rand_core = "0.6.4"
rand_chacha = "0.3.1"
bitfield = "0.13.2"
# TOODO: migrate from bitfield to bitbybit
bitbybit = "1.4.0"
arbitrary-int = "1.2"
bytemuck = "1.24.0"
num-derive = { version = "0.4.2", default-features = false }
num-traits = { version = "0.2.14", default-features = false }
@ -40,6 +44,7 @@ rkyv = { version = "0.8.8", default-features = false, features = [
] }
[features]
keyboard-testing = []
app-uart = []
rawserial = []
pinger = []

View file

@ -256,7 +256,7 @@ fn main() {
// The index of the array corresponds to the slot.
let mut irq_table: [Option<IrqLocalRegistration>; 8] = [None; 8];
// start keyboard emulator service
#[cfg(feature = "board-baosec")]
servers::keyboard::start_keyboard_service();
// claim BIO

View file

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

View file

@ -1,8 +1,131 @@
use arbitrary_int::{Number, u4};
use bao1x_api::IrqNotification;
use bao1x_api::keyboard::*;
use bao1x_hal::board::KeyPress;
use bao1x_hal::kpc_aoint::{AoIntStatus, KpcAoInt};
use num_traits::*;
use utralib::utra::irqarray2;
use utralib::*;
use xous::{CID, MessageSender, msg_blocking_scalar_unpack, msg_scalar_unpack};
use xous_ipc::Buffer;
const KEYUP_DELAY_MS: u64 = 50;
pub fn handler(_irq_no: usize, arg: *mut usize) {
let kpc_aoint = unsafe { &mut *(arg as *mut KpcAoInt) };
let pending = kpc_aoint.irq.r(irqarray2::EV_PENDING);
// clear all pending interrupts
kpc_aoint.irq.wo(irqarray2::EV_PENDING, pending);
// Note to self: this routine might need augmentation if the interrupt source also
// has to be *disabled*. This would be necessary if the interrupt persists as asserted
// instead of being a pulse, to prevent re-entrant interrupting.
for bit in 0..16u32 {
let mask = 1u32 << bit;
if (pending & mask) != 0 {
for notifier in kpc_aoint.args.iter() {
if notifier.bit.value() as u32 == bit {
xous::try_send_message(
notifier.conn,
xous::Message::new_scalar(
notifier.opcode,
pending as usize,
notifier.args[1],
notifier.args[2],
notifier.args[3],
),
)
.ok();
}
}
}
}
}
struct KeypressTimestamp {
pub kp: KeyPress,
pub next_repeat_time: u64,
}
struct KeyTracker {
pub rate_ms: usize,
pub delay_ms: usize,
pub keys: Vec<KeypressTimestamp>,
}
impl KeyTracker {
pub fn new() -> Self { KeyTracker { rate_ms: KEYUP_DELAY_MS as usize, delay_ms: 500, keys: Vec::new() } }
pub fn register_key_down(&mut self, key: KeyPress, ts: u64) {
if let Some(entry) = self.keys.iter_mut().find(|e| e.kp == key) {
// update the existing entry if it exists
entry.next_repeat_time = ts + self.delay_ms as u64;
} else {
self.keys.push(KeypressTimestamp { kp: key, next_repeat_time: ts + self.delay_ms as u64 });
}
}
/// Processes the current keys pressed, at the current time stamp
pub fn update_key_down(&mut self, keys: &[KeyPress], now: u64) {
// Handle the case that key A is held down, then key B is held down simultaneously,
// then key A is released while B continues to hold down
// then key A is pressed again all while key B is held down
//
// The behavior in this case is that A should emit a keydown immediately and will also
// immediately repeat without going through the repeat delay. This is consistent with a
// "video gaming" mode of operation.
//
// Search for keys that are pressed, but not currently in the pressed array
// trigger an effective key report by setting its timestamp to now minus the repeat delay
for key in keys {
// search for key not in keys vector; create a new entry with next repeat equal
// to now, so it gets emitted immediately
if !self.keys.iter().any(|e| e.kp == *key) {
self.keys.push(KeypressTimestamp { kp: *key, next_repeat_time: now });
}
}
// Handle the case that key A is held down, then key B is held down simultaneously.
// Then, key A is released.
//
// This is done after all current keys are registered above.
//
// Each key currently pressed should be present in `self.keys` vector.
// If a currently pressed key is not in the `keys` input slice,
// delete it from the `self.keys` vector. This will prevent it from continuing to generate
// key presses on get_repeats()
self.keys.retain(|entry| keys.iter().any(|key| key == &entry.kp));
}
/// Returns any keys that should have repeat key-press events generated
pub fn get_repeats(&mut self, now: u64) -> Vec<char> {
let mut kps = Vec::new();
for key in self.keys.iter_mut() {
if now >= key.next_repeat_time {
kps.push(map_keypress(key.kp));
// rebasing off of now prevents keys from "lagging on" in case of UI delay
key.next_repeat_time = now + self.rate_ms as u64;
}
}
kps
}
pub fn keys_pressed(&self) -> usize { self.keys.len() }
pub fn clear_keys(&mut self) { self.keys.clear(); }
}
fn map_keypress(kp: KeyPress) -> char {
match kp {
KeyPress::Down => '↓',
KeyPress::Up => '↑',
KeyPress::Left => '←',
KeyPress::Right => '→',
KeyPress::Select => '∴',
KeyPress::Center => '\r',
_ => '\u{0000}',
}
}
pub fn start_keyboard_service() {
std::thread::spawn(move || {
keyboard_service();
@ -37,7 +160,56 @@ fn keyboard_bouncer() {
fn keyboard_service() {
let xns = xous_names::XousNames::new().unwrap();
// "own" the KPC & Always-on registers
let mut kpc_aoint = bao1x_hal::kpc_aoint::KpcAoInt::new(Some(handler));
kpc_aoint.ao.wo(utra::ao_sysctrl::SFR_IOX, 1); // connect PF directly to KP unit, overrides IO mux even???
kpc_aoint.ao.wo(utra::ao_sysctrl::CR_WKUPMASK, 0x3F);
// KPOPO0 defines drive state in phase 0 - here we set it to high
// KPOPO1 defines drive state in phase 1 - here we set it to low
// KPOE0 defines OE state in phase 0 - here we set it to drive
// KPOE1 defines OE state in phase 1 - here we set it to drive
let cfg0 = kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG0_KPOPO0, 1)
// | kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG0_KPOPO1, 1)
| kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG0_KPOOE0, 1)
| kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG0_KPOOE1, 1)
| kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG0_DKPCEN, 1);
kpc_aoint.kpc.wo(utra::dkpc::SFR_CFG0, cfg0);
let cfg1 = kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG1_CFG_STEP, 2)
| kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG1_CFG_FILTER, 2)
| kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG1_CFG_CNT1MS, 4);
kpc_aoint.kpc.wo(utra::dkpc::SFR_CFG1, cfg1);
// CFG2 has format of interval kpo | stop drive kpo | sample point kpi | start drive kpo, each 8 bits wide
kpc_aoint.kpc.wo(utra::dkpc::SFR_CFG2, 0x40_05_03_01); // sets ~24ms scanning rate
kpc_aoint.kpc.wo(utra::dkpc::SFR_CFG3, 0xFFFF_0000); // fall[15:0] | rise[15:0] detection
// this is the deep sleep interval for debouncing the keyboard array
kpc_aoint.kpc.wo(utra::dkpc::SFR_CFG4, 256);
// drain any pending events
while kpc_aoint.kpc.r(utra::dkpc::SFR_SR1) != 0 {
// this register didn't get mapped in register extraction because its type
// is `apb_buf2`: FIXME - adjust the register extraction script to capture this type.
// this register drains the pending interrupts from the wakeup/keyboard queue
let _ = unsafe { kpc_aoint.kpc.base().add(8).read_volatile() };
}
let kbd_sid = xns.register_name(bao1x_api::SERVER_NAME_KBD, None).expect("can't register server");
let kbd_conn = xous::connect(kbd_sid).unwrap();
let kpc_int = u4::new(bao1x_hal::kpc_aoint::IrqMapping::AoInt as u8);
kpc_aoint.add_irq_notifier(IrqNotification {
bit: kpc_int,
conn: kbd_conn,
opcode: KeyboardOpcode::HandlerTrigger.to_usize().unwrap(),
args: [0, 0, 0, 0],
});
// feels like a bit of an abstraction violation, but I don't know how much the other interrupts
// require edge-triggered handling
kpc_aoint.irq.wo(utra::irqarray2::EV_EDGE_TRIGGERED, 1 << kpc_int.as_u32());
kpc_aoint.irq.wo(utra::irqarray2::EV_POLARITY, 1 << kpc_int.as_u32());
kpc_aoint.modify_irq_ena(kpc_int, true);
let tt = ticktimer::Ticktimer::new().unwrap();
let mut listeners: Vec<(CID, usize)> = Vec::new();
let mut observer_conn: Option<CID> = None;
@ -48,6 +220,42 @@ fn keyboard_service() {
// storage for any blocking listeners
let mut blocking_listener = Vec::<MessageSender>::new();
let iox = crate::iox::IoxHal::new();
let (_row, _col) = bao1x_hal::board::setup_kpc_pins(&iox);
#[cfg(feature = "keyboard-testing")]
// this routine is useful for mapping out raw keys on new hardware builds
std::thread::spawn({
let dkpc_ptr = unsafe { kpc_aoint.kpc.base() as usize };
let irq_ptr = unsafe { kpc_aoint.irq.base() as usize };
let ao_ptr = unsafe { kpc_aoint.ao.base() as usize };
move || {
let dkpc = CSR::new(dkpc_ptr as *mut u32);
let mut irq = CSR::new(irq_ptr as *mut u32);
let mut ao = CSR::new(ao_ptr as *mut u32);
let tt = ticktimer::Ticktimer::new().unwrap();
loop {
tt.sleep_ms(1000);
for i in (0..6).chain(12..13).chain(8..9) {
log::info!("{:x}: {:x} ", i * 4, unsafe { kpc_aoint.kpc.base().add(i).read_volatile() });
}
let fr = AoIntStatus::new_with_raw_value(ao.r(utra::ao_sysctrl::SFR_AOFR));
let pending = irq.r(utralib::utra::irqarray2::EV_PENDING);
log::info!(
"int: {:x}/{:x}/{:x}/{:x?}",
irq.r(utralib::utra::irqarray2::EV_ENABLE),
pending,
irq.r(utralib::utra::irqarray2::EV_STATUS),
fr,
);
ao.wo(utra::ao_sysctrl::SFR_AOFR, fr.raw_value());
irq.wo(utra::irqarray2::EV_PENDING, pending);
}
}
});
let mut key_tracker = KeyTracker::new();
let mut last_key_event = 0u64;
loop {
let msg = xous::receive_message(kbd_sid).unwrap(); // this blocks until we get a message
let op = FromPrimitive::from_usize(msg.body.id());
@ -86,17 +294,22 @@ fn keyboard_service() {
}
}
Some(KeyboardOpcode::SelectKeyMap) => {
todo!();
// only one key map for the input keyboard. Key mapping for translation of
// key presess to USB key codes should be set in the USB stack, not here.
unimplemented!()
}
Some(KeyboardOpcode::GetKeyMap) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
log::warn!("Defaulting to DVORAK map");
xous::return_scalar(msg.sender, KeyMap::Dvorak.into()).expect("can't retrieve keymap");
}),
Some(KeyboardOpcode::SetRepeat) => msg_scalar_unpack!(msg, _rate, _delay, _, _, {
todo!();
Some(KeyboardOpcode::SetRepeat) => msg_scalar_unpack!(msg, rate, delay, _, _, {
key_tracker.rate_ms = rate;
key_tracker.delay_ms = delay;
}),
Some(KeyboardOpcode::SetChordInterval) => msg_scalar_unpack!(msg, _delay, _, _, _, {
todo!();
// chording allows us to interpret multiple key hits as a whole new separate key.
// for now we don't implement this feature.
unimplemented!()
}),
Some(KeyboardOpcode::InjectKey) => msg_scalar_unpack!(msg, k, _, _, _, {
// key substitutions to help things work better
@ -188,9 +401,88 @@ fn keyboard_service() {
xous::return_scalar2(listener, key as u32 as usize, 0).unwrap();
}
}),
Some(KeyboardOpcode::HandlerTrigger) => {
todo!("Write this once we have an IRQ handler for keyboard interrupts");
}
Some(KeyboardOpcode::HandlerTrigger) => msg_scalar_unpack!(msg, pending, _, _, _, {
if pending & (1 << bao1x_hal::kpc_aoint::IrqMapping::AoInt as usize) != 0 {
let mut kc: Vec<char> = Vec::new();
let now = tt.elapsed_ms();
if now - last_key_event > KEYUP_DELAY_MS {
key_tracker.clear_keys();
}
last_key_event = now;
// key downs come from this register
if kpc_aoint.kpc.r(utra::dkpc::SFR_SR1) != 0 {
let sr1 = unsafe { kpc_aoint.kpc.base().add(8).read_volatile() };
let key_down = bao1x_hal::board::kpc_sr1_to_key(sr1);
key_tracker.register_key_down(key_down, now);
if key_down != KeyPress::Invalid {
kc.push(map_keypress(key_down))
}
}
// the keys_pressed() check is necessary because the interrupt will fire *before* a key
// press is effectively registered. This is because the interrupt fires as soon as any
// noise is detected on the keyboard, *before* the hardware debounce
// happens!
if key_tracker.keys_pressed() > 0 {
let sr0 = kpc_aoint.kpc.r(utra::dkpc::SFR_SR0);
let keys_down = bao1x_hal::board::kpc_sr0_to_key(sr0);
key_tracker.update_key_down(&keys_down, now);
}
// clear the FR bits
let fr = AoIntStatus::new_with_raw_value(kpc_aoint.ao.r(utra::ao_sysctrl::SFR_AOFR));
kpc_aoint.ao.wo(utra::ao_sysctrl::SFR_AOFR, fr.raw_value());
// add any repeat keys to the key response array
kc.extend_from_slice(&key_tracker.get_repeats(now));
// strip out any null entries that were generated
kc.retain(|&c| c != '\u{0000}');
// send keys, if any
// handle the blocking listeners
if kc.len() > 0 {
for listener in blocking_listener.drain(..) {
xous::return_scalar2(
listener,
if kc.len() >= 1 { kc[0] as u32 as usize } else { 0 },
if kc.len() >= 2 { kc[1] as u32 as usize } else { 0 },
)
.unwrap();
if kc.len() > 2 {
log::warn!(
"Extra keys in multi-hit event went unreported: only 2 of {} total keys reported out of {:?}",
kc.len(),
&kc,
);
}
}
}
// handle the true async listeners
for kv in kc.chunks(4) {
let mut keys: [char; 4] = ['\u{0000}', '\u{0000}', '\u{0000}', '\u{0000}'];
for i in 0..kv.len() {
keys[i] = kv[i];
}
log::trace!("sending keys {:?}", keys);
for &(listener_conn, listener_op) in listeners.iter() {
xous::try_send_message(
listener_conn,
xous::Message::new_scalar(
listener_op,
keys[0] as u32 as usize,
keys[1] as u32 as usize,
keys[2] as u32 as usize,
keys[3] as u32 as usize,
),
)
.ok();
}
}
} else {
log::warn!("Unhandled interrupt: {:x}", pending);
}
}),
None => {
log::error!("couldn't convert KeyboardOpcode");
break;

View file

@ -9,6 +9,7 @@ pub fn keystore(sid: SID) -> ! {
let hal = bao1x_hal_service::Hal::new();
let mut rram = Reram::new();
let mut store = KeyStore::init_mappings(&mut rram);
let mut backup_mgr = bao1x_hal::buram::BackupManager::new();
// does nothing if the keys are already initialized
store.ensure_system_init(&mut rram);
// derive the master key
@ -40,6 +41,7 @@ pub fn keystore(sid: SID) -> ! {
buffer.replace(kwp).unwrap();
}
Opcode::EphemeralOp => {
// this will use the backup_mgr to store ephemeral secrets
todo!()
}
Opcode::InvalidCall => {

View file

@ -322,7 +322,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}
break;
}
println!("{}: {:x}", region.name, region.base);
println!("{:10}: {:x} - {:x}", region.name, region.base, region.base + region.size);
map.insert(
region.name.to_lowercase(),
tools::utils::CsrMemoryRegion {

File diff suppressed because it is too large Load diff

View file

@ -258,14 +258,12 @@ pub const HW_RRC_MEM: usize = 0x40000000;
pub const HW_RRC_MEM_LEN: usize = 65536;
pub const HW_SECSUB_MEM: usize = 0x40050000;
pub const HW_SECSUB_MEM_LEN: usize = 65536;
pub const HW_PIO_MEM: usize = 0x50123000;
pub const HW_PIO_MEM_LEN: usize = 4096;
pub const HW_BIO_BDMA_MEM: usize = 0x50124000;
pub const HW_BIO_BDMA_MEM_LEN: usize = 4096;
pub const HW_AO_MEM: usize = 0x40060000;
pub const HW_AO_MEM_LEN: usize = 65536;
pub const HW_AOPERI_MEM: usize = 0x40061000;
pub const HW_AOPERI_MEM_LEN: usize = 12288;
pub const HW_AOPERI_MEM_LEN: usize = 20480;
pub const HW_SEG_LKEY_MEM: usize = 0x40020000;
pub const HW_SEG_LKEY_MEM_LEN: usize = 256;
pub const HW_SEG_KEY_MEM: usize = 0x40020100;
@ -346,6 +344,8 @@ pub const HW_BIO_FIFO2_MEM: usize = 0x5012b000;
pub const HW_BIO_FIFO2_MEM_LEN: usize = 4096;
pub const HW_BIO_FIFO3_MEM: usize = 0x5012c000;
pub const HW_BIO_FIFO3_MEM_LEN: usize = 4096;
pub const HW_AORAM_MEM: usize = 0x50300000;
pub const HW_AORAM_MEM_LEN: usize = 16384;
// Physical base addresses of registers
pub const HW_D11CTIME_BASE : usize = 0xe0000000;