diff --git a/services/codec/src/backend/tlv320aic3100.rs b/services/codec/src/backend/tlv320aic3100.rs index 041d00e40..e19a25f31 100644 --- a/services/codec/src/backend/tlv320aic3100.rs +++ b/services/codec/src/backend/tlv320aic3100.rs @@ -246,6 +246,7 @@ impl Codec { } pub fn set_speaker_gain_db(&mut self, gain_db: f32) { + self.i2c.i2c_mutex_acquire(); self.speaker_gain = gain_db; if gain_db <= -79.0 { // mute @@ -259,11 +260,13 @@ impl Codec { 0b1_000_0000 | code, ]); } + self.i2c.i2c_mutex_release(); } pub fn set_headphone_gain_db(&mut self, gain_db_left: f32, gain_db_right: f32) { self.headphone_left_gain = gain_db_left; self.headphone_right_gain = gain_db_right; + self.i2c.i2c_mutex_acquire(); if gain_db_left <= -79.0 && gain_db_right <= -79.0 { // mute self.w(0, &[1]); // select page 1 @@ -278,8 +281,9 @@ impl Codec { 0b1_000_0000 | code_right, // HPR ]); } + self.i2c.i2c_mutex_release(); } - + /// Convenience wrapper for I2C transactions. Multiple I2C ops that have to be execute atomically must be manually guarded with a i2c_mutex_[acquire/release] fn w(&mut self, adr: u8, data: &[u8]) -> bool { //log::trace!("writing to 0x{:x}, {:x?}", adr, data); match self.i2c.i2c_write(TLV320AIC3100_I2C_ADR, adr, data) { @@ -294,6 +298,7 @@ impl Codec { _ => {log::error!("try_send_i2c unhandled error"); false} } } + /// Convenience wrapper for I2C transactions. Multiple I2C ops that have to be execute atomically must be manually guarded with a i2c_mutex_[acquire/release] fn r(&mut self, adr: u8, data: &mut[u8]) -> bool { match self.i2c.i2c_read(TLV320AIC3100_I2C_ADR, adr, data) { Ok(status) => { @@ -308,32 +313,40 @@ impl Codec { } pub fn get_headset_code(&mut self) -> u8 { + self.i2c.i2c_mutex_acquire(); self.w(0, &[0]); let mut code: [u8; 1] = [0; 1]; if !self.r(67, &mut code) { log::warn!("headset code read unsuccessful"); }; + self.i2c.i2c_mutex_release(); code[0] } pub fn get_dacflag_code(&mut self) -> u8 { + self.i2c.i2c_mutex_acquire(); self.w(0, &[0]); let mut code: [u8; 1] = [0; 1]; self.r(37, &mut code); + self.i2c.i2c_mutex_release(); code[0] } pub fn get_hp_status(&mut self) -> u8 { + self.i2c.i2c_mutex_acquire(); self.w(0, &[1]); let mut code: [u8; 1] = [0; 1]; self.r(31, &mut code); + self.i2c.i2c_mutex_release(); code[0] } pub fn get_i2s_config(&mut self) -> [u8; 4] { + self.i2c.i2c_mutex_acquire(); self.w(0, &[0]); let mut code: [u8; 4] = [0; 4]; self.r(27, &mut code); + self.i2c.i2c_mutex_release(); code } @@ -352,6 +365,7 @@ impl Codec { /// 8_000 * 128 * 12 = 12_288_000 Hz /// fn audio_clocks(&mut self) { + self.i2c.i2c_mutex_acquire(); self.w(0, &[0]); // select page 0 self.w(1, &[1]); // software reset self.ticktimer.sleep_ms(2).unwrap(); // reset happens in 1 ms; +1 ms due to timing jitter uncertainty @@ -384,6 +398,7 @@ impl Codec { 0x80 | 2, // MADC = 2 128, // AOSR = 128 ]); + self.i2c.i2c_mutex_release(); } /// audio_ports() sets up the digital port bitwidths, modes, and syncs @@ -391,6 +406,7 @@ impl Codec { /// From the hardware i2s block as implemented on betrusted-soc: /// 16 bits per sample, 32 bit word width, stero, master mode, left-justified, MSB first fn audio_ports(&mut self) { + self.i2c.i2c_mutex_acquire(); self.w(0, &[0]); // select page 0 // 32 bits/word * 2 channels * 8000 samples/s = 512_000 = BCLK @@ -413,9 +429,11 @@ impl Codec { // use auto volume control -- DO WE WANT THIS??? //self.w(116, &[0b1_1_01_0_001] ); + self.i2c.i2c_mutex_release(); } pub fn audio_loopback(&mut self, do_loop:bool) { + self.i2c.i2c_mutex_acquire(); self.w(0, &[1]); // select page 1 // DAC routing -- route DAC to mixer channel, don't loopback MIC @@ -424,10 +442,12 @@ impl Codec { } else { self.w(35, &[0b01_0_1_01_1_0]); } + self.i2c.i2c_mutex_release(); } /// set up the audio mixer to sane defaults fn audio_mixer(&mut self) { + self.i2c.i2c_mutex_acquire(); ////////// SETUP DAC -- this is on page 0 self.w(0, &[0]); // select page 0 // DAC setup - both channels on, soft-stepping enabled, left-to-left, right-to-right @@ -503,7 +523,7 @@ impl Codec { 0x01, // noise debounce time = code*4 / fs 0x01, // signal debounce time = code*4 / fs ]); - + self.i2c.i2c_mutex_release(); } /// set up the betrusted-side signals diff --git a/services/llio/src/api/i2c_api.rs b/services/llio/src/api/i2c_api.rs index 7dfc695f1..8cdf201a2 100644 --- a/services/llio/src/api/i2c_api.rs +++ b/services/llio/src/api/i2c_api.rs @@ -61,6 +61,9 @@ pub(crate) enum I2cOpcode { IrqI2cTrace, /// checks if the I2C engine is currently busy, for polling implementations I2cIsBusy, + /// grabs a mutex on the I2C block, for multiple transactions that can't be separated + I2cMutexAcquire, + I2cMutexRelease, /// SuspendResume callback SuspendResume, Quit, diff --git a/services/llio/src/i2c_lib.rs b/services/llio/src/i2c_lib.rs index 7c4b8d991..68403f4ef 100644 --- a/services/llio/src/i2c_lib.rs +++ b/services/llio/src/i2c_lib.rs @@ -25,6 +25,25 @@ impl I2c { 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 + /// 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 + /// another thread interrupting the operation for the result to be valid. However, the API + /// only speaks I2C transactions at a single register read/write level, and can't know if a + /// subsequent read or write depends on the current state. Thus, we must acquire this mutex. + /// The mutex sharing is collaborative, so someone without the mutex could, in theory, just + /// barge in and perform an operation. + pub fn i2c_mutex_acquire(&self) { + xous::send_message(self.conn, + 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. + pub fn i2c_mutex_release(&self) { + xous::send_message(self.conn, + 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 /// useful to just "fire and forget" i2c writes, because actually we cared about the side effect of the diff --git a/services/llio/src/main.rs b/services/llio/src/main.rs index 5abbd8964..20084de7c 100644 --- a/services/llio/src/main.rs +++ b/services/llio/src/main.rs @@ -17,6 +17,7 @@ use llio_hosted::*; use num_traits::*; use xous_ipc::Buffer; use xous::{CID, msg_scalar_unpack, msg_blocking_scalar_unpack}; +use xous::messages::sender::Sender; use std::thread; @@ -31,6 +32,8 @@ fn i2c_thread(i2c_sid: xous::SID) { let mut susres = susres::Susres::new(Some(susres::SuspendOrder::Later), &xns, I2cOpcode::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object"); let mut suspend_pending_token: Option = None; + let mut blocking_callers: Vec:: = Vec::new(); + let mut i2c_mutex_acquired = false; log::trace!("starting i2c main loop"); loop { let msg = xous::receive_message(i2c_sid).unwrap(); @@ -64,10 +67,38 @@ fn i2c_thread(i2c_sid: xous::SID) { // I2C state machine handler irq result i2c.report_read_done(); }), + Some(I2cOpcode::I2cMutexAcquire) => { + if !i2c_mutex_acquired { + i2c_mutex_acquired = true; + xous::return_scalar(msg.sender, 1).ok(); + } else { + blocking_callers.push(msg.sender); + } + }, + Some(I2cOpcode::I2cMutexRelease) => { + assert!(i2c_mutex_acquired == true, "i2c mutex was released when none was acquired"); + let maybe_next = if !blocking_callers.is_empty() { + let next_in_line = blocking_callers.remove(0); + Some(next_in_line) + } else { + i2c_mutex_acquired = false; + None + }; + 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 + // also guaranteeing that the ack happens before we allow the next thread to proceed + if let Some(next) = maybe_next { + assert!(i2c_mutex_acquired == true, "logic bug in passing mutex acquisition to next thread"); + xous::return_scalar(next, 1).ok(); // this unblocks the waiting thread, and immediately hands the quantum to that thread + } + } Some(I2cOpcode::IrqI2cTrace) => { i2c.trace(); }, Some(I2cOpcode::I2cTxRx) => { + if !i2c_mutex_acquired { + log::warn!("TxRx operation was initiated without an acquired mutex. This will become a hard error in future revisions"); + } i2c.initiate(msg); }, Some(I2cOpcode::I2cIsBusy) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { @@ -383,6 +414,7 @@ fn main() -> ! { continue; } let seconds = delay as u8; + i2c.i2c_mutex_acquire(); // make sure battery switchover is enabled, otherwise we won't keep time when power goes off i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &[(Control3::BATT_STD_BL_EN).bits()]).expect("RTC access error"); // set clock units to 1 second, output pulse length to ~218ms @@ -395,9 +427,11 @@ fn main() -> ! { // turn on the timer proper -- the system will wakeup in 5..4..3.... let config = (Config::CLKOUT_DISABLE | Config::TIMER_B_ENABLE).bits(); i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONFIG, &[config]).expect("RTC access error"); + i2c.i2c_mutex_release(); xous::return_scalar(msg.sender, 0).expect("couldn't return to caller"); }), Some(Opcode::ClearWakeupAlarm) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + i2c.i2c_mutex_acquire(); // make sure battery switchover is enabled, otherwise we won't keep time when power goes off i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &[(Control3::BATT_STD_BL_EN).bits()]).expect("RTC access error"); let config = Config::CLKOUT_DISABLE.bits(); @@ -406,6 +440,7 @@ fn main() -> ! { // clear my interrupts and flags let control2 = 0; i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL2, &[control2]).expect("RTC access error"); + i2c.i2c_mutex_release(); xous::return_scalar(msg.sender, 0).expect("couldn't return to caller"); }), #[cfg(any(feature="precursor", feature="renode"))] @@ -422,15 +457,21 @@ fn main() -> ! { let mut success = false; while !success { // retry loop is necessary because this function can get called during "congested" periods + i2c.i2c_mutex_acquire(); match i2c.i2c_read(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &mut settings) { - Ok(llio::I2cStatus::ResponseReadOk) => success = true, + Ok(llio::I2cStatus::ResponseReadOk) => { + i2c.i2c_mutex_release(); + success = true + }, Err(xous::Error::ServerQueueFull) => { + i2c.i2c_mutex_release(); success = false; // give it a short pause before trying again, to avoid hammering the I2C bus at busy times tt.sleep_ms(38).unwrap(); }, _ => { log::error!("Couldn't read seconds from RTC!"); + i2c.i2c_mutex_release(); xous::return_scalar2(msg.sender, 0x8000_0000, 0).expect("couldn't return to caller"); break; }, diff --git a/services/status/src/time.rs b/services/status/src/time.rs index 00283ba15..d276c8842 100644 --- a/services/status/src/time.rs +++ b/services/status/src/time.rs @@ -172,9 +172,14 @@ pub fn start_time_server() { // on boot, do the validation checks of the RTC. If it is not initialized or corrupted, fix it. let mut settings = [0u8; 8]; loop { + i2c.i2c_mutex_acquire(); match i2c.i2c_read(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &mut settings) { - Ok(I2cStatus::ResponseReadOk) => break, + Ok(I2cStatus::ResponseReadOk) => { + i2c.i2c_mutex_release(); + break + }, _ => { + i2c.i2c_mutex_release(); log::error!("Couldn't check RTC, retrying!"); xous::yield_slice(); // recheck in a fast loop, we really should be able to grab this resource on boot. }, @@ -196,7 +201,9 @@ pub fn start_time_server() { settings[MONTHS] = to_bcd((start_time & 0xFF) as u8 % 12 + 1); start_time >>= 8; settings[YEARS] = to_bcd((start_time & 0xFF) as u8 % 10 + 1); + i2c.i2c_mutex_acquire(); i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &settings).expect("RTC access error"); + i2c.i2c_mutex_release(); } rtc_checked.store(true, Ordering::SeqCst); loop { @@ -218,7 +225,9 @@ pub fn start_time_server() { settings[MONTHS] = to_bcd((start_time & 0xFF) as u8 % 12 + 1); start_time >>= 8; settings[YEARS] = to_bcd((start_time & 0xFF) as u8 % 10 + 1); + i2c.i2c_mutex_acquire(); i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &settings).expect("RTC access error"); + i2c.i2c_mutex_release(); xous::return_scalar(msg.sender, 0).unwrap(); }), Some(PrivTimeOp::SusRes) => xous::msg_scalar_unpack!(msg, token, _, _, _, {