mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-15 08:30:02 +00:00
xous-ticktimer: split platform impls
This commit is contained in:
parent
f2e1a89f13
commit
1bbf5621fd
7 changed files with 473 additions and 452 deletions
|
|
@ -23,7 +23,11 @@ num-traits = {version = "0.2.14", default-features = false}
|
|||
xous-semver = "0.1.2"
|
||||
utralib = {version = "0.1.15", optional = true, default-features = false }
|
||||
|
||||
[target.'cfg(target_arch = "arm")'.dependencies]
|
||||
atsama5d27 = { git = "https://github.com/Foundation-Devices/atsama5d27.git", branch = "master" }
|
||||
|
||||
[features]
|
||||
atsama5d27 = ["utralib/atsama5d27"]
|
||||
precursor = ["utralib/precursor", "susres/precursor"]
|
||||
hosted = ["utralib/hosted", "susres/hosted"]
|
||||
renode = ["utralib/renode", "susres/renode"]
|
||||
|
|
|
|||
|
|
@ -10,455 +10,11 @@ use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
|
|||
|
||||
use log::{error, info};
|
||||
|
||||
type TimeoutExpiry = i64;
|
||||
mod platform;
|
||||
use platform::implementation::*;
|
||||
use platform::*;
|
||||
|
||||
#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
|
||||
pub enum RequestKind {
|
||||
Sleep = 0,
|
||||
Timeout = 1,
|
||||
}
|
||||
|
||||
#[derive(Eq)]
|
||||
pub struct TimerRequest {
|
||||
msec: TimeoutExpiry,
|
||||
sender: xous::MessageSender,
|
||||
kind: RequestKind,
|
||||
data: usize,
|
||||
}
|
||||
|
||||
impl core::fmt::Display for TimerRequest {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
write!(f, "TimerRequest {{ msec: {}, {} }}", self.msec, self.sender)
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for TimerRequest {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
write!(f, "TimerRequest {{ msec: {}, {} }}", self.msec, self.sender)
|
||||
}
|
||||
}
|
||||
|
||||
impl core::cmp::Ord for TimerRequest {
|
||||
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
|
||||
if self.msec < other.msec {
|
||||
core::cmp::Ordering::Less
|
||||
} else if self.msec > other.msec {
|
||||
core::cmp::Ordering::Greater
|
||||
} else {
|
||||
self.sender.cmp(&other.sender)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl core::cmp::PartialOrd for TimerRequest {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "precursor", feature = "renode"))]
|
||||
mod implementation {
|
||||
const TICKS_PER_MS: u64 = 1;
|
||||
use super::TimerRequest;
|
||||
use susres::{RegManager, RegOrField, SuspendResume};
|
||||
use utralib::generated::*;
|
||||
|
||||
pub struct XousTickTimer {
|
||||
csr: utralib::CSR<u32>,
|
||||
current_response: Option<TimerRequest>,
|
||||
last_response: Option<TimerRequest>,
|
||||
connection: xous::CID,
|
||||
ticktimer_sr_manager: RegManager<{ utra::ticktimer::TICKTIMER_NUMREGS }>,
|
||||
wdt_sr_manager: RegManager<{ utra::wdt::WDT_NUMREGS }>,
|
||||
wdt: utralib::CSR<u32>,
|
||||
}
|
||||
|
||||
fn handle_irq(_irq_no: usize, arg: *mut usize) {
|
||||
let xtt = unsafe { &mut *(arg as *mut XousTickTimer) };
|
||||
// println!("In IRQ, connection: {}", xtt.connection);
|
||||
|
||||
// Safe because we're in an interrupt, and this interrupt is only
|
||||
// enabled when this value is not None.
|
||||
let response = xtt.current_response.take().unwrap();
|
||||
xous::return_scalar(response.sender, response.kind as usize).ok();
|
||||
|
||||
// Disable the timer
|
||||
xtt.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 0);
|
||||
xtt.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1);
|
||||
|
||||
// This is dangerous and may return an error if the queue is full.
|
||||
// Which is fine, because the queue is always recalculated any time a message arrives.
|
||||
use num_traits::ToPrimitive;
|
||||
xous::try_send_message(
|
||||
xtt.connection,
|
||||
xous::Message::Scalar(xous::ScalarMessage {
|
||||
id: crate::api::Opcode::RecalculateSleep.to_usize().unwrap(),
|
||||
arg1: response.sender.to_usize(),
|
||||
arg2: response.kind as usize,
|
||||
arg3: response.data,
|
||||
arg4: 0,
|
||||
}),
|
||||
)
|
||||
.ok();
|
||||
|
||||
// Save the response so we can be sure we don't double-return messages.
|
||||
xtt.last_response = Some(response);
|
||||
}
|
||||
|
||||
impl XousTickTimer {
|
||||
pub fn new(connection: xous::CID) -> XousTickTimer {
|
||||
// println!("Connection: {}", connection);
|
||||
let csr = xous::syscall::map_memory(
|
||||
xous::MemoryAddress::new(utra::ticktimer::HW_TICKTIMER_BASE),
|
||||
None,
|
||||
4096,
|
||||
xous::MemoryFlags::R | xous::MemoryFlags::W,
|
||||
)
|
||||
.expect("couldn't map Tick Timer CSR range");
|
||||
let wdt = xous::syscall::map_memory(
|
||||
xous::MemoryAddress::new(utra::wdt::HW_WDT_BASE),
|
||||
None,
|
||||
4096,
|
||||
xous::MemoryFlags::R | xous::MemoryFlags::W,
|
||||
)
|
||||
.expect("couldn't map Watchdog timer CSR range");
|
||||
|
||||
let ticktimer_sr_manager = RegManager::new(csr.as_mut_ptr() as *mut u32);
|
||||
let wdt_sr_manager = RegManager::new(wdt.as_mut_ptr() as *mut u32);
|
||||
|
||||
let mut xtt = XousTickTimer {
|
||||
csr: CSR::new(csr.as_mut_ptr() as *mut u32),
|
||||
current_response: None,
|
||||
last_response: None,
|
||||
connection,
|
||||
ticktimer_sr_manager,
|
||||
wdt_sr_manager,
|
||||
wdt: CSR::new(wdt.as_mut_ptr() as *mut u32),
|
||||
};
|
||||
|
||||
#[cfg(feature = "watchdog")]
|
||||
{
|
||||
xtt.wdt.wfo(utra::wdt::PERIOD_PERIOD, 0x7FFF_FFFF); // about 30 seconds +/- 50%
|
||||
xtt.wdt.wfo(utra::wdt::WATCHDOG_ENABLE, 1);
|
||||
// this is a write-once field that is lost later on, so it must be explicitly managed
|
||||
// xtt.wdt_sr_manager.push(RegOrField::Field(utra::wdt::WATCHDOG_ENABLE), None);
|
||||
}
|
||||
|
||||
xous::claim_interrupt(
|
||||
utra::ticktimer::TICKTIMER_IRQ,
|
||||
handle_irq,
|
||||
(&mut xtt) as *mut XousTickTimer as *mut usize,
|
||||
)
|
||||
.expect("couldn't claim irq");
|
||||
|
||||
xtt.ticktimer_sr_manager
|
||||
.push(RegOrField::Reg(utra::ticktimer::MSLEEP_TARGET0), None);
|
||||
xtt.ticktimer_sr_manager
|
||||
.push(RegOrField::Reg(utra::ticktimer::MSLEEP_TARGET1), None);
|
||||
xtt.ticktimer_sr_manager
|
||||
.push_fixed_value(RegOrField::Reg(utra::ticktimer::EV_PENDING), 0xFFFF_FFFF);
|
||||
xtt.ticktimer_sr_manager
|
||||
.push(RegOrField::Reg(utra::ticktimer::EV_ENABLE), None);
|
||||
|
||||
xtt
|
||||
}
|
||||
|
||||
pub fn last_response(&self) -> &Option<TimerRequest> {
|
||||
&self.last_response
|
||||
}
|
||||
|
||||
pub fn clear_last_response(&mut self) {
|
||||
self.last_response = None;
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.csr.wfo(utra::ticktimer::CONTROL_RESET, 0b1);
|
||||
self.csr.wo(utra::ticktimer::CONTROL, 0); // not paused, not reset -> free-run
|
||||
}
|
||||
|
||||
pub fn raw_ticktime(&self) -> u64 {
|
||||
let mut time: u64 = self.csr.r(utra::ticktimer::TIME0) as u64;
|
||||
time |= (self.csr.r(utra::ticktimer::TIME1) as u64) << 32;
|
||||
|
||||
time
|
||||
}
|
||||
|
||||
pub fn elapsed_ms(&self) -> u64 {
|
||||
self.raw_ticktime() / TICKS_PER_MS
|
||||
}
|
||||
|
||||
pub fn stop_interrupt(&mut self) -> Option<TimerRequest> {
|
||||
// Disable the timer
|
||||
self.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 0);
|
||||
|
||||
// Now that the interrupt is disabled, we can see if the interrupt handler has a current response.
|
||||
// If it exists, then that means that an interrupt did NOT fire, and an existing interrupt
|
||||
// is in place.
|
||||
if let Some(sr) = self.current_response.take() {
|
||||
#[cfg(feature = "debug-print")]
|
||||
{
|
||||
log::info!(
|
||||
"Stopping currently-running timer sr.msec: {} elapsed_ms: {}",
|
||||
sr.msec,
|
||||
self.elapsed_ms()
|
||||
);
|
||||
}
|
||||
Some(sr)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn schedule_response(&mut self, request: TimerRequest) {
|
||||
let irq_target = request.msec;
|
||||
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);
|
||||
self.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 0);
|
||||
|
||||
// Save a copy of the current sleep request
|
||||
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 _);
|
||||
|
||||
// Clear previous interrupt (if any)
|
||||
self.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1);
|
||||
|
||||
// Enable the interrupt
|
||||
self.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 1);
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// the ticktimer suspend/resume routines are a bit trickier than normal, so this isn't a great
|
||||
// example of a generic suspend/resume template
|
||||
pub fn suspend(&mut self) {
|
||||
log::trace!("suspending");
|
||||
self.ticktimer_sr_manager.suspend();
|
||||
self.wdt_sr_manager.suspend();
|
||||
|
||||
// by writing this after suspend(), resume will get the prior value
|
||||
self.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 0);
|
||||
}
|
||||
pub fn resume(&mut self) {
|
||||
// this is a write-once bit that's later erased, so it can't be managed automatically
|
||||
// thus we have to restore in manually on a resume
|
||||
#[cfg(feature = "watchdog")]
|
||||
{
|
||||
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.
|
||||
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 time/target: {}/{}",
|
||||
self.csr.r(utra::ticktimer::TIME0),
|
||||
self.csr.r(utra::ticktimer::MSLEEP_TARGET0)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
not(target_os = "xous"),
|
||||
not(any(feature = "precursor", feature = "renode", not(target_os = "xous")))
|
||||
))]
|
||||
mod implementation {
|
||||
use crate::RequestKind;
|
||||
|
||||
use super::TimerRequest;
|
||||
use num_traits::ToPrimitive;
|
||||
use std::convert::TryInto;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum SleepComms {
|
||||
InterruptSleep,
|
||||
StartSleep(
|
||||
xous::MessageSender,
|
||||
i64, /* ms */
|
||||
u64, /* elapsed */
|
||||
),
|
||||
}
|
||||
pub struct XousTickTimer {
|
||||
start: std::time::Instant,
|
||||
sleep_comms: std::sync::mpsc::Sender<SleepComms>,
|
||||
time_remaining_receiver: std::sync::mpsc::Receiver<Option<TimerRequest>>,
|
||||
}
|
||||
|
||||
impl XousTickTimer {
|
||||
pub fn new(cid: xous::CID) -> XousTickTimer {
|
||||
let (sleep_sender, sleep_receiver) = std::sync::mpsc::channel();
|
||||
let (time_remaining_sender, time_remaining_receiver) = std::sync::mpsc::channel();
|
||||
xous::create_thread(move || {
|
||||
let mut timeout = None;
|
||||
let mut current_response: Option<TimerRequest> = None;
|
||||
loop {
|
||||
let result = match timeout {
|
||||
None => sleep_receiver
|
||||
.recv()
|
||||
.map_err(|_| std::sync::mpsc::RecvTimeoutError::Disconnected),
|
||||
Some(s) => sleep_receiver.recv_timeout(s),
|
||||
};
|
||||
match result {
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
|
||||
let response = current_response.take().unwrap();
|
||||
#[cfg(feature = "debug-print")]
|
||||
log::info!("Returning scalar to {}", response.sender);
|
||||
xous::return_scalar(response.sender, response.kind as usize)
|
||||
.expect("couldn't send response");
|
||||
|
||||
// This is dangerous and may panic if the queue is full.
|
||||
xous::try_send_message(
|
||||
cid,
|
||||
xous::Message::Scalar(xous::ScalarMessage {
|
||||
id: crate::api::Opcode::RecalculateSleep.to_usize().unwrap(),
|
||||
arg1: response.sender.to_usize(),
|
||||
arg2: response.kind as usize,
|
||||
arg3: response.data,
|
||||
arg4: 0,
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
timeout = None;
|
||||
}
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
|
||||
return;
|
||||
}
|
||||
Ok(SleepComms::InterruptSleep) => {
|
||||
timeout = None;
|
||||
time_remaining_sender.send(current_response.take()).unwrap()
|
||||
}
|
||||
Ok(SleepComms::StartSleep(new_sender, expiry, elapsed)) => {
|
||||
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
|
||||
);
|
||||
} else {
|
||||
#[cfg(feature = "debug-print")]
|
||||
log::info!(
|
||||
"Clamping duration to 0 (was: {})m returning to {}",
|
||||
duration,
|
||||
new_sender
|
||||
);
|
||||
duration = 0;
|
||||
}
|
||||
timeout = Some(std::time::Duration::from_millis(
|
||||
duration.try_into().unwrap(),
|
||||
));
|
||||
current_response = Some(TimerRequest {
|
||||
sender: new_sender,
|
||||
msec: expiry,
|
||||
kind: RequestKind::Sleep,
|
||||
data: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
XousTickTimer {
|
||||
start: std::time::Instant::now(),
|
||||
time_remaining_receiver,
|
||||
sleep_comms: sleep_sender,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn last_response(&self) -> &Option<TimerRequest> {
|
||||
&None
|
||||
}
|
||||
|
||||
pub fn clear_last_response(&mut self) {}
|
||||
|
||||
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 stop_interrupt(&mut self) -> Option<TimerRequest> {
|
||||
self.sleep_comms.send(SleepComms::InterruptSleep).unwrap();
|
||||
self.time_remaining_receiver.recv().unwrap()
|
||||
}
|
||||
|
||||
pub fn schedule_response(&mut self, request: TimerRequest) {
|
||||
#[cfg(feature = "debug-print")]
|
||||
log::info!(
|
||||
"request.msec: {} self.elapsed_ms: {} returning to: {}",
|
||||
request.msec,
|
||||
self.elapsed_ms(),
|
||||
request.sender
|
||||
);
|
||||
self.sleep_comms
|
||||
.send(SleepComms::StartSleep(
|
||||
request.sender,
|
||||
request.msec as i64,
|
||||
self.elapsed_ms(),
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn reset_wdt(&self) {
|
||||
// dummy function, does nothing
|
||||
}
|
||||
pub fn register_suspend_listener(
|
||||
&self,
|
||||
_opcode: u32,
|
||||
_cid: xous::CID,
|
||||
) -> Result<(), xous::Error> {
|
||||
Ok(())
|
||||
}
|
||||
pub fn suspend(&self) {}
|
||||
pub fn resume(&self) {}
|
||||
}
|
||||
}
|
||||
|
||||
use implementation::*;
|
||||
#[cfg(not(target_arch = "arm"))]
|
||||
use susres::SuspendOrder;
|
||||
|
||||
/// Disable the sleep interrupt and remove the currently-pending sleep item.
|
||||
|
|
@ -521,7 +77,10 @@ fn recalculate_sleep(
|
|||
info!("New sleep request was: {:?}", request);
|
||||
|
||||
// Ensure that each timeout only exists once inside the tree
|
||||
request.msec += ticktimer.elapsed_ms() as i64;
|
||||
#[cfg(not(feature = "atsama5d27"))]
|
||||
{
|
||||
request.msec += ticktimer.elapsed_ms() as i64;
|
||||
}
|
||||
while sleep_heap.contains_key(&request.msec) {
|
||||
request.msec += 1;
|
||||
}
|
||||
|
|
@ -539,7 +98,7 @@ fn recalculate_sleep(
|
|||
|
||||
fn main() -> ! {
|
||||
log_server::init_wait().unwrap();
|
||||
log::set_max_level(log::LevelFilter::Info);
|
||||
log::set_max_level(log::LevelFilter::Trace);
|
||||
info!("my PID is {}", xous::process::id());
|
||||
|
||||
#[cfg(feature = "timestamp")]
|
||||
|
|
@ -570,9 +129,14 @@ fn main() -> ! {
|
|||
ticktimer.reset(); // make sure the time starts from zero
|
||||
|
||||
// register a suspend/resume listener
|
||||
#[cfg(not(target_arch = "arm"))]
|
||||
let xns = xous_names::XousNames::new().unwrap();
|
||||
|
||||
#[cfg(not(target_arch = "arm"))]
|
||||
let sr_cid =
|
||||
xous::connect(ticktimer_server).expect("couldn't create suspend callback connection");
|
||||
|
||||
#[cfg(not(target_arch = "arm"))]
|
||||
let mut susres = susres::Susres::new(
|
||||
Some(SuspendOrder::Last),
|
||||
&xns,
|
||||
|
|
@ -734,10 +298,11 @@ fn main() -> ! {
|
|||
recalculate_sleep(&mut ticktimer, &mut sleep_heap, None);
|
||||
}
|
||||
|
||||
api::Opcode::SuspendResume => xous::msg_scalar_unpack!(msg, token, _, _, _, {
|
||||
api::Opcode::SuspendResume => xous::msg_scalar_unpack!(msg, _token, _, _, _, {
|
||||
ticktimer.suspend();
|
||||
#[cfg(not(target_arch = "arm"))]
|
||||
susres
|
||||
.suspend_until_resume(token)
|
||||
.suspend_until_resume(_token)
|
||||
.expect("couldn't execute suspend/resume");
|
||||
ticktimer.resume();
|
||||
}),
|
||||
|
|
|
|||
153
services/xous-ticktimer/src/platform/hosted/implementation.rs
Normal file
153
services/xous-ticktimer/src/platform/hosted/implementation.rs
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
use crate::RequestKind;
|
||||
use crate::TimerRequest;
|
||||
|
||||
use num_traits::ToPrimitive;
|
||||
use std::convert::TryInto;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum SleepComms {
|
||||
InterruptSleep,
|
||||
StartSleep(
|
||||
xous::MessageSender,
|
||||
i64, /* ms */
|
||||
u64, /* elapsed */
|
||||
),
|
||||
}
|
||||
pub struct XousTickTimer {
|
||||
start: std::time::Instant,
|
||||
sleep_comms: std::sync::mpsc::Sender<SleepComms>,
|
||||
time_remaining_receiver: std::sync::mpsc::Receiver<Option<TimerRequest>>,
|
||||
}
|
||||
|
||||
impl XousTickTimer {
|
||||
pub fn new(cid: xous::CID) -> XousTickTimer {
|
||||
let (sleep_sender, sleep_receiver) = std::sync::mpsc::channel();
|
||||
let (time_remaining_sender, time_remaining_receiver) = std::sync::mpsc::channel();
|
||||
xous::create_thread(move || {
|
||||
let mut timeout = None;
|
||||
let mut current_response: Option<TimerRequest> = None;
|
||||
loop {
|
||||
let result = match timeout {
|
||||
None => sleep_receiver
|
||||
.recv()
|
||||
.map_err(|_| std::sync::mpsc::RecvTimeoutError::Disconnected),
|
||||
Some(s) => sleep_receiver.recv_timeout(s),
|
||||
};
|
||||
match result {
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
|
||||
let response = current_response.take().unwrap();
|
||||
#[cfg(feature = "debug-print")]
|
||||
log::info!("Returning scalar to {}", response.sender);
|
||||
xous::return_scalar(response.sender, response.kind as usize)
|
||||
.expect("couldn't send response");
|
||||
|
||||
// This is dangerous and may panic if the queue is full.
|
||||
xous::try_send_message(
|
||||
cid,
|
||||
xous::Message::Scalar(xous::ScalarMessage {
|
||||
id: crate::api::Opcode::RecalculateSleep.to_usize().unwrap(),
|
||||
arg1: response.sender.to_usize(),
|
||||
arg2: response.kind as usize,
|
||||
arg3: response.data,
|
||||
arg4: 0,
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
timeout = None;
|
||||
}
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
|
||||
return;
|
||||
}
|
||||
Ok(SleepComms::InterruptSleep) => {
|
||||
timeout = None;
|
||||
time_remaining_sender.send(current_response.take()).unwrap()
|
||||
}
|
||||
Ok(SleepComms::StartSleep(new_sender, expiry, elapsed)) => {
|
||||
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
|
||||
);
|
||||
} else {
|
||||
#[cfg(feature = "debug-print")]
|
||||
log::info!(
|
||||
"Clamping duration to 0 (was: {})m returning to {}",
|
||||
duration,
|
||||
new_sender
|
||||
);
|
||||
duration = 0;
|
||||
}
|
||||
timeout = Some(std::time::Duration::from_millis(
|
||||
duration.try_into().unwrap(),
|
||||
));
|
||||
current_response = Some(TimerRequest {
|
||||
sender: new_sender,
|
||||
msec: expiry,
|
||||
kind: RequestKind::Sleep,
|
||||
data: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
XousTickTimer {
|
||||
start: std::time::Instant::now(),
|
||||
time_remaining_receiver,
|
||||
sleep_comms: sleep_sender,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn last_response(&self) -> &Option<TimerRequest> {
|
||||
&None
|
||||
}
|
||||
|
||||
pub fn clear_last_response(&mut self) {}
|
||||
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 stop_interrupt(&mut self) -> Option<TimerRequest> {
|
||||
self.sleep_comms.send(SleepComms::InterruptSleep).unwrap();
|
||||
self.time_remaining_receiver.recv().ok().flatten()
|
||||
}
|
||||
|
||||
pub fn schedule_response(&mut self, request: TimerRequest) {
|
||||
#[cfg(feature = "debug-print")]
|
||||
log::info!(
|
||||
"request.msec: {} self.elapsed_ms: {} returning to: {}",
|
||||
request.msec,
|
||||
self.elapsed_ms(),
|
||||
request.sender
|
||||
);
|
||||
self.sleep_comms
|
||||
.send(SleepComms::StartSleep(
|
||||
request.sender,
|
||||
request.msec as i64,
|
||||
self.elapsed_ms(),
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn reset_wdt(&self) {
|
||||
// dummy function, does nothing
|
||||
}
|
||||
pub fn register_suspend_listener(
|
||||
&self,
|
||||
_opcode: u32,
|
||||
_cid: xous::CID,
|
||||
) -> Result<(), xous::Error> {
|
||||
Ok(())
|
||||
}
|
||||
pub fn suspend(&self) {}
|
||||
pub fn resume(&self) {}
|
||||
}
|
||||
1
services/xous-ticktimer/src/platform/hosted/mod.rs
Normal file
1
services/xous-ticktimer/src/platform/hosted/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
pub mod implementation;
|
||||
66
services/xous-ticktimer/src/platform/mod.rs
Normal file
66
services/xous-ticktimer/src/platform/mod.rs
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
#[cfg(any(feature="precursor", feature="renode"))]
|
||||
#[macro_use]
|
||||
pub mod precursor;
|
||||
#[cfg(any(feature="precursor", feature="renode"))]
|
||||
pub use precursor::*;
|
||||
|
||||
#[cfg(any(not(target_os = "xous"),
|
||||
not(any(feature="precursor", feature="renode", feature="atsama5d27", not(target_os = "xous")))
|
||||
))]
|
||||
pub mod hosted;
|
||||
#[cfg(any(not(target_os = "xous"),
|
||||
not(any(feature="precursor", feature="renode", feature="atsama5d27", not(target_os = "xous")))
|
||||
))]
|
||||
pub use hosted::*;
|
||||
|
||||
pub(crate) type TimeoutExpiry = i64;
|
||||
|
||||
#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
|
||||
pub enum RequestKind {
|
||||
Sleep = 0,
|
||||
Timeout = 1,
|
||||
}
|
||||
|
||||
#[derive(Eq)]
|
||||
pub struct TimerRequest {
|
||||
pub(crate) msec: TimeoutExpiry,
|
||||
pub(crate) sender: xous::MessageSender,
|
||||
pub(crate) kind: RequestKind,
|
||||
pub(crate) data: usize,
|
||||
}
|
||||
|
||||
impl core::fmt::Display for TimerRequest {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
write!(f, "TimerRequest {{ msec: {}, {} }}", self.msec, self.sender)
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for TimerRequest {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
write!(f, "TimerRequest {{ msec: {}, {} }}", self.msec, self.sender)
|
||||
}
|
||||
}
|
||||
|
||||
impl core::cmp::Ord for TimerRequest {
|
||||
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
|
||||
if self.msec < other.msec {
|
||||
core::cmp::Ordering::Less
|
||||
} else if self.msec > other.msec {
|
||||
core::cmp::Ordering::Greater
|
||||
} else {
|
||||
self.sender.cmp(&other.sender)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl core::cmp::PartialOrd for TimerRequest {
|
||||
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
|
||||
}
|
||||
}
|
||||
231
services/xous-ticktimer/src/platform/precursor/implementation.rs
Normal file
231
services/xous-ticktimer/src/platform/precursor/implementation.rs
Normal file
|
|
@ -0,0 +1,231 @@
|
|||
const TICKS_PER_MS: u64 = 1;
|
||||
use crate::TimerRequest;
|
||||
use susres::{RegManager, RegOrField, SuspendResume};
|
||||
use utralib::generated::*;
|
||||
|
||||
pub struct XousTickTimer {
|
||||
csr: utralib::CSR<u32>,
|
||||
current_response: Option<TimerRequest>,
|
||||
last_response: Option<TimerRequest>,
|
||||
connection: xous::CID,
|
||||
ticktimer_sr_manager: RegManager<{ utra::ticktimer::TICKTIMER_NUMREGS }>,
|
||||
wdt_sr_manager: RegManager<{ utra::wdt::WDT_NUMREGS }>,
|
||||
wdt: utralib::CSR<u32>,
|
||||
}
|
||||
|
||||
fn handle_irq(_irq_no: usize, arg: *mut usize) {
|
||||
let xtt = unsafe { &mut *(arg as *mut XousTickTimer) };
|
||||
// println!("In IRQ, connection: {}", xtt.connection);
|
||||
|
||||
// Safe because we're in an interrupt, and this interrupt is only
|
||||
// enabled when this value is not None.
|
||||
let response = xtt.current_response.take().unwrap();
|
||||
xous::return_scalar(response.sender, response.kind as usize).ok();
|
||||
|
||||
// Disable the timer
|
||||
xtt.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 0);
|
||||
xtt.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1);
|
||||
|
||||
// This is dangerous and may return an error if the queue is full.
|
||||
// Which is fine, because the queue is always recalculated any time a message arrives.
|
||||
use num_traits::ToPrimitive;
|
||||
xous::try_send_message(
|
||||
xtt.connection,
|
||||
xous::Message::Scalar(xous::ScalarMessage {
|
||||
id: crate::api::Opcode::RecalculateSleep.to_usize().unwrap(),
|
||||
arg1: response.sender.to_usize(),
|
||||
arg2: response.kind as usize,
|
||||
arg3: response.data,
|
||||
arg4: 0,
|
||||
}),
|
||||
)
|
||||
.ok();
|
||||
|
||||
// Save the response so we can be sure we don't double-return messages.
|
||||
xtt.last_response = Some(response);
|
||||
}
|
||||
|
||||
impl XousTickTimer {
|
||||
pub fn new(connection: xous::CID) -> XousTickTimer {
|
||||
// println!("Connection: {}", connection);
|
||||
let csr = xous::syscall::map_memory(
|
||||
xous::MemoryAddress::new(utra::ticktimer::HW_TICKTIMER_BASE),
|
||||
None,
|
||||
4096,
|
||||
xous::MemoryFlags::R | xous::MemoryFlags::W,
|
||||
)
|
||||
.expect("couldn't map Tick Timer CSR range");
|
||||
let wdt = xous::syscall::map_memory(
|
||||
xous::MemoryAddress::new(utra::wdt::HW_WDT_BASE),
|
||||
None,
|
||||
4096,
|
||||
xous::MemoryFlags::R | xous::MemoryFlags::W,
|
||||
)
|
||||
.expect("couldn't map Watchdog timer CSR range");
|
||||
|
||||
let ticktimer_sr_manager = RegManager::new(csr.as_mut_ptr() as *mut u32);
|
||||
let wdt_sr_manager = RegManager::new(wdt.as_mut_ptr() as *mut u32);
|
||||
|
||||
let mut xtt = XousTickTimer {
|
||||
csr: CSR::new(csr.as_mut_ptr() as *mut u32),
|
||||
current_response: None,
|
||||
last_response: None,
|
||||
connection,
|
||||
ticktimer_sr_manager,
|
||||
wdt_sr_manager,
|
||||
wdt: CSR::new(wdt.as_mut_ptr() as *mut u32),
|
||||
};
|
||||
|
||||
#[cfg(feature = "watchdog")]
|
||||
{
|
||||
xtt.wdt.wfo(utra::wdt::PERIOD_PERIOD, 0x7FFF_FFFF); // about 30 seconds +/- 50%
|
||||
xtt.wdt.wfo(utra::wdt::WATCHDOG_ENABLE, 1);
|
||||
// this is a write-once field that is lost later on, so it must be explicitly managed
|
||||
// xtt.wdt_sr_manager.push(RegOrField::Field(utra::wdt::WATCHDOG_ENABLE), None);
|
||||
}
|
||||
|
||||
xous::claim_interrupt(
|
||||
utra::ticktimer::TICKTIMER_IRQ,
|
||||
handle_irq,
|
||||
(&mut xtt) as *mut XousTickTimer as *mut usize,
|
||||
)
|
||||
.expect("couldn't claim irq");
|
||||
|
||||
xtt.ticktimer_sr_manager
|
||||
.push(RegOrField::Reg(utra::ticktimer::MSLEEP_TARGET0), None);
|
||||
xtt.ticktimer_sr_manager
|
||||
.push(RegOrField::Reg(utra::ticktimer::MSLEEP_TARGET1), None);
|
||||
xtt.ticktimer_sr_manager
|
||||
.push_fixed_value(RegOrField::Reg(utra::ticktimer::EV_PENDING), 0xFFFF_FFFF);
|
||||
xtt.ticktimer_sr_manager
|
||||
.push(RegOrField::Reg(utra::ticktimer::EV_ENABLE), None);
|
||||
|
||||
xtt
|
||||
}
|
||||
|
||||
pub fn last_response(&self) -> &Option<TimerRequest> {
|
||||
&self.last_response
|
||||
}
|
||||
|
||||
pub fn clear_last_response(&mut self) {
|
||||
self.last_response = None;
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.csr.wfo(utra::ticktimer::CONTROL_RESET, 0b1);
|
||||
self.csr.wo(utra::ticktimer::CONTROL, 0); // not paused, not reset -> free-run
|
||||
}
|
||||
|
||||
pub fn raw_ticktime(&self) -> u64 {
|
||||
let mut time: u64 = self.csr.r(utra::ticktimer::TIME0) as u64;
|
||||
time |= (self.csr.r(utra::ticktimer::TIME1) as u64) << 32;
|
||||
|
||||
time
|
||||
}
|
||||
|
||||
pub fn elapsed_ms(&self) -> u64 {
|
||||
self.raw_ticktime() / TICKS_PER_MS
|
||||
}
|
||||
|
||||
pub fn stop_interrupt(&mut self) -> Option<TimerRequest> {
|
||||
// Disable the timer
|
||||
self.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 0);
|
||||
|
||||
// Now that the interrupt is disabled, we can see if the interrupt handler has a current response.
|
||||
// If it exists, then that means that an interrupt did NOT fire, and an existing interrupt
|
||||
// is in place.
|
||||
if let Some(sr) = self.current_response.take() {
|
||||
#[cfg(feature = "debug-print")]
|
||||
{
|
||||
log::info!(
|
||||
"Stopping currently-running timer sr.msec: {} elapsed_ms: {}",
|
||||
sr.msec,
|
||||
self.elapsed_ms()
|
||||
);
|
||||
}
|
||||
Some(sr)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn schedule_response(&mut self, request: TimerRequest) {
|
||||
let irq_target = request.msec;
|
||||
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);
|
||||
self.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 0);
|
||||
|
||||
// Save a copy of the current sleep request
|
||||
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 _);
|
||||
|
||||
// Clear previous interrupt (if any)
|
||||
self.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1);
|
||||
|
||||
// Enable the interrupt
|
||||
self.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 1);
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// the ticktimer suspend/resume routines are a bit trickier than normal, so this isn't a great
|
||||
// example of a generic suspend/resume template
|
||||
pub fn suspend(&mut self) {
|
||||
log::trace!("suspending");
|
||||
self.ticktimer_sr_manager.suspend();
|
||||
self.wdt_sr_manager.suspend();
|
||||
|
||||
// by writing this after suspend(), resume will get the prior value
|
||||
self.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 0);
|
||||
}
|
||||
pub fn resume(&mut self) {
|
||||
// this is a write-once bit that's later erased, so it can't be managed automatically
|
||||
// thus we have to restore in manually on a resume
|
||||
#[cfg(feature = "watchdog")]
|
||||
{
|
||||
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.
|
||||
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 time/target: {}/{}",
|
||||
self.csr.r(utra::ticktimer::TIME0),
|
||||
self.csr.r(utra::ticktimer::MSLEEP_TARGET0)
|
||||
);
|
||||
}
|
||||
}
|
||||
1
services/xous-ticktimer/src/platform/precursor/mod.rs
Normal file
1
services/xous-ticktimer/src/platform/precursor/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
pub mod implementation;
|
||||
Loading…
Reference in a new issue