checkpoint before figuring out how to deal with the String rkyv version issue...

This commit is contained in:
bunnie 2021-03-16 00:11:23 +08:00
parent be38661a1e
commit ab1b839900
3 changed files with 131 additions and 170 deletions

View file

@ -2,7 +2,7 @@ use xous::{Message, ScalarMessage};
use xous::String;
/////////////////////// UART TYPE
#[derive(Debug)]
#[derive(Debug, rkyv::Archive)]
pub enum UartType {
Kernel,
Log,
@ -43,24 +43,48 @@ impl Into<u32> for UartType {
}
/////////////////////// I2C
use core::slice;
use core::ops::{Deref, DerefMut};
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Unarchive)]
// a small book-keeping struct used to report back to I2C requestors as to the status of a transaction
#[derive(Debug, Copy, Clone, rkyv::Archive)]
pub enum I2cStatus {
/// used only as the default, should always be set to one of the below before sending
Uninitialized,
/// used by a managing process to indicate a request
RequestIncoming,
/// everything was OK, request in progress
ResponseInProgress,
/// we tried to process your request, but there was a timeout
ResponseTimeout,
/// I2C had a NACK on the request
ResponseNack,
/// the I2C bus is currently busy and your request was ignored
ResponseBusy,
/// the request was malformed
ResponseFormatError,
/// everything is OK, data here should be valid
ResponseReadOk,
/// everything is OK, write finished. data fields have no meaning
ResponseWriteOk,
}
#[derive(Debug, Copy, Clone, rkyv::Archive)]
pub struct I2cTransaction {
bus_addr: u8,
// write address and read address are encoded in the packet field below
packet: [u8; 258], // up to 258 bytes total packet length; note cost is "same" b/c these are sent via 4kiB page remaps
length: u8,
// read or write type is encoded in the opcode
txbuf: Option<[u8; 258]>, // up to 258 bytes total packet length; note cost is "same" b/c these are sent via 4kiB page remaps
txlen: u32,
rxbuf: Option<[u8; 258]>,
rxlen: u32,
timeout_ms: u32,
// response field to the calling server
status: I2cStatus,
}
impl I2cTransaction {
pub fn new() -> Self {
I2cTransaction{ bus_addr: 0, packet: [0; 258], length: 0 }
I2cTransaction{ bus_addr: 0, txbuf: None, txlen: 0, rxbuf: None, rxlen: 0, timeout_ms: 100, status: I2cStatus::Uninitialized }
}
}
////////////////////////////////// VIBE
#[derive(Debug)]
#[derive(Debug, rkyv::Archive)]
pub enum VibePattern {
Short,
Long,
@ -86,7 +110,7 @@ impl Into<usize> for VibePattern {
}
//////////////////////////////// CLOCK GATING (placeholder)
#[derive(Debug)]
#[derive(Debug, rkyv::Archive)]
pub enum ClockMode {
Low,
AllOn,
@ -109,8 +133,7 @@ impl Into<usize> for ClockMode {
}
//////////////////////////////////// OPCODES
#[allow(dead_code)]
#[derive(Debug, rkyv::Archive, rkyv::Unarchive)]
#[derive(Debug, rkyv::Archive)]
pub enum Opcode {
/// not tested - reboot
RebootRequest,
@ -168,10 +191,12 @@ pub enum Opcode {
AdcGpio2,
/// not tested - I2C functions
I2cWrite(I2cTransaction), /// LEFT OFF HERE -- need rkyv sending of messages
I2cReadSubscribe(String<64>),
I2cRead(I2cTransaction), // if this is issued without first subscribing to responses, the read is just "lost"
IrqI2cTxrxDone, // used internally by the I2C IRQ handler
I2cTxRx(I2cTransaction), // type (tx or rx) encoded in struct
// callback repsonses from the I2C engine -- I2C callers must decode these opcodes
I2cSubscribe(String<64>), // if TxRx is issued without first subscribing to responses, the read data is just "lost"
I2cResponse(I2cTransaction), // for writes, just the status field is valid; for reads, the read data is in the read buffer
// used internally by the I2C IRQ handler, not for external use
IrqI2cTxrxDone,
/// not tested -- events
EventComSubscribe(String<64>),
@ -238,6 +263,7 @@ impl core::convert::TryFrom<& Message> for Opcode {
19 => Ok(Opcode::SelfDestruct(m.arg1 as u32)),
20 => Ok(Opcode::Vibe(m.arg1.into())),
// note 21 is used for RebootCpuConfirm
22 => Ok(Opcode::IrqI2cTxrxDone),
_ => Err("LLIO api: unknown Scalar ID"),
},
Message::BlockingScalar(m) => match m.id {
@ -406,6 +432,10 @@ impl Into<Message> for Opcode {
arg1: pattern as usize, arg2: 0, arg3: 0, arg4: 0,
}),
// note 21 is used by RebootCpuConfirm
Opcode::IrqI2cTxrxDone => Message::Scalar(ScalarMessage {
id: 22,
arg1: 0, arg2: 0, arg3: 0, arg4: 0,
}),
// blocking scalars
Opcode::GpioDataIn => Message::BlockingScalar(ScalarMessage {

View file

@ -3,9 +3,46 @@
/// This is the API that other servers use to call the COM. Read this code as if you
/// are calling these functions inside a different process.
pub mod api;
use api::*;
use xous::{send_message, CID};
// used by the LLIO to send a response to other servers
pub fn send_i2c_response(cid: CID, transaction: I2cTransaction) -> Result<(), xous::Error> {
let op = api::Opcode::I2cResponse(transaction);
let mut writer = rkyv::ser::serializers::BufferSerializer::new(xous::XousBuffer::new(4096));
let pos = {
use rkyv::ser::Serializer;
writer.serialize_value(&op).expect("LLIO_API: couldn't archive I2cResponse");
};
let buf = writer.into_inner();
buf.lend(cid, pos as u32).expect("LLIO_API: I2cResponse operation failure");
Ok(())
}
// used by other servers to request an I2C transaction
pub fn send_i2c_request(cid: CID, transaction: I2cTransaction) -> Result<I2cStatus, xous::Error> {
let op = api::Opcode::I2cTxRx(transaction);
let mut writer = rkyv::ser::serializers::BufferSerializer::new(xous::XousBuffer::new(4096));
let pos = {
use rkyv::ser::Serializer;
writer.serialize_value(&op).expect("LLIO_API: couldn't archive I2cTxRx");
};
let buf = writer.into_inner();
buf.lend_mut(cid, pos as u32).expect("LLIO_API: I2cTxRx operation failure");
let returned = unsafe { rkyv::archived_value::<api::Opcode>(buf.as_ref(), pos)};
if let rkyv::Archived::<api::Opcode>::I2cTxRx(result) = returned {
let i2c_txrx: I2cTransaction = result.unarchive();
Ok(i2c_txrx.status)
} else {
let i2c_txrx = returned.unarchive();
log::info!("send_i2c_request saw an unhandled return type of {:?}", i2c_txrx);
Err(xous::Error::InternalError)
}
}
pub fn allow_power_off(cid: CID, allow: bool) -> Result<(), xous::Error> {
send_message(cid, api::Opcode::PowerSelf(!allow).into()).map(|_| ())
}

View file

@ -3,6 +3,8 @@
mod api;
use api::*;
mod i2c;
use i2c::*;
use core::convert::TryFrom;
@ -16,34 +18,6 @@ mod implementation {
const STD_TIMEOUT: u32 = 100;
#[derive(Debug)]
enum I2cMsg {
TxrxDone,
StartWrite(u8), // arg is the 7-bit I2C address
WriteByte(u8),
StartRead(u8), // arg is the 7-bit I2C address
ReadByte,
}
impl core::convert::TryFrom<& Message> for Opcode {
type Error = &'static str;
fn try_from(message: & Message) -> Result<Self, Self::Error> {
match message {
Message::Scalar(m) => match m.id {
0 => Ok(I2cMsg::TxRxDone),
},
_ => Err("LLIO I2C: unhandled message type"),
}
}
}
impl Into<Message> for Opcode {
fn into(self) -> Message {
match self {
I2cMsg::TxRx => Message::Scalar(ScalarMessage {
id: 0, arg1: 0, arg2: 0, arg3: 0, arg4: 0, }),
}
}
}
pub struct Llio {
reboot_csr: utralib::CSR<u32>,
crg_csr: utralib::CSR<u32>,
@ -51,8 +25,7 @@ mod implementation {
info_csr: utralib::CSR<u32>,
identifier_csr: utralib::CSR<u32>,
i2c_csr: utralib::CSR<u32>,
i2c_sid: xous::SID,
i2c_conn: Option<xous::CID>,
handler_conn: xous::CID,
event_csr: utralib::CSR<u32>,
power_csr: utralib::CSR<u32>,
seed_csr: utralib::CSR<u32>,
@ -61,23 +34,6 @@ mod implementation {
destruct_armed: bool,
}
fn i2c_thread(arg: *mut usize) {
let llio = unsafe {&mut *(arg as *mut Llio)};
// this connection is used by the IRQ responder to send me my done message
llio.i2c_conn = Some(xous::connect(llio.i2c_sid).expect("LLIO|i2c: couldn't create connection to I2C thread responder"));
loop {
let envelope = xous::receive_message(llio.i2c_sid).unwrap();
if let Ok(i2cmsg) = I2cMsg::try_from(&envelope.body) {
// here we implement the core byte-wide read/write ops, and upon receipt of
// the interrupt from the hardware, we send a message to the main loop informing
// it that things had completed
// the main loop itself is responsible for keeping a copy of the I2C data array, managing
// a pointer, and sequencing the overall i2c transaction.
}
}
}
fn handle_event_irq(_irq_no: usize, arg: *mut usize) {
let xl = unsafe { &mut *(arg as *mut Llio) };
// just clear the pending request for now and return
@ -94,7 +50,7 @@ mod implementation {
fn handle_i2c_irq(_irq_no: usize, arg: *mut usize) {
let xl = unsafe { &mut *(arg as *mut Llio) };
if let Some(conn) = xl.i2c_conn {
xous::try_send_message(xl.i2c_conn, I2cMsg::TxrxDone.into()).map(|_| ()).unwrap();
xous::try_send_message(xl.handler_conn, Opcode::IrqI2cTxrxDone.into()).map(|_| ()).unwrap();
} else {
log::error!("LLIO|handle_i2c_irq: TXRX done interrupt, but no connection for notification!");
}
@ -103,7 +59,7 @@ mod implementation {
}
impl Llio {
pub fn new() -> Llio {
pub fn new(local_conn: xous::CID) -> Llio {
let reboot_csr = xous::syscall::map_memory(
xous::MemoryAddress::new(utra::reboot::HW_REBOOT_BASE),
None,
@ -186,8 +142,7 @@ mod implementation {
info_csr: CSR::new(info_csr.as_mut_ptr() as *mut u32),
identifier_csr: CSR::new(identifier_csr.as_mut_ptr() as *mut u32),
i2c_csr: CSR::new(i2c_csr.as_mut_ptr() as *mut u32),
i2c_sid,
i2c_conn: None,
handler_conn, // connection for messages from IRQ handler
event_csr: CSR::new(event_csr.as_mut_ptr() as *mut u32),
power_csr: CSR::new(power_csr.as_mut_ptr() as *mut u32),
seed_csr: CSR::new(seed_csr.as_mut_ptr() as *mut u32),
@ -212,6 +167,8 @@ mod implementation {
)
.expect("couldn't claim GPIO irq");
// disable interrupt, just in case it's enabled from e.g. a warm boot
xl.i2c_csr.wfo(utra::i2c::EV_ENABLE_TXRX_DONE, 0);
xous::claim_interrupt(
utra::i2c::I2C_IRQ,
handle_i2c_irq,
@ -221,10 +178,8 @@ mod implementation {
// initialize i2c
i2c_init(&mut xl, utralib::LITEX_CONFIG_CLOCK_FREQUENCY);
xous::create_thread_simple(i2c_thread, (&mut xl) as *mut Llio as *mut usize).expect("LLIO: couldn't make I2C handler thread");
// clear any interrupts pending, just in case
xl.i2c_csr
.wo(utra::i2c::EV_PENDING, xl.i2c_csr.r(utra::i2c::EV_PENDING));
// clear any interrupts pending, just in case something went pear-shaped during initialization
xl.i2c_csr.wo(utra::i2c::EV_PENDING, xl.i2c_csr.r(utra::i2c::EV_PENDING));
// now enable interrupts
xl.i2c_csr.wfo(utra::i2c::EV_ENABLE_TXRX_DONE, 1);
@ -403,99 +358,6 @@ mod implementation {
// enable the block
self.i2c_csr.rmwf(utra::i2c::CONTROL_EN, 1);
}
// [FIXME] this is a stupid polled implementation of I2C transmission. Once we have
// threads and interurpts, this should be refactored to be asynchronous
/// Wait until a transaction in progress ends. [FIXME] would be good to yield here once threading is enabled.
fn i2c_tip_wait(p: &betrusted_pac::Peripherals, timeout_ms: u32) -> u32 {
let starttime: u32 = get_time_ms(p);
// wait for TIP to go high
loop {
if p.I2C.status.read().tip().bit() == true {
break;
}
if get_time_ms(p) > starttime + timeout_ms {
unsafe{p.I2C.command.write( |w| {w.bits(0)}); }
return 1;
}
}
// wait for tip to go low
loop {
if p.I2C.status.read().tip().bit() == false {
break;
}
if get_time_ms(p) > starttime + timeout_ms {
unsafe{p.I2C.command.write( |w| {w.bits(0)}); }
return 1;
}
}
unsafe{p.I2C.command.write( |w| {w.bits(0)}); }
0
}
/// The primary I2C interface call. This version currently blocks until the transaction is done.
pub fn i2c_controller(p: &betrusted_pac::Peripherals, addr: u8, txbuf: Option<&[u8]>, rxbuf: Option<&mut [u8]>, timeout_ms: u32) -> u32 {
let mut ret: u32 = 0;
// write half
if txbuf.is_some() {
let txbuf_checked : &[u8] = txbuf.unwrap();
unsafe{ p.I2C.txr.write( |w| {w.bits( (addr << 1 | 0) as u32 )}); }
p.I2C.command.write( |w| {w.sta().bit(true).wr().bit(true)});
ret += i2c_tip_wait(p, timeout_ms);
let mut i: usize = 0;
loop {
if i == txbuf_checked.len() as usize {
break;
}
if p.I2C.status.read().rx_ack().bit() {
ret += 1;
}
unsafe{ p.I2C.txr.write( |w| {w.bits( (txbuf_checked[i]) as u32 )}); }
if i == txbuf_checked.len() - 1 && rxbuf.is_none() {
p.I2C.command.write( |w| {w.wr().bit(true).sto().bit(true)});
} else {
p.I2C.command.write( |w| {w.wr().bit(true)});
}
ret += i2c_tip_wait(p, timeout_ms);
i += 1;
}
if p.I2C.status.read().rx_ack().bit() {
ret += 1;
}
}
// read half
if rxbuf.is_some() {
let rxbuf_checked : &mut [u8] = rxbuf.unwrap();
unsafe{ p.I2C.txr.write( |w| {w.bits( (addr << 1 | 1) as u32 )}); }
p.I2C.command.write( |w| {w.sta().bit(true).wr().bit(true)});
ret += i2c_tip_wait(p, timeout_ms);
let mut i: usize = 0;
loop {
if i == rxbuf_checked.len() as usize {
break;
}
if i == rxbuf_checked.len() - 1 {
p.I2C.command.write( |w| {w.rd().bit(true).ack().bit(true).sto().bit(true)});
} else {
p.I2C.command.write( |w| {w.rd().bit(true)});
}
ret += i2c_tip_wait(p, timeout_ms);
rxbuf_checked[i] = p.I2C.rxr.read().bits() as u8;
i += 1;
}
}
ret
}
}
}
@ -582,8 +444,15 @@ fn xmain() -> ! {
let llio_sid = xous_names::register_name(xous::names::SERVER_NAME_LLIO).expect("LLIO: can't register server");
if debug1{info!("LLIO: registered with NS -- {:?}", llio_sid);}
// Create a new com object
let mut llio = Llio::new();
// Create a new llio object
let handler_conn = xous::connect(llio_sid).expect("LLIO: can't create IRQ handler connection");
let mut llio = Llio::new(handler_conn);
// ticktimer is a well-known server
let ticktimer_server_id = xous::SID::from_bytes(b"ticktimer-server").unwrap();
let ticktimer_conn = xous::connect(ticktimer_server_id).unwrap();
// create an i2c state machine handler
let mut i2c_machine = I2cStateMachine::new(ticktimer_conn, llio.i2c_csr);
if debug1{info!("LLIO: starting main loop");}
let mut reboot_requested: bool = false;
@ -719,19 +588,44 @@ fn xmain() -> ! {
Opcode::AdcGpio2 => {
xous::return_scalar(envelope.sender, llio.xadc_gpio2() as _).expect("LLIO: couldn't return Xadc");
},
Opcode::IrqI2cTxrxDone => {
// I2C state machine handler irq received
ic2_machine.handler();
},
_ => error!("LLIO: no handler for opcode"),
}
} else if let xous::Message::Move(m) = &envelope.body {
} else if let xous::Message::MutableBorrow(m) = &envelope.body {
let buf = unsafe { xous::XousBuffer::from_memory_message(m) };
let bytes = Pin::new(buf.as_ref());
let value = unsafe {
archived_value::<Opcode>(&bytes, m.id as usize)
};
match &*value {
rkyv::Archived::<Opcode>::I2cWrite(rkyv_i2c) => {
let i2c_write: I2cTransaction = rkyv_i2c.unarchive();
rkyv::Archived::<Opcode>::I2cTxRx(rkyv_i2c) => {
let i2c_txrx: I2cTransaction = rkyv_i2c.unarchive();
let status = i2c_machine.initiate(i2c_txrx);
i2c_txrx.status = status;
// pack our data back into the buffer to return
use rkyv::Write;
let mut writer = rkyv::ArchiveBuffer::new(buf);
writer.archive(&api::Opcode::I2cTxRx(i2c_txrx)).expect("LLIO: couldn't re-archive return value to I2cTxRx");
},
_ => panic!("LLIO: invalid Move memory message")
_ => panic!("LLIO: invalid MutableBorrow memory message")
};
} else if let xous::Message::Borrow(m) = &envelope.body {
let buf = unsafe { buffer::XousBuffer::from_memory_message(m) };
let bytes = Pin::new(buf.as_ref());
let value = unsafe {
archived_value::<api::Opcode>(&bytes, m.id as usize)
};
match &*value {
rkyv::Archived::<api::Opcode>::I2cSubscribe(registration) => {
let cid = xous_names::request_connection_blocking(registration.as_str()).expect("KBD: can't connect to requested listener for reporting events");
i2c_machine.register_listener(cid).expect("LLIO: probably ran out of slots for I2C event reporting");
},
_ => panic!("LLIO: invalid Borrow memory message"),
};
} else {
error!("LLIO: couldn't convert opcode");