refactor i2c interface to eliminate static mut unsafes

also remove async write callbacks: in practice, these aren't used

Downside of this refactor is that threads for handling the
callbacks are not spawned on demand, they are spawned at boot,
leading to about an extra 68k of RAM used (most of it being
consumed in the codec block, actually). Some of this is also
probably extra object code because we're using more of the stdlib
primitives, which carry some weight.
This commit is contained in:
bunnie 2022-02-19 00:31:25 +08:00
parent 0bd8a97f63
commit 95b857feea
5 changed files with 190 additions and 183 deletions

View file

@ -257,7 +257,7 @@ impl Codec {
fn w(&mut self, adr: u8, data: &[u8]) -> bool {
//log::trace!("writing to 0x{:x}, {:x?}", adr, data);
match self.i2c.i2c_write(TLV320AIC3100_I2C_ADR, adr, data, None) {
match self.i2c.i2c_write(TLV320AIC3100_I2C_ADR, adr, data) {
Ok(status) => {
//log::trace!("write returned with status {:?}", status);
match status {

View file

@ -41,7 +41,7 @@ pub struct I2cTransaction {
// write address and read address are encoded in the packet field below
// NOTE: the number 33 that appears twice below mirrors I2C_MAX_LEN; due to a regression in Rust 1.56 we can't use constants in array types
// pending https://github.com/rust-lang/rust/issues/90195
pub txbuf: Option<[u8; 33]>, // long enough for a 256-byte operation + 2 bytes of "register address"
pub txbuf: Option<[u8; 33]>,
pub txlen: u32,
pub rxbuf: Option<[u8; 33]>,
pub rxlen: u32,
@ -68,3 +68,17 @@ pub(crate) enum I2cOpcode {
SuspendResume,
Quit,
}
/// Routing information for the AsyncRead reporting od I2cReadResult
#[derive(Debug, Copy, Clone)]
pub struct I2cAsyncReadHook {
pub conn: xous::CID,
pub id: u32,
}
/// The data reported by an I2cAsycReadHook message
#[derive(Debug, Copy, Clone, Archive, Serialize, Deserialize)]
pub struct I2cReadResult {
pub rxbuf: [u8; 33],
pub rxlen: u32,
pub status: I2cStatus,
}

View file

@ -3,157 +3,149 @@ use xous_ipc::Buffer;
use num_traits::{ToPrimitive, FromPrimitive};
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use crate::api::*;
use std::sync::{Arc, Mutex};
use std::thread;
// these exist outside the I2C struct because it needs to synchronize across multiple object instances within the same process
static REFCOUNT: AtomicU32 = AtomicU32::new(0);
// this hooks the response of the I2C bus
static mut I2C_CB: Option<fn(I2cTransaction)> = None;
static I2C_IN_PROGRESS_MUTEX: AtomicBool = AtomicBool::new(false);
static mut I2C_RX_HANDOFF: [u8; I2C_MAX_LEN] = [0; I2C_MAX_LEN]; // this is protected by the above mutex
fn sync_i2c_cb(transaction: I2cTransaction) {
if let Some(rxbuf) = transaction.rxbuf {
unsafe {
for i in 0..transaction.rxlen as usize {
I2C_RX_HANDOFF[i] = rxbuf[i];
}
}
}
unsafe{I2C_CB = None;} // break-before-make, ensures that the I2C_RX_HANDOFF data can't be overwritten by another callback
I2C_IN_PROGRESS_MUTEX.store(false, Ordering::Relaxed);
}
static I2C_BUSY: AtomicBool = AtomicBool::new(false);
#[derive(Debug)]
pub struct I2c {
i2c_conn: CID,
i2c_sid: Option<xous::SID>,
i2c_timeout_ms: u32,
conn: CID,
cb_sid: xous::SID,
timeout_ms: u32,
rx_handoff: Arc<Mutex<Vec<u8>>>,
rx_hook: Arc<Mutex<Option<I2cAsyncReadHook>>>,
}
impl I2c {
pub fn new(xns: &xous_names::XousNames) -> Self {
REFCOUNT.fetch_add(1, Ordering::Relaxed);
let i2c_conn = xns.request_connection_blocking(SERVER_NAME_I2C).expect("Can't connect to I2C");
let conn = xns.request_connection_blocking(SERVER_NAME_I2C).expect("Can't connect to I2C");
let cb_sid = xous::create_server().unwrap();
let rx_hook = Arc::new(Mutex::new(None::<I2cAsyncReadHook>));
let rx_handoff = Arc::new(Mutex::new(Vec::<u8>::new()));
let _ = thread::spawn({
let sid = cb_sid.clone();
let hook = rx_hook.clone();
let handoff = rx_handoff.clone();
move || {
loop {
let msg = xous::receive_message(sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(I2cCallback::Result) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let trans = buffer.to_original::<I2cTransaction, _>().unwrap();
if trans.status == I2cStatus::ResponseReadOk {
// grab the mutex on the rx_handoff buff for this block
let mut rx_handoff = handoff.lock().unwrap();
rx_handoff.clear();
// stash a copy of the received value - to be picked up by the blocking call, if specified
if let Some(rxbuf) = trans.rxbuf {
for &rx in rxbuf[..trans.rxlen as usize].iter() {
rx_handoff.push(rx);
}
}
// send a message to the hook, if specified
if let Some(&read_hook) = hook.lock().unwrap().as_ref() {
let mut result = I2cReadResult {
rxbuf: [0; 33],
rxlen: 0,
status: I2cStatus::ResponseReadOk,
};
if let Some(rxbuf) = trans.rxbuf {
for (&src, dst) in rxbuf[..trans.rxlen as usize].iter().zip(result.rxbuf.iter_mut()) {
*dst = src;
}
result.rxlen = trans.rxlen;
}
let buf = Buffer::into_buf(result).unwrap();
buf.send(read_hook.conn, read_hook.id).expect("couldn't send callback result");
}
I2C_BUSY.store(false, Ordering::SeqCst);
}
if trans.status == I2cStatus::ResponseWriteOk {
I2C_BUSY.store(false, Ordering::SeqCst);
}
}
Some(I2cCallback::Drop) => {
xous::return_scalar(msg.sender, 1).unwrap(); // acknowledge the drop
break;
}
_ => {
log::warn!("received unknown message: {:?}", msg);
}
}
}
xous::destroy_server(sid).unwrap();
}
});
I2c {
i2c_sid: None,
i2c_conn,
i2c_timeout_ms: 10,
conn,
cb_sid,
timeout_ms: 10,
rx_handoff,
rx_hook,
}
}
fn check_cb_init(&mut self) {
if self.i2c_sid.is_none() {
let sid = xous::create_server().unwrap();
self.i2c_sid = Some(sid);
let sid_tuple = sid.to_u32();
xous::create_thread_4(i2c_cb_server, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap();
// note: we don't register a callback, because we hand our SID directly to the i2c request for a 1:1 message return
}
}
pub fn i2c_set_timeout(&mut self, timeout: u32) {
self.i2c_timeout_ms = timeout;
self.timeout_ms = timeout;
}
/// initiate an i2c write. if async_cb is `None`, one will be provided and the routine will synchronously block until write is complete.
/// if you want to "fire and forget" the write and don't care when or how it finishes, simply provide a dummy callback.
pub fn i2c_write(&mut self, dev: u8, adr: u8, data: &[u8], async_cb: Option<fn(I2cTransaction)>) -> Result<I2cStatus, xous::Error> {
/// initiate an i2c write. This is always a blocking call. In practice, it turns out it's not terribly
/// useful to just "fire and forget" i2c writes, because actually we cared about the side effect of the
/// write and don't want execution to move on until the write has been committed,
/// even if the write "takes a long time"
pub fn i2c_write(&mut self, dev: u8, adr: u8, data: &[u8]) -> Result<I2cStatus, xous::Error> {
match I2C_BUSY.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) { // if the interface is busy, reject the call
Err(_) => return Err(xous::Error::ServerQueueFull),
Ok(_) => (), // continue on
}
if data.len() > I2C_MAX_LEN - 1 {
return Err(xous::Error::OutOfMemory)
}
let synchronous: bool;
let mut transaction = I2cTransaction::new();
let cb = if let Some(callback) = async_cb {
synchronous = false;
callback
} else {
synchronous = true;
if I2C_IN_PROGRESS_MUTEX.load(Ordering::Relaxed) {
log::error!("entering a synchronous write routine, but somehow a synchronous operation was already in progress!");
return Err(xous::Error::InternalError);
}
sync_i2c_cb
};
self.check_cb_init();
unsafe {
if let Some(old_cb) = I2C_CB {
if old_cb != cb {
log::warn!("Multiple outstanding write transactions, with different callbacks. You are probably making an error!");
}
}
I2C_CB = Some(cb);
}
if synchronous {
I2C_IN_PROGRESS_MUTEX.store(true, Ordering::Relaxed);
}
match self.i2c_sid {
Some(sid) => transaction.listener = Some(sid.to_u32()),
None => log::error!("We requested a local listener, but somehow it's not there!"),
}
let mut txbuf = [0; I2C_MAX_LEN];
txbuf[0] = adr;
for i in 0..data.len() {
txbuf[i+1] = data[i];
}
transaction.listener = Some(self.cb_sid.to_u32());
transaction.bus_addr = dev;
transaction.txbuf = Some(txbuf);
transaction.txlen = (data.len() + 1) as u32;
transaction.status = I2cStatus::RequestIncoming;
transaction.timeout_ms = self.i2c_timeout_ms;
transaction.timeout_ms = self.timeout_ms;
let mut buf = Buffer::into_buf(transaction).or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.i2c_conn, I2cOpcode::I2cTxRx.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.conn, I2cOpcode::I2cTxRx.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
let result = buf.to_original::<I2cStatus, _>().unwrap();
if synchronous {
if result != I2cStatus::ResponseInProgress {
return Err(xous::Error::OutOfMemory);
}
while I2C_IN_PROGRESS_MUTEX.load(Ordering::Relaxed) {
xous::yield_slice();
}
Ok(I2cStatus::ResponseWriteOk)
} else {
Ok(result)
if result != I2cStatus::ResponseInProgress {
return Err(xous::Error::OutOfMemory); // indicates that the I2C work queue was full and the request was denied
}
while I2C_BUSY.load(Ordering::Relaxed) {
xous::yield_slice();
}
Ok(I2cStatus::ResponseWriteOk)
}
/// initiate an i2c read. if asyncread_cb is `None`, one will be provided and the routine will synchronously block until read is complete.
/// synchronous reads will return the data in &mut `data`. Asynchronous reads will provide the result in the `rxbuf` field of the `I2cTransaction`
/// returned via the callback. Note that the callback API may be revised to return a smaller, more targeted structure in the future.
pub fn i2c_read(&mut self, dev: u8, adr: u8, data: &mut[u8], asyncread_cb: Option<fn(I2cTransaction)>) -> Result<I2cStatus, xous::Error> {
pub fn i2c_read(&mut self, dev: u8, adr: u8, data: &mut [u8], asyncread_cb: Option<I2cAsyncReadHook>) -> Result<I2cStatus, xous::Error> {
match I2C_BUSY.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) { // if the interface is busy, reject the call
Err(_) => return Err(xous::Error::ServerQueueFull),
Ok(_) => (), // continue on
}
if data.len() > I2C_MAX_LEN - 1 {
return Err(xous::Error::OutOfMemory)
}
let synchronous: bool;
let read_cb = if let Some(cb) = asyncread_cb {
// user is supplying an async callback
synchronous = false;
cb
} else {
// user hasn't provided a callback, we'll provide one and return synchronously
synchronous = true;
if I2C_IN_PROGRESS_MUTEX.load(Ordering::Relaxed) {
log::error!("trying a synchronous read, but somehow a synchronous operation was already in progress!");
return Err(xous::Error::InternalError);
}
sync_i2c_cb // supply a default callback
};
let mut transaction = I2cTransaction::new();
self.check_cb_init();
unsafe {
if let Some(old_cb) = I2C_CB {
if old_cb != read_cb {
log::warn!("Multiple outstanding read transactions, with different callbacks. Hope you know what you are doing!");
}
}
I2C_CB = Some(read_cb);
}
if synchronous {
I2C_IN_PROGRESS_MUTEX.store(true, Ordering::Relaxed);
}
match self.i2c_sid {
Some(sid) => transaction.listener = Some(sid.to_u32()),
None => log::error!("We requested a local listener, but somehow it's not there!"),
}
transaction.listener = Some(self.cb_sid.to_u32());
let mut txbuf = [0; I2C_MAX_LEN];
txbuf[0] = adr;
let rxbuf = [0; I2C_MAX_LEN];
@ -163,73 +155,40 @@ impl I2c {
transaction.rxbuf = Some(rxbuf);
transaction.rxlen = data.len() as u32;
transaction.status = I2cStatus::RequestIncoming;
transaction.timeout_ms = self.i2c_timeout_ms;
transaction.timeout_ms = self.timeout_ms;
let mut buf = Buffer::into_buf(transaction).or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.i2c_conn, I2cOpcode::I2cTxRx.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.conn, I2cOpcode::I2cTxRx.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
let result = buf.to_original::<I2cStatus, _>().unwrap();
if synchronous {
if let Some(hook) = asyncread_cb {
*self.rx_hook.lock().unwrap() = Some(hook);
Ok(result)
} else {
if result != I2cStatus::ResponseInProgress {
return Err(xous::Error::OutOfMemory);
}
while I2C_IN_PROGRESS_MUTEX.load(Ordering::Relaxed) {
while I2C_BUSY.load(Ordering::Relaxed) {
xous::yield_slice();
}
unsafe {
for (&src, dst) in I2C_RX_HANDOFF.iter().zip(data.iter_mut()) {
*dst = src;
}
for (&src, dst) in self.rx_handoff.lock().unwrap().iter().zip(data.iter_mut()) {
*dst = src;
}
Ok(I2cStatus::ResponseReadOk)
} else {
Ok(result)
}
}
// used by async callback handlers to indicate their completion, allowing e.g. later synchronous operations
pub fn i2c_async_done(&self) {
unsafe{I2C_CB = None};
}
}
fn drop_conn(sid: xous::SID) {
let cid = xous::connect(sid).unwrap();
xous::send_message(cid,
Message::new_scalar(EventCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0)).unwrap();
unsafe{xous::disconnect(cid).unwrap();}
Message::new_blocking_scalar(I2cCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0)).unwrap();
unsafe{xous::disconnect(cid).ok();}
}
impl Drop for I2c {
fn drop(&mut self) {
if let Some(sid) = self.i2c_sid.take() {
drop_conn(sid);
}
drop_conn(self.cb_sid);
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
unsafe{xous::disconnect(self.i2c_conn).unwrap();}
unsafe{xous::disconnect(self.conn).ok();}
}
}
}
/// handles callback messages from I2C server, in the library user's process space.
fn i2c_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
let sid = xous::SID::from_u32(sid0 as u32, sid1 as u32, sid2 as u32, sid3 as u32);
loop {
let msg = xous::receive_message(sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(I2cCallback::Result) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let mut i2cresult = buffer.to_original::<I2cTransaction, _>().unwrap();
i2cresult.listener = None; // don't leak our local server address to the callback
unsafe {
if let Some(cb) = I2C_CB {
cb(i2cresult)
}
}
},
Some(I2cCallback::Drop) => {
break; // this exits the loop and kills the thread
}
None => (),
}
}
xous::destroy_server(sid).unwrap();
}

View file

@ -240,17 +240,19 @@ mod implementation {
pub struct Rtc {
i2c: I2c,
cb_to_main: xous::CID,
rtc_alarm_enabled: bool,
wakeup_alarm_enabled: bool,
ticktimer: ticktimer_server::Ticktimer,
}
impl Rtc {
pub fn new(xns: &xous_names::XousNames) -> Rtc {
pub fn new(xns: &xous_names::XousNames, cb_to_main: xous::CID) -> Rtc {
log::trace!("hardware initialized");
let i2c = I2c::new(xns);
Rtc {
i2c,
cb_to_main,
rtc_alarm_enabled: false,
wakeup_alarm_enabled: false,
ticktimer: ticktimer_server::Ticktimer::new().expect("can't connect to ticktimer"),
@ -290,7 +292,7 @@ mod implementation {
txbuf[6] = to_bcd(months);
txbuf[7] = to_bcd(years);
match self.i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &txbuf, None) {
match self.i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &txbuf) {
Ok(status) => {
match status {
I2cStatus::ResponseWriteOk => Ok(true),
@ -304,7 +306,13 @@ mod implementation {
pub fn rtc_get(&mut self) -> Result<(), xous::Error> {
let mut rxbuf = [0; 7];
match self.i2c.i2c_read(ABRTCMC_I2C_ADR, ABRTCMC_SECONDS, &mut rxbuf, Some(i2c_callback)) {
match self.i2c.i2c_read(ABRTCMC_I2C_ADR, ABRTCMC_SECONDS, &mut rxbuf,
Some(
llio::I2cAsyncReadHook {
conn: self.cb_to_main,
id: RtcOpcode::ResponseDateTime.to_u32().unwrap(),
}
)) {
Ok(status) => {
match status {
I2cStatus::ResponseInProgress => Ok(()),
@ -315,16 +323,13 @@ mod implementation {
_ => Err(xous::Error::InternalError)
}
}
pub fn rtc_get_ack(&mut self) {
self.i2c.i2c_async_done();
}
// the awkward array syntax is a legacy of a port from a previous implementation
// would be fine to clean up method signature as e.g.
// blocking_i2c_write2(adr: u8, data: u8) -> bool
// but need to make sure we don't bork any of the constants later on in this code :P
fn blocking_i2c_write2(&mut self, adr: u8, data: u8) -> bool {
match self.i2c.i2c_write(ABRTCMC_I2C_ADR, adr, &[data], None) {
match self.i2c.i2c_write(ABRTCMC_I2C_ADR, adr, &[data]) {
Ok(status) => {
match status {
I2cStatus::ResponseWriteOk => true,
@ -520,7 +525,7 @@ pub(crate) fn rtc_server(rtc_sid: xous::SID) {
CB_TO_MAIN_CONN.store(xous::connect(rtc_sid).unwrap(), Ordering::Relaxed);
#[cfg(any(target_os = "none", target_os = "xous"))]
let mut rtc = Rtc::new(&xns);
let mut rtc = Rtc::new(&xns, CB_TO_MAIN_CONN.load(Ordering::Relaxed)); // swap the conn variable out later
#[cfg(not(any(target_os = "none", target_os = "xous")))]
let mut rtc = Rtc::new(&xns);
@ -582,27 +587,39 @@ pub(crate) fn rtc_server(rtc_sid: xous::SID) {
unsafe{xous::disconnect(cid).unwrap()};
}),
Some(RtcOpcode::ResponseDateTime) => {
rtc.rtc_get_ack(); // let the async callback interface know we returned
let incoming_buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let dt = incoming_buffer.to_original::<DateTime, _>().unwrap();
log::trace!("ResponseDateTime received: {:?}", dt);
for cid in 1..dt_cb_conns.len() { // 0 is not a valid connection
if dt_cb_conns[cid as usize] {
let outgoing_buf = Buffer::into_buf(dt).or(Err(xous::Error::InternalError)).unwrap();
log::trace!("ResponeDateTime sending to {}", cid);
match outgoing_buf.lend(cid as u32, Return::ReturnDateTime.to_u32().unwrap()) {
Err(xous::Error::ServerNotFound) => {
log::trace!("ServerNotFound, dropping connection");
dt_cb_conns[cid] = false;
},
Ok(_) => {
log::trace!("RespondeDateTime sent successfully");
},
_ => panic!("unhandled error or result in callback processing")
let rx_result = incoming_buffer.to_original::<I2cReadResult, _>().unwrap();
if rx_result.rxlen == 7 {
let dt = DateTime {
seconds: to_binary(rx_result.rxbuf[0] & 0x7f),
minutes: to_binary(rx_result.rxbuf[1] & 0x7f),
hours: to_binary(rx_result.rxbuf[2] & 0x3f),
days: to_binary(rx_result.rxbuf[3] & 0x3f),
weekday: to_weekday(rx_result.rxbuf[4] & 0x7f),
months: to_binary(rx_result.rxbuf[5] & 0x1f),
years: to_binary(rx_result.rxbuf[6]),
};
log::trace!("ResponseDateTime received: {:?}", dt);
for cid in 1..dt_cb_conns.len() { // 0 is not a valid connection
if dt_cb_conns[cid as usize] {
let outgoing_buf = Buffer::into_buf(dt).or(Err(xous::Error::InternalError)).unwrap();
log::trace!("ResponeDateTime sending to {}", cid);
match outgoing_buf.lend(cid as u32, Return::ReturnDateTime.to_u32().unwrap()) {
Err(xous::Error::ServerNotFound) => {
log::trace!("ServerNotFound, dropping connection");
dt_cb_conns[cid] = false;
},
Ok(_) => {
log::trace!("RespondeDateTime sent successfully");
},
_ => panic!("unhandled error or result in callback processing")
}
}
}
log::trace!("ResponeDateTime done");
} else {
log::error!("I2C response for date time has incorrect length of {}", rx_result.rxlen);
}
log::trace!("ResponeDateTime done");
},
Some(RtcOpcode::RequestDateTime) => {
let mut sent = false;
@ -669,3 +686,20 @@ pub(crate) fn rtc_server(rtc_sid: xous::SID) {
xous::destroy_server(rtc_sid).unwrap();
log::trace!("quitting");
}
fn to_binary(bcd: u8) -> u8 {
(bcd & 0xf) + ((bcd >> 4) * 10)
}
fn to_weekday(bcd: u8) -> Weekday {
match bcd {
0 => Weekday::Sunday,
1 => Weekday::Monday,
2 => Weekday::Tuesday,
3 => Weekday::Wednesday,
4 => Weekday::Thursday,
5 => Weekday::Friday,
6 => Weekday::Saturday,
_ => Weekday::Sunday,
}
}

View file

@ -834,7 +834,7 @@ fn rtc_set(i2c: &mut llio::I2c, secs: u8, mins: u8, hours: u8, days: u8, months:
txbuf[6] = to_bcd(months);
txbuf[7] = to_bcd(years);
match i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &txbuf, None) {
match i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &txbuf) {
Ok(status) => {
match status {
I2cStatus::ResponseWriteOk => true,