add timeout logic to I2C driver

This commit is contained in:
bunnie 2023-03-17 22:12:02 +08:00
parent 5efbff0098
commit 76a7d05156
4 changed files with 105 additions and 6 deletions

View file

@ -346,12 +346,17 @@ perform the Xous firmware upgrade. This requires running manual update commands,
- Phase 1 cleaned up and optimized
- VexRiscv core patch to D$ virtual memory flush bug
- Hopefully resolves issue #321
- Unused logic stripped from SoC
- Work-around Vivado tool issue where >10% of compilations were failing due to silent timing failures by decongesting core wishbone arbiter routes
- SoC yield bugs fixed
- Work-around Vivado tool issue where >10% of compilations were failing on some units
- Strip out unused logic to decongest the design
- Requires an update to usb_update.py, precursorupdater to work with the new SoC as the CPU debug port is replaced with a simple reset-halt mechanism for preventing bus traffic during USB updates
- Metastability harden I2C & TRNG
- Move I/O blocks into always-on domain to avoid clock stoppage during fire and forget I/O operation
- More multi-platform support work
- Preliminary Cramium SoC and FPGA targets incorprated
- Preliminary Cramium SoC and FPGA targets incorporated
- atsama5d27 target support via PRs from Foundation Devices (thank you!!). Xous is now booting on the ATSAMA5D27-SOM1-EK1 dev board!
- Fix edge case in phase 1 loader (thanks to @southpawflow for reporting it and providing the test case files)
- Handle I2C timeouts
## Roadmap
- Lots of testing and bug fixes

View file

@ -65,6 +65,8 @@ pub(crate) enum I2cOpcode {
/// grabs a mutex on the I2C block, for multiple transactions that can't be separated
I2cMutexAcquire,
I2cMutexRelease,
/// timeout check
I2cTimeout,
/// SuspendResume callback
SuspendResume,
Quit,

View file

@ -129,6 +129,9 @@ impl I2cStateMachine {
i2c
}
pub fn get_expiry(&self) -> Option<u64> {
self.expiry
}
#[allow(dead_code)]
pub fn set_trace(&mut self, trace: bool) {
self.trace = trace;
@ -143,6 +146,33 @@ impl I2cStateMachine {
self.i2c_susres.resume();
}
pub fn re_initiate(&mut self) {
// execution continues after here because we simply drop the response message back in the sender's queue, and then return here to do more
log::warn!("I2C timeout; resetting hardware block and re-trying");
self.i2c_csr.wfo(utra::i2c::CORE_RESET_RESET, 1);
self.ticktimer.sleep_ms(1).ok();
// set the prescale assuming 100MHz cpu operation: 100MHz / ( 5 * 100kHz ) - 1 = 199
let clkcode = (utralib::LITEX_CONFIG_CLOCK_FREQUENCY as u32) / (5 * 100_000) - 1;
self.i2c_csr.wfo(utra::i2c::PRESCALE_PRESCALE, clkcode & 0xFFFF);
// clear any interrupts pending
self.i2c_csr.wo(utra::i2c::EV_PENDING, self.i2c_csr.r(utra::i2c::EV_PENDING));
// enable the block
self.i2c_csr.rmwf(utra::i2c::CONTROL_EN, 1);
// cleanup state tracking
self.state = I2cState::Idle;
self.expiry = None;
self.transaction = None;
// re-initiate the I2C transaction
if let Some(msg) = self.callback.take() {
let transaction = {
let buffer = unsafe { xous_ipc::Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
buffer.to_original::<I2cTransaction, _>().unwrap().clone()
};
self.checked_initiate(transaction, msg);
}
}
pub fn initiate(&mut self, msg: xous::MessageEnvelope) {
let transaction = {
let buffer = unsafe { xous_ipc::Buffer::from_memory_message(msg.body.memory_message().unwrap()) };

View file

@ -16,11 +16,19 @@ use llio_hosted::*;
use crate::RTC_PWR_MODE;
use num_traits::*;
use xous_ipc::Buffer;
use xous::{CID, msg_scalar_unpack, msg_blocking_scalar_unpack};
use xous::{CID, msg_scalar_unpack, msg_blocking_scalar_unpack, Message, try_send_message};
use xous::messages::sender::Sender;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::thread;
const POLL_INTERVAL_MS: usize = 50;
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
enum PumpOp {
Pump,
}
fn i2c_thread(i2c_sid: xous::SID) {
let xns = xous_names::XousNames::new().unwrap();
@ -28,8 +36,42 @@ fn i2c_thread(i2c_sid: xous::SID) {
let mut i2c = i2c::I2cStateMachine::new(handler_conn);
// register a suspend/resume listener
let sr_cid = xous::connect(i2c_sid).expect("couldn't create suspend callback connection");
let mut susres = susres::Susres::new(Some(susres::SuspendOrder::Later), &xns, I2cOpcode::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object");
let self_cid = xous::connect(i2c_sid).expect("couldn't create suspend callback connection");
let mut susres = susres::Susres::new(Some(susres::SuspendOrder::Later), &xns, I2cOpcode::SuspendResume as u32, self_cid).expect("couldn't create suspend/resume object");
// timeout watcher
let run = Arc::new(AtomicBool::new(false));
let run_sid = xous::create_server().unwrap();
let run_cid = xous::connect(run_sid).unwrap();
let target_msb = Arc::new(AtomicU32::new(0));
let target_lsb = Arc::new(AtomicU32::new(0));
let _ = std::thread::spawn({
let run = run.clone();
let cid = run_cid.clone();
let main_cid = self_cid.clone();
// there is a hazard that msb/lsb is split once every 40 or so days for the precise moment of the rollover. meh?
let target_msb = target_msb.clone();
let target_lsb = target_lsb.clone();
move || {
let tt = ticktimer_server::Ticktimer::new().unwrap();
loop {
let msg = xous::receive_message(run_sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(PumpOp::Pump) => msg_scalar_unpack!(msg, _, _, _, _, {
tt.sleep_ms(POLL_INTERVAL_MS).unwrap();
let target_time = target_lsb.load(Ordering::SeqCst) as u64 | (target_msb.load(Ordering::SeqCst) as u64) << 32;
if tt.elapsed_ms() >= target_time {
try_send_message(main_cid, Message::new_scalar(I2cOpcode::I2cTimeout.to_usize().unwrap(), 0, 0, 0, 0)).ok();
}
if run.load(Ordering::SeqCst) {
try_send_message(cid, Message::new_scalar(PumpOp::Pump.to_usize().unwrap(), 0, 0, 0, 0)).ok();
}
}),
_ => log::error!("Unrecognized message: {:?}", msg),
}
}
}
});
let mut suspend_pending_token: Option<usize> = None;
let mut blocking_callers: Vec::<Sender> = Vec::new();
@ -51,6 +93,7 @@ fn i2c_thread(i2c_sid: xous::SID) {
}
}),
Some(I2cOpcode::IrqI2cTxrxWriteDone) => msg_scalar_unpack!(msg, _, _, _, _, {
run.store(false, Ordering::SeqCst);
if !i2c_mutex_acquired && suspend_pending_token.is_some() {
if let Some(token) = suspend_pending_token.take() {
i2c.suspend();
@ -62,6 +105,7 @@ fn i2c_thread(i2c_sid: xous::SID) {
i2c.report_write_done();
}),
Some(I2cOpcode::IrqI2cTxrxReadDone) => msg_scalar_unpack!(msg, _, _, _, _, {
run.store(false, Ordering::SeqCst);
if !i2c_mutex_acquired && suspend_pending_token.is_some() {
if let Some(token) = suspend_pending_token.take() {
i2c.suspend();
@ -111,11 +155,29 @@ fn i2c_thread(i2c_sid: xous::SID) {
log::warn!("TxRx operation was initiated without an acquired mutex. This will become a hard error in future revisions");
}
i2c.initiate(msg);
// update the timeout interval to whatever was specified by the transaction
if let Some(expiry) = i2c.get_expiry() {
target_msb.store((expiry >> 32) as u32, Ordering::SeqCst);
target_lsb.store(expiry as u32, Ordering::SeqCst);
run.store(true, Ordering::SeqCst);
try_send_message(run_cid, Message::new_scalar(PumpOp::Pump.to_usize().unwrap(), 0, 0, 0, 0)).ok();
}
},
Some(I2cOpcode::I2cIsBusy) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let busy = if i2c.is_busy() {1} else {0};
xous::return_scalar(msg.sender, busy as _).expect("couldn't return I2cIsBusy");
}),
Some(I2cOpcode::I2cTimeout) => {
if i2c.is_busy() {
// timeout happened
i2c.re_initiate();
if let Some(expiry) = i2c.get_expiry() {
target_msb.store((expiry >> 32) as u32, Ordering::SeqCst);
target_lsb.store(expiry as u32, Ordering::SeqCst);
// no need to pump since the timeout loop is already running
}
}
}
Some(I2cOpcode::Quit) => {
log::info!("Received quit opcode, exiting!");
break;