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;
use platform::implementation::*;
use platform::*;
#[cfg(not(any(target_arch = "arm", feature = "cramium-soc", feature = "cramium-fpga")))]
use susres::SuspendOrder;
@ -37,13 +36,13 @@ fn main() -> ! {
log::info!("****************************************************************");
}
let ticktimer_server = xous::create_server_with_address(b"ticktimer-server")
.expect("Couldn't create Ticktimer server");
let ticktimer_server =
xous::create_server_with_address(b"ticktimer-server").expect("Couldn't create Ticktimer server");
info!("Server started with SID {:?}", ticktimer_server);
// 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())
.expect("couldn't connect to self");
let ticktimer_client =
xous::connect(xous::SID::from_bytes(b"ticktimer-server").unwrap()).expect("couldn't connect to self");
// Create a new ticktimer object
let mut ticktimer = XousTickTimer::new(ticktimer_client);
@ -56,17 +55,12 @@ fn main() -> ! {
let xns = xous_names::XousNames::new().unwrap();
#[cfg(not(any(target_arch = "arm", feature = "cramium-soc", feature = "cramium-fpga")))]
let sr_cid =
xous::connect(ticktimer_server).expect("couldn't create suspend callback connection");
let sr_cid = xous::connect(ticktimer_server).expect("couldn't create suspend callback connection");
#[cfg(not(any(target_arch = "arm", feature = "cramium-soc", feature = "cramium-fpga")))]
let mut susres = susres::Susres::new(
Some(SuspendOrder::Last),
&xns,
api::Opcode::SuspendResume as u32,
sr_cid,
)
.expect("couldn't create suspend/resume object");
let mut susres =
susres::Susres::new(Some(SuspendOrder::Last), &xns, api::Opcode::SuspendResume as u32, sr_cid)
.expect("couldn't create suspend/resume object");
// A list of all sleep requests in the system, sorted by the time at which it
// expires. That is, if a request comes in to sleep for 1000 ms, and the ticktimer
@ -81,10 +75,8 @@ fn main() -> ! {
// 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.
let mut notify_table: HashMap<
Option<xous::PID>,
HashMap<usize, VecDeque<xous::MessageSender>>,
> = HashMap::new();
let mut notify_table: HashMap<Option<xous::PID>, HashMap<usize, VecDeque<xous::MessageSender>>> =
HashMap::new();
// 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
@ -105,11 +97,9 @@ fn main() -> ! {
//#[cfg(feature = "watchdog")] // for debugging the watchdog
//ticktimer.check_wdt();
xous::reply_and_receive_next_legacy(ticktimer_server, &mut msg_opt, &mut return_type)
.unwrap();
xous::reply_and_receive_next_legacy(ticktimer_server, &mut msg_opt, &mut return_type).unwrap();
let msg = msg_opt.as_mut().unwrap();
let opcode = num_traits::FromPrimitive::from_usize(msg.body.id())
.unwrap_or(api::Opcode::InvalidCall);
let opcode = num_traits::FromPrimitive::from_usize(msg.body.id()).unwrap_or(api::Opcode::InvalidCall);
log::trace!("msg {:?}: {:x?}", opcode, msg);
match opcode {
api::Opcode::ElapsedMs => {
@ -147,21 +137,16 @@ fn main() -> ! {
// let timeout_queue = timeout_heap.entry(msg.sender.pid()).or_default();
ticktimer.recalculate_sleep(
&mut sleep_heap,
Some(TimerRequest {
msec: ms.into(),
sender,
kind: RequestKind::Sleep,
data: 0,
}),
Some(TimerRequest { msec: ms.into(), sender, kind: RequestKind::Sleep, data: 0 }),
);
}
}
api::Opcode::RecalculateSleep => {
if msg.sender.pid().map(|p| p.get()).unwrap_or_default() as u32
!= xous::process::id()
{
log::error!("got a RecalculateSleep message from a process other than the ticktimer server");
if msg.sender.pid().map(|p| p.get()).unwrap_or_default() as u32 != xous::process::id() {
log::error!(
"got a RecalculateSleep message from a process other than the ticktimer server"
);
continue;
}
@ -183,11 +168,7 @@ fn main() -> ! {
assert!(len_before == len_after);
// It should, however, still be in the notify hash. Remove it.
let awaiting = notify_table
.entry(sender.pid())
.or_default()
.entry(condvar)
.or_default();
let awaiting = notify_table.entry(sender.pid()).or_default().entry(condvar).or_default();
let len_before = awaiting.len();
awaiting.retain(|v| *v != sender);
let len_after = awaiting.len();
@ -195,8 +176,11 @@ fn main() -> ! {
// Note multiple events elapsing since the last recalculate. Theorized to be harmless.
if ticktimer.last_response() != sender {
log::warn!("Multiple events triggered before we could recalculate sleep: ticktimer.last_response() {:?} != sender {:?}; sleep_heap.len(): {}",
ticktimer.last_response(), sender, sleep_heap.len()
log::warn!(
"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, _, _, _, {
ticktimer.suspend();
#[cfg(not(any(
target_arch = "arm",
feature = "cramium-soc",
feature = "cramium-fpga"
)))]
susres
.suspend_until_resume(_token)
.expect("couldn't execute suspend/resume");
#[cfg(not(any(target_arch = "arm", feature = "cramium-soc", feature = "cramium-fpga")))]
susres.suspend_until_resume(_token).expect("couldn't execute suspend/resume");
ticktimer.resume();
}),
@ -227,9 +205,7 @@ fn main() -> ! {
api::Opcode::GetVersion => {
let mut buf = unsafe {
xous_ipc::Buffer::from_memory_message_mut(
msg.body.memory_message_mut().unwrap(),
)
xous_ipc::Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())
};
#[cfg(feature = "timestamp")]
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
// the message will get a response.
mutex_hash
.entry(pid)
.or_default()
.entry(mutex_id)
.or_default()
.push_back(msg.sender);
mutex_hash.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
// 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
let mut returned = false;
if let Some(sender) = mutex_hash
.entry(pid)
.or_default()
.entry(scalar.arg1)
.or_default()
.pop_front()
if let Some(sender) =
mutex_hash.entry(pid).or_default().entry(scalar.arg1).or_default().pop_front()
{
xous::return_scalar(sender, 0).unwrap();
returned = true;
@ -302,12 +269,12 @@ fn main() -> ! {
pid.map(|v| v.get()).unwrap_or_default(),
scalar.arg1
);
if !mutex_ready_table
.entry(pid)
.or_default()
.insert(scalar.arg1)
{
log::error!("attempted to ready mutex {:08x} for PID {:?}, but there was already one waiting", scalar.arg1, pid);
if !mutex_ready_table.entry(pid).or_default().insert(scalar.arg1) {
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
if let Some(responders) = mutex_hash.entry(pid).or_default().remove(&scalar.arg1) {
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
.entry(pid)
.or_default()
.remove(&scalar.arg1)
{
if mutex_ready_table.entry(pid).or_default().remove(&scalar.arg1) {
log::error!(
"When freeing mutex {:08x}, there was one pending unlock request that hasn't been answered",
scalar.arg1,
@ -346,9 +313,7 @@ fn main() -> ! {
api::Opcode::WaitForCondition => {
let pid = msg.sender.pid();
let Some(scalar) = msg.body.scalar_message_mut() else {
log::trace!(
"sender made WaitForCondition request that wasn't a BlockingScalar Message"
);
log::trace!("sender made WaitForCondition request that wasn't a BlockingScalar Message");
continue;
};
@ -385,12 +350,7 @@ fn main() -> ! {
// Add this sender to the global notification table. This table is used
// when notifying senders, which will unblock them and wake them up.
notify_table
.entry(pid)
.or_default()
.entry(condvar)
.or_default()
.push_back(msg.sender);
notify_table.entry(pid).or_default().entry(condvar).or_default().push_back(msg.sender);
// If there is a timeout, then the ticktimer was paused above. Resume
// the ticktimer now that everything is settled.
@ -416,11 +376,7 @@ fn main() -> ! {
let condvar = scalar.arg1;
let mut requested_count: usize = scalar.arg2;
let awaiting = notify_table
.entry(pid)
.or_default()
.entry(condvar)
.or_default();
let awaiting = notify_table.entry(pid).or_default().entry(condvar).or_default();
// As a special case, if 0 conditions are requested to wake, notify all
// waiting conditions.
@ -483,7 +439,9 @@ fn main() -> ! {
Err(xous::Error::ProcessNotFound) => {
log::error!(
"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);
}
@ -507,9 +465,7 @@ fn main() -> ! {
api::Opcode::FreeCondition => {
let pid = msg.sender.pid();
let Some(scalar) = msg.body.scalar_message() else {
info!(
"sender made FreeCondition request that wasn't a Scalar or BlockingScalar Message"
);
info!("sender made FreeCondition request that wasn't a Scalar or BlockingScalar Message");
continue;
};
@ -519,11 +475,7 @@ fn main() -> ! {
let condvar = scalar.arg1;
let awaiting = notify_table
.entry(pid)
.or_default()
.entry(condvar)
.or_default();
let awaiting = notify_table.entry(pid).or_default().entry(condvar).or_default();
if !awaiting.is_empty() {
log::info!(
@ -555,7 +507,9 @@ fn main() -> ! {
assert!(ticktimer.last_response() == entry);
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",
condvar, entry.to_usize());
condvar,
entry.to_usize()
);
continue;
}
}

View file

@ -1,8 +1,9 @@
use std::collections::BTreeMap;
use atsama5d27::tc::Tc;
use log::error;
#[cfg(feature = "debug-print")]
use log::{info, trace};
use log::error;
use utralib::*;
use xous::arch::irq::IrqNumber;
@ -46,7 +47,7 @@ fn handle_irq(_irq_no: usize, arg: *mut usize) {
arg4: 0,
}),
)
.ok();
.ok();
// Save the response so we can be sure we don't double-return messages.
xtt.last_response = Some(response);
@ -63,7 +64,7 @@ impl XousTickTimer {
0x1000, // 16K
xous::MemoryFlags::R | xous::MemoryFlags::W | xous::MemoryFlags::DEV,
)
.expect("couldn't map TC0 CSR range");
.expect("couldn't map TC0 CSR range");
let mut timer = Tc::with_alt_base_addr(csr.as_ptr() as u32);
timer.init();
@ -81,7 +82,7 @@ impl XousTickTimer {
handle_irq,
(&mut xtt) as *mut XousTickTimer as *mut usize,
)
.expect("couldn't claim irq");
.expect("couldn't claim irq");
xtt
}
@ -90,13 +91,10 @@ impl XousTickTimer {
// no-op, the TC0 timer resets itself every time it's started
}
pub fn last_response(&self) -> &Option<TimerRequest> {
&self.last_response
}
pub fn last_response(&self) -> &Option<TimerRequest> { &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 {
let ticktime = self.timer.counter();
#[cfg(feature = "debug-print")]
@ -138,11 +136,7 @@ impl XousTickTimer {
let irq_target = request.msec.saturating_sub(self.running_counter as i64);
if irq_target > u32::MAX as i64 {
error!(
"Invalid sleep target: {} can't be more than {} ms",
irq_target,
u32::MAX
);
error!("Invalid sleep target: {} can't be more than {} ms", irq_target, u32::MAX);
return;
}
@ -214,10 +208,7 @@ impl XousTickTimer {
self.schedule_response(next_response);
} else {
#[cfg(feature = "debug-print")]
info!(
"not scheduling a response since the sleep heap is empty ({:?})",
sleep_heap
);
info!("not scheduling a response since the sleep heap is empty ({:?})", sleep_heap);
}
}
@ -237,7 +228,12 @@ impl XousTickTimer {
log::trace!("Elapsed: {}", elapsed);
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;
// 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 std::collections::BTreeMap;
use crate::TimeoutExpiry;
use crate::TimerRequest;
#[cfg(feature="susres")]
#[cfg(feature = "susres")]
use susres::{RegManager, RegOrField, SuspendResume};
use utralib::generated::*;
use xous::definitions::MessageSender;
use crate::TimeoutExpiry;
use crate::TimerRequest;
/// Latency slack may be necessary for hardware implementations that can't handle
/// 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
@ -24,11 +23,11 @@ const LATENCY_SLACK_MS: i64 = 0;
pub struct XousTickTimer {
csr: utralib::CSR<u32>,
current_response: Option<TimerRequest>,
#[cfg(feature="susres")]
#[cfg(feature = "susres")]
ticktimer_sr_manager: RegManager<{ utra::ticktimer::TICKTIMER_NUMREGS }>,
#[cfg(feature="watchdog")]
#[cfg(feature = "watchdog")]
wdt_sr_manager: RegManager<{ utra::wdt::WDT_NUMREGS }>,
#[cfg(feature="watchdog")]
#[cfg(feature = "watchdog")]
wdt: utralib::CSR<u32>,
}
@ -91,7 +90,7 @@ impl XousTickTimer {
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("couldn't map Tick Timer CSR range");
#[cfg(feature="watchdog")]
#[cfg(feature = "watchdog")]
let wdt = xous::syscall::map_memory(
xous::MemoryAddress::new(utra::wdt::HW_WDT_BASE),
None,
@ -99,20 +98,20 @@ impl XousTickTimer {
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("couldn't map Watchdog timer CSR range");
#[cfg(feature="susres")]
#[cfg(feature = "susres")]
let ticktimer_sr_manager = RegManager::new(csr.as_mut_ptr() as *mut u32);
#[cfg(feature="watchdog")]
#[cfg(feature = "watchdog")]
let wdt_sr_manager = RegManager::new(wdt.as_mut_ptr() as *mut u32);
#[allow(unused_mut)] // sometimes mut, sometimes not based on feature flags.
let mut xtt = XousTickTimer {
csr: CSR::new(csr.as_mut_ptr() as *mut u32),
current_response: None,
#[cfg(feature="susres")]
#[cfg(feature = "susres")]
ticktimer_sr_manager,
#[cfg(feature="watchdog")]
#[cfg(feature = "watchdog")]
wdt_sr_manager,
#[cfg(feature="watchdog")]
#[cfg(feature = "watchdog")]
wdt: CSR::new(wdt.as_mut_ptr() as *mut u32),
};
@ -140,9 +139,7 @@ impl XousTickTimer {
///
/// This function is safe to call only if interrupts are disabled. Otherwise,
/// the value may change during processing.
pub unsafe fn sequence_number() -> usize {
TICKTIMER_SEQUENCE_NUMBER.load(Ordering::Relaxed)
}
pub unsafe fn sequence_number() -> usize { TICKTIMER_SEQUENCE_NUMBER.load(Ordering::Relaxed) }
pub fn init(&mut self) {
xous::claim_interrupt(
@ -152,16 +149,13 @@ impl XousTickTimer {
)
.expect("couldn't claim irq");
#[cfg(feature="susres")]
#[cfg(feature = "susres")]
{
self.ticktimer_sr_manager
.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_TARGET0), None);
self.ticktimer_sr_manager.push(RegOrField::Reg(utra::ticktimer::MSLEEP_TARGET1), 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);
self.ticktimer_sr_manager.push(RegOrField::Reg(utra::ticktimer::EV_ENABLE), None);
}
}
@ -177,9 +171,7 @@ impl XousTickTimer {
time
}
pub fn elapsed_ms(&self) -> u64 {
self.raw_ticktime() / TICKS_PER_MS
}
pub fn elapsed_ms(&self) -> u64 { self.raw_ticktime() / TICKS_PER_MS }
pub fn stop_interrupt(&mut self) -> Option<TimerRequest> {
// Disable the timer
@ -205,11 +197,7 @@ impl XousTickTimer {
pub fn schedule_response(&mut self, request: TimerRequest) {
let irq_target = request.msec.to_i64().wrapping_add(LATENCY_SLACK_MS);
log::trace!(
"setting a response at {} ms (current time: {} ms)",
irq_target,
self.elapsed_ms()
);
log::trace!("setting a response at {} ms (current time: {} ms)", irq_target, self.elapsed_ms());
// Disable the timer interrupt
assert!(self.csr.rf(utra::ticktimer::EV_ENABLE_ALARM) == 0);
@ -219,10 +207,8 @@ impl XousTickTimer {
self.current_response = Some(request);
// Set the new target time
self.csr
.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_TARGET1, (irq_target >> 32) as _);
self.csr.wo(utra::ticktimer::MSLEEP_TARGET0, irq_target as _);
// Clear previous interrupt (if any)
self.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1);
@ -232,21 +218,15 @@ impl XousTickTimer {
}
#[allow(dead_code)]
#[cfg(feature="watchdog")]
pub fn reset_wdt(&mut self) {
self.wdt.wfo(utra::wdt::WATCHDOG_RESET_WDT, 1);
}
#[cfg(feature = "watchdog")]
pub fn reset_wdt(&mut self) { self.wdt.wfo(utra::wdt::WATCHDOG_RESET_WDT, 1); }
#[allow(dead_code)]
#[cfg(feature="watchdog")]
#[cfg(feature = "watchdog")]
pub fn check_wdt(&mut self) {
let state = self.wdt.r(utra::wdt::STATE);
if state & self.wdt.ms(utra::wdt::STATE_DISARMED, 1) == 0 {
log::info!(
"{} WDT is not disarmed, state: 0x{:x}",
self.elapsed_ms(),
state
);
log::info!("{} WDT is not disarmed, state: 0x{:x}", self.elapsed_ms(), state);
}
}
@ -254,9 +234,9 @@ impl XousTickTimer {
// example of a generic suspend/resume template
pub fn suspend(&mut self) {
log::trace!("suspending");
#[cfg(feature="susres")]
#[cfg(feature = "susres")]
self.ticktimer_sr_manager.suspend();
#[cfg(feature="watchdog")]
#[cfg(feature = "watchdog")]
self.wdt_sr_manager.suspend();
// by writing this after suspend(), resume will get the prior value
@ -271,18 +251,16 @@ impl XousTickTimer {
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);
#[cfg(feature="watchdog")]
#[cfg(feature = "watchdog")]
self.wdt_sr_manager.resume();
#[cfg(feature="susres")]
#[cfg(feature = "susres")]
self.ticktimer_sr_manager.resume();
log::trace!(
"ticktimer enable: {}",
self.csr.r(utra::ticktimer::EV_ENABLE)
);
log::trace!("ticktimer enable: {}", self.csr.r(utra::ticktimer::EV_ENABLE));
log::trace!(
"ticktimer time/target: {}/{}",
self.csr.r(utra::ticktimer::TIME0),
@ -306,7 +284,10 @@ impl XousTickTimer {
if let Some(current) = self.stop_interrupt() {
#[cfg(feature = "debug-print")]
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 {
#[cfg(feature = "debug-print")]
log::info!("There was no existing sleep() request");
@ -331,10 +312,7 @@ impl XousTickTimer {
self.schedule_response(next_response);
} else {
#[cfg(feature = "debug-print")]
log::info!(
"not scheduling a response since the sleep heap is empty ({:?})",
sleep_heap
);
log::info!("not scheduling a response since the sleep heap is empty ({:?})", sleep_heap);
}
}
@ -363,7 +341,10 @@ impl XousTickTimer {
#[cfg(feature = "debug-print")]
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 {
#[cfg(feature = "debug-print")]
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::convert::TryInto;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use num_traits::ToPrimitive;
use xous::definitions::MessageSender;
use crate::RequestKind;
use crate::TimeoutExpiry;
use crate::TimerRequest;
/// The Message ID of the last message we responded to
static LAST_RESPONDER: AtomicUsize = AtomicUsize::new(0);
#[derive(Debug)]
enum SleepComms {
InterruptSleep,
StartSleep(
xous::MessageSender,
i64, /* ms */
u64, /* elapsed */
),
StartSleep(xous::MessageSender, i64 /* ms */, u64 /* elapsed */),
}
pub struct XousTickTimer {
start: std::time::Instant,
@ -36,11 +33,12 @@ impl XousTickTimer {
let mut timeout = None;
let mut current_response: Option<TimerRequest> = None;
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 {
None => sleep_receiver
.recv()
.map_err(|_| RecvTimeoutError::Disconnected),
None => sleep_receiver.recv().map_err(|_| RecvTimeoutError::Disconnected),
Some(s) => sleep_receiver.recv_timeout(s),
};
match result {
@ -77,11 +75,7 @@ impl XousTickTimer {
let mut duration = expiry - (elapsed as i64);
if duration > 0 {
#[cfg(feature = "debug-print")]
log::info!(
"Starting sleep for {} ms, returning to {}",
duration,
new_sender
);
log::info!("Starting sleep for {} ms, returning to {}", duration, new_sender);
} else {
#[cfg(feature = "debug-print")]
log::info!(
@ -91,9 +85,7 @@ impl XousTickTimer {
);
duration = 0;
}
timeout = Some(Duration::from_millis(
duration.try_into().unwrap(),
));
timeout = Some(Duration::from_millis(duration.try_into().unwrap()));
current_response = Some(TimerRequest {
sender: new_sender,
msec: expiry.into(),
@ -106,11 +98,7 @@ impl XousTickTimer {
})
.unwrap();
XousTickTimer {
start: Instant::now(),
time_remaining_receiver,
sleep_comms: sleep_sender,
}
XousTickTimer { start: Instant::now(), time_remaining_receiver, sleep_comms: sleep_sender }
}
/// 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))
}
pub fn reset(&mut self) {
self.start = std::time::Instant::now();
}
pub fn reset(&mut self) { self.start = std::time::Instant::now(); }
pub fn elapsed_ms(&self) -> u64 {
self.start.elapsed().as_millis().try_into().unwrap()
}
pub fn elapsed_ms(&self) -> u64 { self.start.elapsed().as_millis().try_into().unwrap() }
pub fn stop_interrupt(&mut self) -> Option<TimerRequest> {
self.sleep_comms.send(SleepComms::InterruptSleep).unwrap();
@ -140,11 +124,7 @@ impl XousTickTimer {
request.sender
);
self.sleep_comms
.send(SleepComms::StartSleep(
request.sender,
request.msec.to_i64(),
self.elapsed_ms(),
))
.send(SleepComms::StartSleep(request.sender, request.msec.to_i64(), self.elapsed_ms()))
.unwrap();
}
@ -152,15 +132,15 @@ impl XousTickTimer {
pub fn reset_wdt(&self) {
// dummy function, does nothing
}
pub fn register_suspend_listener(
&self,
_opcode: u32,
_cid: xous::CID,
) -> Result<(), xous::Error> {
pub fn register_suspend_listener(&self, _opcode: u32, _cid: xous::CID) -> Result<(), xous::Error> {
Ok(())
}
pub fn init(&mut self) {}
pub fn suspend(&self) {}
pub fn resume(&self) {}
/// Disable the sleep interrupt and remove the currently-pending sleep item.
@ -174,7 +154,10 @@ impl XousTickTimer {
if let Some(current) = self.stop_interrupt() {
#[cfg(feature = "debug-print")]
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 {
#[cfg(feature = "debug-print")]
log::info!("There was no existing sleep() request");
@ -198,10 +181,7 @@ impl XousTickTimer {
self.schedule_response(next_response);
} else {
#[cfg(feature = "debug-print")]
log::info!(
"not scheduling a response since the sleep heap is empty ({:?})",
sleep_heap
);
log::info!("not scheduling a response since the sleep heap is empty ({:?})", sleep_heap);
}
}
@ -231,7 +211,10 @@ impl XousTickTimer {
#[cfg(feature = "debug-print")]
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 {
#[cfg(feature = "debug-print")]
log::info!("No new sleep request");

View file

@ -46,46 +46,33 @@ pub use cramium::*;
#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
pub(crate) struct TimeoutExpiry(i64);
impl TimeoutExpiry {
pub fn to_i64(&self) -> i64 {
self.0
}
pub fn to_i64(&self) -> i64 { self.0 }
}
impl Add<i64> for 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 {
fn add_assign(&mut self, rhs: i64) {
self.0 += rhs;
}
fn add_assign(&mut self, rhs: i64) { self.0 += rhs; }
}
impl core::fmt::Display for TimeoutExpiry {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}ms", self.0)
}
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}ms", self.0) }
}
impl core::fmt::Debug for TimeoutExpiry {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}ms", self.0)
}
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}ms", self.0) }
}
impl From<i64> for TimeoutExpiry {
fn from(item: i64) -> Self {
TimeoutExpiry(item)
}
fn from(item: i64) -> Self { TimeoutExpiry(item) }
}
impl From<usize> for TimeoutExpiry {
fn from(item: usize) -> Self {
TimeoutExpiry(item as i64)
}
fn from(item: usize) -> Self { TimeoutExpiry(item as i64) }
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
@ -127,13 +114,9 @@ impl core::cmp::Ord for TimerRequest {
}
impl core::cmp::PartialOrd for TimerRequest {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { Some(self.cmp(other)) }
}
impl core::cmp::PartialEq for TimerRequest {
fn eq(&self, other: &Self) -> bool {
self.msec == other.msec && self.sender == other.sender
}
fn eq(&self, other: &Self) -> bool { 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 std::collections::BTreeMap;
use crate::TimeoutExpiry;
use crate::TimerRequest;
use susres::{RegManager, RegOrField, SuspendResume};
use utralib::generated::*;
use xous::definitions::MessageSender;
use crate::TimeoutExpiry;
use crate::TimerRequest;
/// Latency slack may be necessary for hardware implementations that can't handle
/// 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
@ -130,9 +129,7 @@ impl XousTickTimer {
///
/// This function is safe to call only if interrupts are disabled. Otherwise,
/// the value may change during processing.
pub unsafe fn sequence_number() -> usize {
TICKTIMER_SEQUENCE_NUMBER.load(Ordering::Relaxed)
}
pub unsafe fn sequence_number() -> usize { TICKTIMER_SEQUENCE_NUMBER.load(Ordering::Relaxed) }
pub fn init(&mut self) {
xous::claim_interrupt(
@ -142,14 +139,10 @@ impl XousTickTimer {
)
.expect("couldn't claim irq");
self.ticktimer_sr_manager
.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_fixed_value(RegOrField::Reg(utra::ticktimer::EV_PENDING), 0xFFFF_FFFF);
self.ticktimer_sr_manager
.push(RegOrField::Reg(utra::ticktimer::EV_ENABLE), None);
self.ticktimer_sr_manager.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_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) {
@ -164,9 +157,7 @@ impl XousTickTimer {
time
}
pub fn elapsed_ms(&self) -> u64 {
self.raw_ticktime() / TICKS_PER_MS
}
pub fn elapsed_ms(&self) -> u64 { self.raw_ticktime() / TICKS_PER_MS }
pub fn stop_interrupt(&mut self) -> Option<TimerRequest> {
// Disable the timer
@ -192,11 +183,7 @@ impl XousTickTimer {
pub fn schedule_response(&mut self, request: TimerRequest) {
let irq_target = request.msec.to_i64().wrapping_add(LATENCY_SLACK_MS);
log::trace!(
"setting a response at {} ms (current time: {} ms)",
irq_target,
self.elapsed_ms()
);
log::trace!("setting a response at {} ms (current time: {} ms)", irq_target, self.elapsed_ms());
// Disable the timer interrupt
assert!(self.csr.rf(utra::ticktimer::EV_ENABLE_ALARM) == 0);
@ -206,10 +193,8 @@ impl XousTickTimer {
self.current_response = Some(request);
// Set the new target time
self.csr
.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_TARGET1, (irq_target >> 32) as _);
self.csr.wo(utra::ticktimer::MSLEEP_TARGET0, irq_target as _);
// Clear previous interrupt (if any)
self.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1);
@ -219,19 +204,13 @@ impl XousTickTimer {
}
#[allow(dead_code)]
pub fn reset_wdt(&mut self) {
self.wdt.wfo(utra::wdt::WATCHDOG_RESET_WDT, 1);
}
pub fn reset_wdt(&mut self) { self.wdt.wfo(utra::wdt::WATCHDOG_RESET_WDT, 1); }
#[allow(dead_code)]
pub fn check_wdt(&mut self) {
let state = self.wdt.r(utra::wdt::STATE);
if state & self.wdt.ms(utra::wdt::STATE_DISARMED, 1) == 0 {
log::info!(
"{} WDT is not disarmed, state: 0x{:x}",
self.elapsed_ms(),
state
);
log::info!("{} 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);
}
// 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.wdt_sr_manager.resume();
self.ticktimer_sr_manager.resume();
log::trace!(
"ticktimer enable: {}",
self.csr.r(utra::ticktimer::EV_ENABLE)
);
log::trace!("ticktimer enable: {}", self.csr.r(utra::ticktimer::EV_ENABLE));
log::trace!(
"ticktimer time/target: {}/{}",
self.csr.r(utra::ticktimer::TIME0),
@ -287,7 +264,10 @@ impl XousTickTimer {
if let Some(current) = self.stop_interrupt() {
#[cfg(feature = "debug-print")]
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 {
#[cfg(feature = "debug-print")]
log::info!("There was no existing sleep() request");
@ -312,10 +292,7 @@ impl XousTickTimer {
self.schedule_response(next_response);
} else {
#[cfg(feature = "debug-print")]
log::info!(
"not scheduling a response since the sleep heap is empty ({:?})",
sleep_heap
);
log::info!("not scheduling a response since the sleep heap is empty ({:?})", sleep_heap);
}
}
@ -344,7 +321,10 @@ impl XousTickTimer {
#[cfg(feature = "debug-print")]
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 {
#[cfg(feature = "debug-print")]
log::info!("No new sleep request");