format services/llio

This commit is contained in:
bunnie 2024-01-14 22:25:48 +08:00
parent fd0f3945c7
commit 3d30e6d978
13 changed files with 906 additions and 643 deletions

View file

@ -6,7 +6,7 @@ mod rtc_api;
pub use rtc_api::*; pub use rtc_api::*;
// ///////////////////// UART TYPE // ///////////////////// UART TYPE
#[allow(dead_code)] // we use this constant, but only in the `bin` view (not `lib`), so clippy complains, but this seems more discoverable here. #[allow(dead_code)] // we use this constant, but only in the `bin` view (not `lib`), so clippy complains, but this seems more discoverable here.
pub(crate) const BOOT_UART: u32 = UartType::Log as u32; pub(crate) const BOOT_UART: u32 = UartType::Log as u32;
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, PartialEq, Eq)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, PartialEq, Eq)]
@ -58,18 +58,19 @@ pub(crate) enum Opcode {
/// not tested -- set GPIO /// not tested -- set GPIO
GpioDataOut, //(u32), GpioDataOut, //(u32),
GpioDataIn, GpioDataIn,
GpioDataDrive, //(u32), GpioDataDrive, //(u32),
GpioIntMask, //(u32), GpioIntMask, //(u32),
GpioIntAsFalling, //(u32), GpioIntAsFalling, //(u32),
GpioIntPending, GpioIntPending,
GpioIntEna, //(u32), GpioIntEna, //(u32),
GpioIntSubscribe, //(String<64>), // GpioIntSubscribe, //(String<64>), //
GpioIntHappened, GpioIntHappened,
/// set UART mux /// set UART mux
UartMux, //(UartType), UartMux, //(UartType),
// InfoLitexId, //(String<64>), // TODO: returns the ASCII string baked into the FPGA that describes the FPGA build, inside Registration // InfoLitexId, //(String<64>), // TODO: returns the ASCII string baked into the FPGA that describes the
// FPGA build, inside Registration
InfoDna, InfoDna,
InfoGit, InfoGit,
InfoPlatform, InfoPlatform,
@ -77,7 +78,7 @@ pub(crate) enum Opcode {
/// partially tested -- power /// partially tested -- power
PowerAudio, //(bool), PowerAudio, //(bool),
PowerSelf, //(bool), // setting this to false allows the EC to turn off our power PowerSelf, //(bool), // setting this to false allows the EC to turn off our power
PowerBoostMode, //(bool), PowerBoostMode, //(bool),
PowerCrypto, PowerCrypto,
PowerCryptoStatus, PowerCryptoStatus,
@ -108,7 +109,7 @@ pub(crate) enum Opcode {
EventComSubscribe, //(String<64>), EventComSubscribe, //(String<64>),
//EventRtcSubscribe, //(String<64>), //EventRtcSubscribe, //(String<64>),
EventUsbAttachSubscribe, //(String<64>), EventUsbAttachSubscribe, //(String<64>),
EventComEnable, //(bool), EventComEnable, //(bool),
//EventRtcEnable, //(bool), //EventRtcEnable, //(bool),
EventUsbAttachEnable, //(bool), EventUsbAttachEnable, //(bool),
EventActivityHappened, EventActivityHappened,
@ -157,8 +158,10 @@ the LLIO server, thus protecting the local SID from disclosure.
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub(crate) struct ScalarHook { pub(crate) struct ScalarHook {
pub sid: (u32, u32, u32, u32), pub sid: (u32, u32, u32, u32),
pub id: u32, // ID of the scalar message to send through (e.g. the discriminant of the Enum on the caller's side API) pub id: u32, /* ID of the scalar message to send through (e.g. the discriminant of the Enum on the
pub cid: xous::CID, // caller-side connection ID for the scalar message to route to. Created by the caller before hooking. * caller's side API) */
pub cid: xous::CID, /* caller-side connection ID for the scalar message to route to. Created by the
* caller before hooking. */
} }
// default RTC power mode setting // default RTC power mode setting

View file

@ -1,7 +1,7 @@
use rkyv::{Archive, Deserialize, Serialize}; use rkyv::{Archive, Deserialize, Serialize};
// ///////////////////// I2C // ///////////////////// I2C
pub(crate) const SERVER_NAME_I2C: &str = "_Threaded I2C manager_"; pub(crate) const SERVER_NAME_I2C: &str = "_Threaded I2C manager_";
// a small book-keeping struct used to report back to I2C requestors as to the status of a transaction // 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, rkyv::Serialize, rkyv::Deserialize, Eq, PartialEq)] #[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Eq, PartialEq)]
pub enum I2cStatus { pub enum I2cStatus {
@ -35,7 +35,7 @@ pub(crate) enum I2cCallback {
// and create a "public" version for return values via callbacks. But for now, it's pretty // and create a "public" version for return values via callbacks. But for now, it's pretty
// convenient to reach into the state of the I2C machine to debug problems in the callbacks. // convenient to reach into the state of the I2C machine to debug problems in the callbacks.
#[allow(dead_code)] #[allow(dead_code)]
pub (crate) const I2C_MAX_LEN: usize = 33; pub(crate) const I2C_MAX_LEN: usize = 33;
#[derive(Debug, Copy, Clone, Archive, Serialize, Deserialize)] #[derive(Debug, Copy, Clone, Archive, Serialize, Deserialize)]
pub struct I2cTransaction { pub struct I2cTransaction {
pub bus_addr: u8, pub bus_addr: u8,
@ -49,7 +49,15 @@ pub struct I2cTransaction {
} }
impl I2cTransaction { impl I2cTransaction {
pub fn new() -> Self { pub fn new() -> Self {
I2cTransaction{ bus_addr: 0, txbuf: None, txlen: 0, rxbuf: None, rxlen: 0, timeout_ms: 500, use_repeated_start: true } I2cTransaction {
bus_addr: 0,
txbuf: None,
txlen: 0,
rxbuf: None,
rxlen: 0,
timeout_ms: 500,
use_repeated_start: true,
}
} }
} }
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]

View file

@ -1,4 +1,4 @@
pub(crate) const SERVER_NAME_LLIO: &str = "_Low Level I/O manager_"; pub(crate) const SERVER_NAME_LLIO: &str = "_Low Level I/O manager_";
// //////////////////////////////// VIBE // //////////////////////////////// VIBE
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub enum VibePattern { pub enum VibePattern {

View file

@ -219,7 +219,9 @@ pub fn rtc_to_seconds(settings: &[u8]) -> Option<u64> {
const MONTHS: usize = 6; const MONTHS: usize = 6;
const YEARS: usize = 7; const YEARS: usize = 7;
if ((settings[CTL3] & 0xE0) != crate::RTC_PWR_MODE) // power switchover setting should be initialized if ((settings[CTL3] & 0xE0) != crate::RTC_PWR_MODE) // power switchover setting should be initialized
|| (settings[SECS] & 0x80 != 0) { // clock integrity should be guaranteed || (settings[SECS] & 0x80 != 0)
{
// clock integrity should be guaranteed
log::error!("RTC is in an uninitialized state!, {:x?}", settings); log::error!("RTC is in an uninitialized state!, {:x?}", settings);
return None; return None;
} }
@ -230,7 +232,8 @@ pub fn rtc_to_seconds(settings: &[u8]) -> Option<u64> {
|| (to_binary(settings[HOURS]) > 23) // 24 hour mode is default and assumed || (to_binary(settings[HOURS]) > 23) // 24 hour mode is default and assumed
|| (to_binary(settings[DAYS]) > 31) || (to_binary(settings[DAYS]) == 0) || (to_binary(settings[DAYS]) > 31) || (to_binary(settings[DAYS]) == 0)
|| (to_binary(settings[MONTHS]) > 12) || (to_binary(settings[MONTHS]) == 0) || (to_binary(settings[MONTHS]) > 12) || (to_binary(settings[MONTHS]) == 0)
|| (to_binary(settings[YEARS]) > 99) { || (to_binary(settings[YEARS]) > 99)
{
log::error!("RTC has invalid digits!: {:?}", settings); log::error!("RTC has invalid digits!: {:?}", settings);
return None; return None;
} }
@ -241,20 +244,22 @@ pub fn rtc_to_seconds(settings: &[u8]) -> Option<u64> {
const SECS_PER_DAY: u64 = 86400; const SECS_PER_DAY: u64 = 86400;
// DAYS is checked to be 1-31, so, it's safe to subtract 1 here // DAYS is checked to be 1-31, so, it's safe to subtract 1 here
total_secs += (to_binary(settings[DAYS]) as u64 - 1) * SECS_PER_DAY; total_secs += (to_binary(settings[DAYS]) as u64 - 1) * SECS_PER_DAY;
// this will iterate from 0 through 11; december never has an offset added, because its contribution is directly measured in DAYS // this will iterate from 0 through 11; december never has an offset added, because its contribution is
// directly measured in DAYS
for month in 0..to_binary(settings[MONTHS]) { for month in 0..to_binary(settings[MONTHS]) {
match month { match month {
0 => total_secs += 0u64, 0 => total_secs += 0u64,
1 => total_secs += 31u64 * SECS_PER_DAY, 1 => total_secs += 31u64 * SECS_PER_DAY,
2 => { 2 => {
// per spec sheet: 1) If the year counter contains a value which is exactly divisible by 4 (including the year 00), // per spec sheet: 1) If the year counter contains a value which is exactly divisible by 4
// the AB-RTCMC-32.768kHz-B5ZE-S3 compensates for leap years by adding a 29th day to February. // (including the year 00), the AB-RTCMC-32.768kHz-B5ZE-S3 compensates for
// leap years by adding a 29th day to February.
if (to_binary(settings[YEARS]) % 4) == 0 { if (to_binary(settings[YEARS]) % 4) == 0 {
total_secs += 29u64 * SECS_PER_DAY; total_secs += 29u64 * SECS_PER_DAY;
} else { } else {
total_secs += 28u64 * SECS_PER_DAY; total_secs += 28u64 * SECS_PER_DAY;
}; };
}, }
3 => total_secs += 31u64 * SECS_PER_DAY, 3 => total_secs += 31u64 * SECS_PER_DAY,
4 => total_secs += 30u64 * SECS_PER_DAY, 4 => total_secs += 30u64 * SECS_PER_DAY,
5 => total_secs += 31u64 * SECS_PER_DAY, 5 => total_secs += 31u64 * SECS_PER_DAY,
@ -282,6 +287,4 @@ pub fn rtc_to_seconds(settings: &[u8]) -> Option<u64> {
Some(total_secs) Some(total_secs)
} }
pub fn to_binary(bcd: u8) -> u8 { pub fn to_binary(bcd: u8) -> u8 { (bcd & 0xf) + ((bcd >> 4) * 10) }
(bcd & 0xf) + ((bcd >> 4) * 10)
}

View file

@ -1,10 +1,10 @@
use crate::api::*; use std::sync::{atomic::AtomicBool, atomic::Ordering, Arc};
use utralib::*;
use num_traits::ToPrimitive; use num_traits::ToPrimitive;
use susres::{RegManager, RegOrField, SuspendResume}; use susres::{RegManager, RegOrField, SuspendResume};
use std::sync::{Arc, atomic::AtomicBool, atomic::Ordering}; use utralib::*;
use crate::api::*;
#[derive(Eq, PartialEq, Debug)] #[derive(Eq, PartialEq, Debug)]
enum I2cState { enum I2cState {
@ -22,7 +22,8 @@ enum I2cIntError {
UnexpectedInterrupt, UnexpectedInterrupt,
} }
// 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. // 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) { fn handle_i2c_irq(_irq_no: usize, arg: *mut usize) {
let i2c = unsafe { &mut *(arg as *mut I2cStateMachine) }; let i2c = unsafe { &mut *(arg as *mut I2cStateMachine) };
let event = i2c.i2c_csr.r(utra::i2c::EV_PENDING); let event = i2c.i2c_csr.r(utra::i2c::EV_PENDING);
@ -30,32 +31,53 @@ fn handle_i2c_irq(_irq_no: usize, arg: *mut usize) {
if let Some(conn) = i2c.handler_conn { if let Some(conn) = i2c.handler_conn {
match i2c.handler_i() { match i2c.handler_i() {
I2cHandlerReport::WriteDone => { I2cHandlerReport::WriteDone => {
xous::try_send_message(conn, xous::try_send_message(
xous::Message::new_scalar(I2cOpcode::IrqI2cTxrxWriteDone.to_usize().unwrap(), 0, 0, 0, 0)).map(|_| ()).unwrap(); conn,
}, xous::Message::new_scalar(I2cOpcode::IrqI2cTxrxWriteDone.to_usize().unwrap(), 0, 0, 0, 0),
)
.map(|_| ())
.unwrap();
}
I2cHandlerReport::ReadDone => { I2cHandlerReport::ReadDone => {
xous::try_send_message(conn, xous::try_send_message(
xous::Message::new_scalar(I2cOpcode::IrqI2cTxrxReadDone.to_usize().unwrap(), 0, 0, 0, 0)).map(|_| ()).unwrap(); conn,
}, xous::Message::new_scalar(I2cOpcode::IrqI2cTxrxReadDone.to_usize().unwrap(), 0, 0, 0, 0),
)
.map(|_| ())
.unwrap();
}
I2cHandlerReport::InProgress => { I2cHandlerReport::InProgress => {
if i2c.trace { if i2c.trace {
xous::try_send_message(conn, xous::try_send_message(
xous::Message::new_scalar(I2cOpcode::IrqI2cTrace.to_usize().unwrap(), 0, 0, 0, 0)).map(|_| ()).unwrap(); conn,
xous::Message::new_scalar(I2cOpcode::IrqI2cTrace.to_usize().unwrap(), 0, 0, 0, 0),
)
.map(|_| ())
.unwrap();
} }
}, }
} }
if event != i2c.i2c_csr.ms(utra::i2c::EV_ENABLE_TXRX_DONE, 1) { if event != i2c.i2c_csr.ms(utra::i2c::EV_ENABLE_TXRX_DONE, 1) {
i2c.error = I2cIntError::UnexpectedInterrupt; i2c.error = I2cIntError::UnexpectedInterrupt;
xous::try_send_message(conn, xous::try_send_message(
xous::Message::new_scalar(I2cOpcode::IrqI2cTrace.to_usize().unwrap(), event as usize, 0, 0, 0)).map(|_| ()).unwrap(); conn,
xous::Message::new_scalar(
I2cOpcode::IrqI2cTrace.to_usize().unwrap(),
event as usize,
0,
0,
0,
),
)
.map(|_| ())
.unwrap();
} }
} else { } else {
panic!("|handle_i2c_irq: TXRX done interrupt, but no connection for notification!"); panic!("|handle_i2c_irq: TXRX done interrupt, but no connection for notification!");
} }
// clear all interrupts, regardless of the source // clear all interrupts, regardless of the source
i2c.i2c_csr i2c.i2c_csr.wo(utra::i2c::EV_PENDING, 0xFFFF_FFFF);
.wo(utra::i2c::EV_PENDING, 0xFFFF_FFFF);
} }
#[derive(Debug, Eq, PartialEq)] #[derive(Debug, Eq, PartialEq)]
@ -67,7 +89,7 @@ pub(crate) enum I2cHandlerReport {
pub(crate) struct I2cStateMachine { pub(crate) struct I2cStateMachine {
i2c_csr: utralib::CSR<u32>, i2c_csr: utralib::CSR<u32>,
power_csr: utralib::CSR<u32>, power_csr: utralib::CSR<u32>,
i2c_susres: RegManager::<{utra::i2c::I2C_NUMREGS}>, i2c_susres: RegManager<{ utra::i2c::I2C_NUMREGS }>,
handler_conn: Option<xous::CID>, handler_conn: Option<xous::CID>,
transaction: Option<I2cTransaction>, transaction: Option<I2cTransaction>,
@ -75,17 +97,19 @@ pub(crate) struct I2cStateMachine {
expiry: Option<u64>, // timeout of any pending transaction expiry: Option<u64>, // timeout of any pending transaction
state: I2cState, state: I2cState,
index: u32, // index of the current buffer in the state machine index: u32, // index of the current buffer in the state machine
ticktimer: ticktimer_server::Ticktimer, // a connection to the ticktimer so we can measure timeouts ticktimer: ticktimer_server::Ticktimer, // a connection to the ticktimer so we can measure timeouts
error: I2cIntError, // set if the interrupt handler encountered some kind of error error: I2cIntError, // set if the interrupt handler encountered some kind of error
trace: bool, // set to true for detailed tracing of I2C irq handler state behavior; note that the trace outputs are delayed and may not reflect actual status trace: bool, /* set to true for detailed tracing of I2C irq handler state
* behavior; note that the trace outputs are delayed and may
* not reflect actual status */
workqueue: Vec<(I2cTransaction, xous::MessageEnvelope)>, workqueue: Vec<(I2cTransaction, xous::MessageEnvelope)>,
wfi_state: Arc::<AtomicBool> wfi_state: Arc<AtomicBool>,
} }
impl I2cStateMachine { impl I2cStateMachine {
pub fn new(handler_conn: xous::CID, power_csr_raw: *mut u32, wfi_state: Arc::<AtomicBool>) -> Self { pub fn new(handler_conn: xous::CID, power_csr_raw: *mut u32, wfi_state: Arc<AtomicBool>) -> Self {
let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer"); let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer");
let i2c_csr = xous::syscall::map_memory( let i2c_csr = xous::syscall::map_memory(
xous::MemoryAddress::new(utra::i2c::HW_I2C_BASE), xous::MemoryAddress::new(utra::i2c::HW_I2C_BASE),
@ -121,12 +145,8 @@ impl I2cStateMachine {
} }
pub fn init(&mut self) { pub fn init(&mut self) {
xous::claim_interrupt( xous::claim_interrupt(utra::i2c::I2C_IRQ, handle_i2c_irq, self as *mut I2cStateMachine as *mut usize)
utra::i2c::I2C_IRQ, .expect("couldn't claim I2C irq");
handle_i2c_irq,
self as *mut I2cStateMachine as *mut usize,
)
.expect("couldn't claim I2C irq");
self.i2c_csr.wfo(utra::i2c::CORE_RESET_RESET, 1); self.i2c_csr.wfo(utra::i2c::CORE_RESET_RESET, 1);
self.ticktimer.sleep_ms(10).ok(); self.ticktimer.sleep_ms(10).ok();
@ -148,28 +168,27 @@ impl I2cStateMachine {
self.i2c_susres.push(RegOrField::Reg(utra::i2c::EV_ENABLE), None); self.i2c_susres.push(RegOrField::Reg(utra::i2c::EV_ENABLE), None);
} }
pub fn get_expiry(&self) -> Option<u64> { pub fn get_expiry(&self) -> Option<u64> { self.expiry }
self.expiry
}
#[allow(dead_code)] #[allow(dead_code)]
pub fn set_trace(&mut self, trace: bool) { pub fn set_trace(&mut self, trace: bool) { self.trace = trace; }
self.trace = trace;
}
pub fn suspend(&mut self) { pub fn suspend(&mut self) {
self.i2c_susres.suspend(); self.i2c_susres.suspend();
// disable the I2C block, so it doesn't generate spurious values // disable the I2C block, so it doesn't generate spurious values
self.i2c_csr.rmwf(utra::i2c::CONTROL_EN, 0); self.i2c_csr.rmwf(utra::i2c::CONTROL_EN, 0);
// this happens after suspend, so these disables are "lost" upon resume and replaced with the normal running values // this happens after suspend, so these disables are "lost" upon resume and replaced with the normal
// running values
self.i2c_csr.wo(utra::i2c::EV_ENABLE, 0); self.i2c_csr.wo(utra::i2c::EV_ENABLE, 0);
} }
pub fn resume(&mut self) {
self.i2c_susres.resume(); pub fn resume(&mut self) { self.i2c_susres.resume(); }
}
pub fn re_initiate(&mut self) { 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 // 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"); log::warn!("I2C timeout; resetting hardware block and re-trying");
self.i2c_csr.wfo(utra::i2c::EV_ENABLE_TXRX_DONE, 0); self.i2c_csr.wfo(utra::i2c::EV_ENABLE_TXRX_DONE, 0);
self.i2c_csr.wfo(utra::i2c::CORE_RESET_RESET, 1); self.i2c_csr.wfo(utra::i2c::CORE_RESET_RESET, 1);
@ -190,7 +209,8 @@ impl I2cStateMachine {
// re-initiate the I2C transaction // re-initiate the I2C transaction
if let Some(msg) = self.callback.take() { if let Some(msg) = self.callback.take() {
let transaction = { let transaction = {
let buffer = unsafe { xous_ipc::Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let buffer =
unsafe { xous_ipc::Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
buffer.to_original::<I2cTransaction, _>().unwrap().clone() buffer.to_original::<I2cTransaction, _>().unwrap().clone()
}; };
self.checked_initiate(transaction, msg); self.checked_initiate(transaction, msg);
@ -241,7 +261,8 @@ impl I2cStateMachine {
} else { } else {
self.report_response(I2cStatus::ResponseTimeout, None); // this resets all state variables back to defaults self.report_response(I2cStatus::ResponseTimeout, None); // this resets all state variables back to defaults
} }
// execution continues after here because we simply drop the response message back in the sender's queue, and then return here to do more // 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"); log::warn!("I2C timeout; resetting hardware block");
self.i2c_csr.wfo(utra::i2c::CORE_RESET_RESET, 1); self.i2c_csr.wfo(utra::i2c::CORE_RESET_RESET, 1);
// set the prescale assuming 100MHz cpu operation: 100MHz / ( 5 * 100kHz ) - 1 = 199 // set the prescale assuming 100MHz cpu operation: 100MHz / ( 5 * 100kHz ) - 1 = 199
@ -286,9 +307,9 @@ impl I2cStateMachine {
self.i2c_csr.wfo(utra::i2c::TXR_TXR, (transaction.bus_addr << 1 | 0) as u32); self.i2c_csr.wfo(utra::i2c::TXR_TXR, (transaction.bus_addr << 1 | 0) as u32);
self.transaction = Some(transaction); self.transaction = Some(transaction);
self.index = 0; self.index = 0;
self.i2c_csr.wo(utra::i2c::COMMAND, self.i2c_csr.wo(
self.i2c_csr.ms(utra::i2c::COMMAND_WR, 1) | utra::i2c::COMMAND,
self.i2c_csr.ms(utra::i2c::COMMAND_STA, 1) self.i2c_csr.ms(utra::i2c::COMMAND_WR, 1) | self.i2c_csr.ms(utra::i2c::COMMAND_STA, 1),
); );
log::debug!("Initiate write"); log::debug!("Initiate write");
self.trace(0); self.trace(0);
@ -298,9 +319,9 @@ impl I2cStateMachine {
self.i2c_csr.wfo(utra::i2c::TXR_TXR, (transaction.bus_addr << 1 | 1) as u32); self.i2c_csr.wfo(utra::i2c::TXR_TXR, (transaction.bus_addr << 1 | 1) as u32);
self.transaction = Some(transaction); self.transaction = Some(transaction);
self.index = 0; self.index = 0;
self.i2c_csr.wo(utra::i2c::COMMAND, self.i2c_csr.wo(
self.i2c_csr.ms(utra::i2c::COMMAND_WR, 1) | utra::i2c::COMMAND,
self.i2c_csr.ms(utra::i2c::COMMAND_STA, 1) self.i2c_csr.ms(utra::i2c::COMMAND_WR, 1) | self.i2c_csr.ms(utra::i2c::COMMAND_STA, 1),
); );
log::debug!("Initiate read"); log::debug!("Initiate read");
self.trace(0); self.trace(0);
@ -323,20 +344,15 @@ impl I2cStateMachine {
// the .take() will cause the msg to go out of scope, triggering Drop which unblocks the caller // the .take() will cause the msg to go out of scope, triggering Drop which unblocks the caller
if let Some(mut msg) = self.callback.take() { if let Some(mut msg) = self.callback.take() {
let mut response = I2cResult { let mut response = I2cResult { rxbuf: [0u8; I2C_MAX_LEN], rxlen: 0, status };
rxbuf: [0u8; I2C_MAX_LEN],
rxlen: 0,
status,
};
if let Some(data) = rx { if let Some(data) = rx {
for (&src, dst) in data.iter().zip(response.rxbuf.iter_mut()) { for (&src, dst) in data.iter().zip(response.rxbuf.iter_mut()) {
*dst = src; *dst = src;
} }
response.rxlen = data.len() as _; response.rxlen = data.len() as _;
} }
let mut buf = unsafe { let mut buf =
xous_ipc::Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) unsafe { xous_ipc::Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
};
buf.replace(response).expect("couldn't serialize response to sender"); buf.replace(response).expect("couldn't serialize response to sender");
log::debug!("transaction to None"); log::debug!("transaction to None");
self.transaction.take(); self.transaction.take();
@ -345,7 +361,10 @@ impl I2cStateMachine {
self.index = 0; self.index = 0;
self.error = I2cIntError::NoErr; self.error = I2cIntError::NoErr;
} else { } else {
log::error!("Invalid state: response requested but no request pending {:?}. I2C bus state may be incoherent.", status); log::error!(
"Invalid state: response requested but no request pending {:?}. I2C bus state may be incoherent.",
status
);
} }
if self.workqueue.len() > 0 { if self.workqueue.len() > 0 {
log::debug!("workqueue has pending items: {}", self.workqueue.len()); log::debug!("workqueue has pending items: {}", self.workqueue.len());
@ -359,6 +378,7 @@ impl I2cStateMachine {
// report the end of a write-only transaction to all the listeners // report the end of a write-only transaction to all the listeners
self.report_response(I2cStatus::ResponseWriteOk, None); self.report_response(I2cStatus::ResponseWriteOk, None);
} }
pub fn report_read_done(&mut self) { pub fn report_read_done(&mut self) {
// report the result of a read transaction to all the listeners // report the result of a read transaction to all the listeners
log::debug!("Sending read done {:?}", self.transaction); log::debug!("Sending read done {:?}", self.transaction);
@ -378,24 +398,23 @@ impl I2cStateMachine {
self.report_response(I2cStatus::ResponseFormatError, None); self.report_response(I2cStatus::ResponseFormatError, None);
} }
} }
/// This will indicate the interface is busy if there is a transaction in progress or if there is /// This will indicate the interface is busy if there is a transaction in progress or if there is
/// work in the queue. The intention of this use case is if a caller is planning on doing a fairly /// work in the queue. The intention of this use case is if a caller is planning on doing a fairly
/// extensive set of reads/writes sequentially and they want to volunarily back-off so they aren't overflowing /// extensive set of reads/writes sequentially and they want to volunarily back-off so they aren't
/// the work queues or thrashing the bus by pulling it between two different peripherals. /// overflowing the work queues or thrashing the bus by pulling it between two different peripherals.
pub fn is_busy(&self) -> bool { pub fn is_busy(&self) -> bool {
if self.state == I2cState::Idle || self.workqueue.len() == 0 { if self.state == I2cState::Idle || self.workqueue.len() == 0 { false } else { true }
false
} else {
true
}
} }
/// This returns if a transaction is currently in progress. This differs from is_busy in that is_busy /// This returns if a transaction is currently in progress. This differs from is_busy in that is_busy
/// will return false if the work queue is also empty, even though the interface is performing a transaction. /// will return false if the work queue is also empty, even though the interface is performing a
pub fn in_progress(&self) -> bool { /// transaction.
self.state != I2cState::Idle pub fn in_progress(&self) -> bool { self.state != I2cState::Idle }
}
pub(crate) fn trace(&self, arg: usize) { pub(crate) fn trace(&self, arg: usize) {
log::debug!("I2C trace '{:?}/{:?}'=> PENDING: {:x}, ENABLE: {:x}, CMD: {:x}, STATUS: {:x}, CONTROL: {:x}, PRESCALE: {:x}, arg: {:x}", log::debug!(
"I2C trace '{:?}/{:?}'=> PENDING: {:x}, ENABLE: {:x}, CMD: {:x}, STATUS: {:x}, CONTROL: {:x}, PRESCALE: {:x}, arg: {:x}",
self.state, self.state,
self.error, self.error,
self.i2c_csr.r(utra::i2c::EV_PENDING), self.i2c_csr.r(utra::i2c::EV_PENDING),
@ -419,11 +438,14 @@ impl I2cStateMachine {
// send next byte if there is one // send next byte if there is one
if self.index < transaction.txlen { if self.index < transaction.txlen {
self.i2c_csr.wfo(utra::i2c::TXR_TXR, txbuf[self.index as usize] as u32); self.i2c_csr.wfo(utra::i2c::TXR_TXR, txbuf[self.index as usize] as u32);
if self.index == (transaction.txlen - 1) && (transaction.rxbuf.is_none() || !transaction.use_repeated_start) { if self.index == (transaction.txlen - 1)
&& (transaction.rxbuf.is_none() || !transaction.use_repeated_start)
{
// send a stop bit if this is the very last in the series // send a stop bit if this is the very last in the series
self.i2c_csr.wo(utra::i2c::COMMAND, self.i2c_csr.wo(
self.i2c_csr.ms(utra::i2c::COMMAND_WR, 1) | utra::i2c::COMMAND,
self.i2c_csr.ms(utra::i2c::COMMAND_STO, 1) self.i2c_csr.ms(utra::i2c::COMMAND_WR, 1)
| self.i2c_csr.ms(utra::i2c::COMMAND_STO, 1),
); );
} else { } else {
self.i2c_csr.wfo(utra::i2c::COMMAND_WR, 1); self.i2c_csr.wfo(utra::i2c::COMMAND_WR, 1);
@ -435,9 +457,10 @@ impl I2cStateMachine {
self.state = I2cState::Read; self.state = I2cState::Read;
self.i2c_csr.wfo(utra::i2c::TXR_TXR, (transaction.bus_addr << 1 | 1) as u32); self.i2c_csr.wfo(utra::i2c::TXR_TXR, (transaction.bus_addr << 1 | 1) as u32);
self.index = 0; self.index = 0;
self.i2c_csr.wo(utra::i2c::COMMAND, self.i2c_csr.wo(
self.i2c_csr.ms(utra::i2c::COMMAND_WR, 1) | utra::i2c::COMMAND,
self.i2c_csr.ms(utra::i2c::COMMAND_STA, 1) self.i2c_csr.ms(utra::i2c::COMMAND_WR, 1)
| self.i2c_csr.ms(utra::i2c::COMMAND_STA, 1),
); );
} else { } else {
report = I2cHandlerReport::WriteDone; report = I2cHandlerReport::WriteDone;
@ -448,19 +471,21 @@ impl I2cStateMachine {
// we should never get here, because txbuf was checked as Some() by the setup routine // we should never get here, because txbuf was checked as Some() by the setup routine
self.error = I2cIntError::MissingTx; self.error = I2cIntError::MissingTx;
} }
}, }
I2cState::Read => { I2cState::Read => {
if let Some(rxbuf) = &mut transaction.rxbuf { if let Some(rxbuf) = &mut transaction.rxbuf {
if self.index > 0 { if self.index > 0 {
// we are re-entering from a previous call, store the read value from the previous call // we are re-entering from a previous call, store the read value from the previous
// call
rxbuf[self.index as usize - 1] = self.i2c_csr.rf(utra::i2c::RXR_RXR) as u8; rxbuf[self.index as usize - 1] = self.i2c_csr.rf(utra::i2c::RXR_RXR) as u8;
} }
if self.index < transaction.rxlen { if self.index < transaction.rxlen {
if self.index == (transaction.rxlen - 1) { if self.index == (transaction.rxlen - 1) {
self.i2c_csr.wo(utra::i2c::COMMAND, self.i2c_csr.wo(
self.i2c_csr.ms(utra::i2c::COMMAND_RD, 1) | utra::i2c::COMMAND,
self.i2c_csr.ms(utra::i2c::COMMAND_STO, 1) | self.i2c_csr.ms(utra::i2c::COMMAND_RD, 1)
self.i2c_csr.ms(utra::i2c::COMMAND_ACK, 1) | self.i2c_csr.ms(utra::i2c::COMMAND_STO, 1)
| self.i2c_csr.ms(utra::i2c::COMMAND_ACK, 1),
); );
} else { } else {
self.i2c_csr.wfo(utra::i2c::COMMAND_RD, 1); self.i2c_csr.wfo(utra::i2c::COMMAND_RD, 1);
@ -474,7 +499,7 @@ impl I2cStateMachine {
// we should never get here, because rxbuf was checked as Some() by the setup routine // we should never get here, because rxbuf was checked as Some() by the setup routine
self.error = I2cIntError::MissingRx; self.error = I2cIntError::MissingRx;
} }
}, }
I2cState::Idle => { I2cState::Idle => {
// this shouldn't happen, all we can do is flag an error // this shouldn't happen, all we can do is flag an error
self.error = I2cIntError::UnexpectedState; self.error = I2cIntError::UnexpectedState;

View file

@ -1,21 +1,27 @@
use crate::api::*; use std::sync::{atomic::AtomicBool, Arc};
use std::sync::{Arc, atomic::AtomicBool};
pub(crate) struct I2cStateMachine { use crate::api::*;
}
pub(crate) struct I2cStateMachine {}
impl I2cStateMachine { impl I2cStateMachine {
pub fn new(_handler_conn: xous::CID, _power_csr_raw: *mut u32, _wfi_state: Arc::<AtomicBool>) -> Self { pub fn new(_handler_conn: xous::CID, _power_csr_raw: *mut u32, _wfi_state: Arc<AtomicBool>) -> Self {
I2cStateMachine { I2cStateMachine {}
}
} }
pub fn init(&mut self) {} pub fn init(&mut self) {}
pub fn suspend(&mut self) {} pub fn suspend(&mut self) {}
pub fn resume(&mut self) {} pub fn resume(&mut self) {}
pub fn re_initiate(&mut self) {} pub fn re_initiate(&mut self) {}
pub fn get_expiry(&self) -> Option::<u64> { None }
pub fn get_expiry(&self) -> Option<u64> { None }
pub fn initiate(&mut self, mut msg: xous::MessageEnvelope) { pub fn initiate(&mut self, mut msg: xous::MessageEnvelope) {
let mut buffer = unsafe { xous_ipc::Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut buffer =
unsafe { xous_ipc::Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let transaction = buffer.to_original::<I2cTransaction, _>().unwrap(); let transaction = buffer.to_original::<I2cTransaction, _>().unwrap();
let response = if transaction.rxbuf.is_some() { let response = if transaction.rxbuf.is_some() {
I2cResult { I2cResult {
@ -24,26 +30,20 @@ impl I2cStateMachine {
status: I2cStatus::ResponseReadOk, status: I2cStatus::ResponseReadOk,
} }
} else { } else {
I2cResult { I2cResult { rxbuf: [0u8; I2C_MAX_LEN], rxlen: 0, status: I2cStatus::ResponseWriteOk }
rxbuf: [0u8; I2C_MAX_LEN],
rxlen: 0,
status: I2cStatus::ResponseWriteOk,
}
}; };
buffer.replace(response).unwrap(); buffer.replace(response).unwrap();
} }
pub fn report_write_done(&mut self) {
} pub fn report_write_done(&mut self) {}
pub fn report_read_done(&mut self) {
} pub fn report_read_done(&mut self) {}
pub fn is_busy(&self) -> bool {
false pub fn is_busy(&self) -> bool { false }
}
pub fn in_progress(&self) -> bool { pub fn in_progress(&self) -> bool { false }
false
} pub fn trace(&self, _arg: usize) {}
pub fn trace(&self, _arg: usize) {
} pub fn driver_reset(&mut self) {}
pub fn driver_reset(&mut self) {
}
} }

View file

@ -7,7 +7,7 @@ mod hosted;
#[cfg(not(target_os = "xous"))] #[cfg(not(target_os = "xous"))]
pub use crate::i2c::hosted::*; pub use crate::i2c::hosted::*;
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature = "precursor", feature = "renode"))]
mod hardware; mod hardware;
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature = "precursor", feature = "renode"))]
pub(crate) use crate::i2c::hardware::*; pub(crate) use crate::i2c::hardware::*;

View file

@ -1,10 +1,13 @@
use core::sync::atomic::{AtomicU32, Ordering};
use num_traits::*;
use xous::CID; use xous::CID;
use xous_ipc::Buffer; use xous_ipc::Buffer;
use num_traits::*;
use core::sync::atomic::{AtomicU32, Ordering};
use crate::api::*; use crate::api::*;
// these exist outside the I2C struct because it needs to synchronize across multiple object instances within the same process // 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); static REFCOUNT: AtomicU32 = AtomicU32::new(0);
#[derive(Debug)] #[derive(Debug)]
@ -16,20 +19,21 @@ impl I2c {
pub fn new(xns: &xous_names::XousNames) -> Self { pub fn new(xns: &xous_names::XousNames) -> Self {
REFCOUNT.fetch_add(1, Ordering::Relaxed); REFCOUNT.fetch_add(1, Ordering::Relaxed);
let 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");
I2c { I2c { conn, timeout_ms: 150 }
conn,
timeout_ms: 150,
}
} }
/// Safety: caller must ensure that there are no I2C actions in flight. This resets the mutex to not acquired.
/// Safety: caller must ensure that there are no I2C actions in flight. This resets the mutex to not
/// acquired.
pub unsafe fn i2c_driver_reset(&mut self) { pub unsafe fn i2c_driver_reset(&mut self) {
xous::send_message(self.conn, xous::send_message(
xous::Message::new_blocking_scalar(I2cOpcode::I2cDriverReset.to_usize().unwrap(), 0, 0, 0, 0) self.conn,
).expect("error handling i2c driver reset"); xous::Message::new_blocking_scalar(I2cOpcode::I2cDriverReset.to_usize().unwrap(), 0, 0, 0, 0),
} )
pub fn i2c_set_timeout(&mut self, timeout: u32) { .expect("error handling i2c driver reset");
self.timeout_ms = timeout;
} }
pub fn i2c_set_timeout(&mut self, timeout: u32) { self.timeout_ms = timeout; }
/// Blocks if another I2C operation is in progress, and resumes once the mutex is released /// Blocks if another I2C operation is in progress, and resumes once the mutex is released
/// This *must* be called before doing any I2C transaction -- even if a single action. This /// This *must* be called before doing any I2C transaction -- even if a single action. This
/// operation exists because multiple I2C operations may have to be executed in sequence without /// operation exists because multiple I2C operations may have to be executed in sequence without
@ -39,15 +43,20 @@ impl I2c {
/// The mutex sharing is collaborative, so someone without the mutex could, in theory, just /// The mutex sharing is collaborative, so someone without the mutex could, in theory, just
/// barge in and perform an operation. /// barge in and perform an operation.
pub fn i2c_mutex_acquire(&self) { pub fn i2c_mutex_acquire(&self) {
xous::send_message(self.conn, xous::send_message(
xous::Message::new_blocking_scalar(I2cOpcode::I2cMutexAcquire.to_usize().unwrap(), 0, 0, 0, 0) self.conn,
).expect("error handling i2c mutex acquire"); xous::Message::new_blocking_scalar(I2cOpcode::I2cMutexAcquire.to_usize().unwrap(), 0, 0, 0, 0),
)
.expect("error handling i2c mutex acquire");
} }
/// Must be called after acquire to release the mutex, otherwise the block retains a hold on the system. /// Must be called after acquire to release the mutex, otherwise the block retains a hold on the system.
pub fn i2c_mutex_release(&self) { pub fn i2c_mutex_release(&self) {
xous::send_message(self.conn, xous::send_message(
xous::Message::new_blocking_scalar(I2cOpcode::I2cMutexRelease.to_usize().unwrap(), 0, 0, 0, 0) self.conn,
).expect("error handling i2c mutex release"); xous::Message::new_blocking_scalar(I2cOpcode::I2cMutexRelease.to_usize().unwrap(), 0, 0, 0, 0),
)
.expect("error handling i2c mutex release");
} }
/// initiate an i2c write. This is always a blocking call. In practice, it turns out it's not terribly /// initiate an i2c write. This is always a blocking call. In practice, it turns out it's not terribly
@ -56,14 +65,14 @@ impl I2c {
/// even if the write "takes a long time" /// even if the write "takes a long time"
pub fn i2c_write(&mut self, dev: u8, adr: u8, data: &[u8]) -> Result<I2cStatus, xous::Error> { pub fn i2c_write(&mut self, dev: u8, adr: u8, data: &[u8]) -> Result<I2cStatus, xous::Error> {
if data.len() > I2C_MAX_LEN - 1 { if data.len() > I2C_MAX_LEN - 1 {
return Err(xous::Error::OutOfMemory) return Err(xous::Error::OutOfMemory);
} }
let mut transaction = I2cTransaction::new(); let mut transaction = I2cTransaction::new();
let mut txbuf = [0; I2C_MAX_LEN]; let mut txbuf = [0; I2C_MAX_LEN];
txbuf[0] = adr; txbuf[0] = adr;
for i in 0..data.len() { for i in 0..data.len() {
txbuf[i+1] = data[i]; txbuf[i + 1] = data[i];
} }
transaction.bus_addr = dev; transaction.bus_addr = dev;
transaction.txbuf = Some(txbuf); transaction.txbuf = Some(txbuf);
@ -74,9 +83,7 @@ impl I2c {
buf.lend_mut(self.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::<I2cResult, _>().unwrap(); let result = buf.to_original::<I2cResult, _>().unwrap();
match result.status { match result.status {
I2cStatus::ResponseWriteOk => { I2cStatus::ResponseWriteOk => Ok(I2cStatus::ResponseWriteOk),
Ok(I2cStatus::ResponseWriteOk)
}
_ => { _ => {
log::error!("I2C error: {:?}", result); log::error!("I2C error: {:?}", result);
Err(xous::Error::InternalError) Err(xous::Error::InternalError)
@ -88,7 +95,7 @@ impl I2c {
/// addressing and reading the device. /// addressing and reading the device.
pub fn i2c_read(&mut self, dev: u8, adr: u8, data: &mut [u8]) -> Result<I2cStatus, xous::Error> { pub fn i2c_read(&mut self, dev: u8, adr: u8, data: &mut [u8]) -> Result<I2cStatus, xous::Error> {
if data.len() > I2C_MAX_LEN - 1 { if data.len() > I2C_MAX_LEN - 1 {
return Err(xous::Error::OutOfMemory) return Err(xous::Error::OutOfMemory);
} }
let mut transaction = I2cTransaction::new(); let mut transaction = I2cTransaction::new();
let mut txbuf = [0; I2C_MAX_LEN]; let mut txbuf = [0; I2C_MAX_LEN];
@ -119,9 +126,14 @@ impl I2c {
} }
/// initiate an i2c read, but for devices that don't support repeated starts, such as the AB-RTCMC-32.768 /// initiate an i2c read, but for devices that don't support repeated starts, such as the AB-RTCMC-32.768
pub fn i2c_read_no_repeated_start(&mut self, dev: u8, adr: u8, data: &mut [u8]) -> Result<I2cStatus, xous::Error> { pub fn i2c_read_no_repeated_start(
&mut self,
dev: u8,
adr: u8,
data: &mut [u8],
) -> Result<I2cStatus, xous::Error> {
if data.len() > I2C_MAX_LEN - 1 { if data.len() > I2C_MAX_LEN - 1 {
return Err(xous::Error::OutOfMemory) return Err(xous::Error::OutOfMemory);
} }
let mut transaction = I2cTransaction::new(); let mut transaction = I2cTransaction::new();
let mut txbuf = [0; I2C_MAX_LEN]; let mut txbuf = [0; I2C_MAX_LEN];
@ -151,13 +163,14 @@ impl I2c {
} }
} }
} }
} }
impl Drop for I2c { impl Drop for I2c {
fn drop(&mut self) { fn drop(&mut self) {
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
unsafe{xous::disconnect(self.conn).ok();} unsafe {
xous::disconnect(self.conn).ok();
}
} }
} }
} }

View file

@ -8,9 +8,9 @@ pub use api::*;
pub mod i2c_lib; pub mod i2c_lib;
pub use i2c_lib::I2c; pub use i2c_lib::I2c;
pub mod llio_lib; pub mod llio_lib;
pub use llio_lib::Llio;
use core::sync::atomic::{AtomicU32, Ordering}; use core::sync::atomic::{AtomicU32, Ordering};
pub use llio_lib::Llio;
static TIME_REFCOUNT: AtomicU32 = AtomicU32::new(0); static TIME_REFCOUNT: AtomicU32 = AtomicU32::new(0);
pub struct LocalTime { pub struct LocalTime {
@ -22,22 +22,22 @@ impl LocalTime {
pub fn new() -> LocalTime { pub fn new() -> LocalTime {
TIME_REFCOUNT.fetch_add(1, Ordering::Relaxed); TIME_REFCOUNT.fetch_add(1, Ordering::Relaxed);
let conn = xous::connect(xous::SID::from_bytes(b"timeserverpublic").unwrap()).unwrap(); let conn = xous::connect(xous::SID::from_bytes(b"timeserverpublic").unwrap()).unwrap();
LocalTime { LocalTime { conn, warn_count: 0, time_init: false }
conn,
warn_count: 0,
time_init: false,
}
} }
/// Returns the local time as milliseconds since EPOCH, assuming the time zone is set /// Returns the local time as milliseconds since EPOCH, assuming the time zone is set
/// This is provided because we don't have a `libc` to do time zone lookups with `Chrono`. /// This is provided because we don't have a `libc` to do time zone lookups with `Chrono`.
pub fn get_local_time_ms(&mut self) -> Option<u64> { pub fn get_local_time_ms(&mut self) -> Option<u64> {
if !self.time_init { if !self.time_init {
match xous::send_message(self.conn, match xous::send_message(
self.conn,
xous::Message::new_blocking_scalar( xous::Message::new_blocking_scalar(
6, // WallClockTimeInit -- this should not change because it's a libstd mapping 6, // WallClockTimeInit -- this should not change because it's a libstd mapping
0, 0, 0, 0 0, 0, 0, 0,
) ),
).expect("couldn't get init status") { )
.expect("couldn't get init status")
{
xous::Result::Scalar1(is_init) => { xous::Result::Scalar1(is_init) => {
if is_init == 0 { if is_init == 0 {
if self.warn_count < 10 || (self.warn_count & 0xff) == 0 { if self.warn_count < 10 || (self.warn_count & 0xff) == 0 {
@ -54,17 +54,13 @@ impl LocalTime {
} }
} }
// if we got here, time was initialized. Set a flag so we don't check again in the future. // if we got here, time was initialized. Set a flag so we don't check again in the future.
// this reduces the chatter of messages that may routinely happen, e.g. for getting seconds updates on the RTC. // this reduces the chatter of messages that may routinely happen, e.g. for getting seconds updates on
// the RTC.
self.time_init = true; self.time_init = true;
match xous::send_message(self.conn, match xous::send_message(self.conn, xous::Message::new_blocking_scalar(4, 0, 0, 0, 0))
xous::Message::new_blocking_scalar( .expect("couldn't get time")
4, {
0, 0, 0, 0 xous::Result::Scalar2(hi, lo) => Some((hi as u64) << 32 | (lo as u64)),
)
).expect("couldn't get time") {
xous::Result::Scalar2(hi, lo) => {
Some((hi as u64) << 32 | (lo as u64))
}
_ => { _ => {
log::error!("error retrieving time"); log::error!("error retrieving time");
return None; return None;
@ -76,7 +72,9 @@ impl LocalTime {
impl Drop for LocalTime { impl Drop for LocalTime {
fn drop(&mut self) { fn drop(&mut self) {
if TIME_REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { if TIME_REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
unsafe{xous::disconnect(self.conn).unwrap();} unsafe {
xous::disconnect(self.conn).unwrap();
}
} }
} }
} }

View file

@ -2,96 +2,103 @@
use llio::api::*; use llio::api::*;
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
pub struct Llio { pub struct Llio {}
}
pub fn log_init() -> *mut u32 { 0 as *mut u32 } pub fn log_init() -> *mut u32 { 0 as *mut u32 }
impl Llio { impl Llio {
pub fn new(_handler_conn: xous::CID, _gpio_base: *mut u32) -> Llio { pub fn new(_handler_conn: xous::CID, _gpio_base: *mut u32) -> Llio { Llio {} }
Llio {
}
}
pub fn init(&mut self) {} pub fn init(&mut self) {}
pub fn suspend(&self) {} pub fn suspend(&self) {}
pub fn resume(&self) {} pub fn resume(&self) {}
pub fn gpio_dout(&self, _d: u32) {} pub fn gpio_dout(&self, _d: u32) {}
pub fn gpio_din(&self, ) -> u32 { 0xDEAD_BEEF }
pub fn gpio_din(&self) -> u32 { 0xDEAD_BEEF }
pub fn gpio_drive(&self, _d: u32) {} pub fn gpio_drive(&self, _d: u32) {}
pub fn gpio_int_mask(&self, _d: u32) {} pub fn gpio_int_mask(&self, _d: u32) {}
pub fn gpio_int_as_falling(&self, _d: u32) {} pub fn gpio_int_as_falling(&self, _d: u32) {}
pub fn gpio_int_pending(&self, ) -> u32 { 0x0 }
pub fn gpio_int_pending(&self) -> u32 { 0x0 }
pub fn gpio_int_ena(&self, _d: u32) {} pub fn gpio_int_ena(&self, _d: u32) {}
pub fn set_uart_mux(&self, _mux: UartType) {} pub fn set_uart_mux(&self, _mux: UartType) {}
#[cfg(feature="test-rekey")]
pub fn get_info_dna(&self, ) -> (usize, usize) { (0, 1) } #[cfg(feature = "test-rekey")]
#[cfg(not(feature="test-rekey"))] pub fn get_info_dna(&self) -> (usize, usize) { (0, 1) }
pub fn get_info_dna(&self, ) -> (usize, usize) { (0, 0) }
pub fn get_info_git(&self, ) -> (usize, usize) { (0, 0) } #[cfg(not(feature = "test-rekey"))]
pub fn get_info_platform(&self, ) -> (usize, usize) { (0, 0) } pub fn get_info_dna(&self) -> (usize, usize) { (0, 0) }
pub fn get_info_target(&self, ) -> (usize, usize) { (0, 0) }
pub fn get_info_git(&self) -> (usize, usize) { (0, 0) }
pub fn get_info_platform(&self) -> (usize, usize) { (0, 0) }
pub fn get_info_target(&self) -> (usize, usize) { (0, 0) }
pub fn power_audio(&self, _power_on: bool) {} pub fn power_audio(&self, _power_on: bool) {}
pub fn power_crypto(&self, _power_on: bool) {} pub fn power_crypto(&self, _power_on: bool) {}
pub fn power_crypto_status(&self) -> (bool, bool, bool, bool) {
(true, true, true, true) pub fn power_crypto_status(&self) -> (bool, bool, bool, bool) { (true, true, true, true) }
}
pub fn power_self(&self, _power_on: bool) {} pub fn power_self(&self, _power_on: bool) {}
pub fn power_boost_mode(&self, _power_on: bool) {} pub fn power_boost_mode(&self, _power_on: bool) {}
pub fn ec_snoop_allow(&self, _power_on: bool) {} pub fn ec_snoop_allow(&self, _power_on: bool) {}
pub fn ec_reset(&self, ) {}
pub fn ec_power_on(&self, ) {} pub fn ec_reset(&self) {}
pub fn ec_power_on(&self) {}
pub fn self_destruct(&self, _code: u32) {} pub fn self_destruct(&self, _code: u32) {}
pub fn vibe(&self, pattern: VibePattern) { pub fn vibe(&self, pattern: VibePattern) {
log::info!("Imagine your keyboard vibrating: {:?}", pattern); log::info!("Imagine your keyboard vibrating: {:?}", pattern);
} }
pub fn xadc_vbus(&self) -> u16 { pub fn xadc_vbus(&self) -> u16 {
2 // some small but non-zero value to represent typical noise 2 // some small but non-zero value to represent typical noise
} }
pub fn xadc_vccint(&self) -> u16 {
1296
}
pub fn xadc_vccaux(&self) -> u16 {
2457
}
pub fn xadc_vccbram(&self) -> u16 {
2450
}
pub fn xadc_usbn(&self) -> u16 {
3
}
pub fn xadc_usbp(&self) -> u16 {
4
}
pub fn xadc_temperature(&self) -> u16 {
2463
}
pub fn xadc_gpio5(&self) -> u16 {
0
}
pub fn xadc_gpio2(&self) -> u16 {
0
}
pub fn com_int_ena(self, _ena: bool) { pub fn xadc_vccint(&self) -> u16 { 1296 }
}
pub fn usb_int_ena(self, _ena: bool) { pub fn xadc_vccaux(&self) -> u16 { 2457 }
}
pub fn debug_powerdown(&mut self, _ena: bool) { pub fn xadc_vccbram(&self) -> u16 { 2450 }
}
pub fn debug_wakeup(&mut self, _ena: bool) { pub fn xadc_usbn(&self) -> u16 { 3 }
}
#[allow(dead_code)] pub fn xadc_usbp(&self) -> u16 { 4 }
pub fn activity_get_period(&mut self) -> u32 {
12_000_000 pub fn xadc_temperature(&self) -> u16 { 2463 }
}
pub fn wfi_override(&mut self, _override_: bool) { pub fn xadc_gpio5(&self) -> u16 { 0 }
}
pub fn xadc_gpio2(&self) -> u16 { 0 }
pub fn com_int_ena(self, _ena: bool) {}
pub fn usb_int_ena(self, _ena: bool) {}
pub fn debug_powerdown(&mut self, _ena: bool) {}
pub fn debug_wakeup(&mut self, _ena: bool) {}
#[allow(dead_code)] #[allow(dead_code)]
pub fn tts_sleep_indicate(&mut self) { pub fn activity_get_period(&mut self) -> u32 { 12_000_000 }
}
pub fn get_power_csr_raw(&self) -> u32 { pub fn wfi_override(&mut self, _override_: bool) {}
0
} #[allow(dead_code)]
pub fn tts_sleep_indicate(&mut self) {}
pub fn get_power_csr_raw(&self) -> u32 { 0 }
} }

View file

@ -1,75 +1,98 @@
use crate::api::*;
use log::{error, info}; use log::{error, info};
use utralib::{generated::*, utra::gpio::UARTSEL_UARTSEL};
use num_traits::ToPrimitive; use num_traits::ToPrimitive;
use susres::{RegManager, RegOrField, SuspendResume}; use susres::{RegManager, RegOrField, SuspendResume};
use utralib::{generated::*, utra::gpio::UARTSEL_UARTSEL};
use crate::api::*;
#[allow(dead_code)] #[allow(dead_code)]
pub struct Llio { pub struct Llio {
gpio_csr: utralib::CSR<u32>, gpio_csr: utralib::CSR<u32>,
gpio_susres: RegManager::<{utra::gpio::GPIO_NUMREGS}>, gpio_susres: RegManager<{ utra::gpio::GPIO_NUMREGS }>,
info_csr: utralib::CSR<u32>, info_csr: utralib::CSR<u32>,
handler_conn: Option<xous::CID>, handler_conn: Option<xous::CID>,
event_csr: utralib::CSR<u32>, event_csr: utralib::CSR<u32>,
event_susres: RegManager::<{utra::btevents::BTEVENTS_NUMREGS}>, event_susres: RegManager<{ utra::btevents::BTEVENTS_NUMREGS }>,
power_csr: utralib::CSR<u32>, power_csr: utralib::CSR<u32>,
power_csr_raw: *mut u32, power_csr_raw: *mut u32,
power_susres: RegManager::<{utra::power::POWER_NUMREGS}>, power_susres: RegManager<{ utra::power::POWER_NUMREGS }>,
xadc_csr: utralib::CSR<u32>, // be careful with this as XADC is shared with TRNG xadc_csr: utralib::CSR<u32>, // be careful with this as XADC is shared with TRNG
ticktimer: ticktimer_server::Ticktimer, ticktimer: ticktimer_server::Ticktimer,
activity_period: u32, // 12mhz clock cycles over which to sample activity activity_period: u32, // 12mhz clock cycles over which to sample activity
destruct_armed: bool, destruct_armed: bool,
uartmux_cache: u32, // stash a value of the uartmux -- restore from override into kernel so we can record KPs on resume uartmux_cache: u32, /* stash a value of the uartmux -- restore from override into kernel so we can
* record KPs on resume */
} }
fn handle_event_irq(_irq_no: usize, arg: *mut usize) { fn handle_event_irq(_irq_no: usize, arg: *mut usize) {
let xl = unsafe { &mut *(arg as *mut Llio) }; let xl = unsafe { &mut *(arg as *mut Llio) };
if xl.event_csr.rf(utra::btevents::EV_PENDING_COM_INT) != 0 { if xl.event_csr.rf(utra::btevents::EV_PENDING_COM_INT) != 0 {
if let Some(conn) = xl.handler_conn { if let Some(conn) = xl.handler_conn {
xous::try_send_message(conn, xous::try_send_message(
xous::Message::new_scalar(Opcode::EventComHappened.to_usize().unwrap(), 0, 0, 0, 0)).map(|_|()).unwrap(); conn,
xous::Message::new_scalar(Opcode::EventComHappened.to_usize().unwrap(), 0, 0, 0, 0),
)
.map(|_| ())
.unwrap();
} else { } else {
log::error!("|handle_event_irq: COM interrupt, but no connection for notification!") log::error!("|handle_event_irq: COM interrupt, but no connection for notification!")
} }
} }
xl.event_csr xl.event_csr.wo(utra::btevents::EV_PENDING, xl.event_csr.r(utra::btevents::EV_PENDING));
.wo(utra::btevents::EV_PENDING, xl.event_csr.r(utra::btevents::EV_PENDING));
} }
fn handle_gpio_irq(_irq_no: usize, arg: *mut usize) { fn handle_gpio_irq(_irq_no: usize, arg: *mut usize) {
let xl = unsafe { &mut *(arg as *mut Llio) }; let xl = unsafe { &mut *(arg as *mut Llio) };
if let Some(conn) = xl.handler_conn { if let Some(conn) = xl.handler_conn {
xous::try_send_message(conn, xous::try_send_message(
xous::Message::new_scalar(Opcode::GpioIntHappened.to_usize().unwrap(), conn,
xl.gpio_csr.r(utra::gpio::EV_PENDING) as _, 0, 0, 0)).map(|_|()).unwrap(); xous::Message::new_scalar(
Opcode::GpioIntHappened.to_usize().unwrap(),
xl.gpio_csr.r(utra::gpio::EV_PENDING) as _,
0,
0,
0,
),
)
.map(|_| ())
.unwrap();
} else { } else {
log::error!("|handle_event_irq: GPIO interrupt, but no connection for notification!") log::error!("|handle_event_irq: GPIO interrupt, but no connection for notification!")
} }
xl.gpio_csr xl.gpio_csr.wo(utra::gpio::EV_PENDING, xl.gpio_csr.r(utra::gpio::EV_PENDING));
.wo(utra::gpio::EV_PENDING, xl.gpio_csr.r(utra::gpio::EV_PENDING));
} }
fn handle_power_irq(_irq_no: usize, arg: *mut usize) { fn handle_power_irq(_irq_no: usize, arg: *mut usize) {
let xl = unsafe { &mut *(arg as *mut Llio) }; let xl = unsafe { &mut *(arg as *mut Llio) };
if xl.power_csr.rf(utra::power::EV_PENDING_USB_ATTACH) != 0 { if xl.power_csr.rf(utra::power::EV_PENDING_USB_ATTACH) != 0 {
if let Some(conn) = xl.handler_conn { if let Some(conn) = xl.handler_conn {
xous::try_send_message(conn, xous::try_send_message(
xous::Message::new_scalar(Opcode::EventUsbHappened.to_usize().unwrap(), conn,
0, 0, 0, 0)).map(|_|()).unwrap(); xous::Message::new_scalar(Opcode::EventUsbHappened.to_usize().unwrap(), 0, 0, 0, 0),
)
.map(|_| ())
.unwrap();
} else { } else {
log::error!("|handle_event_irq: USB interrupt, but no connection for notification!") log::error!("|handle_event_irq: USB interrupt, but no connection for notification!")
} }
} else if xl.power_csr.rf(utra::power::EV_PENDING_ACTIVITY_UPDATE) != 0 { } else if xl.power_csr.rf(utra::power::EV_PENDING_ACTIVITY_UPDATE) != 0 {
if let Some(conn) = xl.handler_conn { if let Some(conn) = xl.handler_conn {
let activity = xl.power_csr.rf(utra::power::ACTIVITY_RATE_COUNTS_AWAKE); let activity = xl.power_csr.rf(utra::power::ACTIVITY_RATE_COUNTS_AWAKE);
xous::try_send_message(conn, xous::try_send_message(
xous::Message::new_scalar(Opcode::EventActivityHappened.to_usize().unwrap(), conn,
activity as usize, 0, 0, 0)).map(|_|()).unwrap(); xous::Message::new_scalar(
Opcode::EventActivityHappened.to_usize().unwrap(),
activity as usize,
0,
0,
0,
),
)
.map(|_| ())
.unwrap();
} else { } else {
log::error!("|handle_event_irq: activity interrupt, but no connection for notification!") log::error!("|handle_event_irq: activity interrupt, but no connection for notification!")
} }
} }
xl.power_csr xl.power_csr.wo(utra::power::EV_PENDING, xl.power_csr.r(utra::power::EV_PENDING));
.wo(utra::power::EV_PENDING, xl.power_csr.r(utra::power::EV_PENDING));
} }
pub fn log_init() -> *mut u32 { pub fn log_init() -> *mut u32 {
@ -147,19 +170,11 @@ impl Llio {
) )
.expect("couldn't claim BtEvents irq"); .expect("couldn't claim BtEvents irq");
xous::claim_interrupt( xous::claim_interrupt(utra::gpio::GPIO_IRQ, handle_gpio_irq, self as *mut Llio as *mut usize)
utra::gpio::GPIO_IRQ, .expect("couldn't claim GPIO irq");
handle_gpio_irq,
self as *mut Llio as *mut usize,
)
.expect("couldn't claim GPIO irq");
xous::claim_interrupt( xous::claim_interrupt(utra::power::POWER_IRQ, handle_power_irq, self as *mut Llio as *mut usize)
utra::power::POWER_IRQ, .expect("couldn't claim Power irq");
handle_power_irq,
self as *mut Llio as *mut usize,
)
.expect("couldn't claim Power irq");
self.gpio_susres.push(RegOrField::Reg(utra::gpio::DRIVE), None); self.gpio_susres.push(RegOrField::Reg(utra::gpio::DRIVE), None);
self.gpio_susres.push(RegOrField::Reg(utra::gpio::OUTPUT), None); self.gpio_susres.push(RegOrField::Reg(utra::gpio::OUTPUT), None);
@ -185,15 +200,15 @@ impl Llio {
self.power_susres.push(RegOrField::Reg(utra::power::EV_ENABLE), None); self.power_susres.push(RegOrField::Reg(utra::power::EV_ENABLE), None);
} }
pub(crate) fn get_power_csr_raw(&self) -> *mut u32 { pub(crate) fn get_power_csr_raw(&self) -> *mut u32 { self.power_csr_raw }
self.power_csr_raw
}
pub fn suspend(&mut self) { pub fn suspend(&mut self) {
self.uartmux_cache = self.gpio_csr.rf(UARTSEL_UARTSEL).into(); self.uartmux_cache = self.gpio_csr.rf(UARTSEL_UARTSEL).into();
self.gpio_csr.wfo(utra::gpio::UARTSEL_UARTSEL, 1); // set to console to watch on boot: 0 = kernel, 1 = console, 2 = application self.gpio_csr.wfo(utra::gpio::UARTSEL_UARTSEL, 1); // set to console to watch on boot: 0 = kernel, 1 = console, 2 = application
self.event_susres.suspend(); self.event_susres.suspend();
// this happens after suspend, so these disables are "lost" upon resume and replaced with the normal running values // this happens after suspend, so these disables are "lost" upon resume and replaced with the normal
// running values
self.event_csr.wo(utra::btevents::EV_ENABLE, 0); self.event_csr.wo(utra::btevents::EV_ENABLE, 0);
self.event_csr.wo(utra::btevents::EV_PENDING, 0xFFFF_FFFF); // really make sure we don't have any spurious events in the queue self.event_csr.wo(utra::btevents::EV_PENDING, 0xFFFF_FFFF); // really make sure we don't have any spurious events in the queue
@ -205,6 +220,7 @@ impl Llio {
self.power_csr.wo(utra::power::EV_ENABLE, 0); self.power_csr.wo(utra::power::EV_ENABLE, 0);
self.power_csr.wo(utra::power::EV_PENDING, 0xFFFF_FFFF); self.power_csr.wo(utra::power::EV_PENDING, 0xFFFF_FFFF);
} }
pub fn resume(&mut self) { pub fn resume(&mut self) {
self.power_susres.resume(); self.power_susres.resume();
@ -219,48 +235,43 @@ impl Llio {
// restore the UART mux setting after resume // restore the UART mux setting after resume
self.gpio_csr.wfo(utra::gpio::UARTSEL_UARTSEL, self.uartmux_cache); self.gpio_csr.wfo(utra::gpio::UARTSEL_UARTSEL, self.uartmux_cache);
} }
#[allow(dead_code)] #[allow(dead_code)]
pub fn activity_set_period(&mut self, period: u32) { pub fn activity_set_period(&mut self, period: u32) {
self.activity_period = period; self.activity_period = period;
self.power_csr.wfo(utra::power::SAMPLING_PERIOD_SAMPLE_PERIOD, period); self.power_csr.wfo(utra::power::SAMPLING_PERIOD_SAMPLE_PERIOD, period);
} }
pub fn activity_get_period(&mut self) -> u32 {
self.activity_period
}
pub fn gpio_dout(&mut self, d: u32) { pub fn activity_get_period(&mut self) -> u32 { self.activity_period }
self.gpio_csr.wfo(utra::gpio::OUTPUT_OUTPUT, d);
} pub fn gpio_dout(&mut self, d: u32) { self.gpio_csr.wfo(utra::gpio::OUTPUT_OUTPUT, d); }
pub fn gpio_din(&self) -> u32 {
self.gpio_csr.rf(utra::gpio::INPUT_INPUT) pub fn gpio_din(&self) -> u32 { self.gpio_csr.rf(utra::gpio::INPUT_INPUT) }
}
pub fn gpio_drive(&mut self, d: u32) { pub fn gpio_drive(&mut self, d: u32) { self.gpio_csr.wfo(utra::gpio::DRIVE_DRIVE, d); }
self.gpio_csr.wfo(utra::gpio::DRIVE_DRIVE, d);
} pub fn gpio_int_mask(&mut self, d: u32) { self.gpio_csr.wfo(utra::gpio::INTENA_INTENA, d); }
pub fn gpio_int_mask(&mut self, d: u32) {
self.gpio_csr.wfo(utra::gpio::INTENA_INTENA, d); pub fn gpio_int_as_falling(&mut self, d: u32) { self.gpio_csr.wfo(utra::gpio::INTPOL_INTPOL, d); }
}
pub fn gpio_int_as_falling(&mut self, d: u32) { pub fn gpio_int_pending(&self) -> u32 { self.gpio_csr.r(utra::gpio::EV_PENDING) & 0xff }
self.gpio_csr.wfo(utra::gpio::INTPOL_INTPOL, d);
} pub fn gpio_int_ena(&mut self, d: u32) { self.gpio_csr.wo(utra::gpio::EV_ENABLE, d & 0xff); }
pub fn gpio_int_pending(&self) -> u32 {
self.gpio_csr.r(utra::gpio::EV_PENDING) & 0xff
}
pub fn gpio_int_ena(&mut self, d: u32) {
self.gpio_csr.wo(utra::gpio::EV_ENABLE, d & 0xff);
}
pub fn set_uart_mux(&mut self, mux: UartType) { pub fn set_uart_mux(&mut self, mux: UartType) {
match mux { match mux {
UartType::Kernel => { UartType::Kernel => {
log::warn!("disabling WFI so that kernel console works as expected"); log::warn!("disabling WFI so that kernel console works as expected");
self.power_csr.rmwf(utra::power::POWER_DISABLE_WFI, 1); self.power_csr.rmwf(utra::power::POWER_DISABLE_WFI, 1);
self.gpio_csr.wfo(utra::gpio::UARTSEL_UARTSEL, 0); self.gpio_csr.wfo(utra::gpio::UARTSEL_UARTSEL, 0);
}, }
UartType::Log => { UartType::Log => {
// this is a command mainly for debugging, so we'll accept the chance that we re-enabled WFI e.g. // this is a command mainly for debugging, so we'll accept the chance that we re-enabled WFI
// during a critical operation like SPINOR flashing because we swapped consoles at a bad time. Should be // e.g. during a critical operation like SPINOR flashing because we swapped
// very rare and only affect devs... // consoles at a bad time. Should be very rare and only affect devs...
log::warn!("unsafe re-enabling WFI -- if you issued this command at a bad time, could have side effects"); log::warn!(
"unsafe re-enabling WFI -- if you issued this command at a bad time, could have side effects"
);
if true { if true {
self.power_csr.rmwf(utra::power::POWER_DISABLE_WFI, 0); self.power_csr.rmwf(utra::power::POWER_DISABLE_WFI, 0);
} else { } else {
@ -268,12 +279,12 @@ impl Llio {
self.power_csr.rmwf(utra::power::POWER_DISABLE_WFI, 1); self.power_csr.rmwf(utra::power::POWER_DISABLE_WFI, 1);
} }
self.gpio_csr.wfo(utra::gpio::UARTSEL_UARTSEL, 1) self.gpio_csr.wfo(utra::gpio::UARTSEL_UARTSEL, 1)
}, }
UartType::Application => { UartType::Application => {
log::warn!("disabling WFI so that app console works as expected"); log::warn!("disabling WFI so that app console works as expected");
self.power_csr.rmwf(utra::power::POWER_DISABLE_WFI, 1); self.power_csr.rmwf(utra::power::POWER_DISABLE_WFI, 1);
self.gpio_csr.wfo(utra::gpio::UARTSEL_UARTSEL, 2) self.gpio_csr.wfo(utra::gpio::UARTSEL_UARTSEL, 2)
}, }
_ => info!("invalid UART type specified for mux, doing nothing."), _ => info!("invalid UART type specified for mux, doing nothing."),
} }
} }
@ -281,21 +292,30 @@ impl Llio {
pub fn get_info_dna(&self) -> (usize, usize) { pub fn get_info_dna(&self) -> (usize, usize) {
(self.info_csr.r(utra::info::DNA_ID0) as usize, self.info_csr.r(utra::info::DNA_ID1) as usize) (self.info_csr.r(utra::info::DNA_ID0) as usize, self.info_csr.r(utra::info::DNA_ID1) as usize)
} }
pub fn get_info_git(&self) -> (usize, usize) { pub fn get_info_git(&self) -> (usize, usize) {
( (
((self.info_csr.rf(utra::info::GIT_MAJOR_GIT_MAJOR) as u32) << 24 | ((self.info_csr.rf(utra::info::GIT_MAJOR_GIT_MAJOR) as u32) << 24
(self.info_csr.rf(utra::info::GIT_MINOR_GIT_MINOR) as u32) << 16 | | (self.info_csr.rf(utra::info::GIT_MINOR_GIT_MINOR) as u32) << 16
(self.info_csr.rf(utra::info::GIT_REVISION_GIT_REVISION) as u32) << 8 | | (self.info_csr.rf(utra::info::GIT_REVISION_GIT_REVISION) as u32) << 8
(self.info_csr.rf(utra::info::GIT_GITEXTRA_GIT_GITEXTRA) as u32) & 0xFF << 0) as usize, | (self.info_csr.rf(utra::info::GIT_GITEXTRA_GIT_GITEXTRA) as u32) & 0xFF << 0)
as usize,
self.info_csr.rf(utra::info::GIT_GITREV_GIT_GITREV) as usize self.info_csr.rf(utra::info::GIT_GITREV_GIT_GITREV) as usize,
) )
} }
pub fn get_info_platform(&self) -> (usize, usize) { pub fn get_info_platform(&self) -> (usize, usize) {
(self.info_csr.r(utra::info::PLATFORM_PLATFORM0) as usize, self.info_csr.r(utra::info::PLATFORM_PLATFORM1) as usize) (
self.info_csr.r(utra::info::PLATFORM_PLATFORM0) as usize,
self.info_csr.r(utra::info::PLATFORM_PLATFORM1) as usize,
)
} }
pub fn get_info_target(&self) -> (usize, usize) { pub fn get_info_target(&self) -> (usize, usize) {
(self.info_csr.r(utra::info::PLATFORM_TARGET0) as usize, self.info_csr.r(utra::info::PLATFORM_TARGET1) as usize) (
self.info_csr.r(utra::info::PLATFORM_TARGET0) as usize,
self.info_csr.r(utra::info::PLATFORM_TARGET1) as usize,
)
} }
pub fn power_audio(&mut self, power_on: bool) { pub fn power_audio(&mut self, power_on: bool) {
@ -305,6 +325,7 @@ impl Llio {
self.power_csr.rmwf(utra::power::POWER_AUDIO, 0); self.power_csr.rmwf(utra::power::POWER_AUDIO, 0);
} }
} }
pub fn power_crypto(&mut self, power_on: bool) { pub fn power_crypto(&mut self, power_on: bool) {
if power_on { if power_on {
self.power_csr.rmwf(utra::power::POWER_CRYPTO_ON, 1); self.power_csr.rmwf(utra::power::POWER_CRYPTO_ON, 1);
@ -312,6 +333,7 @@ impl Llio {
self.power_csr.rmwf(utra::power::POWER_CRYPTO_ON, 0); self.power_csr.rmwf(utra::power::POWER_CRYPTO_ON, 0);
} }
} }
// apparently "override" is a reserved keyword in Rust??? // apparently "override" is a reserved keyword in Rust???
pub fn wfi_override(&mut self, override_: bool) { pub fn wfi_override(&mut self, override_: bool) {
if override_ { if override_ {
@ -320,6 +342,7 @@ impl Llio {
self.power_csr.rmwf(utra::power::POWER_DISABLE_WFI, 0); self.power_csr.rmwf(utra::power::POWER_DISABLE_WFI, 0);
} }
} }
pub fn debug_powerdown(&mut self, ena: bool) { pub fn debug_powerdown(&mut self, ena: bool) {
if ena { if ena {
self.power_csr.rmwf(utra::gpio::DEBUG_WFI, 1); self.power_csr.rmwf(utra::gpio::DEBUG_WFI, 1);
@ -327,6 +350,7 @@ impl Llio {
self.power_csr.rmwf(utra::gpio::DEBUG_WFI, 0); self.power_csr.rmwf(utra::gpio::DEBUG_WFI, 0);
} }
} }
pub fn debug_wakeup(&mut self, ena: bool) { pub fn debug_wakeup(&mut self, ena: bool) {
if ena { if ena {
self.power_csr.rmwf(utra::gpio::DEBUG_WAKEUP, 1); self.power_csr.rmwf(utra::gpio::DEBUG_WAKEUP, 1);
@ -334,13 +358,15 @@ impl Llio {
self.power_csr.rmwf(utra::gpio::DEBUG_WAKEUP, 0); self.power_csr.rmwf(utra::gpio::DEBUG_WAKEUP, 0);
} }
} }
pub fn power_crypto_status(&self) -> (bool, bool, bool, bool) { pub fn power_crypto_status(&self) -> (bool, bool, bool, bool) {
let sha = if self.power_csr.rf(utra::power::CLK_STATUS_SHA_ON) == 0 {false} else {true}; let sha = if self.power_csr.rf(utra::power::CLK_STATUS_SHA_ON) == 0 { false } else { true };
let engine = if self.power_csr.rf(utra::power::CLK_STATUS_ENGINE_ON) == 0 {false} else {true}; let engine = if self.power_csr.rf(utra::power::CLK_STATUS_ENGINE_ON) == 0 { false } else { true };
let force = if self.power_csr.rf(utra::power::CLK_STATUS_BTPOWER_ON) == 0 {false} else {true}; let force = if self.power_csr.rf(utra::power::CLK_STATUS_BTPOWER_ON) == 0 { false } else { true };
let overall = if self.power_csr.rf(utra::power::CLK_STATUS_CRYPTO_ON) == 0 {false} else {true}; let overall = if self.power_csr.rf(utra::power::CLK_STATUS_CRYPTO_ON) == 0 { false } else { true };
(overall, sha, engine, force) (overall, sha, engine, force)
} }
pub fn power_self(&mut self, power_on: bool) { pub fn power_self(&mut self, power_on: bool) {
if power_on { if power_on {
info!("setting self-power state to on"); info!("setting self-power state to on");
@ -351,6 +377,7 @@ impl Llio {
self.power_csr.rmwf(utra::power::POWER_SELF, 0); self.power_csr.rmwf(utra::power::POWER_SELF, 0);
} }
} }
pub fn power_boost_mode(&mut self, boost_on: bool) { pub fn power_boost_mode(&mut self, boost_on: bool) {
if boost_on { if boost_on {
self.power_csr.rmwf(utra::power::POWER_BOOSTMODE, 1); self.power_csr.rmwf(utra::power::POWER_BOOSTMODE, 1);
@ -358,6 +385,7 @@ impl Llio {
self.power_csr.rmwf(utra::power::POWER_BOOSTMODE, 0); self.power_csr.rmwf(utra::power::POWER_BOOSTMODE, 0);
} }
} }
pub fn ec_snoop_allow(&mut self, allow: bool) { pub fn ec_snoop_allow(&mut self, allow: bool) {
if allow { if allow {
self.power_csr.rmwf(utra::power::POWER_EC_SNOOP, 1); self.power_csr.rmwf(utra::power::POWER_EC_SNOOP, 1);
@ -365,15 +393,16 @@ impl Llio {
self.power_csr.rmwf(utra::power::POWER_EC_SNOOP, 0); self.power_csr.rmwf(utra::power::POWER_EC_SNOOP, 0);
} }
} }
pub fn ec_reset(&mut self) { pub fn ec_reset(&mut self) {
self.power_csr.rmwf(utra::power::POWER_UP5K_ON, 1); // make sure the power is "on" if we're resetting it self.power_csr.rmwf(utra::power::POWER_UP5K_ON, 1); // make sure the power is "on" if we're resetting it
self.power_csr.rmwf(utra::power::POWER_RESET_EC, 1); self.power_csr.rmwf(utra::power::POWER_RESET_EC, 1);
self.ticktimer.sleep_ms(20).unwrap(); self.ticktimer.sleep_ms(20).unwrap();
self.power_csr.rmwf(utra::power::POWER_RESET_EC, 0); self.power_csr.rmwf(utra::power::POWER_RESET_EC, 0);
} }
pub fn ec_power_on(&mut self) {
self.power_csr.rmwf(utra::power::POWER_UP5K_ON, 1); pub fn ec_power_on(&mut self) { self.power_csr.rmwf(utra::power::POWER_UP5K_ON, 1); }
}
pub fn self_destruct(&mut self, code: u32) { pub fn self_destruct(&mut self, code: u32) {
if self.destruct_armed && code == 0x3141_5926 { if self.destruct_armed && code == 0x3141_5926 {
self.ticktimer.sleep_ms(100).unwrap(); // give a moment for any last words (like clearing the screen, powering down, etc.) self.ticktimer.sleep_ms(100).unwrap(); // give a moment for any last words (like clearing the screen, powering down, etc.)
@ -385,18 +414,19 @@ impl Llio {
error!("self destruct attempted, but incorrect code sequence presented."); error!("self destruct attempted, but incorrect code sequence presented.");
} }
} }
pub fn vibe(&mut self, pattern: VibePattern) { pub fn vibe(&mut self, pattern: VibePattern) {
match pattern { match pattern {
VibePattern::Short => { VibePattern::Short => {
self.power_csr.wfo(utra::power::VIBE_VIBE, 1); self.power_csr.wfo(utra::power::VIBE_VIBE, 1);
self.ticktimer.sleep_ms(80).unwrap(); self.ticktimer.sleep_ms(80).unwrap();
self.power_csr.wfo(utra::power::VIBE_VIBE, 0); self.power_csr.wfo(utra::power::VIBE_VIBE, 0);
}, }
VibePattern::Long => { VibePattern::Long => {
self.power_csr.wfo(utra::power::VIBE_VIBE, 1); self.power_csr.wfo(utra::power::VIBE_VIBE, 1);
self.ticktimer.sleep_ms(1000).unwrap(); self.ticktimer.sleep_ms(1000).unwrap();
self.power_csr.wfo(utra::power::VIBE_VIBE, 0); self.power_csr.wfo(utra::power::VIBE_VIBE, 0);
}, }
VibePattern::Double => { VibePattern::Double => {
self.power_csr.wfo(utra::power::VIBE_VIBE, 1); self.power_csr.wfo(utra::power::VIBE_VIBE, 1);
self.ticktimer.sleep_ms(150).unwrap(); self.ticktimer.sleep_ms(150).unwrap();
@ -405,47 +435,41 @@ impl Llio {
self.power_csr.wfo(utra::power::VIBE_VIBE, 1); self.power_csr.wfo(utra::power::VIBE_VIBE, 1);
self.ticktimer.sleep_ms(150).unwrap(); self.ticktimer.sleep_ms(150).unwrap();
self.power_csr.wfo(utra::power::VIBE_VIBE, 0); self.power_csr.wfo(utra::power::VIBE_VIBE, 0);
}, }
} }
} }
/// this vibrates until the device sleeps /// this vibrates until the device sleeps
#[allow(dead_code)] #[allow(dead_code)]
pub fn tts_sleep_indicate(&mut self) { pub fn tts_sleep_indicate(&mut self) { self.power_csr.wfo(utra::power::VIBE_VIBE, 1); }
self.power_csr.wfo(utra::power::VIBE_VIBE, 1);
} pub fn xadc_vbus(&self) -> u16 { self.xadc_csr.rf(utra::trng::XADC_VBUS_XADC_VBUS) as u16 }
pub fn xadc_vbus(&self) -> u16 {
self.xadc_csr.rf(utra::trng::XADC_VBUS_XADC_VBUS) as u16 pub fn xadc_vccint(&self) -> u16 { self.xadc_csr.rf(utra::trng::XADC_VCCINT_XADC_VCCINT) as u16 }
}
pub fn xadc_vccint(&self) -> u16 { pub fn xadc_vccaux(&self) -> u16 { self.xadc_csr.rf(utra::trng::XADC_VCCAUX_XADC_VCCAUX) as u16 }
self.xadc_csr.rf(utra::trng::XADC_VCCINT_XADC_VCCINT) as u16
} pub fn xadc_vccbram(&self) -> u16 { self.xadc_csr.rf(utra::trng::XADC_VCCBRAM_XADC_VCCBRAM) as u16 }
pub fn xadc_vccaux(&self) -> u16 {
self.xadc_csr.rf(utra::trng::XADC_VCCAUX_XADC_VCCAUX) as u16 pub fn xadc_usbn(&self) -> u16 { self.xadc_csr.rf(utra::trng::XADC_USB_N_XADC_USB_N) as u16 }
}
pub fn xadc_vccbram(&self) -> u16 { pub fn xadc_usbp(&self) -> u16 { self.xadc_csr.rf(utra::trng::XADC_USB_P_XADC_USB_P) as u16 }
self.xadc_csr.rf(utra::trng::XADC_VCCBRAM_XADC_VCCBRAM) as u16
}
pub fn xadc_usbn(&self) -> u16 {
self.xadc_csr.rf(utra::trng::XADC_USB_N_XADC_USB_N) as u16
}
pub fn xadc_usbp(&self) -> u16 {
self.xadc_csr.rf(utra::trng::XADC_USB_P_XADC_USB_P) as u16
}
pub fn xadc_temperature(&self) -> u16 { pub fn xadc_temperature(&self) -> u16 {
self.xadc_csr.rf(utra::trng::XADC_TEMPERATURE_XADC_TEMPERATURE) as u16 self.xadc_csr.rf(utra::trng::XADC_TEMPERATURE_XADC_TEMPERATURE) as u16
} }
pub fn xadc_gpio5(&self) -> u16 {
self.xadc_csr.rf(utra::trng::XADC_GPIO5_XADC_GPIO5) as u16 pub fn xadc_gpio5(&self) -> u16 { self.xadc_csr.rf(utra::trng::XADC_GPIO5_XADC_GPIO5) as u16 }
}
pub fn xadc_gpio2(&self) -> u16 { pub fn xadc_gpio2(&self) -> u16 { self.xadc_csr.rf(utra::trng::XADC_GPIO2_XADC_GPIO2) as u16 }
self.xadc_csr.rf(utra::trng::XADC_GPIO2_XADC_GPIO2) as u16
}
pub fn com_int_ena(&mut self, ena: bool) { pub fn com_int_ena(&mut self, ena: bool) {
let value = if ena {1} else {0}; let value = if ena { 1 } else { 0 };
self.event_csr.rmwf(utra::btevents::EV_ENABLE_COM_INT, value); self.event_csr.rmwf(utra::btevents::EV_ENABLE_COM_INT, value);
} }
pub fn usb_int_ena(&mut self, ena: bool) { pub fn usb_int_ena(&mut self, ena: bool) {
let value = if ena {1} else {0}; let value = if ena { 1 } else { 0 };
self.power_csr.rmwf(utra::power::EV_ENABLE_USB_ATTACH, value); self.power_csr.rmwf(utra::power::EV_ENABLE_USB_ATTACH, value);
} }
} }

View file

@ -1,11 +1,12 @@
use xous::{send_message, CID, Message, msg_scalar_unpack}; use core::sync::atomic::AtomicU32;
use xous_ipc::Buffer;
use num_traits::{ToPrimitive, FromPrimitive};
use core::sync::atomic::Ordering; use core::sync::atomic::Ordering;
use crate::api::*;
use num_traits::{FromPrimitive, ToPrimitive};
use xous::{msg_scalar_unpack, send_message, Message, CID};
use xous_ipc::Buffer;
use xous_semver::SemVer; use xous_semver::SemVer;
use core::sync::atomic::AtomicU32; use crate::api::*;
static REFCOUNT: AtomicU32 = AtomicU32::new(0); static REFCOUNT: AtomicU32 = AtomicU32::new(0);
#[derive(Debug)] #[derive(Debug)]
pub struct Llio { pub struct Llio {
@ -18,32 +19,27 @@ impl Llio {
pub fn new(xns: &xous_names::XousNames) -> Self { pub fn new(xns: &xous_names::XousNames) -> Self {
REFCOUNT.fetch_add(1, Ordering::Relaxed); REFCOUNT.fetch_add(1, Ordering::Relaxed);
let conn = xns.request_connection_blocking(SERVER_NAME_LLIO).expect("Can't connect to LLIO"); let conn = xns.request_connection_blocking(SERVER_NAME_LLIO).expect("Can't connect to LLIO");
Llio { Llio { conn, com_sid: None, usb_sid: None, gpio_sid: None }
conn,
com_sid: None,
usb_sid: None,
gpio_sid: None,
}
}
pub fn vibe(&self, pattern: VibePattern) -> Result<(), xous::Error> {
send_message(self.conn,
Message::new_scalar(Opcode::Vibe.to_usize().unwrap(), pattern.into(), 0, 0, 0)
).map(|_|())
} }
pub fn vibe(&self, pattern: VibePattern) -> Result<(), xous::Error> {
send_message(
self.conn,
Message::new_scalar(Opcode::Vibe.to_usize().unwrap(), pattern.into(), 0, 0, 0),
)
.map(|_| ())
}
pub fn allow_power_off(&self, allow: bool) -> Result<(), xous::Error> { pub fn allow_power_off(&self, allow: bool) -> Result<(), xous::Error> {
let arg = if allow { 0 } else { 1 }; let arg = if allow { 0 } else { 1 };
send_message(self.conn, send_message(self.conn, Message::new_scalar(Opcode::PowerSelf.to_usize().unwrap(), arg, 0, 0, 0))
Message::new_scalar(Opcode::PowerSelf.to_usize().unwrap(), arg, 0, 0, 0) .map(|_| ())
).map(|_| ())
} }
pub fn allow_ec_snoop(&self, allow: bool) -> Result<(), xous::Error> { pub fn allow_ec_snoop(&self, allow: bool) -> Result<(), xous::Error> {
let arg = if allow { 1 } else { 0 }; let arg = if allow { 1 } else { 0 };
send_message(self.conn, send_message(self.conn, Message::new_scalar(Opcode::EcSnoopAllow.to_usize().unwrap(), arg, 0, 0, 0))
Message::new_scalar(Opcode::EcSnoopAllow.to_usize().unwrap(), arg, 0, 0, 0) .map(|_| ())
).map(|_| ())
} }
pub fn is_plugged_in(&self) -> bool { pub fn is_plugged_in(&self) -> bool {
@ -52,8 +48,10 @@ impl Llio {
} }
pub fn adc_vbus(&self) -> Result<u16, xous::Error> { pub fn adc_vbus(&self) -> Result<u16, xous::Error> {
let response = send_message(self.conn, let response = send_message(
Message::new_blocking_scalar(Opcode::AdcVbus.to_usize().unwrap(), 0, 0, 0, 0))?; self.conn,
Message::new_blocking_scalar(Opcode::AdcVbus.to_usize().unwrap(), 0, 0, 0, 0),
)?;
if let xous::Result::Scalar1(val) = response { if let xous::Result::Scalar1(val) = response {
Ok(val as u16) Ok(val as u16)
} else { } else {
@ -61,9 +59,12 @@ impl Llio {
Err(xous::Error::InternalError) Err(xous::Error::InternalError)
} }
} }
pub fn adc_vccint(&self) -> Result<u16, xous::Error> { pub fn adc_vccint(&self) -> Result<u16, xous::Error> {
let response = send_message(self.conn, let response = send_message(
Message::new_blocking_scalar(Opcode::AdcVccInt.to_usize().unwrap(), 0, 0, 0, 0))?; self.conn,
Message::new_blocking_scalar(Opcode::AdcVccInt.to_usize().unwrap(), 0, 0, 0, 0),
)?;
if let xous::Result::Scalar1(val) = response { if let xous::Result::Scalar1(val) = response {
Ok(val as u16) Ok(val as u16)
} else { } else {
@ -71,9 +72,12 @@ impl Llio {
Err(xous::Error::InternalError) Err(xous::Error::InternalError)
} }
} }
pub fn adc_vccaux(&self) -> Result<u16, xous::Error> { pub fn adc_vccaux(&self) -> Result<u16, xous::Error> {
let response = send_message(self.conn, let response = send_message(
Message::new_blocking_scalar(Opcode::AdcVccAux.to_usize().unwrap(), 0, 0, 0, 0))?; self.conn,
Message::new_blocking_scalar(Opcode::AdcVccAux.to_usize().unwrap(), 0, 0, 0, 0),
)?;
if let xous::Result::Scalar1(val) = response { if let xous::Result::Scalar1(val) = response {
Ok(val as u16) Ok(val as u16)
} else { } else {
@ -81,9 +85,12 @@ impl Llio {
Err(xous::Error::InternalError) Err(xous::Error::InternalError)
} }
} }
pub fn adc_vccbram(&self) -> Result<u16, xous::Error> { pub fn adc_vccbram(&self) -> Result<u16, xous::Error> {
let response = send_message(self.conn, let response = send_message(
Message::new_blocking_scalar(Opcode::AdcVccBram.to_usize().unwrap(), 0, 0, 0, 0))?; self.conn,
Message::new_blocking_scalar(Opcode::AdcVccBram.to_usize().unwrap(), 0, 0, 0, 0),
)?;
if let xous::Result::Scalar1(val) = response { if let xous::Result::Scalar1(val) = response {
Ok(val as u16) Ok(val as u16)
} else { } else {
@ -91,9 +98,12 @@ impl Llio {
Err(xous::Error::InternalError) Err(xous::Error::InternalError)
} }
} }
pub fn adc_usb_n(&self) -> Result<u16, xous::Error> { pub fn adc_usb_n(&self) -> Result<u16, xous::Error> {
let response = send_message(self.conn, let response = send_message(
Message::new_blocking_scalar(Opcode::AdcUsbN.to_usize().unwrap(), 0, 0, 0, 0))?; self.conn,
Message::new_blocking_scalar(Opcode::AdcUsbN.to_usize().unwrap(), 0, 0, 0, 0),
)?;
if let xous::Result::Scalar1(val) = response { if let xous::Result::Scalar1(val) = response {
Ok(val as u16) Ok(val as u16)
} else { } else {
@ -101,9 +111,12 @@ impl Llio {
Err(xous::Error::InternalError) Err(xous::Error::InternalError)
} }
} }
pub fn adc_usb_p(&self) -> Result<u16, xous::Error> { pub fn adc_usb_p(&self) -> Result<u16, xous::Error> {
let response = send_message(self.conn, let response = send_message(
Message::new_blocking_scalar(Opcode::AdcUsbP.to_usize().unwrap(), 0, 0, 0, 0))?; self.conn,
Message::new_blocking_scalar(Opcode::AdcUsbP.to_usize().unwrap(), 0, 0, 0, 0),
)?;
if let xous::Result::Scalar1(val) = response { if let xous::Result::Scalar1(val) = response {
Ok(val as u16) Ok(val as u16)
} else { } else {
@ -111,9 +124,12 @@ impl Llio {
Err(xous::Error::InternalError) Err(xous::Error::InternalError)
} }
} }
pub fn adc_temperature(&self) -> Result<u16, xous::Error> { pub fn adc_temperature(&self) -> Result<u16, xous::Error> {
let response = send_message(self.conn, let response = send_message(
Message::new_blocking_scalar(Opcode::AdcTemperature.to_usize().unwrap(), 0, 0, 0, 0))?; self.conn,
Message::new_blocking_scalar(Opcode::AdcTemperature.to_usize().unwrap(), 0, 0, 0, 0),
)?;
if let xous::Result::Scalar1(val) = response { if let xous::Result::Scalar1(val) = response {
Ok(val as u16) Ok(val as u16)
} else { } else {
@ -121,9 +137,12 @@ impl Llio {
Err(xous::Error::InternalError) Err(xous::Error::InternalError)
} }
} }
pub fn adc_gpio5(&self) -> Result<u16, xous::Error> { pub fn adc_gpio5(&self) -> Result<u16, xous::Error> {
let response = send_message(self.conn, let response = send_message(
Message::new_blocking_scalar(Opcode::AdcGpio5.to_usize().unwrap(), 0, 0, 0, 0))?; self.conn,
Message::new_blocking_scalar(Opcode::AdcGpio5.to_usize().unwrap(), 0, 0, 0, 0),
)?;
if let xous::Result::Scalar1(val) = response { if let xous::Result::Scalar1(val) = response {
Ok(val as u16) Ok(val as u16)
} else { } else {
@ -131,9 +150,12 @@ impl Llio {
Err(xous::Error::InternalError) Err(xous::Error::InternalError)
} }
} }
pub fn adc_gpio2(&self) -> Result<u16, xous::Error> { pub fn adc_gpio2(&self) -> Result<u16, xous::Error> {
let response = send_message(self.conn, let response = send_message(
Message::new_blocking_scalar(Opcode::AdcGpio2.to_usize().unwrap(), 0, 0, 0, 0))?; self.conn,
Message::new_blocking_scalar(Opcode::AdcGpio2.to_usize().unwrap(), 0, 0, 0, 0),
)?;
if let xous::Result::Scalar1(val) = response { if let xous::Result::Scalar1(val) = response {
Ok(val as u16) Ok(val as u16)
} else { } else {
@ -141,29 +163,36 @@ impl Llio {
Err(xous::Error::InternalError) Err(xous::Error::InternalError)
} }
} }
// USB hooks // USB hooks
pub fn hook_usb_callback(&mut self, id: u32, cid: CID) -> Result<(), xous::Error> { pub fn hook_usb_callback(&mut self, id: u32, cid: CID) -> Result<(), xous::Error> {
if self.usb_sid.is_none() { if self.usb_sid.is_none() {
let sid = xous::create_server().unwrap(); let sid = xous::create_server().unwrap();
self.usb_sid = Some(sid); self.usb_sid = Some(sid);
let sid_tuple = sid.to_u32(); let sid_tuple = sid.to_u32();
xous::create_thread_4(usb_cb_server, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap(); xous::create_thread_4(
let hookdata = ScalarHook { usb_cb_server,
sid: sid_tuple, sid_tuple.0 as usize,
id, sid_tuple.1 as usize,
cid, sid_tuple.2 as usize,
}; sid_tuple.3 as usize,
)
.unwrap();
let hookdata = ScalarHook { sid: sid_tuple, id, cid };
let buf = Buffer::into_buf(hookdata).or(Err(xous::Error::InternalError))?; let buf = Buffer::into_buf(hookdata).or(Err(xous::Error::InternalError))?;
buf.lend(self.conn, Opcode::EventUsbAttachSubscribe.to_u32().unwrap()).map(|_|()) buf.lend(self.conn, Opcode::EventUsbAttachSubscribe.to_u32().unwrap()).map(|_| ())
} else { } else {
Err(xous::Error::MemoryInUse) // can't hook it twice Err(xous::Error::MemoryInUse) // can't hook it twice
} }
} }
pub fn usb_event_enable(&self, ena: bool) -> Result<(), xous::Error> { pub fn usb_event_enable(&self, ena: bool) -> Result<(), xous::Error> {
let arg = if ena { 1 } else { 0 }; let arg = if ena { 1 } else { 0 };
send_message(self.conn, send_message(
Message::new_scalar(Opcode::EventUsbAttachEnable.to_usize().unwrap(), arg, 0, 0, 0) self.conn,
).map(|_| ()) Message::new_scalar(Opcode::EventUsbAttachEnable.to_usize().unwrap(), arg, 0, 0, 0),
)
.map(|_| ())
} }
// COM IRQ hooks // COM IRQ hooks
@ -172,37 +201,53 @@ impl Llio {
let sid = xous::create_server().unwrap(); let sid = xous::create_server().unwrap();
self.com_sid = Some(sid); self.com_sid = Some(sid);
let sid_tuple = sid.to_u32(); let sid_tuple = sid.to_u32();
xous::create_thread_4(com_cb_server, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap(); xous::create_thread_4(
let hookdata = ScalarHook { com_cb_server,
sid: sid_tuple, sid_tuple.0 as usize,
id, sid_tuple.1 as usize,
cid, sid_tuple.2 as usize,
}; sid_tuple.3 as usize,
)
.unwrap();
let hookdata = ScalarHook { sid: sid_tuple, id, cid };
let buf = Buffer::into_buf(hookdata).or(Err(xous::Error::InternalError))?; let buf = Buffer::into_buf(hookdata).or(Err(xous::Error::InternalError))?;
buf.lend(self.conn, Opcode::EventComSubscribe.to_u32().unwrap()).map(|_|()) buf.lend(self.conn, Opcode::EventComSubscribe.to_u32().unwrap()).map(|_| ())
} else { } else {
Err(xous::Error::MemoryInUse) // can't hook it twice Err(xous::Error::MemoryInUse) // can't hook it twice
} }
} }
pub fn com_event_enable(&self, ena: bool) -> Result<(), xous::Error> { pub fn com_event_enable(&self, ena: bool) -> Result<(), xous::Error> {
let arg = if ena { 1 } else { 0 }; let arg = if ena { 1 } else { 0 };
send_message(self.conn, send_message(self.conn, Message::new_scalar(Opcode::EventComEnable.to_usize().unwrap(), arg, 0, 0, 0))
Message::new_scalar(Opcode::EventComEnable.to_usize().unwrap(), arg, 0, 0, 0) .map(|_| ())
).map(|_| ())
} }
/// Called by the updater routine when EC is ready to run. Note: no authenticity check is done, anyone /// Called by the updater routine when EC is ready to run. Note: no authenticity check is done, anyone
/// could call this and troll the system. /// could call this and troll the system.
pub fn set_ec_ready(&self, ready: bool) { pub fn set_ec_ready(&self, ready: bool) {
send_message(self.conn, send_message(
Message::new_scalar(Opcode::EventEcSetReady.to_usize().unwrap(), if ready {1} else {0}, 0, 0, 0) self.conn,
).unwrap(); Message::new_scalar(
Opcode::EventEcSetReady.to_usize().unwrap(),
if ready { 1 } else { 0 },
0,
0,
0,
),
)
.unwrap();
} }
/// Used to poll if the EC has been set as ready by the updating routine. Domiciled in the LLIO because /// Used to poll if the EC has been set as ready by the updating routine. Domiciled in the LLIO because
/// this crate is already depended upon by most crates that need to poll this status, and we'd rather not /// this crate is already depended upon by most crates that need to poll this status, and we'd rather not
/// expose the COM directly to generic crates. /// expose the COM directly to generic crates.
pub fn is_ec_ready(&self) -> bool { pub fn is_ec_ready(&self) -> bool {
let response = send_message(self.conn, let response = send_message(
Message::new_blocking_scalar(Opcode::EventEcIsReady.to_usize().unwrap(), 0, 0, 0, 0)).unwrap(); self.conn,
Message::new_blocking_scalar(Opcode::EventEcIsReady.to_usize().unwrap(), 0, 0, 0, 0),
)
.unwrap();
if let xous::Result::Scalar1(val) = response { if let xous::Result::Scalar1(val) = response {
val != 0 val != 0
} else { } else {
@ -210,166 +255,210 @@ impl Llio {
false false
} }
} }
/// GPIO IRQ hook. When using this, ensure that the WFI power saving mode is turned off. /// GPIO IRQ hook. When using this, ensure that the WFI power saving mode is turned off.
/// Otherwise interrupts that hit during power save mode can be missed. /// Otherwise interrupts that hit during power save mode can be missed.
pub fn hook_gpio_event_callback(&mut self, id: u32, cid: CID) -> Result<(), xous::Error> { pub fn hook_gpio_event_callback(&mut self, id: u32, cid: CID) -> Result<(), xous::Error> {
log::info!("If relying on GPIO interrupts, WFI power saving must be turned off. Interrupts that hit while powersaving can be missed."); log::info!(
"If relying on GPIO interrupts, WFI power saving must be turned off. Interrupts that hit while powersaving can be missed."
);
if self.gpio_sid.is_none() { if self.gpio_sid.is_none() {
let sid = xous::create_server().unwrap(); let sid = xous::create_server().unwrap();
self.gpio_sid = Some(sid); self.gpio_sid = Some(sid);
let sid_tuple = sid.to_u32(); let sid_tuple = sid.to_u32();
xous::create_thread_4(gpio_cb_server, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap(); xous::create_thread_4(
let hookdata = ScalarHook { gpio_cb_server,
sid: sid_tuple, sid_tuple.0 as usize,
id, sid_tuple.1 as usize,
cid, sid_tuple.2 as usize,
}; sid_tuple.3 as usize,
)
.unwrap();
let hookdata = ScalarHook { sid: sid_tuple, id, cid };
let buf = Buffer::into_buf(hookdata).or(Err(xous::Error::InternalError))?; let buf = Buffer::into_buf(hookdata).or(Err(xous::Error::InternalError))?;
buf.lend(self.conn, Opcode::GpioIntSubscribe.to_u32().unwrap()).map(|_|()) buf.lend(self.conn, Opcode::GpioIntSubscribe.to_u32().unwrap()).map(|_| ())
} else { } else {
Err(xous::Error::MemoryInUse) // can't hook it twice Err(xous::Error::MemoryInUse) // can't hook it twice
} }
} }
pub fn ec_reset(&self) -> Result<(), xous::Error> { pub fn ec_reset(&self) -> Result<(), xous::Error> {
send_message(self.conn, send_message(self.conn, Message::new_scalar(Opcode::EcReset.to_usize().unwrap(), 0, 0, 0, 0))
Message::new_scalar(Opcode::EcReset.to_usize().unwrap(), 0, 0, 0, 0) .map(|_| ())
).map(|_| ())
} }
pub fn self_destruct(&self, code: usize) -> Result<(), xous::Error> { pub fn self_destruct(&self, code: usize) -> Result<(), xous::Error> {
// it's up to the caller to know the code sequence, which is: // it's up to the caller to know the code sequence, which is:
// 0x2718_2818 // 0x2718_2818
// followed by // followed by
// 0x3141_5926 // 0x3141_5926
send_message(self.conn, send_message(self.conn, Message::new_scalar(Opcode::SelfDestruct.to_usize().unwrap(), code, 0, 0, 0))
Message::new_scalar(Opcode::SelfDestruct.to_usize().unwrap(), code, 0, 0, 0) .map(|_| ())
).map(|_| ())
} }
pub fn boost_on(&self, ena: bool) -> Result<(), xous::Error> { pub fn boost_on(&self, ena: bool) -> Result<(), xous::Error> {
let arg = if ena { 1 } else { 0 }; let arg = if ena { 1 } else { 0 };
send_message(self.conn, send_message(self.conn, Message::new_scalar(Opcode::PowerBoostMode.to_usize().unwrap(), arg, 0, 0, 0))
Message::new_scalar(Opcode::PowerBoostMode.to_usize().unwrap(), arg, 0, 0, 0) .map(|_| ())
).map(|_| ())
} }
pub fn audio_on(&self, ena: bool) -> Result<(), xous::Error> { pub fn audio_on(&self, ena: bool) -> Result<(), xous::Error> {
let arg = if ena { 1 } else { 0 }; let arg = if ena { 1 } else { 0 };
send_message(self.conn, send_message(
Message::new_blocking_scalar(Opcode::PowerAudio.to_usize().unwrap(), arg, 0, 0, 0) self.conn,
).map(|_| ()) Message::new_blocking_scalar(Opcode::PowerAudio.to_usize().unwrap(), arg, 0, 0, 0),
)
.map(|_| ())
} }
// -149mA @ 4152mV crypto on // -143mA @ 4149mV crypto off // -149mA @ 4152mV crypto on // -143mA @ 4149mV crypto off
pub fn crypto_on(&self, ena: bool) -> Result<(), xous::Error> { pub fn crypto_on(&self, ena: bool) -> Result<(), xous::Error> {
let arg = if ena { 1 } else { 0 }; let arg = if ena { 1 } else { 0 };
send_message(self.conn, send_message(
Message::new_blocking_scalar(Opcode::PowerCrypto.to_usize().unwrap(), arg, 0, 0, 0) self.conn,
).map(|_| ()) Message::new_blocking_scalar(Opcode::PowerCrypto.to_usize().unwrap(), arg, 0, 0, 0),
)
.map(|_| ())
} }
/// setting this to true turns off WFI capabilities, forcing power always on /// setting this to true turns off WFI capabilities, forcing power always on
pub fn wfi_override(&self, ena: bool) -> Result<(), xous::Error> { pub fn wfi_override(&self, ena: bool) -> Result<(), xous::Error> {
let arg = if ena { 1 } else { 0 }; let arg = if ena { 1 } else { 0 };
send_message(self.conn, send_message(
Message::new_blocking_scalar(Opcode::WfiOverride.to_usize().unwrap(), arg, 0, 0, 0) self.conn,
).map(|_| ()) Message::new_blocking_scalar(Opcode::WfiOverride.to_usize().unwrap(), arg, 0, 0, 0),
)
.map(|_| ())
} }
pub fn crypto_power_status(&self) -> Result<(bool, bool, bool), xous::Error> { // sha, engine, override status
let response = send_message(self.conn, pub fn crypto_power_status(&self) -> Result<(bool, bool, bool), xous::Error> {
Message::new_blocking_scalar(Opcode::PowerCryptoStatus.to_usize().unwrap(), 0, 0, 0, 0) // sha, engine, override status
let response = send_message(
self.conn,
Message::new_blocking_scalar(Opcode::PowerCryptoStatus.to_usize().unwrap(), 0, 0, 0, 0),
)?; )?;
if let xous::Result::Scalar1(val) = response { if let xous::Result::Scalar1(val) = response {
let sha = if (val & 1) == 0 { false } else { true }; let sha = if (val & 1) == 0 { false } else { true };
let engine = if (val & 2) == 0 { false } else { true }; let engine = if (val & 2) == 0 { false } else { true };
let force = if (val & 4) == 0 { false } else { true }; let force = if (val & 4) == 0 { false } else { true };
Ok((sha, engine, force)) Ok((sha, engine, force))
} else { } else {
Err(xous::Error::InternalError) Err(xous::Error::InternalError)
} }
} }
pub fn soc_gitrev(&self) -> Result<SemVer, xous::Error> { pub fn soc_gitrev(&self) -> Result<SemVer, xous::Error> {
let response = send_message(self.conn, let response = send_message(
Message::new_blocking_scalar(Opcode::InfoGit.to_usize().unwrap(), 0, 0, 0, 0))?; self.conn,
Message::new_blocking_scalar(Opcode::InfoGit.to_usize().unwrap(), 0, 0, 0, 0),
)?;
if let xous::Result::Scalar2(val1, val2) = response { if let xous::Result::Scalar2(val1, val2) = response {
Ok( Ok(SemVer {
SemVer { maj: ((val1 >> 24) & 0xff) as u16,
maj: ((val1 >> 24) & 0xff) as u16, min: ((val1 >> 16) & 0xff) as u16,
min: ((val1 >> 16) & 0xff) as u16, rev: ((val1 >> 8) & 0xff) as u16,
rev: ((val1 >> 8) & 0xff) as u16, extra: ((val1 >> 0) & 0xff) as u16,
extra: ((val1 >> 0) & 0xff) as u16, commit: Some(val2 as u32),
commit: Some(val2 as u32), })
}
)
} else { } else {
log::error!("LLIO: unexpected return value: {:#?}", response); log::error!("LLIO: unexpected return value: {:#?}", response);
Err(xous::Error::InternalError) Err(xous::Error::InternalError)
} }
} }
pub fn soc_dna(&self) -> Result<u64, xous::Error> { pub fn soc_dna(&self) -> Result<u64, xous::Error> {
let response = send_message(self.conn, let response = send_message(
Message::new_blocking_scalar(Opcode::InfoDna.to_usize().unwrap(), 0, 0, 0, 0))?; self.conn,
Message::new_blocking_scalar(Opcode::InfoDna.to_usize().unwrap(), 0, 0, 0, 0),
)?;
if let xous::Result::Scalar2(val1, val2) = response { if let xous::Result::Scalar2(val1, val2) = response {
Ok( Ok((val1 as u64) | ((val2 as u64) << 32))
(val1 as u64) | ((val2 as u64) << 32)
)
} else { } else {
log::error!("LLIO: unexpected return value: {:#?}", response); log::error!("LLIO: unexpected return value: {:#?}", response);
Err(xous::Error::InternalError) Err(xous::Error::InternalError)
} }
} }
pub fn gpio_data_direction(&self, dir: u8) -> Result<(), xous::Error> { pub fn gpio_data_direction(&self, dir: u8) -> Result<(), xous::Error> {
send_message(self.conn, send_message(
Message::new_scalar(Opcode::GpioDataDrive.to_usize().unwrap(), dir as usize, 0, 0, 0) self.conn,
).map(|_| ()) Message::new_scalar(Opcode::GpioDataDrive.to_usize().unwrap(), dir as usize, 0, 0, 0),
)
.map(|_| ())
} }
pub fn gpio_debug_powerdown(&self, ena: bool) -> Result<(), xous::Error> { pub fn gpio_debug_powerdown(&self, ena: bool) -> Result<(), xous::Error> {
let arg = if ena { 1 } else { 0 }; let arg = if ena { 1 } else { 0 };
send_message(self.conn, send_message(self.conn, Message::new_scalar(Opcode::DebugPowerdown.to_usize().unwrap(), arg, 0, 0, 0))
Message::new_scalar(Opcode::DebugPowerdown.to_usize().unwrap(), arg, 0, 0, 0) .map(|_| ())
).map(|_| ())
} }
pub fn gpio_debug_wakeup(&self, ena: bool) -> Result<(), xous::Error> { pub fn gpio_debug_wakeup(&self, ena: bool) -> Result<(), xous::Error> {
let arg = if ena { 1 } else { 0 }; let arg = if ena { 1 } else { 0 };
send_message(self.conn, send_message(self.conn, Message::new_scalar(Opcode::DebugWakeup.to_usize().unwrap(), arg, 0, 0, 0))
Message::new_scalar(Opcode::DebugWakeup.to_usize().unwrap(), arg, 0, 0, 0) .map(|_| ())
).map(|_| ())
} }
pub fn activity_instantaneous(&self) -> Result<(u32, u32), xous::Error> { pub fn activity_instantaneous(&self) -> Result<(u32, u32), xous::Error> {
let response = send_message(self.conn, let response = send_message(
Message::new_blocking_scalar(Opcode::GetActivity.to_usize().unwrap(), 0, 0, 0, 0))?; self.conn,
Message::new_blocking_scalar(Opcode::GetActivity.to_usize().unwrap(), 0, 0, 0, 0),
)?;
if let xous::Result::Scalar2(active, total) = response { if let xous::Result::Scalar2(active, total) = response {
Ok( Ok((active as u32, total as u32))
(active as u32, total as u32)
)
} else { } else {
log::error!("LLIO: unexpected return value: {:#?}", response); log::error!("LLIO: unexpected return value: {:#?}", response);
Err(xous::Error::InternalError) Err(xous::Error::InternalError)
} }
} }
pub fn set_uart_mux(&self, setting: UartType) -> Result<(), xous::Error> { pub fn set_uart_mux(&self, setting: UartType) -> Result<(), xous::Error> {
if setting == UartType::Application { if setting == UartType::Application {
log::warn!("Application UART has aggressive power settings, so you will have trouble using it for console input."); log::warn!(
log::warn!("If this UART is critictal, recompile the SoC with the app UART in the always-on power domain."); "Application UART has aggressive power settings, so you will have trouble using it for console input."
log::warn!("It will consume more power but it will make this UART suitable for input via serial."); );
log::warn!(
"If this UART is critictal, recompile the SoC with the app UART in the always-on power domain."
);
log::warn!(
"It will consume more power but it will make this UART suitable for input via serial."
);
} }
let arg = setting.into(); let arg = setting.into();
send_message(self.conn, send_message(self.conn, Message::new_scalar(Opcode::UartMux.to_usize().unwrap(), arg, 0, 0, 0))
Message::new_scalar(Opcode::UartMux.to_usize().unwrap(), arg, 0, 0, 0) .map(|_| ())
).map(|_| ())
} }
/// wakeup alarm will force the system on if it is off, but does not trigger an interrupt on the CPU /// wakeup alarm will force the system on if it is off, but does not trigger an interrupt on the CPU
pub fn set_wakeup_alarm(&self, seconds_from_now: u8) -> Result<(), xous::Error> { pub fn set_wakeup_alarm(&self, seconds_from_now: u8) -> Result<(), xous::Error> {
send_message(self.conn, send_message(
Message::new_blocking_scalar(Opcode::SetWakeupAlarm.to_usize().unwrap(), seconds_from_now as _, 0, 0, 0) self.conn,
).map(|_|()) Message::new_blocking_scalar(
Opcode::SetWakeupAlarm.to_usize().unwrap(),
seconds_from_now as _,
0,
0,
0,
),
)
.map(|_| ())
} }
pub fn clear_wakeup_alarm(&self) -> Result<(), xous::Error> { pub fn clear_wakeup_alarm(&self) -> Result<(), xous::Error> {
send_message(self.conn, send_message(
Message::new_blocking_scalar(Opcode::ClearWakeupAlarm.to_usize().unwrap(), 0, 0, 0, 0) self.conn,
).map(|_|()) Message::new_blocking_scalar(Opcode::ClearWakeupAlarm.to_usize().unwrap(), 0, 0, 0, 0),
)
.map(|_| ())
} }
/// This returns the elapsed seconds on the RTC since an arbitrary start point in the past. /// This returns the elapsed seconds on the RTC since an arbitrary start point in the past.
/// The translation of this is handled by `libstd::SystemTime`; you may use this call, but /// The translation of this is handled by `libstd::SystemTime`; you may use this call, but
/// the interpretation is not terribly meaningful on its own. /// the interpretation is not terribly meaningful on its own.
pub fn get_rtc_secs(&self) -> Result<u64, xous::Error> { pub fn get_rtc_secs(&self) -> Result<u64, xous::Error> {
match send_message(self.conn, match send_message(
Message::new_blocking_scalar(Opcode::GetRtcValue.to_usize().unwrap(), 0, 0, 0, 0) self.conn,
Message::new_blocking_scalar(Opcode::GetRtcValue.to_usize().unwrap(), 0, 0, 0, 0),
)? { )? {
xous::Result::Scalar2(hi, lo) => { xous::Result::Scalar2(hi, lo) => {
if hi & 0x8000_0000 != 0 { if hi & 0x8000_0000 != 0 {
@ -378,19 +467,18 @@ impl Llio {
Ok(((hi as u64) << 32) | lo as u64) Ok(((hi as u64) << 32) | lo as u64)
} }
} }
_ => { _ => Err(xous::Error::InternalError),
Err(xous::Error::InternalError)
}
} }
} }
} }
fn drop_conn(sid: xous::SID) { fn drop_conn(sid: xous::SID) {
let cid = xous::connect(sid).unwrap(); let cid = xous::connect(sid).unwrap();
xous::send_message(cid, xous::send_message(cid, Message::new_scalar(EventCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0))
Message::new_scalar(EventCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0)).unwrap(); .unwrap();
unsafe{xous::disconnect(cid).unwrap();} unsafe {
xous::disconnect(cid).unwrap();
}
} }
impl Drop for Llio { impl Drop for Llio {
fn drop(&mut self) { fn drop(&mut self) {
@ -404,12 +492,13 @@ impl Drop for Llio {
drop_conn(sid); drop_conn(sid);
} }
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
unsafe{xous::disconnect(self.conn).unwrap();} unsafe {
xous::disconnect(self.conn).unwrap();
}
} }
} }
} }
/// handles callback messages that indicate a USB interrupt has happened, in the library user's process space. /// handles callback messages that indicate a USB interrupt has happened, in the library user's process space.
fn usb_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) { fn usb_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); let sid = xous::SID::from_u32(sid0 as u32, sid1 as u32, sid2 as u32, sid3 as u32);
@ -418,9 +507,7 @@ fn usb_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
match FromPrimitive::from_usize(msg.body.id()) { match FromPrimitive::from_usize(msg.body.id()) {
Some(EventCallback::Event) => msg_scalar_unpack!(msg, cid, id, _, _, { Some(EventCallback::Event) => msg_scalar_unpack!(msg, cid, id, _, _, {
// directly pass the scalar message onto the CID with the ID memorized in the original hook // directly pass the scalar message onto the CID with the ID memorized in the original hook
send_message(cid as u32, send_message(cid as u32, Message::new_scalar(id, 0, 0, 0, 0)).unwrap();
Message::new_scalar(id, 0, 0, 0, 0)
).unwrap();
}), }),
Some(EventCallback::Drop) => { Some(EventCallback::Drop) => {
break; // this exits the loop and kills the thread break; // this exits the loop and kills the thread
@ -439,9 +526,7 @@ fn com_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
match FromPrimitive::from_usize(msg.body.id()) { match FromPrimitive::from_usize(msg.body.id()) {
Some(EventCallback::Event) => msg_scalar_unpack!(msg, cid, id, _, _, { Some(EventCallback::Event) => msg_scalar_unpack!(msg, cid, id, _, _, {
// directly pass the scalar message onto the CID with the ID memorized in the original hook // directly pass the scalar message onto the CID with the ID memorized in the original hook
send_message(cid as u32, send_message(cid as u32, Message::new_scalar(id, 0, 0, 0, 0)).unwrap();
Message::new_scalar(id, 0, 0, 0, 0)
).unwrap();
}), }),
Some(EventCallback::Drop) => { Some(EventCallback::Drop) => {
break; // this exits the loop and kills the thread break; // this exits the loop and kills the thread
@ -452,7 +537,8 @@ fn com_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
xous::destroy_server(sid).unwrap(); xous::destroy_server(sid).unwrap();
} }
/// handles callback messages that indicate a GPIO interrupt has happened, in the library user's process space. /// handles callback messages that indicate a GPIO interrupt has happened, in the library user's process
/// space.
fn gpio_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) { fn gpio_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); let sid = xous::SID::from_u32(sid0 as u32, sid1 as u32, sid2 as u32, sid3 as u32);
loop { loop {
@ -460,9 +546,7 @@ fn gpio_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
match FromPrimitive::from_usize(msg.body.id()) { match FromPrimitive::from_usize(msg.body.id()) {
Some(EventCallback::Event) => msg_scalar_unpack!(msg, cid, id, _, _, { Some(EventCallback::Event) => msg_scalar_unpack!(msg, cid, id, _, _, {
// directly pass the scalar message onto the CID with the ID memorized in the original hook // directly pass the scalar message onto the CID with the ID memorized in the original hook
send_message(cid as u32, send_message(cid as u32, Message::new_scalar(id, 0, 0, 0, 0)).unwrap();
Message::new_scalar(id, 0, 0, 0, 0)
).unwrap();
}), }),
Some(EventCallback::Drop) => { Some(EventCallback::Drop) => {
break; // this exits the loop and kills the thread break; // this exits the loop and kills the thread

View file

@ -4,24 +4,25 @@
mod api; mod api;
use api::*; use api::*;
mod i2c; mod i2c;
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature = "precursor", feature = "renode"))]
mod llio_hw; mod llio_hw;
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature = "precursor", feature = "renode"))]
use llio_hw::*; use llio_hw::*;
#[cfg(not(target_os = "xous"))] #[cfg(not(target_os = "xous"))]
mod llio_hosted; mod llio_hosted;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::Arc;
use std::thread;
#[cfg(not(target_os = "xous"))] #[cfg(not(target_os = "xous"))]
use llio_hosted::*; use llio_hosted::*;
use crate::RTC_PWR_MODE;
use num_traits::*; use num_traits::*;
use xous_ipc::Buffer;
use xous::{CID, msg_scalar_unpack, msg_blocking_scalar_unpack, Message, try_send_message};
use xous::messages::sender::Sender; use xous::messages::sender::Sender;
use std::sync::Arc; use xous::{msg_blocking_scalar_unpack, msg_scalar_unpack, try_send_message, Message, CID};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use xous_ipc::Buffer;
use std::thread; use crate::RTC_PWR_MODE;
// This is slower than most timeout specifiers, but it's easier to debug // This is slower than most timeout specifiers, but it's easier to debug
// when the check interval isn't creating a ton of log spew. // when the check interval isn't creating a ton of log spew.
@ -31,7 +32,7 @@ enum PumpOp {
Pump, Pump,
} }
fn i2c_thread(i2c_sid: xous::SID, power_csr_raw: u32, wfi_state: Arc::<AtomicBool>) { fn i2c_thread(i2c_sid: xous::SID, power_csr_raw: u32, wfi_state: Arc<AtomicBool>) {
let xns = xous_names::XousNames::new().unwrap(); let xns = xous_names::XousNames::new().unwrap();
let handler_conn = xous::connect(i2c_sid).expect("couldn't make handler connection for i2c"); let handler_conn = xous::connect(i2c_sid).expect("couldn't make handler connection for i2c");
@ -40,7 +41,13 @@ fn i2c_thread(i2c_sid: xous::SID, power_csr_raw: u32, wfi_state: Arc::<AtomicBoo
// register a suspend/resume listener // register a suspend/resume listener
let self_cid = xous::connect(i2c_sid).expect("couldn't create suspend callback connection"); 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"); 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 // timeout watcher
let run = Arc::new(AtomicBool::new(false)); let run = Arc::new(AtomicBool::new(false));
@ -52,7 +59,8 @@ fn i2c_thread(i2c_sid: xous::SID, power_csr_raw: u32, wfi_state: Arc::<AtomicBoo
let run = run.clone(); let run = run.clone();
let cid = run_cid.clone(); let cid = run_cid.clone();
let main_cid = self_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? // 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_msb = target_msb.clone();
let target_lsb = target_lsb.clone(); let target_lsb = target_lsb.clone();
move || { move || {
@ -63,11 +71,26 @@ fn i2c_thread(i2c_sid: xous::SID, power_csr_raw: u32, wfi_state: Arc::<AtomicBoo
Some(PumpOp::Pump) => msg_scalar_unpack!(msg, _, _, _, _, { Some(PumpOp::Pump) => msg_scalar_unpack!(msg, _, _, _, _, {
tt.sleep_ms(POLL_INTERVAL_MS).unwrap(); tt.sleep_ms(POLL_INTERVAL_MS).unwrap();
if run.load(Ordering::SeqCst) { if run.load(Ordering::SeqCst) {
let target_time = target_lsb.load(Ordering::SeqCst) as u64 | (target_msb.load(Ordering::SeqCst) as u64) << 32; let target_time = target_lsb.load(Ordering::SeqCst) as u64
| (target_msb.load(Ordering::SeqCst) as u64) << 32;
if tt.elapsed_ms() >= target_time { if tt.elapsed_ms() >= target_time {
try_send_message(main_cid, Message::new_scalar(I2cOpcode::I2cTimeout.to_usize().unwrap(), 0, 0, 0, 0)).ok(); try_send_message(
main_cid,
Message::new_scalar(
I2cOpcode::I2cTimeout.to_usize().unwrap(),
0,
0,
0,
0,
),
)
.ok();
} }
try_send_message(cid, Message::new_scalar(PumpOp::Pump.to_usize().unwrap(), 0, 0, 0, 0)).ok(); try_send_message(
cid,
Message::new_scalar(PumpOp::Pump.to_usize().unwrap(), 0, 0, 0, 0),
)
.ok();
} }
}), }),
_ => log::error!("Unrecognized message: {:?}", msg), _ => log::error!("Unrecognized message: {:?}", msg),
@ -77,12 +100,12 @@ fn i2c_thread(i2c_sid: xous::SID, power_csr_raw: u32, wfi_state: Arc::<AtomicBoo
}); });
let mut suspend_pending_token: Option<usize> = None; let mut suspend_pending_token: Option<usize> = None;
let mut blocking_callers: Vec::<Sender> = Vec::new(); let mut blocking_callers: Vec<Sender> = Vec::new();
let mut i2c_mutex_acquired = false; let mut i2c_mutex_acquired = false;
log::trace!("starting i2c main loop"); log::trace!("starting i2c main loop");
loop { loop {
let msg = xous::receive_message(i2c_sid).unwrap(); let msg = xous::receive_message(i2c_sid).unwrap();
let opcode: Option::<I2cOpcode> = FromPrimitive::from_usize(msg.body.id()); let opcode: Option<I2cOpcode> = FromPrimitive::from_usize(msg.body.id());
log::debug!("{:?}", opcode); log::debug!("{:?}", opcode);
match opcode { match opcode {
Some(I2cOpcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, { Some(I2cOpcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, {
@ -127,7 +150,7 @@ fn i2c_thread(i2c_sid: xous::SID, power_csr_raw: u32, wfi_state: Arc::<AtomicBoo
log::debug!("i2c mutex: blocking {:x?}", msg.sender); log::debug!("i2c mutex: blocking {:x?}", msg.sender);
blocking_callers.push(msg.sender); blocking_callers.push(msg.sender);
} }
}, }
Some(I2cOpcode::I2cMutexRelease) => { Some(I2cOpcode::I2cMutexRelease) => {
assert!(i2c_mutex_acquired == true, "i2c mutex was released when none was acquired"); assert!(i2c_mutex_acquired == true, "i2c mutex was released when none was acquired");
let maybe_next = if !blocking_callers.is_empty() { let maybe_next = if !blocking_callers.is_empty() {
@ -146,10 +169,14 @@ fn i2c_thread(i2c_sid: xous::SID, power_csr_raw: u32, wfi_state: Arc::<AtomicBoo
if !i2c_mutex_acquired { if !i2c_mutex_acquired {
xous::return_scalar(msg.sender, 1).ok(); // acknowledge the release, after the mutex is marked false xous::return_scalar(msg.sender, 1).ok(); // acknowledge the release, after the mutex is marked false
} }
// the somewhat awkward structure is because we want to guarantee the release of mutex before ack, while // the somewhat awkward structure is because we want to guarantee the release of mutex before
// also guaranteeing that the ack happens before we allow the next thread to proceed // ack, while also guaranteeing that the ack happens before we allow the next
// thread to proceed
if let Some(next) = maybe_next { if let Some(next) = maybe_next {
assert!(i2c_mutex_acquired == true, "logic bug in passing mutex acquisition to next thread"); assert!(
i2c_mutex_acquired == true,
"logic bug in passing mutex acquisition to next thread"
);
log::debug!("i2c mutex: unblocking {:x?}", next); log::debug!("i2c mutex: unblocking {:x?}", next);
xous::return_scalar(next, 1).ok(); // this unblocks the waiting thread, and immediately hands the quantum to that thread xous::return_scalar(next, 1).ok(); // this unblocks the waiting thread, and immediately hands the quantum to that thread
} }
@ -159,7 +186,9 @@ fn i2c_thread(i2c_sid: xous::SID, power_csr_raw: u32, wfi_state: Arc::<AtomicBoo
}), }),
Some(I2cOpcode::I2cTxRx) => { Some(I2cOpcode::I2cTxRx) => {
if !i2c_mutex_acquired { if !i2c_mutex_acquired {
log::warn!("TxRx operation was initiated without an acquired mutex. This is only allowed as the last operation before a shutdown."); log::warn!(
"TxRx operation was initiated without an acquired mutex. This is only allowed as the last operation before a shutdown."
);
} }
i2c.initiate(msg); i2c.initiate(msg);
// update the timeout interval to whatever was specified by the transaction // update the timeout interval to whatever was specified by the transaction
@ -167,11 +196,15 @@ fn i2c_thread(i2c_sid: xous::SID, power_csr_raw: u32, wfi_state: Arc::<AtomicBoo
target_msb.store((expiry >> 32) as u32, Ordering::SeqCst); target_msb.store((expiry >> 32) as u32, Ordering::SeqCst);
target_lsb.store(expiry as u32, Ordering::SeqCst); target_lsb.store(expiry as u32, Ordering::SeqCst);
run.store(true, 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(); 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, _, _, _, _, { Some(I2cOpcode::I2cIsBusy) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let busy = if i2c.is_busy() {1} else {0}; let busy = if i2c.is_busy() { 1 } else { 0 };
xous::return_scalar(msg.sender, busy as _).expect("couldn't return I2cIsBusy"); xous::return_scalar(msg.sender, busy as _).expect("couldn't return I2cIsBusy");
}), }),
Some(I2cOpcode::I2cTimeout) => { Some(I2cOpcode::I2cTimeout) => {
@ -206,7 +239,6 @@ fn i2c_thread(i2c_sid: xous::SID, power_csr_raw: u32, wfi_state: Arc::<AtomicBoo
xous::destroy_server(i2c_sid).unwrap(); xous::destroy_server(i2c_sid).unwrap();
} }
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
struct ScalarCallback { struct ScalarCallback {
server_to_cb_cid: CID, server_to_cb_cid: CID,
@ -235,7 +267,8 @@ fn main() -> ! {
// - oqc-test (for testing the vibe motor) // - oqc-test (for testing the vibe motor)
// - net (for COM interrupt dispatch) // - net (for COM interrupt dispatch)
// - pddb also allocates a connection, but then releases it, to read the DNA field. // - pddb also allocates a connection, but then releases it, to read the DNA field.
// We've migrated the I2C function out (which is arguably the most sensitive bit), so we can now set this more safely to unrestriced connection counts. // We've migrated the I2C function out (which is arguably the most sensitive bit), so we can now set this
// more safely to unrestriced connection counts.
let llio_sid = xns.register_name(api::SERVER_NAME_LLIO, None).expect("can't register server"); let llio_sid = xns.register_name(api::SERVER_NAME_LLIO, None).expect("can't register server");
log::trace!("registered with NS -- {:?}", llio_sid); log::trace!("registered with NS -- {:?}", llio_sid);
@ -243,10 +276,11 @@ fn main() -> ! {
// - codec // - codec
// - time server // - time server
// - llio // - llio
// I2C can be used to set time, which can have security implications; we are more strict on counting who can have access to this resource. // I2C can be used to set time, which can have security implications; we are more strict on counting who
#[cfg(all(any(feature="precursor", feature="renode"), not(feature="dvt")))] // can have access to this resource.
#[cfg(all(any(feature = "precursor", feature = "renode"), not(feature = "dvt")))]
let i2c_sid = xns.register_name(api::SERVER_NAME_I2C, Some(3)).expect("can't register I2C thread"); let i2c_sid = xns.register_name(api::SERVER_NAME_I2C, Some(3)).expect("can't register I2C thread");
#[cfg(all(any(feature="precursor", feature="renode"), feature="dvt"))] // dvt build has less in it #[cfg(all(any(feature = "precursor", feature = "renode"), feature = "dvt"))] // dvt build has less in it
let i2c_sid = xns.register_name(api::SERVER_NAME_I2C, Some(2)).expect("can't register I2C thread"); let i2c_sid = xns.register_name(api::SERVER_NAME_I2C, Some(2)).expect("can't register I2C thread");
#[cfg(not(target_os = "xous"))] #[cfg(not(target_os = "xous"))]
let i2c_sid = xns.register_name(api::SERVER_NAME_I2C, Some(1)).expect("can't register I2C thread"); let i2c_sid = xns.register_name(api::SERVER_NAME_I2C, Some(1)).expect("can't register I2C thread");
@ -276,7 +310,9 @@ fn main() -> ! {
// register a suspend/resume listener // register a suspend/resume listener
let sr_cid = xous::connect(llio_sid).expect("couldn't create suspend callback connection"); let sr_cid = xous::connect(llio_sid).expect("couldn't create suspend callback connection");
let mut susres = susres::Susres::new(Some(susres::SuspendOrder::Late), &xns, Opcode::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object"); let mut susres =
susres::Susres::new(Some(susres::SuspendOrder::Late), &xns, Opcode::SuspendResume as u32, sr_cid)
.expect("couldn't create suspend/resume object");
let mut latest_activity = 0; let mut latest_activity = 0;
let mut usb_cb_conns: [Option<ScalarCallback>; 32] = [None; 32]; let mut usb_cb_conns: [Option<ScalarCallback>; 32] = [None; 32];
@ -296,21 +332,22 @@ fn main() -> ! {
log::debug!("starting main loop"); log::debug!("starting main loop");
loop { loop {
let msg = xous::receive_message(llio_sid).unwrap(); let msg = xous::receive_message(llio_sid).unwrap();
let opcode: Option::<Opcode> = FromPrimitive::from_usize(msg.body.id()); let opcode: Option<Opcode> = FromPrimitive::from_usize(msg.body.id());
log::debug!("{:?}", opcode); log::debug!("{:?}", opcode);
match opcode { match opcode {
Some(Opcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, { Some(Opcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, {
let mut dummy = [0u8; 1]; let mut dummy = [0u8; 1];
// make the last transaction to I2C a "read", so that any subsequent noise reads the device, instead of writing junk to the registers // make the last transaction to I2C a "read", so that any subsequent noise reads the device,
// the address 0xc is chosen to put it far "after" any critical registers // instead of writing junk to the registers the address 0xc is chosen to put
// it far "after" any critical registers
i2c.i2c_read_no_repeated_start(ABRTCMC_I2C_ADR, 0xC, &mut dummy).expect("RTC access error"); i2c.i2c_read_no_repeated_start(ABRTCMC_I2C_ADR, 0xC, &mut dummy).expect("RTC access error");
llio.suspend(); llio.suspend();
#[cfg(feature="tts")] #[cfg(feature = "tts")]
llio.tts_sleep_indicate(); // this happens after the suspend call because we don't want the sleep indicator to be restored on resume llio.tts_sleep_indicate(); // this happens after the suspend call because we don't want the sleep indicator to be restored on resume
susres.suspend_until_resume(token).expect("couldn't execute suspend/resume"); susres.suspend_until_resume(token).expect("couldn't execute suspend/resume");
llio.resume(); llio.resume();
#[cfg(feature="tts")] #[cfg(feature = "tts")]
llio.vibe(VibePattern::Double); llio.vibe(VibePattern::Double);
}), }),
Some(Opcode::CrgMode) => msg_scalar_unpack!(msg, _mode, _, _, _, { Some(Opcode::CrgMode) => msg_scalar_unpack!(msg, _mode, _, _, _, {
@ -320,7 +357,8 @@ fn main() -> ! {
llio.gpio_dout(d as u32); llio.gpio_dout(d as u32);
}), }),
Some(Opcode::GpioDataIn) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { Some(Opcode::GpioDataIn) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.gpio_din() as usize).expect("couldn't return gpio data in"); xous::return_scalar(msg.sender, llio.gpio_din() as usize)
.expect("couldn't return gpio data in");
}), }),
Some(Opcode::GpioDataDrive) => msg_scalar_unpack!(msg, d, _, _, _, { Some(Opcode::GpioDataDrive) => msg_scalar_unpack!(msg, d, _, _, _, {
llio.gpio_drive(d as u32); llio.gpio_drive(d as u32);
@ -332,17 +370,18 @@ fn main() -> ! {
llio.gpio_int_as_falling(d as u32); llio.gpio_int_as_falling(d as u32);
}), }),
Some(Opcode::GpioIntPending) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { Some(Opcode::GpioIntPending) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.gpio_int_pending() as usize).expect("couldn't return gpio pending vector"); xous::return_scalar(msg.sender, llio.gpio_int_pending() as usize)
.expect("couldn't return gpio pending vector");
}), }),
Some(Opcode::GpioIntEna) => msg_scalar_unpack!(msg, d, _, _, _, { Some(Opcode::GpioIntEna) => msg_scalar_unpack!(msg, d, _, _, _, {
llio.gpio_int_ena(d as u32); llio.gpio_int_ena(d as u32);
}), }),
Some(Opcode::DebugPowerdown) => msg_scalar_unpack!(msg, arg, _, _, _, { Some(Opcode::DebugPowerdown) => msg_scalar_unpack!(msg, arg, _, _, _, {
let ena = if arg == 0 {false} else {true}; let ena = if arg == 0 { false } else { true };
llio.debug_powerdown(ena); llio.debug_powerdown(ena);
}), }),
Some(Opcode::DebugWakeup) => msg_scalar_unpack!(msg, arg, _, _, _, { Some(Opcode::DebugWakeup) => msg_scalar_unpack!(msg, arg, _, _, _, {
let ena = if arg == 0 {false} else {true}; let ena = if arg == 0 { false } else { true };
llio.debug_wakeup(ena); llio.debug_wakeup(ena);
}), }),
Some(Opcode::UartMux) => msg_scalar_unpack!(msg, mux, _, _, _, { Some(Opcode::UartMux) => msg_scalar_unpack!(msg, mux, _, _, _, {
@ -393,9 +432,15 @@ fn main() -> ! {
Some(Opcode::PowerCryptoStatus) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { Some(Opcode::PowerCryptoStatus) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let (_, sha, engine, force) = llio.power_crypto_status(); let (_, sha, engine, force) = llio.power_crypto_status();
let mut ret = 0; let mut ret = 0;
if sha { ret |= 1 }; if sha {
if engine { ret |= 2 }; ret |= 1
if force { ret |= 4 }; };
if engine {
ret |= 2
};
if force {
ret |= 4
};
xous::return_scalar(msg.sender, ret).expect("couldn't return crypto unit power status"); xous::return_scalar(msg.sender, ret).expect("couldn't return crypto unit power status");
}), }),
Some(Opcode::PowerSelf) => msg_scalar_unpack!(msg, power_on, _, _, _, { Some(Opcode::PowerSelf) => msg_scalar_unpack!(msg, power_on, _, _, _, {
@ -489,10 +534,10 @@ fn main() -> ! {
}), }),
Some(Opcode::EventComHappened) => { Some(Opcode::EventComHappened) => {
send_event(&com_cb_conns, 0); send_event(&com_cb_conns, 0);
}, }
Some(Opcode::EventUsbHappened) => { Some(Opcode::EventUsbHappened) => {
send_event(&usb_cb_conns, 0); send_event(&usb_cb_conns, 0);
}, }
Some(Opcode::GpioIntHappened) => msg_scalar_unpack!(msg, channel, _, _, _, { Some(Opcode::GpioIntHappened) => msg_scalar_unpack!(msg, channel, _, _, _, {
send_event(&gpio_cb_conns, channel as usize); send_event(&gpio_cb_conns, channel as usize);
}), }),
@ -501,16 +546,19 @@ fn main() -> ! {
latest_activity = activity as u32; latest_activity = activity as u32;
}), }),
Some(Opcode::GetActivity) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { Some(Opcode::GetActivity) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature = "precursor", feature = "renode"))]
{ {
let period = llio.activity_get_period() as u32; let period = llio.activity_get_period() as u32;
// log::debug!("activity/period: {}/{}, {:.2}%", latest_activity, period, (latest_activity as f32 / period as f32) * 100.0); // log::debug!("activity/period: {}/{}, {:.2}%", latest_activity, period, (latest_activity
xous::return_scalar2(msg.sender, latest_activity as usize, period as usize).expect("couldn't return activity"); // as f32 / period as f32) * 100.0);
xous::return_scalar2(msg.sender, latest_activity as usize, period as usize)
.expect("couldn't return activity");
} }
#[cfg(not(target_os = "xous"))] // fake an activity #[cfg(not(target_os = "xous"))] // fake an activity
{ {
let period = 12_000; let period = 12_000;
xous::return_scalar2(msg.sender, latest_activity as usize, period as usize).expect("couldn't return activity"); xous::return_scalar2(msg.sender, latest_activity as usize, period as usize)
.expect("couldn't return activity");
latest_activity += period / 20; latest_activity += period / 20;
latest_activity %= period; latest_activity %= period;
} }
@ -519,7 +567,7 @@ fn main() -> ! {
ec_ready = ready != 0; ec_ready = ready != 0;
}), }),
Some(Opcode::EventEcIsReady) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { Some(Opcode::EventEcIsReady) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, if ec_ready {1} else {0}).ok(); xous::return_scalar(msg.sender, if ec_ready { 1 } else { 0 }).ok();
}), }),
Some(Opcode::SetWakeupAlarm) => msg_blocking_scalar_unpack!(msg, delay, _, _, _, { Some(Opcode::SetWakeupAlarm) => msg_blocking_scalar_unpack!(msg, delay, _, _, _, {
if delay > u8::MAX as usize { if delay > u8::MAX as usize {
@ -531,7 +579,12 @@ fn main() -> ! {
i2c.i2c_mutex_acquire(); i2c.i2c_mutex_acquire();
// set clock units to 1 second, output pulse length to ~218ms // set clock units to 1 second, output pulse length to ~218ms
// and program the elapsed time (TIMERB_CLK is followed by TIMERB) // and program the elapsed time (TIMERB_CLK is followed by TIMERB)
i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_TIMERB_CLK, &[(TimerClk::CLK_1_S | TimerClk::PULSE_218_MS).bits()]).expect("RTC access error"); i2c.i2c_write(
ABRTCMC_I2C_ADR,
ABRTCMC_TIMERB_CLK,
&[(TimerClk::CLK_1_S | TimerClk::PULSE_218_MS).bits()],
)
.expect("RTC access error");
// program elapsed time // program elapsed time
i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_TIMERB, &[seconds]).expect("RTC access error"); i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_TIMERB, &[seconds]).expect("RTC access error");
// enable timerb countdown interrupt, also clears any prior interrupt flag // enable timerb countdown interrupt, also clears any prior interrupt flag
@ -542,7 +595,8 @@ fn main() -> ! {
i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONFIG, &[config]).expect("RTC access error"); i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONFIG, &[config]).expect("RTC access error");
i2c.i2c_mutex_release(); i2c.i2c_mutex_release();
// this readback, even though it just goes to debug, seems necessary to get the values to "stick" in the RTC. // this readback, even though it just goes to debug, seems necessary to get the values to
// "stick" in the RTC.
let mut d = [0u8; 0x14]; let mut d = [0u8; 0x14];
i2c.i2c_mutex_acquire(); i2c.i2c_mutex_acquire();
i2c.i2c_read_no_repeated_start(ABRTCMC_I2C_ADR, 0, &mut d).ok(); i2c.i2c_read_no_repeated_start(ABRTCMC_I2C_ADR, 0, &mut d).ok();
@ -561,15 +615,16 @@ fn main() -> ! {
i2c.i2c_mutex_release(); i2c.i2c_mutex_release();
xous::return_scalar(msg.sender, 0).expect("couldn't return to caller"); xous::return_scalar(msg.sender, 0).expect("couldn't return to caller");
}), }),
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature = "precursor", feature = "renode"))]
Some(Opcode::GetRtcValue) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { Some(Opcode::GetRtcValue) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
// There is a possibility that the RTC hardware is actually in an invalid state. // There is a possibility that the RTC hardware is actually in an invalid state.
// Thus, this will return a u64 which is formatted as follows: // Thus, this will return a u64 which is formatted as follows:
// [63] - invalid (0 for valid, 1 for invalid) // [63] - invalid (0 for valid, 1 for invalid)
// [62:0] - time in seconds // [62:0] - time in seconds
// This is okay because 2^63 is much larger than the total number of seconds trackable by the RTC hardware. // This is okay because 2^63 is much larger than the total number of seconds trackable by the
// The RTC hardware can only count up to 100 years before rolling over, which is 3.1*10^9 seconds. // RTC hardware. The RTC hardware can only count up to 100 years before
// Note that we start the RTC at somewhere between 0-10 years, so in practice, a user can expect between 90-100 years // rolling over, which is 3.1*10^9 seconds. Note that we start the RTC at
// somewhere between 0-10 years, so in practice, a user can expect between 90-100 years
// of continuous uptime service out of the RTC. // of continuous uptime service out of the RTC.
let mut settings = [0u8; 8]; let mut settings = [0u8; 8];
let mut aborted = false; let mut aborted = false;
@ -580,27 +635,33 @@ fn main() -> ! {
Ok(llio::I2cStatus::ResponseReadOk) => { Ok(llio::I2cStatus::ResponseReadOk) => {
i2c.i2c_mutex_release(); i2c.i2c_mutex_release();
break; break;
}, }
Err(xous::Error::ServerQueueFull) => { Err(xous::Error::ServerQueueFull) => {
i2c.i2c_mutex_release(); i2c.i2c_mutex_release();
// give it a short pause before trying again, to avoid hammering the I2C bus at busy times // give it a short pause before trying again, to avoid hammering the I2C bus at
// busy times
tt.sleep_ms(38).unwrap(); tt.sleep_ms(38).unwrap();
xous::return_scalar2(msg.sender, 0x8000_0000, 0).expect("couldn't return to caller"); xous::return_scalar2(msg.sender, 0x8000_0000, 0)
.expect("couldn't return to caller");
aborted = true; aborted = true;
break; break;
}, }
_ => { _ => {
log::error!("Couldn't read seconds from RTC!"); log::error!("Couldn't read seconds from RTC!");
// reset the hardware driver, in case that's the problem // reset the hardware driver, in case that's the problem
// this will reset the mutex to not acquired, even if someone else is using it. Very dangerous! // this will reset the mutex to not acquired, even if someone else is using it.
unsafe{i2c.i2c_driver_reset();} // Very dangerous!
unsafe {
i2c.i2c_driver_reset();
}
tt.sleep_ms(37).unwrap(); // short pause in case the upset was caused by too much activity tt.sleep_ms(37).unwrap(); // short pause in case the upset was caused by too much activity
xous::return_scalar2(msg.sender, 0x8000_0000, 0).expect("couldn't return to caller"); xous::return_scalar2(msg.sender, 0x8000_0000, 0)
.expect("couldn't return to caller");
aborted = true; aborted = true;
break; break;
}, }
}; };
} }
// this continue has to be outside the above loop to avoid a double-free error! // this continue has to be outside the above loop to avoid a double-free error!
@ -620,31 +681,32 @@ fn main() -> ! {
None => { None => {
// ensure nobody else is using the I2C block // ensure nobody else is using the I2C block
i2c.i2c_mutex_acquire(); i2c.i2c_mutex_acquire();
// this will reset the mutex to not acquired, even if someone else is using it. Very dangerous! // this will reset the mutex to not acquired, even if someone else is using it.
unsafe{i2c.i2c_driver_reset();} // Very dangerous!
unsafe {
i2c.i2c_driver_reset();
}
tt.sleep_ms(37).unwrap(); // short pause in case the upset was caused by too much activity tt.sleep_ms(37).unwrap(); // short pause in case the upset was caused by too much activity
// re-acquire the mutex, because it was released by the driver reset // re-acquire the mutex, because it was released by the driver reset
i2c.i2c_mutex_acquire(); i2c.i2c_mutex_acquire();
let secs = if to_binary(settings[1] & 0x7f) < 60 { let secs =
settings[1] & 0x7f if to_binary(settings[1] & 0x7f) < 60 { settings[1] & 0x7f } else { 0 };
} else {
0
};
if to_binary(settings[7]) > 99 { if to_binary(settings[7]) > 99 {
settings[7] = settings[7] & 0x7f; settings[7] = settings[7] & 0x7f;
} }
if to_binary(settings[3]) > 23 { if to_binary(settings[3]) > 23 {
settings[3] = settings[3] & 0x1f; settings[3] = settings[3] & 0x1f;
} }
// do a "hot reset" -- just clears error flags, but does our best to avoid rewriting time // do a "hot reset" -- just clears error flags, but does our best to avoid
// if a lot of values are wrong, it means that the RTC had garbage written to it on the // rewriting time if a lot of values are wrong, it
// means that the RTC had garbage written to it on the
// previous shutdown. This at least gets us *working* again, but time is lost. // previous shutdown. This at least gets us *working* again, but time is lost.
let reset_values = [ let reset_values = [
0x0, // clear all interrupts, return to normal operations 0x0, // clear all interrupts, return to normal operations
0x0, // clear all interrupts 0x0, // clear all interrupts
RTC_PWR_MODE, // reset power mode RTC_PWR_MODE, // reset power mode
secs, // write the seconds register back without the error flag secs, // write the seconds register back without the error flag
settings[2] & 0x7f, settings[2] & 0x7f,
settings[3], // requires a fix interpreting BCD settings[3], // requires a fix interpreting BCD
settings[4] & 0x3F, settings[4] & 0x3F,
@ -652,7 +714,8 @@ fn main() -> ! {
settings[6] & 0x1F, settings[6] & 0x1F,
settings[7], // this requires a fix interpreting BCD, which is above settings[7], // this requires a fix interpreting BCD, which is above
]; ];
i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL1, &reset_values).expect("RTC access error"); i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL1, &reset_values)
.expect("RTC access error");
i2c.i2c_mutex_release(); i2c.i2c_mutex_release();
} }
} }
@ -660,7 +723,9 @@ fn main() -> ! {
if retries > 10 { if retries > 10 {
// this will likely cause an upstream failure, because a lot of logic can't proceed // this will likely cause an upstream failure, because a lot of logic can't proceed
// without a valid resolution to the RTC setting! // without a valid resolution to the RTC setting!
log::error!("rtc_to_seconds() never returned a valid value. Returning an error, that may result in a panic..."); log::error!(
"rtc_to_seconds() never returned a valid value. Returning an error, that may result in a panic..."
);
xous::return_scalar2(msg.sender, 0x8000_0000, 0).expect("couldn't return to caller"); xous::return_scalar2(msg.sender, 0x8000_0000, 0).expect("couldn't return to caller");
aborted = true; aborted = true;
break; break;
@ -672,10 +737,12 @@ fn main() -> ! {
if aborted || total_secs == 0 { if aborted || total_secs == 0 {
continue; continue;
} else { } else {
xous::return_scalar2(msg.sender, xous::return_scalar2(
msg.sender,
((total_secs >> 32) & 0xFFFF_FFFF) as usize, ((total_secs >> 32) & 0xFFFF_FFFF) as usize,
(total_secs & 0xFFFF_FFFF) as usize, (total_secs & 0xFFFF_FFFF) as usize,
).expect("couldn't return to caller"); )
.expect("couldn't return to caller");
} }
}), }),
#[cfg(not(target_os = "xous"))] #[cfg(not(target_os = "xous"))]
@ -683,19 +750,26 @@ fn main() -> ! {
use chrono::prelude::*; use chrono::prelude::*;
let now = Local::now(); let now = Local::now();
let total_secs = now.timestamp_millis() / 1000 - 148409348; // sets the offset to something like 1974, which is roughly where an RTC value ends up in reality let total_secs = now.timestamp_millis() / 1000 - 148409348; // sets the offset to something like 1974, which is roughly where an RTC value ends up in reality
xous::return_scalar2(msg.sender, xous::return_scalar2(
msg.sender,
((total_secs >> 32) & 0xFFFF_FFFF) as usize, ((total_secs >> 32) & 0xFFFF_FFFF) as usize,
(total_secs & 0xFFFF_FFFF) as usize, (total_secs & 0xFFFF_FFFF) as usize,
).expect("couldn't return to caller"); )
.expect("couldn't return to caller");
// use the tt variable so we don't get a warning // use the tt variable so we don't get a warning
let _ = tt.elapsed_ms(); let _ = tt.elapsed_ms();
}), }),
Some(Opcode::Quit) => { Some(Opcode::Quit) => {
log::info!("Received quit opcode, exiting."); log::info!("Received quit opcode, exiting.");
let dropconn = xous::connect(i2c_sid).unwrap(); let dropconn = xous::connect(i2c_sid).unwrap();
xous::send_message(dropconn, xous::send_message(
xous::Message::new_scalar(I2cOpcode::Quit.to_usize().unwrap(), 0, 0, 0, 0)).unwrap(); dropconn,
unsafe{xous::disconnect(dropconn).unwrap();} xous::Message::new_scalar(I2cOpcode::Quit.to_usize().unwrap(), 0, 0, 0, 0),
)
.unwrap();
unsafe {
xous::disconnect(dropconn).unwrap();
}
break; break;
} }
None => { None => {
@ -737,10 +811,14 @@ fn do_hook(hookdata: ScalarHook, cb_conns: &mut [Option<ScalarCallback>; 32]) {
fn unhook(cb_conns: &mut [Option<ScalarCallback>; 32]) { fn unhook(cb_conns: &mut [Option<ScalarCallback>; 32]) {
for entry in cb_conns.iter_mut() { for entry in cb_conns.iter_mut() {
if let Some(scb) = entry { if let Some(scb) = entry {
xous::send_message(scb.server_to_cb_cid, xous::send_message(
xous::Message::new_blocking_scalar(EventCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0) scb.server_to_cb_cid,
).unwrap(); xous::Message::new_blocking_scalar(EventCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0),
unsafe{xous::disconnect(scb.server_to_cb_cid).unwrap();} )
.unwrap();
unsafe {
xous::disconnect(scb.server_to_cb_cid).unwrap();
}
} }
*entry = None; *entry = None;
} }
@ -748,19 +826,30 @@ fn unhook(cb_conns: &mut [Option<ScalarCallback>; 32]) {
fn send_event(cb_conns: &[Option<ScalarCallback>; 32], which: usize) { fn send_event(cb_conns: &[Option<ScalarCallback>; 32], which: usize) {
for entry in cb_conns.iter() { for entry in cb_conns.iter() {
if let Some(scb) = entry { if let Some(scb) = entry {
// note that the "which" argument is only used for GPIO events, to indicate which pin had the event // note that the "which" argument is only used for GPIO events, to indicate which pin had the
match xous::try_send_message(scb.server_to_cb_cid, // event
xous::Message::new_scalar(EventCallback::Event.to_usize().unwrap(), match xous::try_send_message(
scb.cb_to_client_cid as usize, scb.cb_to_client_id as usize, which, 0) scb.server_to_cb_cid,
xous::Message::new_scalar(
EventCallback::Event.to_usize().unwrap(),
scb.cb_to_client_cid as usize,
scb.cb_to_client_id as usize,
which,
0,
),
) { ) {
Ok(_) => {}, Ok(_) => {}
Err(e) => { Err(e) => {
match e { match e {
xous::Error::ServerQueueFull => { xous::Error::ServerQueueFull => {
// this triggers if an interrupt storm happens. This could be perfectly natural and/or // this triggers if an interrupt storm happens. This could be perfectly natural
// "expected", and the "best" behavior is probably to drop the events, but leave a warning. // and/or "expected", and the "best" behavior is
// probably to drop the events, but leave a warning.
// Examples of this would be a ping flood overwhelming the network stack. // Examples of this would be a ping flood overwhelming the network stack.
log::warn!("Attempted to send event, but destination queue is full. Event was dropped: {:?}", scb); log::warn!(
"Attempted to send event, but destination queue is full. Event was dropped: {:?}",
scb
);
} }
xous::Error::ServerNotFound => { xous::Error::ServerNotFound => {
log::warn!("Event callback subscriber has died. Event was dropped: {:?}", scb); log::warn!("Event callback subscriber has died. Event was dropped: {:?}", scb);
@ -780,11 +869,12 @@ fn send_event(cb_conns: &[Option<ScalarCallback>; 32], which: usize) {
// --test-threads=1 so we can see the output in sequence // --test-threads=1 so we can see the output in sequence
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use llio::rtc_to_seconds; use llio::rtc_to_seconds;
use rand::Rng; use rand::Rng;
use super::*;
fn to_bcd(binary: u8) -> u8 { fn to_bcd(binary: u8) -> u8 {
let mut lsd: u8 = binary % 10; let mut lsd: u8 = binary % 10;
if lsd > 9 { if lsd > 9 {
@ -800,18 +890,20 @@ mod tests {
#[test] #[test]
fn test_rtc_to_secs() { fn test_rtc_to_secs() {
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
let rtc_base = DateTime::<Utc>::from_utc(chrono::NaiveDate::from_ymd(2000, 1, 1) let rtc_base =
.and_hms(0, 0, 0), Utc); DateTime::<Utc>::from_utc(chrono::NaiveDate::from_ymd(2000, 1, 1).and_hms(0, 0, 0), Utc);
// test every year, every month, every day, with a random time stamp // test every year, every month, every day, with a random time stamp
for year in 0..99 { for year in 0..99 {
for month in 1..=12 { for month in 1..=12 {
let days = match month { let days = match month {
1 => 1..=31, 1 => 1..=31,
2 => if (year % 4) == 0 { 2 => {
1..=29 if (year % 4) == 0 {
} else { 1..=29
1..=28 } else {
1..=28
}
} }
3 => 1..=31, 3 => 1..=31,
4 => 1..=30, 4 => 1..=30,
@ -823,15 +915,18 @@ mod tests {
10 => 1..=31, 10 => 1..=31,
11 => 1..=30, 11 => 1..=30,
12 => 1..=31, 12 => 1..=31,
_ => {panic!("invalid month")}, _ => {
panic!("invalid month")
}
}; };
for day in days { for day in days {
let h = rng.gen_range(0..24); let h = rng.gen_range(0..24);
let m = rng.gen_range(0..60); let m = rng.gen_range(0..60);
let s = rng.gen_range(0..60); let s = rng.gen_range(0..60);
let rtc_test = DateTime::<Utc>::from_utc( let rtc_test = DateTime::<Utc>::from_utc(
chrono::NaiveDate::from_ymd(2000 + year, month, day) chrono::NaiveDate::from_ymd(2000 + year, month, day).and_hms(h, m, s),
.and_hms(h, m, s), Utc); Utc,
);
let diff = rtc_test.signed_duration_since(rtc_base); let diff = rtc_test.signed_duration_since(rtc_base);
let settings = [ let settings = [
@ -846,11 +941,14 @@ mod tests {
]; ];
if diff.num_seconds() != rtc_to_seconds(&settings).unwrap() as i64 { if diff.num_seconds() != rtc_to_seconds(&settings).unwrap() as i64 {
println!("{} vs {}", diff.num_seconds(), rtc_to_seconds(&settings).unwrap()); println!("{} vs {}", diff.num_seconds(), rtc_to_seconds(&settings).unwrap());
println!("Duration to {}/{}/{}-{}:{}:{} -- {}", println!(
"Duration to {}/{}/{}-{}:{}:{} -- {}",
2000 + year, 2000 + year,
month, month,
day, day,
h, m, s, h,
m,
s,
diff.num_seconds() diff.num_seconds()
); );
} }