Merge pull request #840 from betrusted-io/ux

Add progress bar to loader on baosec targets
This commit is contained in:
bunnie 2026-03-26 03:11:23 +08:00 committed by GitHub
commit 8ac6e17301
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 338 additions and 17 deletions

View file

@ -14,6 +14,9 @@ pub const PAGE: u8 = ROW as u8 / 8;
// IFRAM space reserved for UDMA channel commands
const SIDEBAND_LEN: usize = 256;
// 0x4f is a bit too bright
pub const DEFAULT_BRIGHTNESS: u8 = 0x3f;
pub struct MainThreadToken(());
impl MainThreadToken {
pub fn new() -> Self { MainThreadToken(()) }
@ -465,7 +468,7 @@ impl<'a> Oled128x128<'a> {
SetDCDCSettings(0x0),
SetStartLine(0),
SetDisplayOffset(0),
SetContrastControl(0x3f), // was 0x4f, was a bit too bright
SetContrastControl(DEFAULT_BRIGHTNESS),
SetAddressMode(AddressMode::Column),
SetSegmentReMap(false),
SetCOMScanDirection(Direction::Inverted),
@ -512,6 +515,61 @@ impl<'a> Oled128x128<'a> {
crate::board::assert_periph_reset(self.iox, false);
self.powerdown = false;
}
pub fn brightness(&mut self, level: u8) {
let bytes = Command::SetContrastControl(level).encode();
self.send_command(bytes);
}
#[cfg(feature = "std")]
pub fn render_bitmap(&mut self, bitmap: ux_api::service::api::BaosecBitmap) {
const W: isize = WIDTH as _;
const H: isize = LINES as _;
// Clamp bounding box to valid bitmap dimensions.
// If br > 128, truncate. If tl < 0, clamp to 0.
let src_x0 = bitmap.bounding_box.tl.x.max(0);
let src_y0 = bitmap.bounding_box.tl.y.max(0);
let src_x1 = bitmap.bounding_box.br.x.min(W);
let src_y1 = bitmap.bounding_box.br.y.min(H);
for src_y in src_y0..src_y1 {
// Map this bitmap row to its destination row in the framebuffer.
let dst_y = src_y + bitmap.top_left.y;
// Skip rows that land outside the framebuffer.
if dst_y < 0 || dst_y >= H {
continue;
}
for src_x in src_x0..src_x1 {
// Map this bitmap column to its destination column.
let dst_x = src_x + bitmap.top_left.x;
// Skip columns that land outside the framebuffer.
if dst_x < 0 || dst_x >= W {
continue;
}
// --- read source bit ---
let src_linear = (src_x + src_y * W) as usize;
let src_word = src_linear >> 5; // / 32
let src_shift = src_linear & 0x1F; // % 32
let on = (bitmap.bits[src_word] >> src_shift) & 1;
// --- write destination bit ---
let dst_linear = (dst_x + dst_y * W) as usize;
let dst_word = dst_linear >> 5;
let dst_shift = dst_linear & 0x1F;
if on != 0 {
self.buffer[dst_word] |= 1 << dst_shift;
} else {
self.buffer[dst_word] &= !(1 << dst_shift);
}
}
}
}
}
impl<'a> FrameBuffer for Oled128x128<'a> {

View file

@ -21,6 +21,7 @@ pub enum Opcode {
// ----- below are non-cryptographic opcodes but used to manipulate sensitive state -----
/// Set bootwait parameters
Bootwait = 4096,
IsDeveloper = 4097,
/// Used to map unknown opcodes
InvalidCall = 65535,

View file

@ -36,7 +36,7 @@ use crate::platform;
/// Abstract trait for a FrameBuffer. Slower than native manipulation
/// of the [u8] contents of a frame buffer, but more portable.
pub trait FrameBuffer {
/// Puts a pixel of ColorNative at x, y. (0, 0) is defined as the lower left corner.
/// Puts a pixel of ColorNative at x, y. (0, 0) is defined as the top left corner.
fn put_pixel(&mut self, p: Point, color: ColorNative);
/// For higher-performance loops that have guaranteed bounds checking in the point location.
unsafe fn put_pixel_unchecked(&mut self, p: Point, on: ColorNative);
@ -56,6 +56,27 @@ pub trait FrameBuffer {
unsafe fn raw_mut(&mut self) -> &mut platform::FbRaw;
}
// Newtype wrapping the FrameBuffer, to allow for sized passing of the object around
pub struct DynFb<'a>(pub &'a mut dyn FrameBuffer);
impl FrameBuffer for DynFb<'_> {
fn put_pixel(&mut self, p: Point, c: ColorNative) { self.0.put_pixel(p, c) }
fn xor_pixel(&mut self, p: Point) { self.0.xor_pixel(p) }
unsafe fn put_pixel_unchecked(&mut self, p: Point, on: ColorNative) { self.0.put_pixel_unchecked(p, on); }
fn get_pixel(&self, p: Point) -> Option<ColorNative> { self.0.get_pixel(p) }
fn draw(&mut self) { self.0.draw(); }
fn clear(&mut self) { self.0.clear(); }
fn dimensions(&self) -> Point { self.0.dimensions() }
unsafe fn raw_mut(&mut self) -> &mut platform::FbRaw { self.0.raw_mut() }
}
/// A TypesetWord is a Word that has beet turned into sprites and placed at a specific location on the canvas,
/// defined by its `bb` record. The intention is that this abstract representation can be passed directly to
/// a rasterizer for rendering.

View file

@ -107,6 +107,11 @@ pub enum GfxOpcode {
PowerDown,
#[cfg(feature = "board-baosec")]
PowerUp,
#[cfg(feature = "board-baosec")]
/// This call is specific and highly optimized to the display on Baosec
BaosecBitmap,
#[cfg(feature = "board-baosec")]
Brightness,
/// Gutter for invalid calls
InvalidCall,
@ -154,3 +159,14 @@ pub struct KeyboardRegistration {
pub server_name: String,
pub listener_op_id: usize,
}
#[cfg(feature = "board-baosec")]
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Clone)]
pub struct BaosecBitmap {
// exactly enough for a 128x128 black and white display = 2048 bytes
pub bits: [u32; 512],
// top left corner of the bitmap
pub top_left: crate::minigfx::Point,
// bounding box of the bitmap - if we want only a portion of the bitmap to be drawn
pub bounding_box: crate::minigfx::Rectangle,
}

View file

@ -769,6 +769,38 @@ impl Gfx {
}
}
#[cfg(feature = "board-baosec")]
pub fn bitmap(
&self,
bitmap: &[u32],
top_left: Option<Point>,
bounding_box: Option<Rectangle>,
) -> Result<(), xous::Error> {
let mut bmp = BaosecBitmap {
bits: [0u32; 512],
top_left: top_left.unwrap_or(Point::new(0, 0)),
bounding_box: bounding_box.unwrap_or(Rectangle {
tl: Point::new(0, 0),
// br is *exclusive*
br: Point::new(128, 128),
style: DrawStyle { fill_color: None, stroke_color: None, stroke_width: 0 },
}),
};
bmp.bits[..bitmap.len().min(512)].copy_from_slice(&bitmap[..bitmap.len().min(512)]);
let mut buf = Buffer::into_buf(bmp).unwrap();
buf.lend_mut(self.conn, GfxOpcode::BaosecBitmap.to_u32().unwrap())?;
Ok(())
}
#[cfg(feature = "board-baosec")]
pub fn brightness(&self, level: u8) -> Result<(), xous::Error> {
send_message(
self.conn,
Message::new_blocking_scalar(GfxOpcode::Brightness.to_usize().unwrap(), level as usize, 0, 0, 0),
)
.map(|_| ())
}
#[cfg(feature = "hosted-baosec")]
pub fn acquire_qr(&self) -> Result<QrAcquisition, xous::Error> {
let dummy = "otpauth://totp/ACME%20Co:john.doe@email.com?secret=HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ&issuer=ACME%20Co&algorithm=SHA1&digits=6&period=30".to_string();

View file

@ -43,12 +43,12 @@ pub const APP_UART_IFRAM_ADDR: usize = bao1x_hal::board::APP_UART_IFRAM_ADDR;
pub const GUARD_MEMORY_BYTES: usize = 3 * crate::PAGE_SIZE;
/// Amount of space for loader stack only, with swap
#[cfg(all(feature = "swap", not(feature = "resume"), not(feature = "bao1x")))]
pub const GUARD_MEMORY_BYTES: usize = 7 * crate::PAGE_SIZE;
pub const GUARD_MEMORY_BYTES: usize = 8 * crate::PAGE_SIZE;
#[cfg(all(feature = "swap", not(feature = "resume"), feature = "bao1x"))]
pub const GUARD_MEMORY_BYTES: usize = 7 * crate::PAGE_SIZE;
/// Amount of space for loader stack plus clean suspend, with swap
pub const GUARD_MEMORY_BYTES: usize = 8 * crate::PAGE_SIZE;
/// Amount of space for loader stack plus clean suspend, with swap. +1 page cost for the loading bar graphics
#[cfg(all(feature = "swap", feature = "resume"))]
pub const GUARD_MEMORY_BYTES: usize = 8 * crate::PAGE_SIZE; // 1 extra page for clean suspend
pub const GUARD_MEMORY_BYTES: usize = 9 * crate::PAGE_SIZE; // 1 extra page for clean suspend
#[cfg(feature = "swap")]
pub const SWAPPER_PID: u8 = 2;

View file

@ -470,6 +470,15 @@ fn boot_sequence(
_perclk_freq: u32,
detached_app: bool,
) -> ! {
#[cfg(feature = "board-baosec")]
let mut iox = bao1x_hal::iox::Iox::new(utralib::utra::iox::HW_IOX_BASE as *mut u32);
#[cfg(feature = "board-baosec")]
let mut udma_global = bao1x_hal::udma::GlobalConfig::new();
#[cfg(feature = "board-baosec")]
let mut oled = crate::platform::oled_init(&mut iox, &mut udma_global, _perclk_freq);
#[cfg(feature = "board-baosec")]
crate::platform::progress_bar(&mut oled, 0);
// Store the initial boot config on the stack. We don't know
// where in heap this memory will go.
#[allow(clippy::cast_ptr_alignment)] // This test only works on 32-bit systems
@ -525,8 +534,19 @@ fn boot_sequence(
// cold boot path
println!("No suspend marker found, doing a cold boot!");
clear_ram(&mut cfg);
phase_1(&mut cfg, detached_app);
phase_2(&mut cfg, env_variables);
#[cfg(feature = "board-baosec")]
{
phase_1(&mut cfg, detached_app, Some(&mut oled));
phase_2(&mut cfg, env_variables, Some(&mut oled));
crate::platform::progress_bar(&mut oled, 100);
}
#[cfg(not(feature = "board-baosec"))]
{
phase_1(&mut cfg, detached_app, None);
phase_2(&mut cfg, env_variables, None);
}
#[cfg(any(feature = "debug-print", feature = "swap"))]
if VDBG || SDBG {
check_load(&mut cfg);

View file

@ -92,6 +92,7 @@ impl MiniElf {
let mut current_page_addr: usize = 0;
let mut previous_addr: usize = 0;
let mut last_mapped_xip = 0;
#[cfg(feature = "swap")]
let mut last_mapped_swap_virt = 0; // track the last virtual address mapped to swap, to catch gaps
let image_phys_base = allocator.base_addr as usize + self.load_offset as usize;
// It is a requirement that the image generator lay out the artifacts on disk such that

View file

@ -1,8 +1,14 @@
use core::{mem::size_of, slice};
#[cfg(any(feature = "board-baosec", feature = "board-baosor"))]
use ux_api::minigfx::FrameBuffer;
#[cfg(feature = "atsama5d27")]
pub use crate::platform::atsama5d27::load::InitialProcess;
use crate::*;
// define an uninhabited stub type for boards without framebuffers
#[cfg(not(any(feature = "board-baosec", feature = "board-baosor")))]
pub trait FrameBuffer {}
#[repr(C)]
#[cfg(not(feature = "atsama5d27"))]
@ -30,7 +36,7 @@ pub struct InitialProcess {
/// We don't memorize the allocated results (in part because we don't have malloc/alloc to stick
/// the table, and we don't know a priori how big it will be); we simply memorize the maximum extent,
/// after which we allocate the book-keeping tables.
pub fn phase_1(cfg: &mut BootConfig, detached_app: bool) {
pub fn phase_1(cfg: &mut BootConfig, detached_app: bool, fb: Option<&mut dyn FrameBuffer>) {
// Allocate space for the stack pointer.
// The bootloader should have placed the stack pointer at the end of RAM
// prior to jumping to our program. Reserve space for the stack, so that it does not smash
@ -161,7 +167,7 @@ pub fn phase_1(cfg: &mut BootConfig, detached_app: bool) {
// Copy the processes to RAM, if requested.
if !cfg.no_copy {
println!("Copying processes");
copy_processes(cfg);
copy_processes(cfg, fb);
}
// activate this to debug stack-smashing during copy_process(). The RPT is the first structure that gets
// smashed if the stack overflows! It should be all 0's if the stack did not overrun.
@ -499,9 +505,11 @@ impl TagType {
/// Copy program data from the SPI flash into newly-allocated RAM
/// located at the end of memory space.
fn copy_processes(cfg: &mut BootConfig) {
fn copy_processes(cfg: &mut BootConfig, mut _fb: Option<&mut dyn FrameBuffer>) {
let mut _pid = 1;
for tag in cfg.args.iter() {
#[cfg(feature = "board-baosec")]
let arg_len = cfg.args.iter().count();
for (_i, tag) in cfg.args.iter().enumerate() {
let tag_type = TagType::from(tag.name);
match tag_type {
TagType::IniF | TagType::IniE => {
@ -879,6 +887,14 @@ fn copy_processes(cfg: &mut BootConfig) {
}
_ => {}
}
#[cfg(feature = "board-baosec")]
if let Some(ref mut fb) = _fb {
let start = 5;
let end = 70;
let increment = (end - start) / arg_len;
let percentage = start + increment * _i;
crate::platform::progress_bar(*fb, percentage);
}
}
}

View file

@ -1,15 +1,20 @@
#[cfg(any(feature = "board-baosec", feature = "board-baosor"))]
use ux_api::minigfx::FrameBuffer;
#[cfg(feature = "swap")]
use xous::arch::{SWAP_CFG_VADDR, SWAP_COUNT_VADDR, SWAP_PT_VADDR};
#[cfg(feature = "swap")]
use crate::swap::*;
use crate::{env::EnvVariables, *};
// define an uninhabited stub type for boards without framebuffers
#[cfg(not(any(feature = "board-baosec", feature = "board-baosor")))]
pub trait FrameBuffer {}
/// Phase 2 bootloader
///
/// Set up all the page tables, allocating new root page tables for SATPs and corresponding
/// sub-pages starting from the base of previously copied process data.
pub fn phase_2(cfg: &mut BootConfig, env_variables: EnvVariables) {
pub fn phase_2(cfg: &mut BootConfig, env_variables: EnvVariables, mut _fb: Option<&mut dyn FrameBuffer>) {
let args = cfg.args;
// This is the offset in RAM where programs are loaded from.
@ -41,7 +46,9 @@ pub fn phase_2(cfg: &mut BootConfig, env_variables: EnvVariables) {
#[cfg(feature = "bao1x")]
trng.setup_raw_generation(32); // this is safe to call multiple times to affirm the TRNG state
for tag in args.iter() {
#[cfg(feature = "board-baosec")]
let arg_len = args.iter().count();
for (_i, tag) in args.iter().enumerate() {
let mut env_header = crate::env::EnvHeader::default();
#[allow(unused_mut)]
let mut pid_env = env_variables.clone();
@ -104,6 +111,14 @@ pub fn phase_2(cfg: &mut BootConfig, env_variables: EnvVariables) {
}
process_offset -= load_size_rounded;
}
#[cfg(feature = "board-baosec")]
if let Some(ref mut fb) = _fb {
let start = 70;
let end = 95;
let increment = (end - start) / arg_len;
let percentage = start + increment * _i;
crate::platform::progress_bar(*fb, percentage);
}
}
println!("Done loading.");

View file

@ -6,9 +6,13 @@ use bao1x_api::signatures::SIGBLOCK_LEN;
use bao1x_api::*;
#[allow(unused_imports)]
use bao1x_hal::iox::Iox;
#[cfg(feature = "board-baosec")]
use bao1x_hal::sh1107::Oled128x128;
#[cfg(feature = "bao1x")]
use bao1x_hal::udma;
use utralib::generated::*;
#[cfg(feature = "board-baosec")]
use ux_api::minigfx::FrameBuffer;
// Notes about the reset vector location
// This can be set using fuses in the IFR (also called 'info') region
@ -211,6 +215,26 @@ pub fn early_init_hw() -> u32 {
perclk
}
#[cfg(feature = "board-baosec")]
pub fn oled_init<'a>(
iox: &'a mut Iox,
udma_global: &'a mut bao1x_hal::udma::GlobalConfig,
perclk: u32,
) -> Oled128x128<'a> {
use ux_api::minigfx::FrameBuffer;
let mut sh1107 = bao1x_hal::sh1107::Oled128x128::new(
bao1x_hal::sh1107::MainThreadToken::new(),
perclk,
iox,
udma_global,
);
sh1107.init();
sh1107.buffer_mut().fill(0xFFFF_FFFF);
sh1107.blit_screen(&ux_api::bitmaps::baochip128x128::BITMAP);
sh1107.draw();
sh1107
}
#[cfg(feature = "board-dabao")]
pub fn setup_console<T: IoSetup + IoGpio>(
board_type: &bao1x_api::BoardTypeCoding,
@ -316,3 +340,80 @@ pub fn delay_at_sysfreq(ms: usize, sysclk_freq: u32) {
timer.wfo(utra::timer0::EV_PENDING_ZERO, 1);
}
}
#[cfg(feature = "board-baosec")]
/// Progress is a number from 0-100 that represents how complete the operation is.
pub fn progress_bar(fb: &mut dyn FrameBuffer, progress: usize) {
use ux_api::bitmaps::baochip128x128::MARQUEE_BELOW;
use ux_api::minigfx::{DrawStyle, PixelColor, Point, Rectangle};
const DISPLAY_WIDTH: isize = 128;
const DISPLAY_HEIGHT: isize = 128;
/// Left/right margin of the progress bar relative to the display edges, in pixels.
const PROGRESS_BAR_MARGIN: isize = 8;
/// Maximum height of the progress bar, in pixels.
const PROGRESS_BAR_HEIGHT: isize = 8;
// cast the fb into a concrete type that can be used with the minigfx::op
let mut fb = ux_api::minigfx::DynFb(fb);
let progress = progress.min(100);
// The available vertical region is between MARQUEE_BELOW and the bottom of the display.
let region_top = MARQUEE_BELOW as isize;
let region_height = DISPLAY_HEIGHT - region_top;
// Center the bar vertically within that region.
let bar_top = region_top + (region_height - PROGRESS_BAR_HEIGHT) / 2;
let bar_bottom = bar_top + PROGRESS_BAR_HEIGHT; // exclusive
if progress == 0 {
// blank out the marquee
ux_api::minigfx::op::rectangle(
&mut fb,
Rectangle::new_with_style(
Point::new(0, MARQUEE_BELOW as isize),
Point::new(DISPLAY_WIDTH, DISPLAY_HEIGHT),
DrawStyle::new(ux_api::minigfx::PixelColor::Dark, ux_api::minigfx::PixelColor::Dark, 1),
),
None,
false,
);
}
// --- Outline (always full width) ---
ux_api::minigfx::op::rectangle(
&mut fb,
Rectangle {
tl: Point { x: PROGRESS_BAR_MARGIN, y: bar_top },
br: Point { x: DISPLAY_WIDTH - PROGRESS_BAR_MARGIN, y: bar_bottom },
style: DrawStyle { fill_color: None, stroke_color: Some(PixelColor::Light), stroke_width: 1 },
},
None,
false,
);
// --- Fill (grows left to right with progress) ---
// Interior is 1px inset from the stroke on every side.
let inner_x0 = PROGRESS_BAR_MARGIN + 1;
let inner_x1 = DISPLAY_WIDTH - PROGRESS_BAR_MARGIN - 1;
let inner_width = inner_x1 - inner_x0;
let fill_width = (inner_width * progress as isize) / 100;
if fill_width > 0 {
ux_api::minigfx::op::rectangle(
&mut fb,
Rectangle {
tl: Point { x: inner_x0, y: bar_top + 1 },
br: Point { x: inner_x0 + fill_width, y: bar_bottom - 1 },
style: DrawStyle { fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0 },
},
None,
false,
);
}
fb.0.draw();
}

View file

@ -56,6 +56,7 @@ hosted-baosec = ["bao1x-emu", "ux-api/hosted-baosec", "no-gam"]
# temporary feature - remove after we have properly created a camera control API
autotest = []
with-logo = []
bao1x = ["utralib/bao1x", "blitstr2/bao1x"]
b64-export = ["base64"]
default = [

View file

@ -236,9 +236,12 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! {
// but it'll do the job 90% of the time and it's way better than having none at all.
let is_panic = Arc::new(AtomicBool::new(false));
// ---- boot logo
display.blit_screen(&ux_api::bitmaps::baochip128x128::BITMAP);
display.redraw();
// ---- Baochip boot logo, if enabled
#[cfg(feature = "with-logo")]
{
display.blit_screen(&ux_api::bitmaps::baochip128x128::BITMAP);
display.redraw();
}
// This is safe because the SPIM is finished with initialization, and the handler is
// Mutex-protected.
@ -861,6 +864,19 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! {
scalar.arg1 = 1;
}
}
#[cfg(feature = "board-baosec")]
GfxOpcode::BaosecBitmap => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let bitmap = buffer.to_original::<BaosecBitmap, _>().unwrap();
display.render_bitmap(bitmap);
}
#[cfg(feature = "board-baosec")]
GfxOpcode::Brightness => {
if let Some(scalar) = msg.body.scalar_message_mut() {
let brightness = scalar.arg1.min(255) as u8;
display.brightness(brightness);
}
}
GfxOpcode::Quit => break,
_ => {
// This is perfectly normal because not all opcodes are handled by all platforms.

View file

@ -192,6 +192,22 @@ impl Keystore {
_ => unimplemented!(),
}
}
pub fn is_developer(&self) -> Result<bool, xous::Error> {
match xous::send_message(
self.conn,
xous::Message::new_blocking_scalar(Opcode::IsDeveloper.to_usize().unwrap(), 0, 0, 0, 0),
)? {
xous::Result::Scalar5(_, is_developer, _, _, _) => {
if is_developer == 0 {
Ok(true)
} else {
Ok(false)
}
}
_ => unimplemented!(),
}
}
}
use core::sync::atomic::{AtomicU32, Ordering};

View file

@ -72,6 +72,11 @@ pub fn keystore(sid: SID) -> ! {
}
}
}
Opcode::IsDeveloper => {
if let Some(scalar) = msg.body.scalar_message_mut() {
if store.is_developer() { scalar.arg1 = 0 } else { scalar.arg1 = 1 }
}
}
Opcode::InvalidCall => {
log::error!("Invalid call in keystore: {:?}", opcode);
}

View file

@ -384,4 +384,6 @@ impl KeyStore {
BootWaitCoding::Disable => Ok(false),
}
}
pub fn is_developer(&self) -> bool { self.owc.get(bao1x_api::DEVELOPER_MODE).unwrap() != 0 }
}