'fix' for timeout issue on SPIM during display writes

occassionally the hardware block just goes unresponsive. the
'fix' is to reset it, and then re-initialize the interface.

I suspect this has to do with the UDMA silently dropping transactions
when there's too much contention on the bus.
This commit is contained in:
bunnie 2026-03-30 23:34:25 +08:00
parent b7826c2ebc
commit 3993a0dc88
6 changed files with 81 additions and 50 deletions

View file

@ -183,6 +183,7 @@ pub struct Oled128x128<'a> {
powerdown: bool, powerdown: bool,
power_port: IoxPort, power_port: IoxPort,
power_pin: u8, power_pin: u8,
clk_div: u8,
} }
impl<'a> Oled128x128<'a> { impl<'a> Oled128x128<'a> {
@ -267,9 +268,19 @@ impl<'a> Oled128x128<'a> {
power_port, power_port,
power_pin, power_pin,
powerdown: false, powerdown: false,
clk_div: ((perclk_freq / 2) / 2_000_000) as u8,
} }
} }
// used to recover a wedged SPI interface
pub fn reinit_spi(&mut self) {
self.spim.send_cmd_list(&[crate::udma::SpimCmd::Config(
SpimClkPol::LeadingEdgeRise,
SpimClkPha::CaptureOnLeading,
self.clk_div,
)]);
}
/// This should only be called to initialize the panic handler with its own /// This should only be called to initialize the panic handler with its own
/// copy of hardware registers. /// copy of hardware registers.
/// ///
@ -300,8 +311,9 @@ impl<'a> Oled128x128<'a> {
Option<CommandSet>, Option<CommandSet>,
), ),
bool, bool,
u8,
) { ) {
(self.spim.into_raw_parts(), self.powerdown) (self.spim.into_raw_parts(), self.powerdown, self.clk_div)
} }
/// Creates a clone of the display handle. This is only safe if the handles are used in a /// Creates a clone of the display handle. This is only safe if the handles are used in a
@ -331,6 +343,7 @@ impl<'a> Oled128x128<'a> {
Option<CommandSet>, Option<CommandSet>,
), ),
bool, bool,
u8,
), ),
iox: &'a T, iox: &'a T,
) -> Self ) -> Self
@ -354,6 +367,7 @@ impl<'a> Oled128x128<'a> {
command_set, command_set,
), ),
powerdown, powerdown,
clk_div,
) = display_parts; ) = display_parts;
// compile them into a new object // compile them into a new object
let mut spim = unsafe { let mut spim = unsafe {
@ -398,6 +412,7 @@ impl<'a> Oled128x128<'a> {
powerdown, powerdown,
power_pin, power_pin,
power_port, power_port,
clk_div,
} }
} }
@ -407,7 +422,7 @@ impl<'a> Oled128x128<'a> {
pub fn screen_size(&self) -> Point { Point::new(WIDTH, LINES) } pub fn screen_size(&self) -> Point { Point::new(WIDTH, LINES) }
pub fn redraw(&mut self) { self.draw(); } pub fn redraw(&mut self) -> Result<(), xous::Error> { self.draw() }
pub fn blit_screen(&mut self, bmp: &[u32]) { self.buffer.copy_from_slice(bmp); } pub fn blit_screen(&mut self, bmp: &[u32]) { self.buffer.copy_from_slice(bmp); }
@ -417,21 +432,21 @@ impl<'a> Oled128x128<'a> {
pub fn stash(&mut self) { self.stash.copy_from_slice(&self.buffer); } pub fn stash(&mut self) { self.stash.copy_from_slice(&self.buffer); }
pub fn pop(&mut self) { pub fn pop(&mut self) -> Result<(), xous::Error> {
self.buffer.copy_from_slice(&self.stash); self.buffer.copy_from_slice(&self.stash);
self.redraw(); self.redraw()
} }
fn set_data(&self) { self.iox.set_gpio_pin_value(self.cd_port, self.cd_pin, IoxValue::High); } fn set_data(&self) { self.iox.set_gpio_pin_value(self.cd_port, self.cd_pin, IoxValue::High); }
fn set_command(&self) { self.iox.set_gpio_pin_value(self.cd_port, self.cd_pin, IoxValue::Low); } fn set_command(&self) { self.iox.set_gpio_pin_value(self.cd_port, self.cd_pin, IoxValue::Low); }
pub fn send_command<'b, U>(&'b mut self, cmd: U) pub fn send_command<'b, U>(&'b mut self, cmd: U) -> Result<(), xous::Error>
where where
U: IntoIterator<Item = u8> + 'b, U: IntoIterator<Item = u8> + 'b,
{ {
if self.powerdown { if self.powerdown {
return; return Ok(());
} }
self.set_command(); self.set_command();
let total_buf_len = self.buffer.len() * size_of::<u32>(); let total_buf_len = self.buffer.len() * size_of::<u32>();
@ -451,16 +466,12 @@ impl<'a> Oled128x128<'a> {
.txrx_data_async_from_parts::<u8>(total_buf_len, len, true, false) .txrx_data_async_from_parts::<u8>(total_buf_len, len, true, false)
.expect("Couldn't initiate oled command"); .expect("Couldn't initiate oled command");
} }
self.spim.txrx_await(false).unwrap_or_else(|_e| { self.spim.txrx_await(false).map(|_| ())
#[cfg(feature = "std")]
log::error!("txrx err {:?}", _e);
&[]
});
} }
pub fn init(&mut self) { pub fn init(&mut self) -> Result<(), xous::Error> {
if self.powerdown { if self.powerdown {
return; return Ok(());
} }
use Command::*; use Command::*;
let init_sequence = [ let init_sequence = [
@ -483,17 +494,18 @@ impl<'a> Oled128x128<'a> {
for command in init_sequence { for command in init_sequence {
let bytes = command.encode(); let bytes = command.encode();
self.send_command(bytes); self.send_command(bytes)?;
} }
// clear the frame buffer // clear the frame buffer
self.buffer_mut().fill(0xFFFF_FFFF); self.buffer_mut().fill(0xFFFF_FFFF);
self.draw(); self.draw()?;
let display_on = [DisplayOnOff(DisplayState::On)]; let display_on = [DisplayOnOff(DisplayState::On)];
for command in display_on { for command in display_on {
let bytes = command.encode(); let bytes = command.encode();
self.send_command(bytes); self.send_command(bytes)?;
} }
Ok(())
} }
pub fn powerdown(&mut self) { pub fn powerdown(&mut self) {
@ -516,9 +528,9 @@ impl<'a> Oled128x128<'a> {
self.powerdown = false; self.powerdown = false;
} }
pub fn brightness(&mut self, level: u8) { pub fn brightness(&mut self, level: u8) -> Result<(), xous::Error> {
let bytes = Command::SetContrastControl(level).encode(); let bytes = Command::SetContrastControl(level).encode();
self.send_command(bytes); self.send_command(bytes)
} }
#[cfg(feature = "std")] #[cfg(feature = "std")]
@ -574,10 +586,10 @@ impl<'a> Oled128x128<'a> {
impl<'a> FrameBuffer for Oled128x128<'a> { impl<'a> FrameBuffer for Oled128x128<'a> {
/// Copies the SRAM buffer to IFRAM and then transfers that over SPI /// Copies the SRAM buffer to IFRAM and then transfers that over SPI
fn draw(&mut self) { fn draw(&mut self) -> Result<(), xous::Error> {
self.hw_buf.copy_from_slice(&self.buffer); self.hw_buf.copy_from_slice(&self.buffer);
if self.powerdown { if self.powerdown {
return; return Ok(());
} }
let chunk_size = 16; let chunk_size = 16;
let chunks = self.buffer().len() * size_of::<u32>() / chunk_size; let chunks = self.buffer().len() * size_of::<u32>() / chunk_size;
@ -588,8 +600,8 @@ impl<'a> FrameBuffer for Oled128x128<'a> {
// the transaction is done before the data is done transmitting, and we have to // the transaction is done before the data is done transmitting, and we have to
// toggle set_data() only after the physical transaction is done, not after the // toggle set_data() only after the physical transaction is done, not after the
// the last UDMA action has been queued. // the last UDMA action has been queued.
self.send_command(Command::SetPageAddress(0).encode()); self.send_command(Command::SetPageAddress(0).encode())?;
self.send_command(Command::SetColumnAddress(page as u8).encode()); self.send_command(Command::SetColumnAddress(page as u8).encode())?;
// wait for commands to finish before toggling set_data // wait for commands to finish before toggling set_data
// self.spim.tx_data_await(false); // self.spim.tx_data_await(false);
// crate::println!("Send page {}, offset {:x}", page, page * chunk_size); // crate::println!("Send page {}, offset {:x}", page, page * chunk_size);
@ -600,12 +612,9 @@ impl<'a> FrameBuffer for Oled128x128<'a> {
.txrx_data_async_from_parts::<u8>(page * chunk_size, chunk_size, true, false) .txrx_data_async_from_parts::<u8>(page * chunk_size, chunk_size, true, false)
.expect("Couldn't initiate oled data transfer"); .expect("Couldn't initiate oled data transfer");
} }
self.spim.txrx_await(false).unwrap_or_else(|_e| { self.spim.txrx_await(false)?;
#[cfg(feature = "std")]
log::error!("txrx err {:?}", _e);
&[]
});
} }
Ok(())
} }
fn clear(&mut self) { self.buffer_mut().fill(0xFFFF_FFFF); } fn clear(&mut self) { self.buffer_mut().fill(0xFFFF_FFFF); }

View file

@ -476,7 +476,7 @@ impl Spim {
&self.ifram.as_phys_slice()[..self.tx_buf_len_bytes / size_of::<T>()] &self.ifram.as_phys_slice()[..self.tx_buf_len_bytes / size_of::<T>()]
} }
fn send_cmd_list(&mut self, cmds: &[SpimCmd]) { pub fn send_cmd_list(&mut self, cmds: &[SpimCmd]) {
for cmd_chunk in cmds.chunks(SPIM_CMD_BUF_LEN_BYTES / size_of::<u32>()) { for cmd_chunk in cmds.chunks(SPIM_CMD_BUF_LEN_BYTES / size_of::<u32>()) {
for (src, dst) in cmd_chunk.iter().zip(self.cmd_buf_mut().iter_mut()) { for (src, dst) in cmd_chunk.iter().zip(self.cmd_buf_mut().iter_mut()) {
*dst = (*src).into(); *dst = (*src).into();

View file

@ -47,7 +47,7 @@ pub trait FrameBuffer {
/// and background colors for a color theme. /// and background colors for a color theme.
fn xor_pixel(&mut self, p: Point); fn xor_pixel(&mut self, p: Point);
/// Swaps the drawable buffer to the screen and sends it to the hardware /// Swaps the drawable buffer to the screen and sends it to the hardware
fn draw(&mut self); fn draw(&mut self) -> Result<(), xous::Error>;
/// Clears the drawable buffer /// Clears the drawable buffer
fn clear(&mut self); fn clear(&mut self);
/// Returns the size of the frame buffer as a Point /// Returns the size of the frame buffer as a Point
@ -68,7 +68,7 @@ impl FrameBuffer for DynFb<'_> {
fn get_pixel(&self, p: Point) -> Option<ColorNative> { self.0.get_pixel(p) } fn get_pixel(&self, p: Point) -> Option<ColorNative> { self.0.get_pixel(p) }
fn draw(&mut self) { self.0.draw(); } fn draw(&mut self) -> Result<(), xous::Error> { self.0.draw() }
fn clear(&mut self) { self.0.clear(); } fn clear(&mut self) { self.0.clear(); }

View file

@ -168,10 +168,10 @@ pub fn early_init_hw() -> u32 {
&mut iox, &mut iox,
&mut udma_global, &mut udma_global,
); );
sh1107.init(); sh1107.init().ok();
sh1107.buffer_mut().fill(0xFFFF_FFFF); sh1107.buffer_mut().fill(0xFFFF_FFFF);
sh1107.blit_screen(&ux_api::bitmaps::baochip128x128::BITMAP); sh1107.blit_screen(&ux_api::bitmaps::baochip128x128::BITMAP);
sh1107.draw(); sh1107.draw().ok();
} }
#[cfg(feature = "board-dabao")] #[cfg(feature = "board-dabao")]
@ -228,10 +228,10 @@ pub fn oled_init<'a>(
iox, iox,
udma_global, udma_global,
); );
sh1107.init(); sh1107.init().ok();
sh1107.buffer_mut().fill(0xFFFF_FFFF); sh1107.buffer_mut().fill(0xFFFF_FFFF);
sh1107.blit_screen(&ux_api::bitmaps::baochip128x128::BITMAP); sh1107.blit_screen(&ux_api::bitmaps::baochip128x128::BITMAP);
sh1107.draw(); sh1107.draw().ok();
sh1107 sh1107
} }
@ -415,5 +415,5 @@ pub fn progress_bar(fb: &mut dyn FrameBuffer, progress: usize) {
false, false,
); );
} }
fb.0.draw(); fb.0.draw().ok();
} }

View file

@ -227,9 +227,10 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! {
let hal = Hal::new(); let hal = Hal::new();
let mut display = Oled128x128::new(main_thread_token, bao1x_api::PERCLK, &iox, &udma_global); let mut display = Oled128x128::new(main_thread_token, bao1x_api::PERCLK, &iox, &udma_global);
display.init(); // these unwrap because if we have a time-out at this stage, it's likely a hardware problem
display.init().unwrap();
display.clear(); display.clear();
display.draw(); display.draw().unwrap();
// ---- panic handler - set up early so we can see panics quickly // ---- 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, // install the graphical panic handler. It won't catch really early panics, or panics in this crate,
@ -522,7 +523,9 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! {
) )
}; };
response.replace(acquisition).unwrap(); response.replace(acquisition).unwrap();
display.pop(); display
.pop()
.unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display));
hal.set_preemption(true); hal.set_preemption(true);
} }
// forward messages on to listeners iff we don't have an active modal // forward messages on to listeners iff we don't have an active modal
@ -603,7 +606,9 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! {
Mono::White.into(), Mono::White.into(),
Mono::Black.into(), Mono::Black.into(),
); );
display.draw(); display
.draw()
.unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display));
let mut img = let mut img =
rqrr::PreparedImage::prepare_from_greyscale(IMAGE_WIDTH, IMAGE_HEIGHT, |x, y| { rqrr::PreparedImage::prepare_from_greyscale(IMAGE_WIDTH, IMAGE_HEIGHT, |x, y| {
frame[y * IMAGE_WIDTH + x] frame[y * IMAGE_WIDTH + x]
@ -641,7 +646,9 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! {
) )
}; };
response.replace(acquisition).unwrap(); response.replace(acquisition).unwrap();
display.pop(); display.pop().unwrap_or_else(|_| {
display_timeout_handler(&udma_global, &mut display)
});
#[cfg(not(feature = "hosted-baosec"))] #[cfg(not(feature = "hosted-baosec"))]
hal.set_preemption(true); hal.set_preemption(true);
} else { } else {
@ -685,7 +692,7 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! {
); );
} }
display.draw(); display.draw().unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display));
// clear the front buffer // clear the front buffer
display.clear(); display.clear();
@ -762,7 +769,9 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! {
GfxOpcode::Flush => { GfxOpcode::Flush => {
if qr_request.is_none() { if qr_request.is_none() {
log::trace!("***gfx flush*** redraw##"); log::trace!("***gfx flush*** redraw##");
display.redraw(); display
.redraw()
.unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display));
} }
} }
GfxOpcode::Clear => { GfxOpcode::Clear => {
@ -797,7 +806,9 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! {
GfxOpcode::DrawSleepScreen => { GfxOpcode::DrawSleepScreen => {
if let Some(_scalar) = msg.body.scalar_message() { if let Some(_scalar) = msg.body.scalar_message() {
display.blit_screen(&ux_api::bitmaps::baochip128x128::BITMAP); display.blit_screen(&ux_api::bitmaps::baochip128x128::BITMAP);
display.redraw(); display
.redraw()
.unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display));
} else { } else {
panic!("Incorrect message type"); panic!("Incorrect message type");
} }
@ -805,7 +816,9 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! {
GfxOpcode::DrawBootLogo => { GfxOpcode::DrawBootLogo => {
if let Some(_scalar) = msg.body.scalar_message() { if let Some(_scalar) = msg.body.scalar_message() {
display.blit_screen(&ux_api::bitmaps::baochip128x128::BITMAP); display.blit_screen(&ux_api::bitmaps::baochip128x128::BITMAP);
display.redraw(); display
.redraw()
.unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display));
} else { } else {
panic!("Incorrect message type"); panic!("Incorrect message type");
} }
@ -833,7 +846,7 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! {
// no failure if it's not // no failure if it's not
} }
GfxOpcode::Pop => { GfxOpcode::Pop => {
display.pop(); display.pop().unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display));
if let Some(scalar) = msg.body.scalar_message_mut() { if let Some(scalar) = msg.body.scalar_message_mut() {
// ack the message if it's a blocking scalar // ack the message if it's a blocking scalar
scalar.arg1 = 1; scalar.arg1 = 1;
@ -857,8 +870,8 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! {
// safety: this is safe because we call init() a prescribed delay after power-up // safety: this is safe because we call init() a prescribed delay after power-up
unsafe { display.powerup() }; unsafe { display.powerup() };
tt.sleep_ms(5).ok(); tt.sleep_ms(5).ok();
display.init(); display.init().unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display));
display.pop(); display.pop().unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display));
if let Some(scalar) = msg.body.scalar_message_mut() { if let Some(scalar) = msg.body.scalar_message_mut() {
// ack the message if it's a blocking scalar // ack the message if it's a blocking scalar
scalar.arg1 = 1; scalar.arg1 = 1;
@ -874,7 +887,9 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! {
GfxOpcode::Brightness => { GfxOpcode::Brightness => {
if let Some(scalar) = msg.body.scalar_message_mut() { if let Some(scalar) = msg.body.scalar_message_mut() {
let brightness = scalar.arg1.min(255) as u8; let brightness = scalar.arg1.min(255) as u8;
display.brightness(brightness); display
.brightness(brightness)
.unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display));
} }
} }
GfxOpcode::Quit => break, GfxOpcode::Quit => break,
@ -894,3 +909,9 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! {
log::trace!("quitting"); log::trace!("quitting");
xous::terminate_process(0) xous::terminate_process(0)
} }
fn display_timeout_handler(udma_global: &UdmaGlobal, display: &mut Oled128x128) {
log::info!("resetting display spim block");
udma_global.reset(PeriphId::from(bao1x_hal::board::get_display_pins().0));
display.reinit_spi();
}

View file

@ -57,6 +57,7 @@ pub(crate) fn panic_handler_thread(
Option<CommandSet>, Option<CommandSet>,
), ),
bool, bool,
u8,
), ),
) { ) {
thread::spawn({ thread::spawn({
@ -111,7 +112,7 @@ pub(crate) fn panic_handler_thread(
} }
} }
display.draw(); display.draw().ok();
append_string("~Guru Meditation~", &mut display); append_string("~Guru Meditation~", &mut display);
} }
let body = match msg.body.memory_message() { let body = match msg.body.memory_message() {
@ -138,7 +139,7 @@ pub(crate) fn panic_handler_thread(
&mut display, &mut display,
); );
} }
display.draw(); display.draw().ok();
} }
} }
}); });