half-baked i2c stuff, but about to tear a bunch of it out

This commit is contained in:
bunnie 2021-03-15 14:58:48 +08:00
parent 2f71f2a1f5
commit be38661a1e
4 changed files with 247 additions and 78 deletions

74
Cargo.lock generated
View file

@ -70,7 +70,7 @@ dependencies = [
"graphics-server",
"log",
"log-server",
"rkyv",
"rkyv 0.3.1",
"ticktimer-server",
"utralib",
"xous",
@ -83,7 +83,7 @@ version = "0.1.0"
dependencies = [
"log",
"log-server",
"rkyv",
"rkyv 0.3.1",
"utralib",
"xous",
"xous-names",
@ -124,7 +124,7 @@ version = "0.5.0"
source = "git+https://github.com/betrusted-io/blitstr.git?rev=d4516b0a6fa3ae6d29e5e323513158c4cd6b8b16#d4516b0a6fa3ae6d29e5e323513158c4cd6b8b16"
dependencies = [
"log",
"rkyv",
"rkyv 0.3.1",
]
[[package]]
@ -241,7 +241,7 @@ dependencies = [
"heapless",
"log",
"log-server",
"rkyv",
"rkyv 0.3.1",
"ticktimer-server",
"typenum",
"utralib",
@ -276,7 +276,7 @@ version = "0.1.0"
dependencies = [
"graphics-server",
"log",
"rkyv",
"rkyv 0.3.1",
"xous",
"xous-names",
]
@ -415,7 +415,7 @@ dependencies = [
"keyboard",
"log",
"log-server",
"rkyv",
"rkyv 0.3.1",
"ticktimer-server",
"trng",
"utralib",
@ -479,7 +479,7 @@ dependencies = [
"log",
"log-server",
"minifb",
"rkyv",
"rkyv 0.3.1",
"utralib",
"xous",
"xous-names",
@ -559,7 +559,7 @@ dependencies = [
"keyboard",
"log",
"log-server",
"rkyv",
"rkyv 0.3.1",
"ticktimer-server",
"utralib",
"xous",
@ -572,7 +572,7 @@ version = "0.1.0"
dependencies = [
"graphics-server",
"log",
"rkyv",
"rkyv 0.3.1",
"xous",
"xous-names",
]
@ -585,7 +585,7 @@ dependencies = [
"ime-plugin-api",
"log",
"log-server",
"rkyv",
"rkyv 0.3.1",
"ticktimer-server",
"utralib",
"xous",
@ -613,7 +613,7 @@ dependencies = [
"heapless",
"log",
"log-server",
"rkyv",
"rkyv 0.3.1",
"ticktimer-server",
"utralib",
"xous",
@ -655,7 +655,7 @@ dependencies = [
"heapless",
"log",
"log-server",
"rkyv",
"rkyv 0.4.1",
"ticktimer-server",
"utralib",
"xous",
@ -836,6 +836,26 @@ dependencies = [
"unicode-xid 0.2.1",
]
[[package]]
name = "ptr_meta"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aad980f4bb4053abd4733b1680024a8c71ffde345f6e584c6af9eb6f0067a198"
dependencies = [
"ptr_meta_derive",
]
[[package]]
name = "ptr_meta_derive"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7bcd6232fa7d7fcd15703da5c07c9f10d203ee4fdf6ecf6d7ac5056db78089a3"
dependencies = [
"proc-macro2 1.0.24",
"quote 1.0.8",
"syn 1.0.60",
]
[[package]]
name = "quick-error"
version = "1.2.3"
@ -1016,7 +1036,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ba0dea2b9efaa468bc76d09a06741839d84c70a746edb1793d9653828532666"
dependencies = [
"memoffset",
"rkyv_derive",
"rkyv_derive 0.3.1",
]
[[package]]
name = "rkyv"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45a6fdbe501948402e00ede914b4dc21d340105b2eff740ed47e3d45ac846f5c"
dependencies = [
"memoffset",
"ptr_meta",
"rkyv_derive 0.4.0",
]
[[package]]
@ -1030,6 +1061,17 @@ dependencies = [
"syn 1.0.60",
]
[[package]]
name = "rkyv_derive"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95a169f6bc5a81033e86ed39d0f4150e2608160b73d2b93c6e8e6a3efa873f14"
dependencies = [
"proc-macro2 1.0.24",
"quote 1.0.8",
"syn 1.0.60",
]
[[package]]
name = "rustc-hash"
version = "1.1.0"
@ -1114,7 +1156,7 @@ dependencies = [
"llio",
"log",
"log-server",
"rkyv",
"rkyv 0.3.1",
"ticktimer-server",
"utralib",
"xous",
@ -1551,7 +1593,7 @@ dependencies = [
"hex",
"lazy_static",
"log",
"rkyv",
"rkyv 0.3.1",
"rustc-std-workspace-core",
"xous-macros",
]
@ -1575,7 +1617,7 @@ dependencies = [
"heapless",
"log",
"log-server",
"rkyv",
"rkyv 0.3.1",
"ticktimer-server",
"utralib",
"xous",

View file

@ -12,7 +12,11 @@ log-server = { path = "../log-server" }
ticktimer-server = { path = "../ticktimer-server" }
xous-names = { path = "../xous-names" }
log = "0.4"
rkyv = { version = "0.3.1", default_features = false }
[dependencies.rkyv]
version = "0.4.1"
default-features = false
features = ["const_generics"]
[target.'cfg(not(any(windows,unix)))'.dependencies]
utralib = { path = "../../utralib"}

View file

@ -45,7 +45,7 @@ impl Into<u32> for UartType {
/////////////////////// I2C
use core::slice;
use core::ops::{Deref, DerefMut};
#[derive(Debug, Copy, Clone)]
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Unarchive)]
pub struct I2cTransaction {
bus_addr: u8,
// write address and read address are encoded in the packet field below
@ -58,62 +58,6 @@ impl I2cTransaction {
I2cTransaction{ bus_addr: 0, packet: [0; 258], length: 0 }
}
}
impl Deref for I2cTransaction {
type Target = [u8];
fn deref(&self) -> &[u8] {
unsafe {
slice::from_raw_parts(self as *const I2cTransaction as *const u8, core::mem::size_of::<I2cTransaction>())
as &[u8]
}
}
}
impl DerefMut for I2cTransaction {
fn deref_mut(&mut self) -> &mut[u8] {
unsafe {
slice::from_raw_parts_mut(self as *mut I2cTransaction as *mut u8, core::mem::size_of::<I2cTransaction>())
as &mut [u8]
}
}
}
pub struct ArchivedI2cTransaction {
ptr: rkyv::RelPtr,
}
pub struct I2cTransactionResolver {
bytes_pos: usize,
}
impl rkyv::Resolve<I2cTransaction> for I2cTransactionResolver {
type Archived = ArchivedI2cTransaction;
fn resolve(self, pos: usize, _value: &I2cTransaction) -> Self::Archived {
Self::Archived {
ptr: unsafe {
rkyv::RelPtr::new(pos + rkyv::offset_of!(ArchivedI2cTransaction, ptr), self.bytes_pos)
},
}
}
}
impl rkyv::Archive for I2cTransaction {
type Archived = ArchivedI2cTransaction;
type Resolver = I2cTransactionResolver;
fn archive<W: rkyv::Write + ?Sized>(&self, writer: &mut W) -> core::result::Result<Self::Resolver, W::Error> {
let bytes_pos = writer.pos();
writer.write(self.deref())?;
Ok(Self::Resolver { bytes_pos })
}
}
impl rkyv::Unarchive<I2cTransaction> for ArchivedI2cTransaction {
fn unarchive(&self) -> I2cTransaction {
let mut i2c: I2cTransaction = I2cTransaction::new();
unsafe {
let p = self.ptr.as_ptr() as *const u8;
for(i, val) in i2c.deref_mut().iter_mut().enumerate() {
*val = p.add(i).read();
}
};
i2c
}
}
////////////////////////////////// VIBE
#[derive(Debug)]
@ -166,7 +110,7 @@ impl Into<usize> for ClockMode {
//////////////////////////////////// OPCODES
#[allow(dead_code)]
#[derive(Debug)]
#[derive(Debug, rkyv::Archive, rkyv::Unarchive)]
pub enum Opcode {
/// not tested - reboot
RebootRequest,
@ -225,9 +169,9 @@ pub enum Opcode {
/// not tested - I2C functions
I2cWrite(I2cTransaction), /// LEFT OFF HERE -- need rkyv sending of messages
I2cReadBlocking(I2cTransaction),
I2cReadSubscribe(String<64>),
I2cReadNonBlocking(I2cTransaction),
I2cRead(I2cTransaction), // if this is issued without first subscribing to responses, the read is just "lost"
IrqI2cTxrxDone, // used internally by the I2C IRQ handler
/// not tested -- events
EventComSubscribe(String<64>),

View file

@ -16,6 +16,34 @@ 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>,
@ -23,6 +51,8 @@ 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>,
event_csr: utralib::CSR<u32>,
power_csr: utralib::CSR<u32>,
seed_csr: utralib::CSR<u32>,
@ -31,6 +61,23 @@ 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
@ -43,9 +90,14 @@ mod implementation {
xl.gpio_csr
.wo(utra::gpio::EV_PENDING, xl.gpio_csr.r(utra::gpio::EV_PENDING));
}
// ASSUME: we are only ever handling txrx done interrupts. If implementing ARB interrupts, this needs to be refactored to read the source and dispatch accordingly.
fn handle_i2c_irq(_irq_no: usize, arg: *mut usize) {
let xl = unsafe { &mut *(arg as *mut Llio) };
// just clear the pending request for now and return
if let Some(conn) = xl.i2c_conn {
xous::try_send_message(xl.i2c_conn, I2cMsg::TxrxDone.into()).map(|_| ()).unwrap();
} else {
log::error!("LLIO|handle_i2c_irq: TXRX done interrupt, but no connection for notification!");
}
xl.i2c_csr
.wo(utra::i2c::EV_PENDING, xl.i2c_csr.r(utra::i2c::EV_PENDING));
}
@ -94,6 +146,7 @@ mod implementation {
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("couldn't map I2C CSR range");
let i2c_sid = xous::create_server_id().expect("LLIO: couldn't get random server ID for I2C");
let event_csr = xous::syscall::map_memory(
xous::MemoryAddress::new(utra::btevents::HW_BTEVENTS_BASE),
None,
@ -133,6 +186,8 @@ 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,
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),
@ -164,6 +219,15 @@ mod implementation {
)
.expect("couldn't claim I2C irq");
// 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));
// now enable interrupts
xl.i2c_csr.wfo(utra::i2c::EV_ENABLE_TXRX_DONE, 1);
xl
}
@ -329,6 +393,109 @@ mod implementation {
pub fn xadc_gpio2(&self) -> u16 {
self.xadc_csr.rf(utra::trng::XADC_GPIO2_XADC_GPIO2) as u16
}
fn i2c_init(&mut self, clock_hz: u32) {
// set the prescale assuming 100MHz cpu operation: 100MHz / ( 5 * 100kHz ) - 1 = 199
let clkcode: u32 = clock_hz / (5 * 100_000) - 1;
self.i2c_csr.wfo(utra::i2c::PRESCALE_PRESCALE, clkcode & 0xFFFF);
// 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
}
}
}
@ -554,6 +721,18 @@ fn xmain() -> ! {
},
_ => error!("LLIO: no handler for opcode"),
}
} else if let xous::Message::Move(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();
},
_ => panic!("LLIO: invalid Move memory message")
};
} else {
error!("LLIO: couldn't convert opcode");
}