format services/xous-ticktimer

This commit is contained in:
bunnie 2024-01-14 22:58:20 +08:00
parent 4bf9e8bf3a
commit 913beaa791
6 changed files with 178 additions and 301 deletions

View file

@ -13,7 +13,6 @@ use log::{error, info};
mod platform; mod platform;
use platform::implementation::*; use platform::implementation::*;
use platform::*; use platform::*;
#[cfg(not(any(target_arch = "arm", feature = "cramium-soc", feature = "cramium-fpga")))] #[cfg(not(any(target_arch = "arm", feature = "cramium-soc", feature = "cramium-fpga")))]
use susres::SuspendOrder; use susres::SuspendOrder;
@ -37,13 +36,13 @@ fn main() -> ! {
log::info!("****************************************************************"); log::info!("****************************************************************");
} }
let ticktimer_server = xous::create_server_with_address(b"ticktimer-server") let ticktimer_server =
.expect("Couldn't create Ticktimer server"); xous::create_server_with_address(b"ticktimer-server").expect("Couldn't create Ticktimer server");
info!("Server started with SID {:?}", ticktimer_server); info!("Server started with SID {:?}", ticktimer_server);
// Connect to our own server so we can send the "Recalculate" message // Connect to our own server so we can send the "Recalculate" message
let ticktimer_client = xous::connect(xous::SID::from_bytes(b"ticktimer-server").unwrap()) let ticktimer_client =
.expect("couldn't connect to self"); xous::connect(xous::SID::from_bytes(b"ticktimer-server").unwrap()).expect("couldn't connect to self");
// Create a new ticktimer object // Create a new ticktimer object
let mut ticktimer = XousTickTimer::new(ticktimer_client); let mut ticktimer = XousTickTimer::new(ticktimer_client);
@ -56,16 +55,11 @@ fn main() -> ! {
let xns = xous_names::XousNames::new().unwrap(); let xns = xous_names::XousNames::new().unwrap();
#[cfg(not(any(target_arch = "arm", feature = "cramium-soc", feature = "cramium-fpga")))] #[cfg(not(any(target_arch = "arm", feature = "cramium-soc", feature = "cramium-fpga")))]
let sr_cid = let sr_cid = xous::connect(ticktimer_server).expect("couldn't create suspend callback connection");
xous::connect(ticktimer_server).expect("couldn't create suspend callback connection");
#[cfg(not(any(target_arch = "arm", feature = "cramium-soc", feature = "cramium-fpga")))] #[cfg(not(any(target_arch = "arm", feature = "cramium-soc", feature = "cramium-fpga")))]
let mut susres = susres::Susres::new( let mut susres =
Some(SuspendOrder::Last), susres::Susres::new(Some(SuspendOrder::Last), &xns, api::Opcode::SuspendResume as u32, sr_cid)
&xns,
api::Opcode::SuspendResume as u32,
sr_cid,
)
.expect("couldn't create suspend/resume object"); .expect("couldn't create suspend/resume object");
// A list of all sleep requests in the system, sorted by the time at which it // A list of all sleep requests in the system, sorted by the time at which it
@ -81,10 +75,8 @@ fn main() -> ! {
// A list of message IDs that are waiting to receive a Notification. This queue is drained // A list of message IDs that are waiting to receive a Notification. This queue is drained
// by threads sending `NotifyCondition` to us, or by a condvar timing out. // by threads sending `NotifyCondition` to us, or by a condvar timing out.
let mut notify_table: HashMap< let mut notify_table: HashMap<Option<xous::PID>, HashMap<usize, VecDeque<xous::MessageSender>>> =
Option<xous::PID>, HashMap::new();
HashMap<usize, VecDeque<xous::MessageSender>>,
> = HashMap::new();
// Keep track of which notifications have timeouts. This is used to determine which // Keep track of which notifications have timeouts. This is used to determine which
// notifications have already been responded to by the interrupt, as well as to // notifications have already been responded to by the interrupt, as well as to
@ -105,11 +97,9 @@ fn main() -> ! {
//#[cfg(feature = "watchdog")] // for debugging the watchdog //#[cfg(feature = "watchdog")] // for debugging the watchdog
//ticktimer.check_wdt(); //ticktimer.check_wdt();
xous::reply_and_receive_next_legacy(ticktimer_server, &mut msg_opt, &mut return_type) xous::reply_and_receive_next_legacy(ticktimer_server, &mut msg_opt, &mut return_type).unwrap();
.unwrap();
let msg = msg_opt.as_mut().unwrap(); let msg = msg_opt.as_mut().unwrap();
let opcode = num_traits::FromPrimitive::from_usize(msg.body.id()) let opcode = num_traits::FromPrimitive::from_usize(msg.body.id()).unwrap_or(api::Opcode::InvalidCall);
.unwrap_or(api::Opcode::InvalidCall);
log::trace!("msg {:?}: {:x?}", opcode, msg); log::trace!("msg {:?}: {:x?}", opcode, msg);
match opcode { match opcode {
api::Opcode::ElapsedMs => { api::Opcode::ElapsedMs => {
@ -147,21 +137,16 @@ fn main() -> ! {
// let timeout_queue = timeout_heap.entry(msg.sender.pid()).or_default(); // let timeout_queue = timeout_heap.entry(msg.sender.pid()).or_default();
ticktimer.recalculate_sleep( ticktimer.recalculate_sleep(
&mut sleep_heap, &mut sleep_heap,
Some(TimerRequest { Some(TimerRequest { msec: ms.into(), sender, kind: RequestKind::Sleep, data: 0 }),
msec: ms.into(),
sender,
kind: RequestKind::Sleep,
data: 0,
}),
); );
} }
} }
api::Opcode::RecalculateSleep => { api::Opcode::RecalculateSleep => {
if msg.sender.pid().map(|p| p.get()).unwrap_or_default() as u32 if msg.sender.pid().map(|p| p.get()).unwrap_or_default() as u32 != xous::process::id() {
!= xous::process::id() log::error!(
{ "got a RecalculateSleep message from a process other than the ticktimer server"
log::error!("got a RecalculateSleep message from a process other than the ticktimer server"); );
continue; continue;
} }
@ -183,11 +168,7 @@ fn main() -> ! {
assert!(len_before == len_after); assert!(len_before == len_after);
// It should, however, still be in the notify hash. Remove it. // It should, however, still be in the notify hash. Remove it.
let awaiting = notify_table let awaiting = notify_table.entry(sender.pid()).or_default().entry(condvar).or_default();
.entry(sender.pid())
.or_default()
.entry(condvar)
.or_default();
let len_before = awaiting.len(); let len_before = awaiting.len();
awaiting.retain(|v| *v != sender); awaiting.retain(|v| *v != sender);
let len_after = awaiting.len(); let len_after = awaiting.len();
@ -195,8 +176,11 @@ fn main() -> ! {
// Note multiple events elapsing since the last recalculate. Theorized to be harmless. // Note multiple events elapsing since the last recalculate. Theorized to be harmless.
if ticktimer.last_response() != sender { if ticktimer.last_response() != sender {
log::warn!("Multiple events triggered before we could recalculate sleep: ticktimer.last_response() {:?} != sender {:?}; sleep_heap.len(): {}", log::warn!(
ticktimer.last_response(), sender, sleep_heap.len() "Multiple events triggered before we could recalculate sleep: ticktimer.last_response() {:?} != sender {:?}; sleep_heap.len(): {}",
ticktimer.last_response(),
sender,
sleep_heap.len()
); );
} }
} }
@ -209,14 +193,8 @@ fn main() -> ! {
api::Opcode::SuspendResume => xous::msg_scalar_unpack!(msg, _token, _, _, _, { api::Opcode::SuspendResume => xous::msg_scalar_unpack!(msg, _token, _, _, _, {
ticktimer.suspend(); ticktimer.suspend();
#[cfg(not(any( #[cfg(not(any(target_arch = "arm", feature = "cramium-soc", feature = "cramium-fpga")))]
target_arch = "arm", susres.suspend_until_resume(_token).expect("couldn't execute suspend/resume");
feature = "cramium-soc",
feature = "cramium-fpga"
)))]
susres
.suspend_until_resume(_token)
.expect("couldn't execute suspend/resume");
ticktimer.resume(); ticktimer.resume();
}), }),
@ -227,9 +205,7 @@ fn main() -> ! {
api::Opcode::GetVersion => { api::Opcode::GetVersion => {
let mut buf = unsafe { let mut buf = unsafe {
xous_ipc::Buffer::from_memory_message_mut( xous_ipc::Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())
msg.body.memory_message_mut().unwrap(),
)
}; };
#[cfg(feature = "timestamp")] #[cfg(feature = "timestamp")]
buf.replace(version::get_version()).unwrap(); buf.replace(version::get_version()).unwrap();
@ -261,12 +237,7 @@ fn main() -> ! {
// Add this to the end of the list of entries to call so that when `UnlockMutex` is sent // Add this to the end of the list of entries to call so that when `UnlockMutex` is sent
// the message will get a response. // the message will get a response.
mutex_hash mutex_hash.entry(pid).or_default().entry(mutex_id).or_default().push_back(msg.sender);
.entry(pid)
.or_default()
.entry(mutex_id)
.or_default()
.push_back(msg.sender);
// We've saved the `msg.sender` above and will return the lock as part of the mutex // We've saved the `msg.sender` above and will return the lock as part of the mutex
// work thread. Forget the contents of `msg_opt` without running its destructor. // work thread. Forget the contents of `msg_opt` without running its destructor.
@ -287,12 +258,8 @@ fn main() -> ! {
// If there's something waiting in the queue, respond to that message // If there's something waiting in the queue, respond to that message
let mut returned = false; let mut returned = false;
if let Some(sender) = mutex_hash if let Some(sender) =
.entry(pid) mutex_hash.entry(pid).or_default().entry(scalar.arg1).or_default().pop_front()
.or_default()
.entry(scalar.arg1)
.or_default()
.pop_front()
{ {
xous::return_scalar(sender, 0).unwrap(); xous::return_scalar(sender, 0).unwrap();
returned = true; returned = true;
@ -302,12 +269,12 @@ fn main() -> ! {
pid.map(|v| v.get()).unwrap_or_default(), pid.map(|v| v.get()).unwrap_or_default(),
scalar.arg1 scalar.arg1
); );
if !mutex_ready_table if !mutex_ready_table.entry(pid).or_default().insert(scalar.arg1) {
.entry(pid) log::error!(
.or_default() "attempted to ready mutex {:08x} for PID {:?}, but there was already one waiting",
.insert(scalar.arg1) scalar.arg1,
{ pid
log::error!("attempted to ready mutex {:08x} for PID {:?}, but there was already one waiting", scalar.arg1, pid); );
} }
} }
@ -327,15 +294,15 @@ fn main() -> ! {
// Remove all instances of this mutex from the mutex hash // Remove all instances of this mutex from the mutex hash
if let Some(responders) = mutex_hash.entry(pid).or_default().remove(&scalar.arg1) { if let Some(responders) = mutex_hash.entry(pid).or_default().remove(&scalar.arg1) {
if responders.len() != 0 { if responders.len() != 0 {
log::error!("When freeing mutex {:08x}, there were {} mutexes awaiting to be unlocked", scalar.arg1, responders.len()); log::error!(
"When freeing mutex {:08x}, there were {} mutexes awaiting to be unlocked",
scalar.arg1,
responders.len()
);
} }
} }
if mutex_ready_table if mutex_ready_table.entry(pid).or_default().remove(&scalar.arg1) {
.entry(pid)
.or_default()
.remove(&scalar.arg1)
{
log::error!( log::error!(
"When freeing mutex {:08x}, there was one pending unlock request that hasn't been answered", "When freeing mutex {:08x}, there was one pending unlock request that hasn't been answered",
scalar.arg1, scalar.arg1,
@ -346,9 +313,7 @@ fn main() -> ! {
api::Opcode::WaitForCondition => { api::Opcode::WaitForCondition => {
let pid = msg.sender.pid(); let pid = msg.sender.pid();
let Some(scalar) = msg.body.scalar_message_mut() else { let Some(scalar) = msg.body.scalar_message_mut() else {
log::trace!( log::trace!("sender made WaitForCondition request that wasn't a BlockingScalar Message");
"sender made WaitForCondition request that wasn't a BlockingScalar Message"
);
continue; continue;
}; };
@ -385,12 +350,7 @@ fn main() -> ! {
// Add this sender to the global notification table. This table is used // Add this sender to the global notification table. This table is used
// when notifying senders, which will unblock them and wake them up. // when notifying senders, which will unblock them and wake them up.
notify_table notify_table.entry(pid).or_default().entry(condvar).or_default().push_back(msg.sender);
.entry(pid)
.or_default()
.entry(condvar)
.or_default()
.push_back(msg.sender);
// If there is a timeout, then the ticktimer was paused above. Resume // If there is a timeout, then the ticktimer was paused above. Resume
// the ticktimer now that everything is settled. // the ticktimer now that everything is settled.
@ -416,11 +376,7 @@ fn main() -> ! {
let condvar = scalar.arg1; let condvar = scalar.arg1;
let mut requested_count: usize = scalar.arg2; let mut requested_count: usize = scalar.arg2;
let awaiting = notify_table let awaiting = notify_table.entry(pid).or_default().entry(condvar).or_default();
.entry(pid)
.or_default()
.entry(condvar)
.or_default();
// As a special case, if 0 conditions are requested to wake, notify all // As a special case, if 0 conditions are requested to wake, notify all
// waiting conditions. // waiting conditions.
@ -483,7 +439,9 @@ fn main() -> ! {
Err(xous::Error::ProcessNotFound) => { Err(xous::Error::ProcessNotFound) => {
log::error!( log::error!(
"process {} exited -- removing remaining entries for PID {:?}/condvar {:08x}", "process {} exited -- removing remaining entries for PID {:?}/condvar {:08x}",
pid.map(|v| v.get()).unwrap_or_default(), pid, condvar pid.map(|v| v.get()).unwrap_or_default(),
pid,
condvar
); );
mutex_hash.remove(&pid); mutex_hash.remove(&pid);
} }
@ -507,9 +465,7 @@ fn main() -> ! {
api::Opcode::FreeCondition => { api::Opcode::FreeCondition => {
let pid = msg.sender.pid(); let pid = msg.sender.pid();
let Some(scalar) = msg.body.scalar_message() else { let Some(scalar) = msg.body.scalar_message() else {
info!( info!("sender made FreeCondition request that wasn't a Scalar or BlockingScalar Message");
"sender made FreeCondition request that wasn't a Scalar or BlockingScalar Message"
);
continue; continue;
}; };
@ -519,11 +475,7 @@ fn main() -> ! {
let condvar = scalar.arg1; let condvar = scalar.arg1;
let awaiting = notify_table let awaiting = notify_table.entry(pid).or_default().entry(condvar).or_default();
.entry(pid)
.or_default()
.entry(condvar)
.or_default();
if !awaiting.is_empty() { if !awaiting.is_empty() {
log::info!( log::info!(
@ -555,7 +507,9 @@ fn main() -> ! {
assert!(ticktimer.last_response() == entry); assert!(ticktimer.last_response() == entry);
log::error!( log::error!(
"got a request to destroy a condvar ({:08x}) that we just responded to with entry {:08x} -- suspect there's a thread waiting in the server queue to clean it up", "got a request to destroy a condvar ({:08x}) that we just responded to with entry {:08x} -- suspect there's a thread waiting in the server queue to clean it up",
condvar, entry.to_usize()); condvar,
entry.to_usize()
);
continue; continue;
} }
} }

View file

@ -1,8 +1,9 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use atsama5d27::tc::Tc; use atsama5d27::tc::Tc;
use log::error;
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
use log::{info, trace}; use log::{info, trace};
use log::error;
use utralib::*; use utralib::*;
use xous::arch::irq::IrqNumber; use xous::arch::irq::IrqNumber;
@ -90,13 +91,10 @@ impl XousTickTimer {
// no-op, the TC0 timer resets itself every time it's started // no-op, the TC0 timer resets itself every time it's started
} }
pub fn last_response(&self) -> &Option<TimerRequest> { pub fn last_response(&self) -> &Option<TimerRequest> { &self.last_response }
&self.last_response
} pub fn clear_last_response(&mut self) { self.last_response = None; }
pub fn clear_last_response(&mut self) {
self.last_response = None;
}
pub fn raw_ticktime(&self) -> u32 { pub fn raw_ticktime(&self) -> u32 {
let ticktime = self.timer.counter(); let ticktime = self.timer.counter();
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
@ -138,11 +136,7 @@ impl XousTickTimer {
let irq_target = request.msec.saturating_sub(self.running_counter as i64); let irq_target = request.msec.saturating_sub(self.running_counter as i64);
if irq_target > u32::MAX as i64 { if irq_target > u32::MAX as i64 {
error!( error!("Invalid sleep target: {} can't be more than {} ms", irq_target, u32::MAX);
"Invalid sleep target: {} can't be more than {} ms",
irq_target,
u32::MAX
);
return; return;
} }
@ -214,10 +208,7 @@ impl XousTickTimer {
self.schedule_response(next_response); self.schedule_response(next_response);
} else { } else {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
info!( info!("not scheduling a response since the sleep heap is empty ({:?})", sleep_heap);
"not scheduling a response since the sleep heap is empty ({:?})",
sleep_heap
);
} }
} }
@ -237,7 +228,12 @@ impl XousTickTimer {
log::trace!("Elapsed: {}", elapsed); log::trace!("Elapsed: {}", elapsed);
self.clear_last_response(); self.clear_last_response();
log::trace!("Increasing running counter {} by {}: {}", self.running_counter, elapsed, self.running_counter + elapsed as u64); log::trace!(
"Increasing running counter {} by {}: {}",
self.running_counter,
elapsed,
self.running_counter + elapsed as u64
);
self.running_counter += elapsed as u64; self.running_counter += elapsed as u64;
// If we have a new sleep request, add it to the heap. // If we have a new sleep request, add it to the heap.

View file

@ -3,15 +3,14 @@ const TICKS_PER_MS: u64 = 1;
use core::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; use core::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
use std::collections::BTreeMap; use std::collections::BTreeMap;
use crate::TimeoutExpiry;
use crate::TimerRequest;
#[cfg(feature = "susres")] #[cfg(feature = "susres")]
use susres::{RegManager, RegOrField, SuspendResume}; use susres::{RegManager, RegOrField, SuspendResume};
use utralib::generated::*; use utralib::generated::*;
use xous::definitions::MessageSender; use xous::definitions::MessageSender;
use crate::TimeoutExpiry;
use crate::TimerRequest;
/// Latency slack may be necessary for hardware implementations that can't handle /// Latency slack may be necessary for hardware implementations that can't handle
/// events that happened in the past. However, for Precursor hardware, alarms will /// events that happened in the past. However, for Precursor hardware, alarms will
/// trigger based on a "less than or equal to current time" basis, so even if an /// trigger based on a "less than or equal to current time" basis, so even if an
@ -140,9 +139,7 @@ impl XousTickTimer {
/// ///
/// This function is safe to call only if interrupts are disabled. Otherwise, /// This function is safe to call only if interrupts are disabled. Otherwise,
/// the value may change during processing. /// the value may change during processing.
pub unsafe fn sequence_number() -> usize { pub unsafe fn sequence_number() -> usize { TICKTIMER_SEQUENCE_NUMBER.load(Ordering::Relaxed) }
TICKTIMER_SEQUENCE_NUMBER.load(Ordering::Relaxed)
}
pub fn init(&mut self) { pub fn init(&mut self) {
xous::claim_interrupt( xous::claim_interrupt(
@ -154,14 +151,11 @@ impl XousTickTimer {
#[cfg(feature = "susres")] #[cfg(feature = "susres")]
{ {
self.ticktimer_sr_manager self.ticktimer_sr_manager.push(RegOrField::Reg(utra::ticktimer::MSLEEP_TARGET0), None);
.push(RegOrField::Reg(utra::ticktimer::MSLEEP_TARGET0), None); self.ticktimer_sr_manager.push(RegOrField::Reg(utra::ticktimer::MSLEEP_TARGET1), None);
self.ticktimer_sr_manager
.push(RegOrField::Reg(utra::ticktimer::MSLEEP_TARGET1), None);
self.ticktimer_sr_manager self.ticktimer_sr_manager
.push_fixed_value(RegOrField::Reg(utra::ticktimer::EV_PENDING), 0xFFFF_FFFF); .push_fixed_value(RegOrField::Reg(utra::ticktimer::EV_PENDING), 0xFFFF_FFFF);
self.ticktimer_sr_manager self.ticktimer_sr_manager.push(RegOrField::Reg(utra::ticktimer::EV_ENABLE), None);
.push(RegOrField::Reg(utra::ticktimer::EV_ENABLE), None);
} }
} }
@ -177,9 +171,7 @@ impl XousTickTimer {
time time
} }
pub fn elapsed_ms(&self) -> u64 { pub fn elapsed_ms(&self) -> u64 { self.raw_ticktime() / TICKS_PER_MS }
self.raw_ticktime() / TICKS_PER_MS
}
pub fn stop_interrupt(&mut self) -> Option<TimerRequest> { pub fn stop_interrupt(&mut self) -> Option<TimerRequest> {
// Disable the timer // Disable the timer
@ -205,11 +197,7 @@ impl XousTickTimer {
pub fn schedule_response(&mut self, request: TimerRequest) { pub fn schedule_response(&mut self, request: TimerRequest) {
let irq_target = request.msec.to_i64().wrapping_add(LATENCY_SLACK_MS); let irq_target = request.msec.to_i64().wrapping_add(LATENCY_SLACK_MS);
log::trace!( log::trace!("setting a response at {} ms (current time: {} ms)", irq_target, self.elapsed_ms());
"setting a response at {} ms (current time: {} ms)",
irq_target,
self.elapsed_ms()
);
// Disable the timer interrupt // Disable the timer interrupt
assert!(self.csr.rf(utra::ticktimer::EV_ENABLE_ALARM) == 0); assert!(self.csr.rf(utra::ticktimer::EV_ENABLE_ALARM) == 0);
@ -219,10 +207,8 @@ impl XousTickTimer {
self.current_response = Some(request); self.current_response = Some(request);
// Set the new target time // Set the new target time
self.csr self.csr.wo(utra::ticktimer::MSLEEP_TARGET1, (irq_target >> 32) as _);
.wo(utra::ticktimer::MSLEEP_TARGET1, (irq_target >> 32) as _); self.csr.wo(utra::ticktimer::MSLEEP_TARGET0, irq_target as _);
self.csr
.wo(utra::ticktimer::MSLEEP_TARGET0, irq_target as _);
// Clear previous interrupt (if any) // Clear previous interrupt (if any)
self.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1); self.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1);
@ -233,20 +219,14 @@ impl XousTickTimer {
#[allow(dead_code)] #[allow(dead_code)]
#[cfg(feature = "watchdog")] #[cfg(feature = "watchdog")]
pub fn reset_wdt(&mut self) { pub fn reset_wdt(&mut self) { self.wdt.wfo(utra::wdt::WATCHDOG_RESET_WDT, 1); }
self.wdt.wfo(utra::wdt::WATCHDOG_RESET_WDT, 1);
}
#[allow(dead_code)] #[allow(dead_code)]
#[cfg(feature = "watchdog")] #[cfg(feature = "watchdog")]
pub fn check_wdt(&mut self) { pub fn check_wdt(&mut self) {
let state = self.wdt.r(utra::wdt::STATE); let state = self.wdt.r(utra::wdt::STATE);
if state & self.wdt.ms(utra::wdt::STATE_DISARMED, 1) == 0 { if state & self.wdt.ms(utra::wdt::STATE_DISARMED, 1) == 0 {
log::info!( log::info!("{} WDT is not disarmed, state: 0x{:x}", self.elapsed_ms(), state);
"{} WDT is not disarmed, state: 0x{:x}",
self.elapsed_ms(),
state
);
} }
} }
@ -271,7 +251,8 @@ impl XousTickTimer {
self.wdt.wfo(utra::wdt::WATCHDOG_ENABLE, 1); self.wdt.wfo(utra::wdt::WATCHDOG_ENABLE, 1);
} }
// manually clear any pending ticktimer events. This is mainly releveant for a "touch-and-go" simulated suspend. // manually clear any pending ticktimer events. This is mainly releveant for a "touch-and-go"
// simulated suspend.
self.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1); self.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1);
#[cfg(feature = "watchdog")] #[cfg(feature = "watchdog")]
@ -279,10 +260,7 @@ impl XousTickTimer {
#[cfg(feature = "susres")] #[cfg(feature = "susres")]
self.ticktimer_sr_manager.resume(); self.ticktimer_sr_manager.resume();
log::trace!( log::trace!("ticktimer enable: {}", self.csr.r(utra::ticktimer::EV_ENABLE));
"ticktimer enable: {}",
self.csr.r(utra::ticktimer::EV_ENABLE)
);
log::trace!( log::trace!(
"ticktimer time/target: {}/{}", "ticktimer time/target: {}/{}",
self.csr.r(utra::ticktimer::TIME0), self.csr.r(utra::ticktimer::TIME0),
@ -306,7 +284,10 @@ impl XousTickTimer {
if let Some(current) = self.stop_interrupt() { if let Some(current) = self.stop_interrupt() {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!("Existing request was {:?}", current); log::info!("Existing request was {:?}", current);
assert!(sleep_heap.insert(current.msec, current).is_none(), "Existing sleep_heap entry would be overwritten"); assert!(
sleep_heap.insert(current.msec, current).is_none(),
"Existing sleep_heap entry would be overwritten"
);
} else { } else {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!("There was no existing sleep() request"); log::info!("There was no existing sleep() request");
@ -331,10 +312,7 @@ impl XousTickTimer {
self.schedule_response(next_response); self.schedule_response(next_response);
} else { } else {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!( log::info!("not scheduling a response since the sleep heap is empty ({:?})", sleep_heap);
"not scheduling a response since the sleep heap is empty ({:?})",
sleep_heap
);
} }
} }
@ -363,7 +341,10 @@ impl XousTickTimer {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!("Modified, the request was: {:?}", request); log::info!("Modified, the request was: {:?}", request);
assert!(sleep_heap.insert(request.msec, request).is_none(), "Existing sleep_heap entry would be overwritten"); assert!(
sleep_heap.insert(request.msec, request).is_none(),
"Existing sleep_heap entry would be overwritten"
);
} else { } else {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!("No new sleep request"); log::info!("No new sleep request");

View file

@ -1,25 +1,22 @@
use crate::RequestKind;
use crate::TimeoutExpiry;
use crate::TimerRequest;
use num_traits::ToPrimitive;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::convert::TryInto; use std::convert::TryInto;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use num_traits::ToPrimitive;
use xous::definitions::MessageSender; use xous::definitions::MessageSender;
use crate::RequestKind;
use crate::TimeoutExpiry;
use crate::TimerRequest;
/// The Message ID of the last message we responded to /// The Message ID of the last message we responded to
static LAST_RESPONDER: AtomicUsize = AtomicUsize::new(0); static LAST_RESPONDER: AtomicUsize = AtomicUsize::new(0);
#[derive(Debug)] #[derive(Debug)]
enum SleepComms { enum SleepComms {
InterruptSleep, InterruptSleep,
StartSleep( StartSleep(xous::MessageSender, i64 /* ms */, u64 /* elapsed */),
xous::MessageSender,
i64, /* ms */
u64, /* elapsed */
),
} }
pub struct XousTickTimer { pub struct XousTickTimer {
start: std::time::Instant, start: std::time::Instant,
@ -36,11 +33,12 @@ impl XousTickTimer {
let mut timeout = None; let mut timeout = None;
let mut current_response: Option<TimerRequest> = None; let mut current_response: Option<TimerRequest> = None;
loop { loop {
log::trace!("waiting for{} for an event", timeout.map(|d: Duration| format!(" {} ms", d.as_millis())).unwrap_or("ever".to_string())); log::trace!(
"waiting for{} for an event",
timeout.map(|d: Duration| format!(" {} ms", d.as_millis())).unwrap_or("ever".to_string())
);
let result = match timeout { let result = match timeout {
None => sleep_receiver None => sleep_receiver.recv().map_err(|_| RecvTimeoutError::Disconnected),
.recv()
.map_err(|_| RecvTimeoutError::Disconnected),
Some(s) => sleep_receiver.recv_timeout(s), Some(s) => sleep_receiver.recv_timeout(s),
}; };
match result { match result {
@ -77,11 +75,7 @@ impl XousTickTimer {
let mut duration = expiry - (elapsed as i64); let mut duration = expiry - (elapsed as i64);
if duration > 0 { if duration > 0 {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!( log::info!("Starting sleep for {} ms, returning to {}", duration, new_sender);
"Starting sleep for {} ms, returning to {}",
duration,
new_sender
);
} else { } else {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!( log::info!(
@ -91,9 +85,7 @@ impl XousTickTimer {
); );
duration = 0; duration = 0;
} }
timeout = Some(Duration::from_millis( timeout = Some(Duration::from_millis(duration.try_into().unwrap()));
duration.try_into().unwrap(),
));
current_response = Some(TimerRequest { current_response = Some(TimerRequest {
sender: new_sender, sender: new_sender,
msec: expiry.into(), msec: expiry.into(),
@ -106,11 +98,7 @@ impl XousTickTimer {
}) })
.unwrap(); .unwrap();
XousTickTimer { XousTickTimer { start: Instant::now(), time_remaining_receiver, sleep_comms: sleep_sender }
start: Instant::now(),
time_remaining_receiver,
sleep_comms: sleep_sender,
}
} }
/// Used for sanity-checking to make sure we're not double-responding /// Used for sanity-checking to make sure we're not double-responding
@ -118,13 +106,9 @@ impl XousTickTimer {
MessageSender::from_usize(LAST_RESPONDER.load(Ordering::Relaxed)) MessageSender::from_usize(LAST_RESPONDER.load(Ordering::Relaxed))
} }
pub fn reset(&mut self) { pub fn reset(&mut self) { self.start = std::time::Instant::now(); }
self.start = std::time::Instant::now();
}
pub fn elapsed_ms(&self) -> u64 { pub fn elapsed_ms(&self) -> u64 { self.start.elapsed().as_millis().try_into().unwrap() }
self.start.elapsed().as_millis().try_into().unwrap()
}
pub fn stop_interrupt(&mut self) -> Option<TimerRequest> { pub fn stop_interrupt(&mut self) -> Option<TimerRequest> {
self.sleep_comms.send(SleepComms::InterruptSleep).unwrap(); self.sleep_comms.send(SleepComms::InterruptSleep).unwrap();
@ -140,11 +124,7 @@ impl XousTickTimer {
request.sender request.sender
); );
self.sleep_comms self.sleep_comms
.send(SleepComms::StartSleep( .send(SleepComms::StartSleep(request.sender, request.msec.to_i64(), self.elapsed_ms()))
request.sender,
request.msec.to_i64(),
self.elapsed_ms(),
))
.unwrap(); .unwrap();
} }
@ -152,15 +132,15 @@ impl XousTickTimer {
pub fn reset_wdt(&self) { pub fn reset_wdt(&self) {
// dummy function, does nothing // dummy function, does nothing
} }
pub fn register_suspend_listener(
&self, pub fn register_suspend_listener(&self, _opcode: u32, _cid: xous::CID) -> Result<(), xous::Error> {
_opcode: u32,
_cid: xous::CID,
) -> Result<(), xous::Error> {
Ok(()) Ok(())
} }
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) {}
/// Disable the sleep interrupt and remove the currently-pending sleep item. /// Disable the sleep interrupt and remove the currently-pending sleep item.
@ -174,7 +154,10 @@ impl XousTickTimer {
if let Some(current) = self.stop_interrupt() { if let Some(current) = self.stop_interrupt() {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!("Existing request was {:?}", current); log::info!("Existing request was {:?}", current);
assert!(sleep_heap.insert(current.msec, current).is_none(), "Existing sleep_heap entry would be overwritten"); assert!(
sleep_heap.insert(current.msec, current).is_none(),
"Existing sleep_heap entry would be overwritten"
);
} else { } else {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!("There was no existing sleep() request"); log::info!("There was no existing sleep() request");
@ -198,10 +181,7 @@ impl XousTickTimer {
self.schedule_response(next_response); self.schedule_response(next_response);
} else { } else {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!( log::info!("not scheduling a response since the sleep heap is empty ({:?})", sleep_heap);
"not scheduling a response since the sleep heap is empty ({:?})",
sleep_heap
);
} }
} }
@ -231,7 +211,10 @@ impl XousTickTimer {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!("Modified, the request was: {:?}", request); log::info!("Modified, the request was: {:?}", request);
assert!(sleep_heap.insert(request.msec, request).is_none(), "Existing sleep_heap entry would be overwritten"); assert!(
sleep_heap.insert(request.msec, request).is_none(),
"Existing sleep_heap entry would be overwritten"
);
} else { } else {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!("No new sleep request"); log::info!("No new sleep request");

View file

@ -46,46 +46,33 @@ pub use cramium::*;
#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] #[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
pub(crate) struct TimeoutExpiry(i64); pub(crate) struct TimeoutExpiry(i64);
impl TimeoutExpiry { impl TimeoutExpiry {
pub fn to_i64(&self) -> i64 { pub fn to_i64(&self) -> i64 { self.0 }
self.0
}
} }
impl Add<i64> for TimeoutExpiry { impl Add<i64> for TimeoutExpiry {
type Output = TimeoutExpiry; type Output = TimeoutExpiry;
fn add(self, rhs: i64) -> Self::Output {
TimeoutExpiry(self.0 + rhs) fn add(self, rhs: i64) -> Self::Output { TimeoutExpiry(self.0 + rhs) }
}
} }
impl AddAssign<i64> for TimeoutExpiry { impl AddAssign<i64> for TimeoutExpiry {
fn add_assign(&mut self, rhs: i64) { fn add_assign(&mut self, rhs: i64) { self.0 += rhs; }
self.0 += rhs;
}
} }
impl core::fmt::Display for TimeoutExpiry { impl core::fmt::Display for TimeoutExpiry {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}ms", self.0) }
write!(f, "{}ms", self.0)
}
} }
impl core::fmt::Debug for TimeoutExpiry { impl core::fmt::Debug for TimeoutExpiry {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}ms", self.0) }
write!(f, "{}ms", self.0)
}
} }
impl From<i64> for TimeoutExpiry { impl From<i64> for TimeoutExpiry {
fn from(item: i64) -> Self { fn from(item: i64) -> Self { TimeoutExpiry(item) }
TimeoutExpiry(item)
}
} }
impl From<usize> for TimeoutExpiry { impl From<usize> for TimeoutExpiry {
fn from(item: usize) -> Self { fn from(item: usize) -> Self { TimeoutExpiry(item as i64) }
TimeoutExpiry(item as i64)
}
} }
#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] #[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
@ -127,13 +114,9 @@ impl core::cmp::Ord for TimerRequest {
} }
impl core::cmp::PartialOrd for TimerRequest { impl core::cmp::PartialOrd for TimerRequest {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { Some(self.cmp(other)) }
Some(self.cmp(other))
}
} }
impl core::cmp::PartialEq for TimerRequest { impl core::cmp::PartialEq for TimerRequest {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool { self.msec == other.msec && self.sender == other.sender }
self.msec == other.msec && self.sender == other.sender
}
} }

View file

@ -3,14 +3,13 @@ const TICKS_PER_MS: u64 = 1;
use core::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; use core::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
use std::collections::BTreeMap; use std::collections::BTreeMap;
use crate::TimeoutExpiry;
use crate::TimerRequest;
use susres::{RegManager, RegOrField, SuspendResume}; use susres::{RegManager, RegOrField, SuspendResume};
use utralib::generated::*; use utralib::generated::*;
use xous::definitions::MessageSender; use xous::definitions::MessageSender;
use crate::TimeoutExpiry;
use crate::TimerRequest;
/// Latency slack may be necessary for hardware implementations that can't handle /// Latency slack may be necessary for hardware implementations that can't handle
/// events that happened in the past. However, for Precursor hardware, alarms will /// events that happened in the past. However, for Precursor hardware, alarms will
/// trigger based on a "less than or equal to current time" basis, so even if an /// trigger based on a "less than or equal to current time" basis, so even if an
@ -130,9 +129,7 @@ impl XousTickTimer {
/// ///
/// This function is safe to call only if interrupts are disabled. Otherwise, /// This function is safe to call only if interrupts are disabled. Otherwise,
/// the value may change during processing. /// the value may change during processing.
pub unsafe fn sequence_number() -> usize { pub unsafe fn sequence_number() -> usize { TICKTIMER_SEQUENCE_NUMBER.load(Ordering::Relaxed) }
TICKTIMER_SEQUENCE_NUMBER.load(Ordering::Relaxed)
}
pub fn init(&mut self) { pub fn init(&mut self) {
xous::claim_interrupt( xous::claim_interrupt(
@ -142,14 +139,10 @@ impl XousTickTimer {
) )
.expect("couldn't claim irq"); .expect("couldn't claim irq");
self.ticktimer_sr_manager self.ticktimer_sr_manager.push(RegOrField::Reg(utra::ticktimer::MSLEEP_TARGET0), None);
.push(RegOrField::Reg(utra::ticktimer::MSLEEP_TARGET0), None); self.ticktimer_sr_manager.push(RegOrField::Reg(utra::ticktimer::MSLEEP_TARGET1), None);
self.ticktimer_sr_manager self.ticktimer_sr_manager.push_fixed_value(RegOrField::Reg(utra::ticktimer::EV_PENDING), 0xFFFF_FFFF);
.push(RegOrField::Reg(utra::ticktimer::MSLEEP_TARGET1), None); self.ticktimer_sr_manager.push(RegOrField::Reg(utra::ticktimer::EV_ENABLE), None);
self.ticktimer_sr_manager
.push_fixed_value(RegOrField::Reg(utra::ticktimer::EV_PENDING), 0xFFFF_FFFF);
self.ticktimer_sr_manager
.push(RegOrField::Reg(utra::ticktimer::EV_ENABLE), None);
} }
pub fn reset(&mut self) { pub fn reset(&mut self) {
@ -164,9 +157,7 @@ impl XousTickTimer {
time time
} }
pub fn elapsed_ms(&self) -> u64 { pub fn elapsed_ms(&self) -> u64 { self.raw_ticktime() / TICKS_PER_MS }
self.raw_ticktime() / TICKS_PER_MS
}
pub fn stop_interrupt(&mut self) -> Option<TimerRequest> { pub fn stop_interrupt(&mut self) -> Option<TimerRequest> {
// Disable the timer // Disable the timer
@ -192,11 +183,7 @@ impl XousTickTimer {
pub fn schedule_response(&mut self, request: TimerRequest) { pub fn schedule_response(&mut self, request: TimerRequest) {
let irq_target = request.msec.to_i64().wrapping_add(LATENCY_SLACK_MS); let irq_target = request.msec.to_i64().wrapping_add(LATENCY_SLACK_MS);
log::trace!( log::trace!("setting a response at {} ms (current time: {} ms)", irq_target, self.elapsed_ms());
"setting a response at {} ms (current time: {} ms)",
irq_target,
self.elapsed_ms()
);
// Disable the timer interrupt // Disable the timer interrupt
assert!(self.csr.rf(utra::ticktimer::EV_ENABLE_ALARM) == 0); assert!(self.csr.rf(utra::ticktimer::EV_ENABLE_ALARM) == 0);
@ -206,10 +193,8 @@ impl XousTickTimer {
self.current_response = Some(request); self.current_response = Some(request);
// Set the new target time // Set the new target time
self.csr self.csr.wo(utra::ticktimer::MSLEEP_TARGET1, (irq_target >> 32) as _);
.wo(utra::ticktimer::MSLEEP_TARGET1, (irq_target >> 32) as _); self.csr.wo(utra::ticktimer::MSLEEP_TARGET0, irq_target as _);
self.csr
.wo(utra::ticktimer::MSLEEP_TARGET0, irq_target as _);
// Clear previous interrupt (if any) // Clear previous interrupt (if any)
self.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1); self.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1);
@ -219,19 +204,13 @@ impl XousTickTimer {
} }
#[allow(dead_code)] #[allow(dead_code)]
pub fn reset_wdt(&mut self) { pub fn reset_wdt(&mut self) { self.wdt.wfo(utra::wdt::WATCHDOG_RESET_WDT, 1); }
self.wdt.wfo(utra::wdt::WATCHDOG_RESET_WDT, 1);
}
#[allow(dead_code)] #[allow(dead_code)]
pub fn check_wdt(&mut self) { pub fn check_wdt(&mut self) {
let state = self.wdt.r(utra::wdt::STATE); let state = self.wdt.r(utra::wdt::STATE);
if state & self.wdt.ms(utra::wdt::STATE_DISARMED, 1) == 0 { if state & self.wdt.ms(utra::wdt::STATE_DISARMED, 1) == 0 {
log::info!( log::info!("{} WDT is not disarmed, state: 0x{:x}", self.elapsed_ms(), state);
"{} WDT is not disarmed, state: 0x{:x}",
self.elapsed_ms(),
state
);
} }
} }
@ -254,16 +233,14 @@ impl XousTickTimer {
self.wdt.wfo(utra::wdt::WATCHDOG_ENABLE, 1); self.wdt.wfo(utra::wdt::WATCHDOG_ENABLE, 1);
} }
// manually clear any pending ticktimer events. This is mainly releveant for a "touch-and-go" simulated suspend. // manually clear any pending ticktimer events. This is mainly releveant for a "touch-and-go"
// simulated suspend.
self.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1); self.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1);
self.wdt_sr_manager.resume(); self.wdt_sr_manager.resume();
self.ticktimer_sr_manager.resume(); self.ticktimer_sr_manager.resume();
log::trace!( log::trace!("ticktimer enable: {}", self.csr.r(utra::ticktimer::EV_ENABLE));
"ticktimer enable: {}",
self.csr.r(utra::ticktimer::EV_ENABLE)
);
log::trace!( log::trace!(
"ticktimer time/target: {}/{}", "ticktimer time/target: {}/{}",
self.csr.r(utra::ticktimer::TIME0), self.csr.r(utra::ticktimer::TIME0),
@ -287,7 +264,10 @@ impl XousTickTimer {
if let Some(current) = self.stop_interrupt() { if let Some(current) = self.stop_interrupt() {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!("Existing request was {:?}", current); log::info!("Existing request was {:?}", current);
assert!(sleep_heap.insert(current.msec, current).is_none(), "Existing sleep_heap entry would be overwritten"); assert!(
sleep_heap.insert(current.msec, current).is_none(),
"Existing sleep_heap entry would be overwritten"
);
} else { } else {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!("There was no existing sleep() request"); log::info!("There was no existing sleep() request");
@ -312,10 +292,7 @@ impl XousTickTimer {
self.schedule_response(next_response); self.schedule_response(next_response);
} else { } else {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!( log::info!("not scheduling a response since the sleep heap is empty ({:?})", sleep_heap);
"not scheduling a response since the sleep heap is empty ({:?})",
sleep_heap
);
} }
} }
@ -344,7 +321,10 @@ impl XousTickTimer {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!("Modified, the request was: {:?}", request); log::info!("Modified, the request was: {:?}", request);
assert!(sleep_heap.insert(request.msec, request).is_none(), "Existing sleep_heap entry would be overwritten"); assert!(
sleep_heap.insert(request.msec, request).is_none(),
"Existing sleep_heap entry would be overwritten"
);
} else { } else {
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
log::info!("No new sleep request"); log::info!("No new sleep request");