From 951bf4cb4fbbd7ec505cea2ca3dcc594ba1494b7 Mon Sep 17 00:00:00 2001 From: Andy Chan Date: Sun, 5 Apr 2026 01:36:01 -0700 Subject: [PATCH 01/22] Add AI contribution policy. Signed-off-by: Andy Chan --- CONTRIBUTING.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b7a7b47ea..d941455b7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -32,6 +32,23 @@ By participating in this project you agree to abide by the (please read the full text so that you can understand what actions will and will not be tolerated). +## AI-Assisted Project Contributions + +- You may use AI assistance for contributing to this project in accordance with these principles of accountability and transparency. + +### Accountability + +- When you submit a contribution, you represent that you are the author and that you are fully accountable for the entirety of the contribution. +- You are responsible for your contribution, including vouching for the quality, license compliance, and utility of your submission. +- Using AI assistance in your contribution does not relieve you of the responsibility to ensure that your contribution meets project standards; your contributions must be modular, reviewable, and clearly explainable. + +### Transparency + +- You **must** disclose the use of AI tools when a significant part of the contribution is generated without changes. +- You **should** disclose the use of AI tools where it might be helpful to the maintainer reviewing your contribution. +- Using AI tools to correct grammar and spelling does not require disclosure. +- Make your disclosure in your commit message as a trailer; e.g. `Assisted-by: ChatGPTv5` + ## Contribution Workflow This is an overview of the contribution workflow: From b10b7e6309bb0c2a4878893116b23722ccb42c9c Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 21 Apr 2026 01:20:42 +0800 Subject: [PATCH 02/22] add serdes for VbusIrq to usize --- libs/bao1x-hal/src/axp2101.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/libs/bao1x-hal/src/axp2101.rs b/libs/bao1x-hal/src/axp2101.rs index f8534c95f..584b21c1f 100644 --- a/libs/bao1x-hal/src/axp2101.rs +++ b/libs/bao1x-hal/src/axp2101.rs @@ -80,6 +80,29 @@ impl From for VbusIrq { } } +impl From for usize { + fn from(v: VbusIrq) -> usize { + match v { + VbusIrq::None => 0, + VbusIrq::Insert => 1, + VbusIrq::Remove => 2, + VbusIrq::InsertAndRemove => 3, + } + } +} + +impl From for VbusIrq { + fn from(v: usize) -> VbusIrq { + match v { + 0 => VbusIrq::None, + 1 => VbusIrq::Insert, + 2 => VbusIrq::Remove, + 3 => VbusIrq::InsertAndRemove, + _ => VbusIrq::None, // infallible: unknown values collapse to None + } + } +} + #[repr(u8)] #[derive(PartialEq, Eq, Clone, Copy)] pub enum WhichLdo { From 0d2c7233d652302daf12233d523ed6aa17013e63 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 21 Apr 2026 01:21:13 +0800 Subject: [PATCH 03/22] improve stability of USB when not plugged in don't try to use the USB stack when nothing is plugged in --- services/usb-bao1x/src/api.rs | 2 +- services/usb-bao1x/src/hw.rs | 2 +- services/usb-bao1x/src/lib.rs | 2 ++ services/usb-bao1x/src/main.rs | 33 ++++++++++++++++++++++++++++++++- 4 files changed, 36 insertions(+), 3 deletions(-) diff --git a/services/usb-bao1x/src/api.rs b/services/usb-bao1x/src/api.rs index 8d79fb6de..5147c9c07 100644 --- a/services/usb-bao1x/src/api.rs +++ b/services/usb-bao1x/src/api.rs @@ -4,7 +4,7 @@ pub(crate) const SERVER_NAME_USB_DEVICE: &'static str = "_Xous USB device driver_"; #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] -pub(crate) enum Opcode { +pub enum Opcode { /// Returns the link status LinkStatus = 0, /// Send a keyboard code diff --git a/services/usb-bao1x/src/hw.rs b/services/usb-bao1x/src/hw.rs index ab169c68d..d3b158091 100644 --- a/services/usb-bao1x/src/hw.rs +++ b/services/usb-bao1x/src/hw.rs @@ -162,7 +162,7 @@ impl<'a> Bao1xUsb<'a> { /// Process an unplug event - only valid on baosec, because dabao doesn't have a battery and unplugging /// it would power it down. - #[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] + #[cfg(all(feature = "board-baosec"))] pub fn unplug(&mut self) { // disable all interrupts so we can safely go through initialization routines self.irq_csr.wo(utra::irqarray1::EV_ENABLE, 0); diff --git a/services/usb-bao1x/src/lib.rs b/services/usb-bao1x/src/lib.rs index 85b841878..15d166259 100644 --- a/services/usb-bao1x/src/lib.rs +++ b/services/usb-bao1x/src/lib.rs @@ -364,6 +364,8 @@ impl UsbHid { ) .unwrap(); } + + pub fn cid(&self) -> xous::CID { self.conn } } use core::sync::atomic::{AtomicU32, Ordering}; diff --git a/services/usb-bao1x/src/main.rs b/services/usb-bao1x/src/main.rs index cafc1360c..bd86eb26c 100644 --- a/services/usb-bao1x/src/main.rs +++ b/services/usb-bao1x/src/main.rs @@ -309,6 +309,16 @@ pub(crate) fn main_hw() -> ! { // log::warn!("Received an interrupt but no actual event reported"); } }, + #[cfg(all(feature = "board-baosec", feature = "oem-baosec-lite"))] + Opcode::PmicIrq => { + use bao1x_hal::axp2101::VbusIrq; + if let Some(scalar) = msg.body.scalar_message_mut() { + let vbus_irq = VbusIrq::from(scalar.arg1); + if vbus_irq == VbusIrq::Remove { + cu.unplug(); + } + } + } Opcode::U2fRxDeferred => { // notify the event listener, if any if observer_conn.is_some() && observer_op.is_some() { @@ -432,6 +442,11 @@ pub(crate) fn main_hw() -> ! { let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut u2f_ipc = buffer.to_original::().unwrap(); + if cu.device.state() != usb_device::device::UsbDeviceState::Configured { + u2f_ipc.code = U2fCode::Hangup; + buffer.replace(u2f_ipc).unwrap(); + continue; + } if fido_listener_pid == msg.sender.pid() { let mut u2f_msg = RawFidoReport::default(); assert_eq!(u2f_ipc.code, U2fCode::Tx, "Expected U2fCode::Tx in wrapper"); @@ -450,6 +465,10 @@ pub(crate) fn main_hw() -> ! { } Opcode::SendKeyCode => { if let Some(scalar) = msg.body.scalar_message_mut() { + if cu.device.state() != usb_device::device::UsbDeviceState::Configured { + continue; + } + let code0 = scalar.arg1; let code1 = scalar.arg2; let code2 = scalar.arg3; @@ -493,6 +512,12 @@ pub(crate) fn main_hw() -> ! { unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut usb_send = buffer.to_original::().unwrap(); let mut sent = 0; + if cu.device.state() != usb_device::device::UsbDeviceState::Configured { + log::warn!("Aborting send, no USB configured"); + usb_send.sent = Some(0); + buffer.replace(usb_send).unwrap(); + continue; + } // check keymap on every call because we may need to toggle this for e.g. plugging // into a new host with a different map @@ -696,6 +721,9 @@ pub(crate) fn main_hw() -> ! { serial_listener.take(); } Opcode::SerialFlush => msg_scalar_unpack!(msg, _, _, _, _, { + if cu.device.state() != usb_device::device::UsbDeviceState::Configured { + continue; + } // this will hardware flush any pending items in usb_serial driver cu.serial_port.flush().ok(); // this tries to return any data that's pending within the main loop's buffers @@ -738,6 +766,9 @@ pub(crate) fn main_hw() -> ! { } }), Opcode::SerialSendData => { + if cu.device.state() != usb_device::device::UsbDeviceState::Configured { + continue; + } let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let data = buffer.to_original::().unwrap(); let mut total_sent = 0; @@ -791,7 +822,7 @@ pub(crate) fn main_hw() -> ! { break; } _ => { - unimplemented!( + log::warn!( "Opcode {:?} not implemented for this version of the USB stack: {:?}", opcode, msg From 2ec739e54ec58a6ed080f4768dd5c8fec6562b6e Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 21 Apr 2026 01:21:51 +0800 Subject: [PATCH 04/22] fix orientation flipping during QR scan mode turns out you don't just flip everything all the time! when you flip the board upside down, the camera also flips. so then you end up with a flipped image which is super-confusing. however, the overlay text needs to flip. so this adds the cases to handle that. --- services/bao-video/src/gfx.rs | 86 ++++++++++++++++++---------------- services/bao-video/src/main.rs | 64 ++++++++++++++++++++----- 2 files changed, 97 insertions(+), 53 deletions(-) diff --git a/services/bao-video/src/gfx.rs b/services/bao-video/src/gfx.rs index 89c732cfb..ef845ac05 100644 --- a/services/bao-video/src/gfx.rs +++ b/services/bao-video/src/gfx.rs @@ -26,65 +26,71 @@ fn char_offset(c: char) -> isize { fallback } -pub fn msg<'a>(fb: &mut dyn FrameBuffer, text: &'a str, ll_pos: Point, fg: ColorNative, bg: ColorNative) { - let mut ll_pos = ll_pos.clone(); - // this routine is adapted from the embedded graphics crate https://docs.rs/embedded-graphics/0.7.1/embedded_graphics/ +pub fn msg<'a>( + fb: &mut dyn FrameBuffer, + text: &'a str, + ll_pos: Point, + fg: ColorNative, + bg: ColorNative, + upside_down: bool, + screen_size: Point, // e.g. Point::new(SCREEN_WIDTH, SCREEN_HEIGHT); ignored when !upside_down +) { + let mut ll_pos = ll_pos; // no need for .clone() on Copy types let char_per_row = FONT_IMAGE_WIDTH / CHAR_WIDTH; - let mut idx = 0; + let mut idx: isize = 0; + for current_char in text.chars() { - let mut char_walk_x = 0; - let mut char_walk_y = 0; + let cur_byte = current_char as u8; + let is_cr = cur_byte == 0x0d; + let is_lf = cur_byte == 0x0a; + let is_visible = !is_cr && !is_lf; + // -- Per-character constants (hoisted out of the pixel loop) ---------- + let char_offset = char_offset(current_char); + let row = char_offset / char_per_row; + let char_x = (char_offset - (row * char_per_row)) * CHAR_WIDTH; + let char_y = row * CHAR_HEIGHT; + // Base bit index in the font bitmap for the top-left of this glyph + let base_bitmap_idx = char_x + FONT_IMAGE_WIDTH * char_y; + // Screen X of the left edge of this character + let char_screen_x = ll_pos.x + CHAR_WIDTH * idx; + + // -- Pixel walk ------------------------------------------------------- + let mut char_walk_x: isize = 0; + let mut char_walk_y: isize = 0; loop { - // Char _code_ offset from first char, most often a space - // E.g. first char = ' ' (32), target char = '!' (33), offset = 33 - 32 = 1 - let char_offset = char_offset(current_char); - let row = char_offset / char_per_row; + if is_visible { + let bitmap_bit_idx = base_bitmap_idx + char_walk_x + char_walk_y * FONT_IMAGE_WIDTH; + let bitmap_byte = (bitmap_bit_idx / 8) as usize; + let bitmap_bit = bitmap_bit_idx as u8 & 7 ^ 7; + let color = if FONT_IMAGE[bitmap_byte] & (1 << bitmap_bit) != 0 { fg } else { bg }; - // Top left corner of character, in pixels - let char_x = (char_offset - (row * char_per_row)) * CHAR_WIDTH; - let char_y = row * CHAR_HEIGHT; + let px = char_screen_x + char_walk_x; + let py = ll_pos.y + char_walk_y; - // Bit index - // = X pixel offset for char - // + Character row offset (row 0 = 0, row 1 = (192 * 8) = 1536) - // + X offset for the pixel block that comprises this char - // + Y offset for pixel block - let bitmap_bit_index = - char_x + (FONT_IMAGE_WIDTH * char_y) + char_walk_x + (char_walk_y * FONT_IMAGE_WIDTH); + // For upside-down: mirror the screen position. + let draw_point = if upside_down { + Point::new(screen_size.x - 1 - px, screen_size.y - 1 - py) + } else { + Point::new(px, py) + }; - let bitmap_byte = bitmap_bit_index / 8; - let bitmap_bit = 7 - (bitmap_bit_index % 8); - - let color = if FONT_IMAGE[bitmap_byte as usize] & (1 << bitmap_bit) != 0 { fg } else { bg }; - - let x = ll_pos.x + CHAR_WIDTH * idx + char_walk_x; - let y = ll_pos.y + char_walk_y; - - // draw color at x, y - if (current_char as u8 != 0xd) && (current_char as u8 != 0xa) { - // don't draw CRLF specials - fb.put_pixel(Point::new(x, y), color); + fb.put_pixel(draw_point, color); } char_walk_x += 1; - if char_walk_x >= CHAR_WIDTH { char_walk_x = 0; char_walk_y += 1; - - // Done with this char, move on to the next one if char_walk_y >= CHAR_HEIGHT { - if current_char as u8 == 0xd { - // '\n' + if is_cr { ll_pos.y += CHAR_HEIGHT; - } else if current_char as u8 == 0xa { - // '\r' + } else if is_lf { ll_pos.x = LEFT_MARGIN; + idx = 0; } else { idx += 1; } - break; } } diff --git a/services/bao-video/src/main.rs b/services/bao-video/src/main.rs index 948e36995..722e92ba2 100644 --- a/services/bao-video/src/main.rs +++ b/services/bao-video/src/main.rs @@ -70,14 +70,11 @@ use xous_ipc::Buffer; pub const IMAGE_WIDTH: usize = 256; pub const IMAGE_HEIGHT: usize = 240; -// Next steps for performance improvement: -// -// Improve qr::mapping -> point_from_hv_lines such that we're not just deriving the HV -// lines from the the edges of the finder regions, we're also using the very edge of -// the whole QR code itself to guide the line. This will improve the intersection point -// so that we can accurately hit the "fourth corner". At the moment it's sort of a -// luck of the draw if the interpolation hits exactly right, or if we're roughly a module -// off from ideal, which causes the data around that point to be interpreted incorrectly. +#[derive(PartialEq, Eq, Clone, Copy)] +enum DisplayOrientation { + Normal, + UpsideDown, +} #[cfg(feature = "b64-export")] #[allow(dead_code)] @@ -412,6 +409,7 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { // ---- main loop variables let screen_clip = Rectangle::new(Point::new(0, 0), display.screen_size()); + let screen_size = display.screen_size(); // make a copy so the borrow checker doesn't complain // this will kick the hardware into the QR code scanning routine automatically. Eventually // this needs to be turned into a call that can invoke and abort the QR code scanning. @@ -433,6 +431,7 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { let mut bw_thresh: u8 = 128; let mut qr_request: Option = None; let mut kbd_listeners: Vec<(CID, usize)> = Vec::new(); + let mut orientation = DisplayOrientation::Normal; loop { if !is_panic.load(Ordering::Relaxed) { xous::reply_and_receive_next(sid, &mut msg_opt).unwrap(); @@ -505,12 +504,18 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { log::error!("test image failed to decode, this shouldn't happen!"); } - // now start acquisition - cam.capture_async(); // turning off preemption makes camera acquisition smoother; the OS will naturally try // to schedule other tasks between camera frames after each // CamIrq interrupt hal.set_preemption(false); + // fix orientation if it's upside down + if orientation == DisplayOrientation::UpsideDown { + display + .flip_vertical(false) + .unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display)) + } + // now start acquisition + cam.capture_async(); } // if qr_request is already pending, ignore any new acquisition requests } @@ -526,6 +531,11 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { ) }; response.replace(acquisition).unwrap(); + if orientation == DisplayOrientation::UpsideDown { + display + .flip_vertical(true) + .unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display)) + } display .pop() .unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display)); @@ -609,6 +619,8 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { Point::new(0, 0), Mono::White.into(), Mono::Black.into(), + orientation == DisplayOrientation::UpsideDown, + screen_size, ); display .draw() @@ -632,6 +644,8 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { Point::new(0, 0), Mono::White.into(), Mono::Black.into(), + orientation == DisplayOrientation::UpsideDown, + screen_size, ); display.draw().unwrap_or_else(|_| { display_timeout_handler(&udma_global, &mut display) @@ -663,6 +677,11 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { ) }; response.replace(acquisition).unwrap(); + if orientation == DisplayOrientation::UpsideDown { + display.flip_vertical(true).unwrap_or_else(|_| { + display_timeout_handler(&udma_global, &mut display) + }) + } #[cfg(not(feature = "hosted-baosec"))] hal.set_preemption(true); continue; @@ -675,6 +694,8 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { Point::new(0, 0), Mono::White.into(), Mono::Black.into(), + orientation == DisplayOrientation::UpsideDown, + screen_size, ); gfx::msg( &mut display, @@ -682,6 +703,8 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { Point::new(0, 64), Mono::White.into(), Mono::Black.into(), + orientation == DisplayOrientation::UpsideDown, + screen_size, ); } } @@ -693,6 +716,8 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { Point::new(0, 0), Mono::White.into(), Mono::Black.into(), + orientation == DisplayOrientation::UpsideDown, + screen_size, ); } } @@ -704,6 +729,8 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { Point::new(0, 0), Mono::White.into(), Mono::Black.into(), + orientation == DisplayOrientation::UpsideDown, + screen_size, ); } @@ -910,9 +937,20 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { #[cfg(feature = "board-baosec")] GfxOpcode::FlipScreen => { if let Some(scalar) = msg.body.scalar_message_mut() { - display - .flip_vertical(scalar.arg1 != 0) - .unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display)) + log::info!("gfx flip"); + if scalar.arg1 != 0 { + orientation = DisplayOrientation::UpsideDown; + } else { + orientation = DisplayOrientation::Normal; + } + if qr_request.is_none() { + display + .flip_vertical(scalar.arg1 != 0) + .unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display)); + display + .redraw() + .unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display)); + } } } GfxOpcode::Quit => break, From 8521d698d78e7ac14b5e8d09109a5e865bd20d18 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 21 Apr 2026 16:27:10 +0800 Subject: [PATCH 05/22] add hooks for pre-clock transition on bio this hook allows the application logic to warn the BIO app that a clock transition is coming so that glitches can be suppressed. --- libs/bao1x-api/src/bio.rs | 5 +++++ libs/bao1x-hal/src/bio.rs | 8 ++++++++ libs/bao1x-hal/src/bio_hw.rs | 4 ++++ services/bao1x-hal-service/src/servers/bio.rs | 11 +++++++++++ services/bao1x-hal-service/src/servers/susres.rs | 2 ++ 5 files changed, 30 insertions(+) diff --git a/libs/bao1x-api/src/bio.rs b/libs/bao1x-api/src/bio.rs index e4c31bd6b..01234d36e 100644 --- a/libs/bao1x-api/src/bio.rs +++ b/libs/bao1x-api/src/bio.rs @@ -51,6 +51,10 @@ pub trait BioApi<'a> { /// that the clocks may have changed. fn update_bio_freq(&mut self, freq: u32) -> u32; + /// Called before frequency changes to activate any application-specific callbacks + /// to avoid glitches. + fn prep_freq_change(&mut self); + /// Returns the frequency, in Hz, of the incoming clock to the BIO cores. fn get_bio_freq(&self) -> u32; @@ -192,6 +196,7 @@ pub enum BioOp { InitCore, DeInitCore, UpdateBioFreq, + PrepFreqChange, GetCoreFreq, GetBioFreq, CoreState, diff --git a/libs/bao1x-hal/src/bio.rs b/libs/bao1x-hal/src/bio.rs index c23386102..40dbce042 100644 --- a/libs/bao1x-hal/src/bio.rs +++ b/libs/bao1x-hal/src/bio.rs @@ -134,6 +134,14 @@ impl<'a> BioApi<'a> for Bio { } } + fn prep_freq_change(&mut self) { + send_message( + self.conn, + Message::new_blocking_scalar(BioOp::PrepFreqChange.to_usize().unwrap(), 0, 0, 0, 0), + ) + .ok(); + } + fn get_bio_freq(&self) -> u32 { match send_message( self.conn, diff --git a/libs/bao1x-hal/src/bio_hw.rs b/libs/bao1x-hal/src/bio_hw.rs index fca4086ef..d6c4fc69d 100644 --- a/libs/bao1x-hal/src/bio_hw.rs +++ b/libs/bao1x-hal/src/bio_hw.rs @@ -502,6 +502,10 @@ impl<'a> BioApi<'a> for BioSharedState { prev_freq } + fn prep_freq_change(&mut self) { + // at the hw level, there's nothing to do; a handler at the `std` level is invoked instead + } + unsafe fn get_core_handle(&self, _fifo: Fifo) -> Result, BioError> { unimplemented!("This is managed by the main loop server, not the hardware interface"); } diff --git a/services/bao1x-hal-service/src/servers/bio.rs b/services/bao1x-hal-service/src/servers/bio.rs index 59573599c..77f46d374 100644 --- a/services/bao1x-hal-service/src/servers/bio.rs +++ b/services/bao1x-hal-service/src/servers/bio.rs @@ -15,6 +15,9 @@ fn bio_service(clk_freq: u32) { let mut resource_tracker = ResourceTracker::new(); + #[cfg(feature = "oem-baosec-lite")] + let led_conn = xns.request_connection_blocking("_oem_led_").unwrap(); + let mut bio_ss = bio_hw::BioSharedState::new(clk_freq); let mut msg_opt = None; loop { @@ -125,6 +128,14 @@ fn bio_service(clk_freq: u32) { } } + BioOp::PrepFreqChange => { + if let Some(_scalar) = msg_opt.as_mut().unwrap().body.scalar_message_mut() { + // pause rendering while the clock transitions, avoiding 'bright glitches' + #[cfg(feature = "oem-baosec-lite")] + xous::send_message(led_conn, xous::Message::new_blocking_scalar(128, 0, 0, 0, 0)).ok(); + } + } + BioOp::GetBioFreq => { if let Some(scalar) = msg_opt.as_mut().unwrap().body.scalar_message_mut() { scalar.arg1 = bio_ss.get_bio_freq() as usize; diff --git a/services/bao1x-hal-service/src/servers/susres.rs b/services/bao1x-hal-service/src/servers/susres.rs index fe7568bed..174cfad13 100644 --- a/services/bao1x-hal-service/src/servers/susres.rs +++ b/services/bao1x-hal-service/src/servers/susres.rs @@ -210,6 +210,7 @@ fn susres_service() { // - The update_bio_freq routine is being "too clever" and compensating for the fd // setting. But it seems like the routine just takes the putative fclk setting as // the argument to update_bio_freq(), I don't see any compensation happening... + bio.prep_freq_change(); if fclk_fd_backup == 0xff { bio.update_bio_freq(48_000_000); } else { @@ -222,6 +223,7 @@ fn susres_service() { // clk_mgr.set_fclk_fd(fclk_fd_backup); // restore the FD before restoring potentially // fast PLL setting + bio.prep_freq_change(); clk_mgr.restore_wfi(); bio.update_bio_freq(clk_mgr.fclk); From d94041bfeb957d2d6a6407edef7e83bbda610ac6 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 22 Apr 2026 01:21:08 +0800 Subject: [PATCH 06/22] add wdt driver translated from C SDK with help of Claude Sonnet 4.6 --- libs/bao1x-hal/src/wdt.rs | 315 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 315 insertions(+) create mode 100644 libs/bao1x-hal/src/wdt.rs diff --git a/libs/bao1x-hal/src/wdt.rs b/libs/bao1x-hal/src/wdt.rs new file mode 100644 index 000000000..3144ec43b --- /dev/null +++ b/libs/bao1x-hal/src/wdt.rs @@ -0,0 +1,315 @@ +use utralib::*; + +// This file mainly machine generated using Claude Sonnet 4.6 Adaptive, by +// feeding in the RTC driver as a template, the Crossbar WDG C driver as a reference, +// and the verilog source files for the IP block. +// +// So far, the only tested aspects are enabling and feeding the watchdog; the +// interrupt feature set is not yet tested. + +/* + This is the ARM "CMSDK APB Watchdog" IP (PrimeCell part number 0x824, + designer 0x3B / ARM). + + The full APB address window is 4 KB (PADDR[11:2]), so a single + xous::map_memory call of 0x1000 bytes covers every register including + LOCK at offset 0xC00. + + Main register block (word indices 0–5, offsets 0x000–0x014) + ----------------------------------------------------------- + LOAD 0x000 32-bit down-counter reload value. + Writing here also immediately reloads the running + counter (the hardware does a synchronised load on + the next WDOGCLK edge). + + VALUE 0x004 Current counter value (read-only). + Read-back of wdog_load is returned immediately after + a write before the first WDOGCLK edge, so the freshly + written value is always visible. + + CONTROL 0x008 [1] RESEN – assert WDOGRES (hardware reset) when the + counter expires while the interrupt is already + active (i.e. the dog was not fed after the first + timeout). + [0] INTEN – enable the counter AND the WDOGINT output. + The counter only decrements while this bit is set. + Clearing it freezes the counter; the reload value + is NOT lost. + + INTCLR 0x00C Write 0x5A to feed the dog (reload counter + clear + the interrupt). Any other value is ignored by the + hardware. + + RAWINTSTAT 0x010 [0] RIS – raw (unmasked) interrupt flag. Set when the + counter reaches zero; cleared by writing INTCLR. + + MASKINTSTAT 0x014 [0] MIS – masked interrupt status (RIS & INTEN). + This is the signal that actually reaches the interrupt subsystem. + + Lock register (word index 768, offset 0xC00) + -------------------------------------------- + LOCK 0xC00 Write LOCK_MAGIC (0x1ACCE551) to unlock all writable + registers. Any other write re-locks them. Reads back + the current lock state (0 = unlocked, 1 = locked). + Reset state is unlocked (wdog_lock = 0). + + Interrupt / reset behaviour summary + ------------------------------------ + First timeout → RAWINTSTAT[0] set, WDOGINT asserted (if INTEN=1). + Feed dog → write 0x5A to INTCLR; counter reloads, interrupt clears. + Second timeout → WDOGRES asserted (if RESEN=1), counter freezes until + LOAD is written again. + + Typical "reset-only, no CPU interrupt" configuration + ------------------------------------------------------ + Set CONTROL = 0b11 (RESEN|INTEN). Do NOT wire the interrupt. + Feed the dog periodically by writing INTCLR. If the firmware hangs the + counter will expire twice and assert the hardware reset line. + This matches the usage in the C HAL (daric_hal_wdg.c). +*/ + +// -- Main registers ------------------------------------------------------------ + +/// Down-counter reload value. Write to set; also reloads the running counter. +pub const LOAD: Register = Register::new(0, 0xFFFF_FFFF); + +/// Current counter value (read-only). +pub const VALUE: Register = Register::new(1, 0xFFFF_FFFF); + +/// Control register. +pub const CONTROL: Register = Register::new(2, 0x3); +/// CONTROL[0]: counter enable + interrupt output enable. +/// The counter only runs while this bit is set. +pub const CONTROL_INTEN: Field = Field::new(1, 0, CONTROL); +/// CONTROL[1]: hardware reset output enable. +pub const CONTROL_RESEN: Field = Field::new(1, 1, CONTROL); + +/// Interrupt clear / dog-feed register. Write [`INTCLR_FEED`] to feed. +pub const INTCLR: Register = Register::new(3, 0xFF); + +/// Raw (unmasked) interrupt status. +pub const RAWINTSTAT: Register = Register::new(4, 0x1); +/// RAWINTSTAT[0]: set when counter reaches zero; cleared by feeding. +pub const RAWINTSTAT_RIS: Field = Field::new(1, 0, RAWINTSTAT); + +/// Masked interrupt status (RAWINTSTAT & INTEN). +pub const MASKINTSTAT: Register = Register::new(5, 0x1); +/// MASKINTSTAT[0]: the interrupt signal seen by the hardware interrupt subsystem. +pub const MASKINTSTAT_MIS: Field = Field::new(1, 0, MASKINTSTAT); + +// -- Lock register (offset 0xC00 = word index 768) ---------------------------- + +/// Software lock register. Protects all writable registers. +/// Word index 768 = byte offset 0xC00, still within the 4 KB APB window. +pub const LOCK: Register = Register::new(768, 0xFFFF_FFFF); + +// -- Constants ----------------------------------------------------------------- + +/// Write to [`LOCK`] to unlock all writable registers. +pub const LOCK_MAGIC: u32 = 0x1ACCE551; +/// Write to [`LOCK`] to re-lock all writable registers. +pub const LOCK_VALUE: u32 = 0x0000_0000; +/// Write to [`INTCLR`] to feed the dog and clear the interrupt. +pub const INTCLR_FEED: u32 = 0x5A; + +/// Physical base address of the WDT peripheral. +pub const HW_WDT_BASE: usize = 0x40041000; +/// Number of 32-bit words needed to cover LOAD … LOCK (inclusive). +/// 769 = indices 0–5 (main regs) + index 768 (LOCK). +pub const WDT_NUMREGS: usize = 769; + +// -- Op enum (for future message-passing integration) ------------------------- + +/// Operations that can be sent to a WDT service. +/// +/// Variants 0–127 are for externally-visible APIs; 1024+ are for +/// implementation-private operations (mirroring the TimeOp convention). +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub enum WdgOp { + /// Enable the watchdog. + /// arg1: load value (ticks); arg2: enable_reset (bool); arg3: enable_irq (bool) + Enable = 0, + + /// Disable the watchdog (freeze counter, clear CONTROL). + Disable = 1, + + /// Feed the dog — reset the counter and clear any pending interrupt. + Feed = 2, + + /// Returns the current counter value in arg1. + GetValue = 3, + + /// Returns 1 in arg1 if the watchdog is currently running (CONTROL != 0). + IsEnabled = 4, + + /// Returns raw interrupt status in arg1 and masked status in arg2. + GetInterruptStatus = 5, + + // -- Implementation-private ops ---------------------------------------- + /// Enable the interrupt output (sets CONTROL[INTEN]; preserves RESEN). + /// Does NOT connect the interrupt — use xous::claim_interrupt separately. + UnmaskInterrupt = 1024, + + /// Disable the interrupt output (clears CONTROL[INTEN]; preserves RESEN). + /// Leaves the counter running if RESEN is still set. + MaskInterrupt = 1025, +} + +// -- Driver ------------------------------------------------------------------- + +/// Single-owner driver for the ARM CMSDK APB Watchdog. +/// +/// # Memory mapping +/// When compiled with the `std` feature (Xous userspace), `new()` calls +/// `xous::map_memory` to obtain a virtual mapping of the 4 KB APB window. +/// Without `std` (bare-metal / privileged context) it uses the physical +/// address directly. +/// +/// # Lock protocol +/// Every write to a protected register must be bracketed by `unlock` / +/// `lock`. Reads do not require unlocking. +/// +/// # Typical "reset-only" setup +/// ```ignore +/// let mut wdt = Wdt::new(); +/// // Feed interval (e.g. 500 ms) expressed in watchdog clock ticks. +/// // Use the WDG_TICKS_PER_MS macro / constant from the BSP. +/// wdt.enable(500 * TICKS_PER_MS, /*enable_reset=*/ true, /*enable_irq=*/ false); +/// +/// loop { +/// do_work(); +/// wdt.feed(); +/// } +/// ``` +pub struct Wdt { + csr: CSR, +} + +impl Wdt { + /// Construct a new `Wdt` driver, mapping hardware memory as required. + pub fn new() -> Self { + #[cfg(feature = "std")] + { + let wdt_range = xous::map_memory( + xous::MemoryAddress::new(HW_WDT_BASE), + None, + // 4 KB covers the full APB window including LOCK at 0xC00 + // and the ID registers at 0xFE0–0xFFC. + 4096, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ) + .expect("couldn't map WDT range"); + Wdt { csr: CSR::new(wdt_range.as_mut_ptr() as *mut u32) } + } + #[cfg(not(feature = "std"))] + { + Wdt { csr: CSR::new(HW_WDT_BASE as *mut u32) } + } + } + + // -- Lock helpers --------------------------------------------------------- + + #[inline] + fn unlock(&mut self) { self.csr.wo(LOCK, LOCK_MAGIC); } + + #[inline] + fn lock(&mut self) { self.csr.wo(LOCK, LOCK_VALUE); } + + // -- Public API ----------------------------------------------------------- + + /// Enable the watchdog and start the counter. + /// + /// - `load_value`: initial (and reload) counter value in watchdog clock ticks. The counter counts down + /// from this value. The clock runs at (pclk / 2) + /// - `enable_reset`: assert the hardware reset output on the *second* consecutive timeout (i.e. when the + /// dog was not fed after the first expiry). Set this `true` for a normal watchdog reset. + /// - `enable_irq`: set CONTROL[INTEN], which both starts the counter *and* drives the WDOGINT output to + /// the interrupt system. For reset-only usage (no CPU interrupt desired) pass `false` here — the + /// counter will still run because INTEN is always forced set internally; see note. + /// + /// # Note on INTEN and the counter + /// The ARM CMSDK watchdog only decrements the counter while INTEN=1 + /// (CONTROL[0]). To use the watchdog *purely* for reset (no interrupt + /// servicing) you still need the counter running, so this function always + /// sets INTEN regardless of whether the interrupt is registered or not + /// with the rest of the system. + pub fn enable(&mut self, load_value: u32, enable_reset: bool) { + self.unlock(); + self.csr.wo(LOAD, load_value); + // INTEN (bit 0) must always be set to start the counter. + // RESEN (bit 1) gates the hardware reset output. + let ctrl = 0b01 | if enable_reset { 0b10 } else { 0 }; + self.csr.wo(CONTROL, ctrl); + self.lock(); + } + + /// Disable the watchdog. + /// + /// Clears CONTROL (freezes the counter and de-asserts outputs) and + /// resets LOAD to the all-ones sentinel so that if the watchdog is + /// inadvertently re-enabled it will take the maximum possible time + /// before expiring. + pub fn disable(&mut self) { + self.unlock(); + self.csr.wo(CONTROL, 0x0); + self.csr.wo(LOAD, 0xFFFF_FFFF); + self.lock(); + } + + /// Feed the dog — reload the counter and clear any pending interrupt. + /// + /// Writes the magic byte `0x5A` to INTCLR. The hardware ignores any + /// other value, so there is no need to check the current state first. + pub fn feed(&mut self) { + self.unlock(); + self.csr.wo(INTCLR, INTCLR_FEED); + self.lock(); + } + + /// Returns `true` if the watchdog counter is currently running + /// (CONTROL != 0). + pub fn is_enabled(&self) -> bool { self.csr.r(CONTROL) != 0 } + + /// Returns the current value of the down-counter. + /// + /// Immediately after writing [`enable`], this reflects the freshly loaded + /// value before the first WDOGCLK edge. + pub fn current_value(&self) -> u32 { self.csr.r(VALUE) } + + /// Returns the raw (unmasked) interrupt flag. + /// + /// Set when the counter reaches zero. Cleared by [`feed`]. + /// This flag is independent of INTEN, so it is visible even when + /// the counter-enable bit is cleared. + pub fn raw_interrupt_pending(&self) -> bool { self.csr.rf(RAWINTSTAT_RIS) != 0 } + + /// Returns the masked interrupt status (RAWINTSTAT & INTEN). + /// + /// This is the signal that would be presented to the CPU if the + /// interrupt line were connected via `xous::claim_interrupt`. + pub fn masked_interrupt_pending(&self) -> bool { self.csr.rf(MASKINTSTAT_MIS) != 0 } + + /// Enable the WDOGINT interrupt output (set CONTROL[INTEN]). + /// + /// Preserves the current RESEN setting. Does NOT connect the CPU — + /// call `xous::claim_interrupt` separately when you are ready to handle + /// the interrupt in software. + pub fn unmask_interrupt(&mut self) { + self.unlock(); + let ctrl = self.csr.r(CONTROL) | 0b01; + self.csr.wo(CONTROL, ctrl); + self.lock(); + } + + /// Disable the WDOGINT interrupt output (clear CONTROL[INTEN]). + /// + /// Preserves the current RESEN setting. Note that clearing INTEN also + /// freezes the counter — call [`unmask_interrupt`] or [`enable`] to + /// resume it. + pub fn mask_interrupt(&mut self) { + self.unlock(); + let ctrl = self.csr.r(CONTROL) & !0b01; + self.csr.wo(CONTROL, ctrl); + self.lock(); + } +} From 4a236cfd68480487eed1692bc21544c4f7e58471 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 22 Apr 2026 01:21:47 +0800 Subject: [PATCH 07/22] add explicit power-off command to display --- libs/bao1x-hal/src/lib.rs | 2 ++ libs/bao1x-hal/src/sh1107.rs | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/libs/bao1x-hal/src/lib.rs b/libs/bao1x-hal/src/lib.rs index 790bc306d..8f36d73d6 100644 --- a/libs/bao1x-hal/src/lib.rs +++ b/libs/bao1x-hal/src/lib.rs @@ -60,6 +60,8 @@ pub mod rtc; pub mod sigcheck; #[cfg(not(feature = "hosted-baosec"))] pub mod sram_trim; +#[cfg(not(feature = "hosted-baosec"))] +pub mod wdt; #[inline(always)] pub fn cache_flush() { diff --git a/libs/bao1x-hal/src/sh1107.rs b/libs/bao1x-hal/src/sh1107.rs index d940ef124..db841d674 100644 --- a/libs/bao1x-hal/src/sh1107.rs +++ b/libs/bao1x-hal/src/sh1107.rs @@ -532,6 +532,11 @@ impl<'a> Oled128x128<'a> { pub fn powerdown(&mut self) { self.powerdown = true; + let powoff = [Command::DisplayOnOff(DisplayState::Off)]; + for command in powoff { + let bytes = command.encode(); + self.send_command(bytes).ok(); + } // assert reset crate::board::assert_periph_reset(self.iox, true); self.iox.set_gpio_pin_value(self.cd_port, self.cd_pin, IoxValue::Low); From d020bda4be509b7ceec74a5e9c8ebe273dc23ad5 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 22 Apr 2026 01:22:18 +0800 Subject: [PATCH 08/22] ignore accelerometer "keys" in video loop --- services/bao-video/src/main.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/services/bao-video/src/main.rs b/services/bao-video/src/main.rs index 722e92ba2..16ee32f55 100644 --- a/services/bao-video/src/main.rs +++ b/services/bao-video/src/main.rs @@ -521,6 +521,11 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { } GfxOpcode::KeyPress => { if let Some(scalar) = msg.body.scalar_message() { + let k = char::from_u32(scalar.arg1 as u32).unwrap_or('\u{0000}'); + if k == '🔽' || k == '🔼' { + // ignore accelerometer reports + continue; + } #[cfg(not(feature = "hosted-baosec"))] // any key press will abort QR acquisition by taking the qr_request. if let Some(mut envelope) = qr_request.take() { From fbe6aad8bb1c644efaf82631a441d3ec6d4e9f5d Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 22 Apr 2026 01:22:31 +0800 Subject: [PATCH 09/22] try to improve suspend/resume stability --- .../bao1x-hal-service/src/servers/keyboard.rs | 2 +- .../bao1x-hal-service/src/servers/susres.rs | 26 ++++++++++++++++--- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/services/bao1x-hal-service/src/servers/keyboard.rs b/services/bao1x-hal-service/src/servers/keyboard.rs index 652d1a0a9..5b6a3e00c 100644 --- a/services/bao1x-hal-service/src/servers/keyboard.rs +++ b/services/bao1x-hal-service/src/servers/keyboard.rs @@ -489,7 +489,7 @@ fn keyboard_service() { ), ) .unwrap_or_else(|_| { - log::info!("Input overflow, dropping keys!"); + log::info!("Input overflow to {}, dropping keys!", conn); xous::Result::Ok }); } diff --git a/services/bao1x-hal-service/src/servers/susres.rs b/services/bao1x-hal-service/src/servers/susres.rs index 174cfad13..9c4d51af2 100644 --- a/services/bao1x-hal-service/src/servers/susres.rs +++ b/services/bao1x-hal-service/src/servers/susres.rs @@ -379,7 +379,14 @@ fn susres_service() { }), Some(Opcode::Quit) => break, Some(Opcode::PlatformSpecific) => { - msg_blocking_scalar_unpack!(msg, op, _arg2, _arg3, _arg4, { + if let xous::Message::BlockingScalar(xous::ScalarMessage { + id: _id, + arg1: op, + arg2: _arg2, + arg3: _arg3, + arg4: _arg4, + }) = msg.body + { let platform_op = FromPrimitive::from_usize(op); match platform_op { Some(ClockOp::GetVco) => { @@ -403,15 +410,26 @@ fn susres_service() { Some(ClockOp::GetPer) => { xous::return_scalar(msg.sender, clk_mgr.perclk as usize).unwrap() } + _ => panic!("Incorrect PlatformOp"), + } + } + if let xous::Message::Scalar(xous::ScalarMessage { + id: _id, + arg1: op, + arg2: _arg2, + arg3: _arg3, + arg4: _arg4, + }) = msg.body + { + let platform_op = FromPrimitive::from_usize(op); + match platform_op { Some(ClockOp::DeepSleep) => { - log::info!("entering deep sleep"); clk_mgr.deep_sleep(); - xous::return_scalar(msg.sender, 1).ok(); // system is shut down after this point, no code runs } _ => panic!("Incorrect PlatformOp"), } - }) + } } None => { log::error!("couldn't convert opcode"); From 8f16270efaa4c33f8b535b82b9ee33d914a2b293 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 22 Apr 2026 03:05:00 +0800 Subject: [PATCH 10/22] fix handling of orientation inputs --- services/bao-video/src/main.rs | 41 +++++++++++++++++----------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/services/bao-video/src/main.rs b/services/bao-video/src/main.rs index 16ee32f55..bb97270a6 100644 --- a/services/bao-video/src/main.rs +++ b/services/bao-video/src/main.rs @@ -522,29 +522,28 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { GfxOpcode::KeyPress => { if let Some(scalar) = msg.body.scalar_message() { let k = char::from_u32(scalar.arg1 as u32).unwrap_or('\u{0000}'); - if k == '🔽' || k == '🔼' { - // ignore accelerometer reports - continue; - } #[cfg(not(feature = "hosted-baosec"))] - // any key press will abort QR acquisition by taking the qr_request. - if let Some(mut envelope) = qr_request.take() { - let acquisition = QrAcquisition { content: None, meta: None }; - let mut response = unsafe { - xous_ipc::Buffer::from_memory_message_mut( - envelope.body.memory_message_mut().unwrap(), - ) - }; - response.replace(acquisition).unwrap(); - if orientation == DisplayOrientation::UpsideDown { + // ignore accelerometer reports + if !(k == '🔽' || k == '🔼') { + // any key press will abort QR acquisition by taking the qr_request. + if let Some(mut envelope) = qr_request.take() { + let acquisition = QrAcquisition { content: None, meta: None }; + let mut response = unsafe { + xous_ipc::Buffer::from_memory_message_mut( + envelope.body.memory_message_mut().unwrap(), + ) + }; + response.replace(acquisition).unwrap(); + if orientation == DisplayOrientation::UpsideDown { + display.flip_vertical(true).unwrap_or_else(|_| { + display_timeout_handler(&udma_global, &mut display) + }) + } display - .flip_vertical(true) - .unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display)) + .pop() + .unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display)); + hal.set_preemption(true); } - display - .pop() - .unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display)); - hal.set_preemption(true); } // forward messages on to listeners iff we don't have an active modal if modal_queue.len() == 0 { @@ -942,7 +941,7 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { #[cfg(feature = "board-baosec")] GfxOpcode::FlipScreen => { if let Some(scalar) = msg.body.scalar_message_mut() { - log::info!("gfx flip"); + log::debug!("gfx flip"); if scalar.arg1 != 0 { orientation = DisplayOrientation::UpsideDown; } else { From a40eba8199b48b62cc2295144e21c84e3bb8389e Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 22 Apr 2026 12:07:49 +0800 Subject: [PATCH 11/22] fix hosted mode warnings --- services/bao-video/src/main.rs | 3 +++ services/bao1x-emu/src/display.rs | 5 +++++ services/bao1x-emu/src/main.rs | 4 ---- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/services/bao-video/src/main.rs b/services/bao-video/src/main.rs index bb97270a6..6f71149ce 100644 --- a/services/bao-video/src/main.rs +++ b/services/bao-video/src/main.rs @@ -431,6 +431,7 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { let mut bw_thresh: u8 = 128; let mut qr_request: Option = None; let mut kbd_listeners: Vec<(CID, usize)> = Vec::new(); + #[allow(unused_mut)] let mut orientation = DisplayOrientation::Normal; loop { if !is_panic.load(Ordering::Relaxed) { @@ -521,6 +522,7 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { } GfxOpcode::KeyPress => { if let Some(scalar) = msg.body.scalar_message() { + #[cfg(not(feature = "hosted-baosec"))] let k = char::from_u32(scalar.arg1 as u32).unwrap_or('\u{0000}'); #[cfg(not(feature = "hosted-baosec"))] // ignore accelerometer reports @@ -975,6 +977,7 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { xous::terminate_process(0) } +#[allow(unused_variables)] fn display_timeout_handler(udma_global: &UdmaGlobal, display: &mut Oled128x128) { log::info!("resetting display spim block"); #[cfg(feature = "board-baosec")] diff --git a/services/bao1x-emu/src/display.rs b/services/bao1x-emu/src/display.rs index cc9ff2c34..26e390241 100644 --- a/services/bao1x-emu/src/display.rs +++ b/services/bao1x-emu/src/display.rs @@ -134,6 +134,11 @@ impl<'a> Oled128x128 { unimplemented!("devboot feature does not exist on this platform"); } + pub fn flip_vertical(&mut self, _flip: bool) -> Result<(), xous::Error> { + log::warn!("flipping not implemented"); + Ok(()) + } + pub fn stash(&mut self) { self.stash.copy_from_slice(&self.buffer); } pub fn pop(&mut self) -> Result<(), xous::Error> { diff --git a/services/bao1x-emu/src/main.rs b/services/bao1x-emu/src/main.rs index 9cd433da8..5b0815b5c 100644 --- a/services/bao1x-emu/src/main.rs +++ b/services/bao1x-emu/src/main.rs @@ -134,8 +134,4 @@ fn main() { } } } - xns.unregister_server(sid).unwrap(); - xous::destroy_server(sid).unwrap(); - log::trace!("quitting"); - xous::terminate_process(0) } From cbd8fa0ea75908a8d77c1f85b2e783137598ef58 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 22 Apr 2026 20:39:18 +0800 Subject: [PATCH 12/22] Update CONTRIBUTING.md --- CONTRIBUTING.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d941455b7..12ad7b9b9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -48,6 +48,7 @@ will not be tolerated). - You **should** disclose the use of AI tools where it might be helpful to the maintainer reviewing your contribution. - Using AI tools to correct grammar and spelling does not require disclosure. - Make your disclosure in your commit message as a trailer; e.g. `Assisted-by: ChatGPTv5` +- Use the tag "AI" on pull requests that were primarily generated or guided by AI tools ## Contribution Workflow From e94b804fc75e8dac459314e447c16f45b29c2b85 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 22 Apr 2026 21:24:01 +0800 Subject: [PATCH 13/22] Update CONTRIBUTING.md --- CONTRIBUTING.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 12ad7b9b9..3f4c22fc3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -50,6 +50,11 @@ will not be tolerated). - Make your disclosure in your commit message as a trailer; e.g. `Assisted-by: ChatGPTv5` - Use the tag "AI" on pull requests that were primarily generated or guided by AI tools +### Scope and Cadence +- Prefer one concern per PR. Bug fixes, refactors, and documentation updates belong in separate PRs even when they touch the same file. +- For mechanical changes that span many files or services (e.g. pattern sweeps), split into per-target PRs and open no more than two per week so review stays tractable. +- Before a large or cross-cutting change, open an issue or discussion first to align on scope. + ## Contribution Workflow This is an overview of the contribution workflow: From 16073c9cf872abcfd2d370bb950a39dda79b5916 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 23 Apr 2026 00:32:43 +0800 Subject: [PATCH 14/22] refactor to cleanup font inclusions allows more degrees of freedom to free up space --- libs/blitstr2/Cargo.toml | 17 ++-- libs/blitstr2/src/fonts.rs | 9 ++ libs/blitstr2/src/lib.rs | 25 +++++ libs/blitstr2/src/style_macros.rs | 152 +++++++++++++++--------------- 4 files changed, 122 insertions(+), 81 deletions(-) diff --git a/libs/blitstr2/Cargo.toml b/libs/blitstr2/Cargo.toml index ad71706c3..09375c379 100644 --- a/libs/blitstr2/Cargo.toml +++ b/libs/blitstr2/Cargo.toml @@ -19,13 +19,18 @@ rkyv = { version = "0.8.8", default-features = false, features = [ ] } [features] +zh = [] +ja = [] +kr = [] +emoji = [] + # selection of board settings for display resolution bao1x = [] -board-baosec = [] -board-baosor = [] -hosted-baosec = [] -hosted = [] -renode = [] -precursor = [] +board-baosec = ["emoji", "ja"] +board-baosor = ["emoji", "ja", "zh", "kr"] +hosted-baosec = ["emoji", "ja", "zh", "kr"] +hosted = ["emoji", "ja", "zh", "kr"] +renode = ["emoji", "ja", "zh", "kr"] +precursor = ["emoji", "ja", "zh", "kr"] default = [] diff --git a/libs/blitstr2/src/fonts.rs b/libs/blitstr2/src/fonts.rs index e50e29af8..ba41467bc 100644 --- a/libs/blitstr2/src/fonts.rs +++ b/libs/blitstr2/src/fonts.rs @@ -3,13 +3,17 @@ // #![allow(dead_code)] pub mod bold; +#[cfg(feature = "emoji")] pub mod emoji; +#[cfg(feature = "ja")] pub mod ja; +#[cfg(feature = "kr")] pub mod kr; pub mod mono; pub mod regular; pub mod small; pub mod tall; +#[cfg(feature = "zh")] pub mod zh; use crate::GlyphSprite; @@ -184,6 +188,7 @@ pub fn tall_glyph(ch: char) -> Result { } } +#[cfg(feature = "emoji")] pub fn emoji_glyph(ch: char) -> Result { match emoji::CODEPOINTS.binary_search(&(ch as u32)) { Ok(n) => { @@ -208,6 +213,7 @@ pub fn emoji_glyph(ch: char) -> Result { } } +#[cfg(feature = "emoji")] pub fn emoji_large_glyph(ch: char) -> Result { match emoji::CODEPOINTS.binary_search(&(ch as u32)) { Ok(n) => { @@ -232,6 +238,7 @@ pub fn emoji_large_glyph(ch: char) -> Result { } } +#[cfg(feature = "zh")] pub fn zh_glyph(ch: char) -> Result { match zh::CODEPOINTS.binary_search(&(ch as u32)) { Ok(n) => { @@ -256,6 +263,7 @@ pub fn zh_glyph(ch: char) -> Result { } } +#[cfg(feature = "ja")] pub fn ja_glyph(ch: char) -> Result { match ja::CODEPOINTS.binary_search(&(ch as u32)) { Ok(n) => { @@ -280,6 +288,7 @@ pub fn ja_glyph(ch: char) -> Result { } } +#[cfg(feature = "kr")] pub fn kr_glyph(ch: char) -> Result { match kr::CODEPOINTS.binary_search(&(ch as u32)) { Ok(n) => { diff --git a/libs/blitstr2/src/lib.rs b/libs/blitstr2/src/lib.rs index 0beab11cd..25b33295a 100644 --- a/libs/blitstr2/src/lib.rs +++ b/libs/blitstr2/src/lib.rs @@ -61,3 +61,28 @@ pub fn glyph_height_hint(g: GlyphStyle) -> usize { GlyphStyle::Tall => 19, } } + +/// Find glyph for char using latin regular, emoji, ja, zh, and kr font data +pub fn style_glyph(locale: &'static str, ch: char, base_style: &GlyphStyle) -> GlyphSprite { + match locale { + #[cfg(feature = "zh")] + "zh" => { + style_wrapper!(zh_rules, base_style, ch) + } + #[cfg(feature = "ja")] + "jp" => { + style_wrapper!(jp_rules, base_style, ch) + } + #[cfg(feature = "kr")] + "kr" => { + style_wrapper!(kr_rules, base_style, ch) + } + "en-tts" => { + style_wrapper!(en_audio_rules, base_style, ch) + } + // default to English rules + _ => { + style_wrapper!(english_rules, base_style, ch) + } + } +} diff --git a/libs/blitstr2/src/style_macros.rs b/libs/blitstr2/src/style_macros.rs index 219769157..7f0688483 100644 --- a/libs/blitstr2/src/style_macros.rs +++ b/libs/blitstr2/src/style_macros.rs @@ -30,78 +30,79 @@ macro_rules! style_wrapper { } #[macro_export] +#[cfg(feature = "zh")] macro_rules! zh_rules { - ($base_style:expr, $emoji_style:expr, $ch:ident) => { - match zh_glyph($ch) { - Ok(g) => g, - _ => match $base_style($ch) { - Ok(g) => g, - _ => match $emoji_style($ch) { - Ok(g) => g, - _ => match ja_glyph($ch) { - Ok(g) => g, - _ => match kr_glyph($ch) { - Ok(g) => g, - _ => match $base_style(REPLACEMENT) { - Ok(g) => g, - _ => NULL_GLYPH_SPRITE, - }, - }, - }, - }, - }, + ($base_style:expr, $emoji_style:expr, $ch:ident) => {{ + // Always-present: zh itself, base, emoji + #[allow(unused_mut)] + let mut result = + zh_glyph($ch).ok().or_else(|| $base_style($ch).ok()).or_else(|| $emoji_style($ch).ok()); + + #[cfg(feature = "ja")] + if result.is_none() { + result = ja_glyph($ch).ok(); } - }; + + #[cfg(feature = "kr")] + if result.is_none() { + result = kr_glyph($ch).ok(); + } + + // Always-present: replacement and null sentinel + result.or_else(|| $base_style(REPLACEMENT).ok()).unwrap_or(NULL_GLYPH_SPRITE) + }}; } #[macro_export] +#[cfg(feature = "ja")] macro_rules! jp_rules { - ($base_style:expr, $emoji_style:expr, $ch:ident) => { - match ja_glyph($ch) { - Ok(g) => g, - _ => match $base_style($ch) { - Ok(g) => g, - _ => match $emoji_style($ch) { - Ok(g) => g, - _ => match zh_glyph($ch) { - Ok(g) => g, - _ => match kr_glyph($ch) { - Ok(g) => g, - _ => match $base_style(REPLACEMENT) { - Ok(g) => g, - _ => NULL_GLYPH_SPRITE, - }, - }, - }, - }, - }, + ($base_style:expr, $emoji_style:expr, $ch:ident) => {{ + // Always-present: ja itself, base, emoji + #[allow(unused_mut)] + let mut result = + ja_glyph($ch).ok().or_else(|| $base_style($ch).ok()).or_else(|| $emoji_style($ch).ok()); + + // Optional: zh fallback only if zh is in the build + #[cfg(feature = "zh")] + if result.is_none() { + result = zh_glyph($ch).ok(); } - }; + + // Optional: kr fallback only if kr is in the build + #[cfg(feature = "kr")] + if result.is_none() { + result = kr_glyph($ch).ok(); + } + + // Always-present: replacement and null sentinel + result.or_else(|| $base_style(REPLACEMENT).ok()).unwrap_or(NULL_GLYPH_SPRITE) + }}; } #[macro_export] +#[cfg(feature = "kr")] macro_rules! kr_rules { - ($base_style:expr, $emoji_style:expr, $ch:ident) => { - match kr_glyph($ch) { - Ok(g) => g, - _ => match $base_style($ch) { - Ok(g) => g, - _ => match $emoji_style($ch) { - Ok(g) => g, - _ => match ja_glyph($ch) { - Ok(g) => g, - _ => match zh_glyph($ch) { - Ok(g) => g, - _ => match $base_style(REPLACEMENT) { - Ok(g) => g, - _ => NULL_GLYPH_SPRITE, - }, - }, - }, - }, - }, + ($base_style:expr, $emoji_style:expr, $ch:ident) => {{ + // Always-present: kr itself, base, emoji + #[allow(unused_mut)] + let mut result = + kr_glyph($ch).ok().or_else(|| $base_style($ch).ok()).or_else(|| $emoji_style($ch).ok()); + + // Optional: ja fallback only if ja is in the build + #[cfg(feature = "ja")] + if result.is_none() { + result = ja_glyph($ch).ok(); } - }; + + // Optional: zh fallback only if zh is in the build + #[cfg(feature = "zh")] + if result.is_none() { + result = zh_glyph($ch).ok(); + } + + // Always-present: replacement and null sentinel + result.or_else(|| $base_style(REPLACEMENT).ok()).unwrap_or(NULL_GLYPH_SPRITE) + }}; } #[macro_export] @@ -150,27 +151,28 @@ macro_rules! english_rules { // Reflect reduced font space on small-memory footprint devices #[cfg(any(feature = "board-baosec", feature = "hosted-baosec"))] macro_rules! english_rules { - ($base_style:expr, $emoji_style:expr, $ch:ident) => { - match $base_style($ch) { - Ok(g) => g, - _ => match $emoji_style($ch) { - Ok(g) => g, - // add more character sets to bao1x target by adding match clauses here - _ => match zh_glyph($ch) { - Ok(g) => g, - _ => match $base_style(REPLACEMENT) { - Ok(g) => g, - _ => NULL_GLYPH_SPRITE, - }, - }, - }, + ($base_style:expr, $emoji_style:expr, $ch:ident) => {{ + // Always-present: base, emoji + #[allow(unused_mut)] + let mut result = $base_style($ch).ok().or_else(|| $emoji_style($ch).ok()); + + // Optional: zh fallback only if zh is in the build + #[cfg(feature = "zh")] + if result.is_none() { + result = zh_glyph($ch).ok(); } - }; + + // Always-present: replacement and null sentinel + result.or_else(|| $base_style(REPLACEMENT).ok()).unwrap_or(NULL_GLYPH_SPRITE) + }}; } pub use en_audio_rules; pub use english_rules; +#[cfg(feature = "ja")] pub use jp_rules; +#[cfg(feature = "kr")] pub use kr_rules; pub use style_wrapper; +#[cfg(feature = "zh")] pub use zh_rules; From 4102cfd3a589e8b923846b496a1d5649679e9fa8 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 23 Apr 2026 00:33:47 +0800 Subject: [PATCH 15/22] move locales macro to blitstr2 this keeps font features in a single crate --- libs/ux-api/src/widgets/modal.rs | 10 ++------- libs/ux-api/src/wordwrap.rs | 37 ++++++++------------------------ 2 files changed, 11 insertions(+), 36 deletions(-) diff --git a/libs/ux-api/src/widgets/modal.rs b/libs/ux-api/src/widgets/modal.rs index d363ea852..ae7878198 100644 --- a/libs/ux-api/src/widgets/modal.rs +++ b/libs/ux-api/src/widgets/modal.rs @@ -293,10 +293,7 @@ fn layout(modal: &mut Modal, top_text: Option<&str>, bot_text: Option<&str>, sty top_tv.invert = true; // specify a clip rect that's the biggest possible allowed. If we don't do this, the current // canvas bounds are used, and the operation will fail if the text has to get bigger. - top_tv.clip_rect = Some(Rectangle::new( - Point::new(0, 0), - Point::new(current_bounds.x, LINES - 2 * modal.line_height), - )); + top_tv.clip_rect = Some(Rectangle::new(Point::new(0, 0), current_bounds)); write!(top_tv.text, "{}", top_str).unwrap(); log::trace!("posting top tv: {:?}", top_tv); @@ -340,10 +337,7 @@ fn layout(modal: &mut Modal, top_text: Option<&str>, bot_text: Option<&str>, sty bot_tv.invert = true; // specify a clip rect that's the biggest possible allowed. If we don't do this, the current canvas // bounds are used, and the operation will fail if the text has to get bigger. - bot_tv.clip_rect = Some(Rectangle::new( - Point::new(0, 0), - Point::new(current_bounds.x, LINES - 2 * modal.line_height), - )); + bot_tv.clip_rect = Some(Rectangle::new(Point::new(0, 0), current_bounds)); write!(bot_tv.text, "{}", bot_str).unwrap(); log::trace!("posting bot tv: {:?}", bot_tv); diff --git a/libs/ux-api/src/wordwrap.rs b/libs/ux-api/src/wordwrap.rs index a73947889..02ec84597 100644 --- a/libs/ux-api/src/wordwrap.rs +++ b/libs/ux-api/src/wordwrap.rs @@ -244,15 +244,15 @@ pub struct Typesetter { impl Typesetter { pub fn setup(s: &str, extent: &Point, base_style: &GlyphStyle, insertion_point: Option) -> Self { let bb = ClipRect::new(0, 0, extent.x, extent.y); - let mut space = style_glyph(' ', base_style); + let mut space = style_glyph(locales::LANG, ' ', base_style); space.kern = 0; - let mut ellipsis = style_glyph('…', base_style); + let mut ellipsis = style_glyph(locales::LANG, '…', base_style); ellipsis.kern = 0; #[cfg(not(feature = "bao1x"))] - let mut large_space = style_glyph(' ', &GlyphStyle::Cjk); + let mut large_space = style_glyph(locales::LANG, ' ', &GlyphStyle::Cjk); #[cfg(feature = "bao1x")] - let mut large_space = style_glyph(' ', &GlyphStyle::Tall); + let mut large_space = style_glyph(locales::LANG, ' ', &GlyphStyle::Tall); if cfg!(feature = "bao1x") { large_space.wide = glyph_to_height_hint(GlyphStyle::Tall) as u8; @@ -396,8 +396,11 @@ impl Typesetter { // line for it. // 5. The evolving word fits a line but doesn't fit this line, and there is no more space at // all. - let mut gs = - if ch != '\t' { style_glyph(ch, &self.base_style) } else { self.large_space.clone() }; + let mut gs = if ch != '\t' { + style_glyph(locales::LANG, ch, &self.base_style) + } else { + self.large_space.clone() + }; if self.is_insert_point() { gs.insert = true; } @@ -637,25 +640,3 @@ fn tsw_debug(tsw: &TypesetWord) { } log::info!("{} @ {},{}+{}={}", &s, tsw.origin.x, tsw.origin.y, tsw.height, tsw.origin.y + tsw.height); } - -/// Find glyph for char using latin regular, emoji, ja, zh, and kr font data -pub fn style_glyph(ch: char, base_style: &GlyphStyle) -> GlyphSprite { - match locales::LANG { - "zh" => { - style_wrapper!(zh_rules, base_style, ch) - } - "jp" => { - style_wrapper!(jp_rules, base_style, ch) - } - "kr" => { - style_wrapper!(kr_rules, base_style, ch) - } - "en-tts" => { - style_wrapper!(en_audio_rules, base_style, ch) - } - // default to English rules - _ => { - style_wrapper!(english_rules, base_style, ch) - } - } -} From 4319faa9d0a437b6b6f2575da257da1f4d77e87a Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 23 Apr 2026 00:34:15 +0800 Subject: [PATCH 16/22] improve layout for modals --- services/modals/src/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/modals/src/main.rs b/services/modals/src/main.rs index 645361eda..69a44a684 100644 --- a/services/modals/src/main.rs +++ b/services/modals/src/main.rs @@ -139,7 +139,7 @@ fn wrapped_main() -> ! { Some("Placeholder"), None, DEFAULT_STYLE, - 8, + 4, ); #[cfg(any(feature = "hosted-baosec", feature = "bao1x"))] let mut renderer_modal = Modal::new( @@ -148,7 +148,7 @@ fn wrapped_main() -> ! { Some("Placeholder"), None, DEFAULT_STYLE, - 8, + 4, ); #[cfg(any(feature = "hosted-baosec", feature = "bao1x"))] { From 9815e33f4e243fc08746b6d78087df80b51c8c31 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 23 Apr 2026 00:34:35 +0800 Subject: [PATCH 17/22] fix missing packet issue due to storage overflow --- services/usb-bao1x/src/hw.rs | 6 +++--- services/usb-bao1x/src/main.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/usb-bao1x/src/hw.rs b/services/usb-bao1x/src/hw.rs index d3b158091..c09748a66 100644 --- a/services/usb-bao1x/src/hw.rs +++ b/services/usb-bao1x/src/hw.rs @@ -47,7 +47,7 @@ pub struct Bao1xUsb<'a> { >, >, // storage for hid_packets to expatriate from the interrupt handler - pub hid_packet: Option<[u8; 64]>, + pub hid_packet: VecDeque<[u8; 64]>, pub serial_port: SerialPort<'a, CorigineWrapper, [u8; 1024], [u8; 1024]>, // holds one HS packet - must be statically allocated in IRQ handler. Valid length is // passed as part of the interrupt recovery message. @@ -117,7 +117,7 @@ impl<'a> Bao1xUsb<'a> { fido_tx_queue: RefCell::new(VecDeque::new()), kbd_tx_queue: RefCell::new(VecDeque::new()), irq_req: None, - hid_packet: None, + hid_packet: VecDeque::with_capacity(4), serial_port, serial_rx: [0u8; SERIAL_MAX_PACKET_SIZE], double_lock: AtomicBool::new(false), @@ -299,7 +299,7 @@ pub(crate) fn composite_handler(_irq_no: usize, arg: *mut usize) { match class.device::, _>().read_report() { Ok(u2f_report) => { // crate::println!("got report {:x?}", u2f_report); - usb.hid_packet = Some(u2f_report.packet); + usb.hid_packet.push_back(u2f_report.packet); xous::try_send_message( usb.conn, Message::new_scalar(Opcode::IrqFidoRx.to_usize().unwrap(), 0, 0, 0, 0), diff --git a/services/usb-bao1x/src/main.rs b/services/usb-bao1x/src/main.rs index bd86eb26c..58f15fc79 100644 --- a/services/usb-bao1x/src/main.rs +++ b/services/usb-bao1x/src/main.rs @@ -414,7 +414,7 @@ pub(crate) fn main_hw() -> ! { } } Opcode::IrqFidoRx => { - if let Some(raw_report) = cu.hid_packet.take() { + if let Some(raw_report) = cu.hid_packet.pop_front() { let u2f_report = HIDReport(raw_report); if let Some(mut listener) = fido_listener.take() { let mut response = unsafe { From 0850e0d7afb5175df11c7482f3ab1086db12f9b1 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 23 Apr 2026 12:29:59 +0800 Subject: [PATCH 18/22] fix guard memory error in CI --- loader/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/loader/src/lib.rs b/loader/src/lib.rs index d9b220f56..84eeb9a43 100644 --- a/loader/src/lib.rs +++ b/loader/src/lib.rs @@ -45,7 +45,7 @@ pub const GUARD_MEMORY_BYTES: usize = 3 * crate::PAGE_SIZE; #[cfg(all(feature = "swap", not(feature = "resume"), not(feature = "bao1x")))] 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 = 8 * crate::PAGE_SIZE; +pub const GUARD_MEMORY_BYTES: usize = 9 * 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 = 9 * crate::PAGE_SIZE; // 1 extra page for clean suspend From c8528747e969b9d16409d0edfd28fb196b1eb5eb Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 23 Apr 2026 15:13:11 +0800 Subject: [PATCH 19/22] adjust other configurations stack limit --- loader/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/loader/src/lib.rs b/loader/src/lib.rs index 84eeb9a43..9e8d7e3a8 100644 --- a/loader/src/lib.rs +++ b/loader/src/lib.rs @@ -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 = 8 * crate::PAGE_SIZE; +pub const GUARD_MEMORY_BYTES: usize = 9 * crate::PAGE_SIZE; #[cfg(all(feature = "swap", not(feature = "resume"), feature = "bao1x"))] pub const GUARD_MEMORY_BYTES: usize = 9 * 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 = 9 * crate::PAGE_SIZE; // 1 extra page for clean suspend +pub const GUARD_MEMORY_BYTES: usize = 10 * crate::PAGE_SIZE; // 1 extra page for clean suspend #[cfg(feature = "swap")] pub const SWAPPER_PID: u8 = 2; From 4d1dc33ef10a1484eef950b0397146eea7bfc575 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 23 Apr 2026 15:14:27 +0800 Subject: [PATCH 20/22] add a diffusive transition option to the graphics library makes changing between bitmaps less jarring --- Cargo.lock | 3 + libs/bao1x-hal/src/sh1107.rs | 164 +++++++++++++++++++++++++++++++++ libs/ux-api/src/service/api.rs | 3 + libs/ux-api/src/service/gfx.rs | 23 +++++ services/bao-video/Cargo.toml | 5 + services/bao-video/src/main.rs | 9 ++ 6 files changed, 207 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index a06f9bbd6..056c68448 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -397,6 +397,7 @@ dependencies = [ "bao1x-hal-service", "base64 0.22.1", "blitstr2", + "getrandom 0.2.12", "libm 0.2.8", "locales", "log", @@ -404,6 +405,8 @@ dependencies = [ "nalgebra", "num-derive 0.4.2", "num-traits", + "rand 0.8.5", + "rand_core 0.6.4", "rkyv 0.8.8", "rqrr", "utralib 0.1.27", diff --git a/libs/bao1x-hal/src/sh1107.rs b/libs/bao1x-hal/src/sh1107.rs index db841d674..48e579c21 100644 --- a/libs/bao1x-hal/src/sh1107.rs +++ b/libs/bao1x-hal/src/sh1107.rs @@ -609,6 +609,170 @@ impl<'a> Oled128x128<'a> { } } } + + /// A diffusion-transition effect courtesy of Claude Sonnet 4.6. Query fed in `render_bitmap` code + /// and asked for a variant that does a "diffusive dither" transition. Applied largely without changes; + /// the main change was adjusting the seed to be passed, in instead of fixed, so the transition can be + /// different every call. + #[cfg(feature = "std")] + pub fn render_bitmap_diffuse( + &mut self, + bitmap: &ux_api::service::api::BaosecBitmap, + frames: usize, + seed: u64, + ) -> Result<(), xous::Error> { + use std::collections::VecDeque; + + const W: isize = WIDTH as isize; + const H: isize = LINES as isize; + + // -- 1. Build per-pixel metadata for the destination region -------------- + // + // We work in framebuffer linear-index space (0..WIDTH*LINES). + // Three bitmasks, each 512 u32 words == 16 384 bits == one bit per pixel. + + let mut in_region = [0u32; 512]; // 1 = this fb pixel is touched by the bitmap + let mut target_bit = [0u32; 512]; // desired final value for pixels in region + let mut settled = [0u32; 512]; // 1 = pixel already written this transition + + // Clamp the source bounding box (mirrors render_bitmap). + 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); + + let mut total: usize = 0; + + for src_y in src_y0..src_y1 { + let dst_y = src_y + bitmap.top_left.y; + if dst_y < 0 || dst_y >= H { + continue; + } + for src_x in src_x0..src_x1 { + let dst_x = src_x + bitmap.top_left.x; + if dst_x < 0 || dst_x >= W { + continue; + } + + let src_lin = (src_x + src_y * W) as usize; + let dst_lin = (dst_x + dst_y * W) as usize; + + in_region[dst_lin >> 5] |= 1 << (dst_lin & 31); + total += 1; + + let bit = (bitmap.bits[src_lin >> 5] >> (src_lin & 31)) & 1; + if bit != 0 { + target_bit[dst_lin >> 5] |= 1 << (dst_lin & 31); + } + } + } + + if total == 0 || frames == 0 { + return Ok(()); + } + + // -- 2. Collect region pixel indices for random seeding ------------------ + + let mut region_pixels: Vec = Vec::with_capacity(total); + for i in 0..(WIDTH as usize * LINES as usize) { + if (in_region[i >> 5] >> (i & 31)) & 1 != 0 { + region_pixels.push(i); + } + } + + // -- 3. Tiny xorshift-64 RNG (no std::collections dependency needed) ----- + + let mut rng: u64 = seed ^ total as u64; + macro_rules! rand { + () => {{ + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + rng + }}; + } + + // -- 4. Diffusion loop ---------------------------------------------------- + + let pixels_per_frame = (total / frames).max(1); + + // Scatter a handful of seeds so diffusion starts from multiple origins. + let mut frontier: VecDeque = VecDeque::new(); + let n_seeds = (total / 32).clamp(1, 64); + for _ in 0..n_seeds { + let dl = region_pixels[(rand!() as usize) % total]; + if (settled[dl >> 5] >> (dl & 31)) & 1 == 0 { + settled[dl >> 5] |= 1 << (dl & 31); + frontier.push_back(dl); + } + } + + let mut committed: usize = 0; + + while committed < total { + let mut this_frame: usize = 0; + + while this_frame < pixels_per_frame { + // If the frontier runs dry, plant a new random seed. + if frontier.is_empty() { + let mut planted = false; + for _ in 0..64 { + let dl = region_pixels[(rand!() as usize) % total]; + if (settled[dl >> 5] >> (dl & 31)) & 1 == 0 { + settled[dl >> 5] |= 1 << (dl & 31); + frontier.push_back(dl); + planted = true; + break; + } + } + if !planted { + break; + } // all pixels settled + } + + // -- commit the next frontier pixel ------------------------------- + let dl = frontier.pop_front().unwrap(); + + let on = (target_bit[dl >> 5] >> (dl & 31)) & 1; + if on != 0 { + self.buffer[dl >> 5] |= 1 << (dl & 31); + } else { + self.buffer[dl >> 5] &= !(1 << (dl & 31)); + } + this_frame += 1; + + // -- expand to unsettled cardinal neighbours in the region --------- + let dst_x = (dl % WIDTH as usize) as isize; + let dst_y = (dl / WIDTH as usize) as isize; + + for (nx, ny) in + [(dst_x - 1, dst_y), (dst_x + 1, dst_y), (dst_x, dst_y - 1), (dst_x, dst_y + 1)] + { + if nx < 0 || nx >= W || ny < 0 || ny >= H { + continue; + } + let ndl = (nx + ny * W) as usize; + if (in_region[ndl >> 5] >> (ndl & 31)) & 1 == 0 { + continue; + } + if (settled[ndl >> 5] >> (ndl & 31)) & 1 != 0 { + continue; + } + settled[ndl >> 5] |= 1 << (ndl & 31); + frontier.push_back(ndl); + } + } + + committed += this_frame; + if this_frame > 0 { + self.redraw()?; + } + if this_frame == 0 { + break; + } // guard against impossible stuck state + } + Ok(()) + } } impl<'a> FrameBuffer for Oled128x128<'a> { diff --git a/libs/ux-api/src/service/api.rs b/libs/ux-api/src/service/api.rs index 236439f5f..344dfc561 100644 --- a/libs/ux-api/src/service/api.rs +++ b/libs/ux-api/src/service/api.rs @@ -111,6 +111,9 @@ pub enum GfxOpcode { /// This call is specific and highly optimized to the display on Baosec BaosecBitmap, #[cfg(feature = "board-baosec")] + /// This call is specific and highly optimized to the display on Baosec + BaosecBitmapDiffuse, + #[cfg(feature = "board-baosec")] Brightness, #[cfg(feature = "board-baosec")] FlipScreen, diff --git a/libs/ux-api/src/service/gfx.rs b/libs/ux-api/src/service/gfx.rs index 07f1b730c..383c5ace8 100644 --- a/libs/ux-api/src/service/gfx.rs +++ b/libs/ux-api/src/service/gfx.rs @@ -792,6 +792,29 @@ impl Gfx { Ok(()) } + #[cfg(feature = "board-baosec")] + pub fn bitmap_diffusion( + &self, + bitmap: &[u32], + top_left: Option, + bounding_box: Option, + ) -> 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::BaosecBitmapDiffuse.to_u32().unwrap())?; + Ok(()) + } + #[cfg(feature = "board-baosec")] pub fn brightness(&self, level: u8) -> Result<(), xous::Error> { send_message( diff --git a/services/bao-video/Cargo.toml b/services/bao-video/Cargo.toml index a764b225e..6daaf0042 100644 --- a/services/bao-video/Cargo.toml +++ b/services/bao-video/Cargo.toml @@ -35,6 +35,11 @@ base64 = { version = "0.22.1", optional = true } locales = { path = "../../locales" } +# diffusion dithering +rand = { version = "0.8.5", features = ["getrandom"] } +rand_core = "0.6.4" +getrandom = "=0.2.12" + [features] no-gam = ["modals/no-gam"] gfx-testing = [] diff --git a/services/bao-video/src/main.rs b/services/bao-video/src/main.rs index 6f71149ce..01238d6e0 100644 --- a/services/bao-video/src/main.rs +++ b/services/bao-video/src/main.rs @@ -932,6 +932,15 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { display.render_bitmap(bitmap); } #[cfg(feature = "board-baosec")] + GfxOpcode::BaosecBitmapDiffuse => { + use rand::Rng; + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let bitmap = buffer.to_original::().unwrap(); + display + .render_bitmap_diffuse(&bitmap, 10, rand::thread_rng().gen::()) + .unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display)); + } + #[cfg(feature = "board-baosec")] GfxOpcode::Brightness => { if let Some(scalar) = msg.body.scalar_message_mut() { let brightness = scalar.arg1.min(255) as u8; From 6a7caff54c65a31282528a3d9e49d7bdf8f0a051 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 26 Apr 2026 17:32:05 +0800 Subject: [PATCH 21/22] improve display boot stability an instance of the SPI interface timing out was observed on boot. It's rare, but it happens. This wraps those early calls with a retry loop and then fail to reboot in case something really goes wrong. Assisted-by: qwen3.6:27b (local) --- Cargo.lock | 1 + services/bao-video/Cargo.toml | 1 + services/bao-video/src/main.rs | 48 +++++++++++++++++++++++++++------- 3 files changed, 41 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 056c68448..e22169404 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -414,6 +414,7 @@ dependencies = [ "xous 0.9.70 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.10 (registry+https://github.com/rust-lang/crates.io-index)", ] diff --git a/services/bao-video/Cargo.toml b/services/bao-video/Cargo.toml index 6daaf0042..e746da8a5 100644 --- a/services/bao-video/Cargo.toml +++ b/services/bao-video/Cargo.toml @@ -26,6 +26,7 @@ rkyv = { version = "0.8.8", default-features = false, features = [ "alloc", ] } modals = { path = "../modals", optional = true } +susres = { package = "xous-api-susres", path = "../../api/xous-api-susres" } # QR decoding libm = { version = "0.2.8" } diff --git a/services/bao-video/src/main.rs b/services/bao-video/src/main.rs index 01238d6e0..28373db6a 100644 --- a/services/bao-video/src/main.rs +++ b/services/bao-video/src/main.rs @@ -70,6 +70,8 @@ use xous_ipc::Buffer; pub const IMAGE_WIDTH: usize = 256; pub const IMAGE_HEIGHT: usize = 240; +const MAX_RETRIES: u32 = 5; + #[derive(PartialEq, Eq, Clone, Copy)] enum DisplayOrientation { Normal, @@ -224,10 +226,9 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { let hal = Hal::new(); let mut display = Oled128x128::new(main_thread_token, bao1x_api::PERCLK, &iox, &udma_global); - // these unwrap because if we have a time-out at this stage, it's likely a hardware problem - display.init().unwrap(); + retry_display_op(&udma_global, &mut display, |d| d.init()).unwrap(); display.clear(); - display.draw().unwrap(); + retry_display_op(&udma_global, &mut display, |d| d.draw()).unwrap(); // ---- panic handler - set up early so we can see panics quickly // install the graphical panic handler. It won't catch really early panics, or panics in this crate, @@ -968,7 +969,9 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { } } } - GfxOpcode::Quit => break, + GfxOpcode::Quit => { + log::info!("refusing to quit, this operation is not supported on this platform!"); + } _ => { // This is perfectly normal because not all opcodes are handled by all platforms. log::debug!("Invalid or unhandled opcode: {:?}", opcode); @@ -979,11 +982,6 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { tt.sleep_ms(10_000).unwrap(); } } - log::trace!("main loop exit, destroying servers"); - xns.unregister_server(sid).unwrap(); - xous::destroy_server(sid).unwrap(); - log::trace!("quitting"); - xous::terminate_process(0) } #[allow(unused_variables)] @@ -995,3 +993,35 @@ fn display_timeout_handler(udma_global: &UdmaGlobal, display: &mut Oled128x128) display.reinit_spi(); } } + +/// This is actually "infalliable" in the sense that if we can't initialize the +/// display, we diverge and reboot. +fn retry_display_op(udma: &UdmaGlobal, display: &mut Oled128x128, mut op: F) -> Result +where + F: FnMut(&mut Oled128x128) -> Result, + E: core::fmt::Debug, +{ + let mut attempts = 0; + loop { + match op(display) { + Ok(val) => return Ok(val), + Err(e) => { + std::thread::sleep(std::time::Duration::from_millis(50)); + attempts += 1; + if attempts >= MAX_RETRIES { + log::warn!("Display seems stuck, rebooting whole chip."); + let xns = xous_names::XousNames::new().unwrap(); + let susres = susres::Susres::new_without_hook(&xns).unwrap(); + susres.reboot(true).ok(); + } + log::warn!( + "Display op failed (attempt {}/{}), resetting SPI block... {:?}", + attempts, + MAX_RETRIES, + e + ); + display_timeout_handler(udma, display); + } + } + } +} From dd45a11c7b3352ab9adb01e431fcaebb821ec09b Mon Sep 17 00:00:00 2001 From: tunnell <2406627+tunnell@users.noreply.github.com> Date: Sun, 26 Apr 2026 08:39:01 -0500 Subject: [PATCH 22/22] emulation: cast frequency to ulong for Renode v1.16+ compatibility Renode v1.16 changed the LimitTimer constructor signature from `long frequency` to `ulong frequency`. Without this cast, the LiteX_Timer_32 peripheral fails to compile against current Renode versions, causing emulation to exit immediately with a peripheral build failure rather than booting Xous. Tested with Renode v1.16.1.4499 (build 9d55b4e6-202604170227) against the standard emulation/xous-release.resc startup. With the cast, Xous boots through to the main loop. Without it, Renode exits before any boot output appears. --- emulation/peripherals/LiteX_Timer_32.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/emulation/peripherals/LiteX_Timer_32.cs b/emulation/peripherals/LiteX_Timer_32.cs index c85124a20..5b2a277f0 100644 --- a/emulation/peripherals/LiteX_Timer_32.cs +++ b/emulation/peripherals/LiteX_Timer_32.cs @@ -20,7 +20,7 @@ namespace Antmicro.Renode.Peripherals.Timers.Betrusted public LiteX_Timer_32(Machine machine, long frequency) : base(machine) { IRQ = new GPIO(); - innerTimer = new LimitTimer(machine.ClockSource, frequency, this, "LiteXTimer32", eventEnabled: true, autoUpdate: true); + innerTimer = new LimitTimer(machine.ClockSource, (ulong)frequency, this, "LiteXTimer32", eventEnabled: true, autoUpdate: true); innerTimer.LimitReached += delegate { this.Log(LogLevel.Noisy, "Limit reached");