2020-09-24 19:59:20 +02:00
|
|
|
use core::cell::Cell;
|
2021-08-03 22:08:13 +02:00
|
|
|
use core::sync::atomic::{compiler_fence, AtomicU32, AtomicU8, Ordering};
|
|
|
|
use core::{mem, ptr};
|
2022-06-12 22:15:44 +02:00
|
|
|
|
2021-05-11 00:57:52 +02:00
|
|
|
use critical_section::CriticalSection;
|
2022-08-22 21:46:09 +02:00
|
|
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
|
|
|
use embassy_sync::blocking_mutex::CriticalSectionMutex as Mutex;
|
2022-08-17 23:40:16 +02:00
|
|
|
use embassy_time::driver::{AlarmHandle, Driver};
|
2020-09-25 23:38:42 +02:00
|
|
|
|
2022-06-12 22:15:44 +02:00
|
|
|
use crate::interrupt::{Interrupt, InterruptExt};
|
|
|
|
use crate::{interrupt, pac};
|
2021-08-03 22:08:13 +02:00
|
|
|
|
|
|
|
fn rtc() -> &'static pac::rtc0::RegisterBlock {
|
|
|
|
unsafe { &*pac::RTC1::ptr() }
|
|
|
|
}
|
2020-09-24 19:59:20 +02:00
|
|
|
|
2022-02-23 05:14:32 +01:00
|
|
|
/// Calculate the timestamp from the period count and the tick count.
|
|
|
|
///
|
|
|
|
/// The RTC counter is 24 bit. Ticking at 32768hz, it overflows every ~8 minutes. This is
|
|
|
|
/// too short. We must make it "never" overflow.
|
|
|
|
///
|
|
|
|
/// The obvious way would be to count overflow periods. Every time the counter overflows,
|
|
|
|
/// increase a `periods` variable. `now()` simply does `periods << 24 + counter`. So, the logic
|
|
|
|
/// around an overflow would look like this:
|
|
|
|
///
|
|
|
|
/// ```not_rust
|
|
|
|
/// periods = 1, counter = 0xFF_FFFE --> now = 0x1FF_FFFE
|
|
|
|
/// periods = 1, counter = 0xFF_FFFF --> now = 0x1FF_FFFF
|
|
|
|
/// **OVERFLOW**
|
|
|
|
/// periods = 2, counter = 0x00_0000 --> now = 0x200_0000
|
|
|
|
/// periods = 2, counter = 0x00_0001 --> now = 0x200_0001
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// The problem is this is vulnerable to race conditions if `now()` runs at the exact time an
|
|
|
|
/// overflow happens.
|
|
|
|
///
|
|
|
|
/// If `now()` reads `periods` first and `counter` later, and overflow happens between the reads,
|
|
|
|
/// it would return a wrong value:
|
|
|
|
///
|
|
|
|
/// ```not_rust
|
|
|
|
/// periods = 1 (OLD), counter = 0x00_0000 (NEW) --> now = 0x100_0000 -> WRONG
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// It fails similarly if it reads `counter` first and `periods` second.
|
|
|
|
///
|
|
|
|
/// To fix this, we define a "period" to be 2^23 ticks (instead of 2^24). One "overflow cycle" is 2 periods.
|
|
|
|
///
|
|
|
|
/// - `period` is incremented on overflow (at counter value 0)
|
|
|
|
/// - `period` is incremented "midway" between overflows (at counter value 0x80_0000)
|
|
|
|
///
|
|
|
|
/// Therefore, when `period` is even, counter is in 0..0x7f_ffff. When odd, counter is in 0x80_0000..0xFF_FFFF
|
|
|
|
/// This allows for now() to return the correct value even if it races an overflow.
|
|
|
|
///
|
|
|
|
/// To get `now()`, `period` is read first, then `counter` is read. If the counter value matches
|
|
|
|
/// the expected range for the `period` parity, we're done. If it doesn't, this means that
|
|
|
|
/// a new period start has raced us between reading `period` and `counter`, so we assume the `counter` value
|
|
|
|
/// corresponds to the next period.
|
|
|
|
///
|
|
|
|
/// `period` is a 32bit integer, so It overflows on 2^32 * 2^23 / 32768 seconds of uptime, which is 34865
|
|
|
|
/// years. For comparison, flash memory like the one containing your firmware is usually rated to retain
|
|
|
|
/// data for only 10-20 years. 34865 years is long enough!
|
2020-09-24 19:59:20 +02:00
|
|
|
fn calc_now(period: u32, counter: u32) -> u64 {
|
2021-02-15 01:01:45 +01:00
|
|
|
((period as u64) << 23) + ((counter ^ ((period & 1) << 23)) as u64)
|
2020-09-24 19:59:20 +02:00
|
|
|
}
|
|
|
|
|
2020-09-26 00:35:25 +02:00
|
|
|
fn compare_n(n: usize) -> u32 {
|
|
|
|
1 << (n + 16)
|
|
|
|
}
|
|
|
|
|
2021-02-14 01:41:36 +01:00
|
|
|
#[cfg(tests)]
|
2020-09-24 19:59:20 +02:00
|
|
|
mod test {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_calc_now() {
|
|
|
|
assert_eq!(calc_now(0, 0x000000), 0x0_000000);
|
|
|
|
assert_eq!(calc_now(0, 0x000001), 0x0_000001);
|
|
|
|
assert_eq!(calc_now(0, 0x7FFFFF), 0x0_7FFFFF);
|
2021-02-15 01:01:45 +01:00
|
|
|
assert_eq!(calc_now(1, 0x7FFFFF), 0x1_7FFFFF);
|
2020-09-24 19:59:20 +02:00
|
|
|
assert_eq!(calc_now(0, 0x800000), 0x0_800000);
|
|
|
|
assert_eq!(calc_now(1, 0x800000), 0x0_800000);
|
|
|
|
assert_eq!(calc_now(1, 0x800001), 0x0_800001);
|
|
|
|
assert_eq!(calc_now(1, 0xFFFFFF), 0x0_FFFFFF);
|
2021-02-15 01:01:45 +01:00
|
|
|
assert_eq!(calc_now(2, 0xFFFFFF), 0x1_FFFFFF);
|
2020-09-24 19:59:20 +02:00
|
|
|
assert_eq!(calc_now(1, 0x000000), 0x1_000000);
|
|
|
|
assert_eq!(calc_now(2, 0x000000), 0x1_000000);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-25 23:25:49 +02:00
|
|
|
struct AlarmState {
|
|
|
|
timestamp: Cell<u64>,
|
2021-08-03 22:08:13 +02:00
|
|
|
|
|
|
|
// This is really a Option<(fn(*mut ()), *mut ())>
|
|
|
|
// but fn pointers aren't allowed in const yet
|
|
|
|
callback: Cell<*const ()>,
|
|
|
|
ctx: Cell<*mut ()>,
|
2020-09-25 23:25:49 +02:00
|
|
|
}
|
|
|
|
|
2021-08-03 22:08:13 +02:00
|
|
|
unsafe impl Send for AlarmState {}
|
|
|
|
|
2020-09-25 23:25:49 +02:00
|
|
|
impl AlarmState {
|
2021-08-03 22:08:13 +02:00
|
|
|
const fn new() -> Self {
|
2020-09-25 23:25:49 +02:00
|
|
|
Self {
|
|
|
|
timestamp: Cell::new(u64::MAX),
|
2021-08-03 22:08:13 +02:00
|
|
|
callback: Cell::new(ptr::null()),
|
|
|
|
ctx: Cell::new(ptr::null_mut()),
|
2020-09-25 23:25:49 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const ALARM_COUNT: usize = 3;
|
|
|
|
|
2021-08-25 18:50:05 +02:00
|
|
|
struct RtcDriver {
|
2020-09-24 19:59:20 +02:00
|
|
|
/// Number of 2^23 periods elapsed since boot.
|
|
|
|
period: AtomicU32,
|
2021-08-03 22:08:13 +02:00
|
|
|
alarm_count: AtomicU8,
|
2020-09-24 19:59:20 +02:00
|
|
|
/// Timestamp at which to fire alarm. u64::MAX if no alarm is scheduled.
|
2020-09-25 23:25:49 +02:00
|
|
|
alarms: Mutex<[AlarmState; ALARM_COUNT]>,
|
2020-09-24 19:59:20 +02:00
|
|
|
}
|
|
|
|
|
2021-08-03 22:08:13 +02:00
|
|
|
const ALARM_STATE_NEW: AlarmState = AlarmState::new();
|
2022-08-17 23:40:16 +02:00
|
|
|
embassy_time::time_driver_impl!(static DRIVER: RtcDriver = RtcDriver {
|
2021-08-03 22:08:13 +02:00
|
|
|
period: AtomicU32::new(0),
|
|
|
|
alarm_count: AtomicU8::new(0),
|
2022-02-11 23:25:30 +01:00
|
|
|
alarms: Mutex::const_new(CriticalSectionRawMutex::new(), [ALARM_STATE_NEW; ALARM_COUNT]),
|
2021-08-25 18:50:05 +02:00
|
|
|
});
|
2020-09-24 22:41:52 +02:00
|
|
|
|
2021-08-25 18:50:05 +02:00
|
|
|
impl RtcDriver {
|
2021-08-18 22:12:36 +02:00
|
|
|
fn init(&'static self, irq_prio: crate::interrupt::Priority) {
|
2021-08-03 22:08:13 +02:00
|
|
|
let r = rtc();
|
2021-03-27 03:12:58 +01:00
|
|
|
r.cc[3].write(|w| unsafe { w.bits(0x800000) });
|
2020-09-24 19:59:20 +02:00
|
|
|
|
2021-03-27 03:12:58 +01:00
|
|
|
r.intenset.write(|w| {
|
2020-09-24 19:59:20 +02:00
|
|
|
let w = w.ovrflw().set();
|
2020-09-26 00:35:25 +02:00
|
|
|
let w = w.compare3().set();
|
2020-09-24 19:59:20 +02:00
|
|
|
w
|
|
|
|
});
|
|
|
|
|
2021-03-27 03:12:58 +01:00
|
|
|
r.tasks_clear.write(|w| unsafe { w.bits(1) });
|
|
|
|
r.tasks_start.write(|w| unsafe { w.bits(1) });
|
2020-09-24 19:59:20 +02:00
|
|
|
|
|
|
|
// Wait for clear
|
2021-03-27 03:12:58 +01:00
|
|
|
while r.counter.read().bits() != 0 {}
|
2020-09-24 19:59:20 +02:00
|
|
|
|
2021-08-18 22:12:36 +02:00
|
|
|
let irq = unsafe { interrupt::RTC1::steal() };
|
|
|
|
irq.set_priority(irq_prio);
|
|
|
|
irq.enable();
|
2020-09-24 19:59:20 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
fn on_interrupt(&self) {
|
2021-08-03 22:08:13 +02:00
|
|
|
let r = rtc();
|
2021-03-27 03:12:58 +01:00
|
|
|
if r.events_ovrflw.read().bits() == 1 {
|
|
|
|
r.events_ovrflw.write(|w| w);
|
2020-09-24 19:59:20 +02:00
|
|
|
self.next_period();
|
|
|
|
}
|
|
|
|
|
2021-03-27 03:12:58 +01:00
|
|
|
if r.events_compare[3].read().bits() == 1 {
|
|
|
|
r.events_compare[3].write(|w| w);
|
2020-09-24 19:59:20 +02:00
|
|
|
self.next_period();
|
|
|
|
}
|
|
|
|
|
2020-09-25 23:25:49 +02:00
|
|
|
for n in 0..ALARM_COUNT {
|
2021-03-27 03:12:58 +01:00
|
|
|
if r.events_compare[n].read().bits() == 1 {
|
|
|
|
r.events_compare[n].write(|w| w);
|
2021-05-11 00:57:52 +02:00
|
|
|
critical_section::with(|cs| {
|
2020-09-25 23:25:49 +02:00
|
|
|
self.trigger_alarm(n, cs);
|
|
|
|
})
|
|
|
|
}
|
2020-09-24 19:59:20 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn next_period(&self) {
|
2021-05-11 00:57:52 +02:00
|
|
|
critical_section::with(|cs| {
|
2021-08-03 22:08:13 +02:00
|
|
|
let r = rtc();
|
2021-02-20 01:43:10 +01:00
|
|
|
let period = self.period.fetch_add(1, Ordering::Relaxed) + 1;
|
2020-09-24 19:59:20 +02:00
|
|
|
let t = (period as u64) << 23;
|
|
|
|
|
2020-09-26 00:35:25 +02:00
|
|
|
for n in 0..ALARM_COUNT {
|
|
|
|
let alarm = &self.alarms.borrow(cs)[n];
|
2020-09-25 23:25:49 +02:00
|
|
|
let at = alarm.timestamp.get();
|
2020-09-24 19:59:20 +02:00
|
|
|
|
2021-08-03 22:08:13 +02:00
|
|
|
if at < t + 0xc00000 {
|
|
|
|
// just enable it. `set_alarm` has already set the correct CC val.
|
2021-03-27 03:12:58 +01:00
|
|
|
r.intenset.write(|w| unsafe { w.bits(compare_n(n)) });
|
2020-09-25 23:25:49 +02:00
|
|
|
}
|
2020-09-24 19:59:20 +02:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-08-03 22:08:13 +02:00
|
|
|
fn get_alarm<'a>(&'a self, cs: CriticalSection<'a>, alarm: AlarmHandle) -> &'a AlarmState {
|
|
|
|
// safety: we're allowed to assume the AlarmState is created by us, and
|
|
|
|
// we never create one that's out of bounds.
|
|
|
|
unsafe { self.alarms.borrow(cs).get_unchecked(alarm.id() as usize) }
|
|
|
|
}
|
|
|
|
|
2021-05-11 00:57:52 +02:00
|
|
|
fn trigger_alarm(&self, n: usize, cs: CriticalSection) {
|
2021-08-03 22:08:13 +02:00
|
|
|
let r = rtc();
|
2021-03-27 03:12:58 +01:00
|
|
|
r.intenclr.write(|w| unsafe { w.bits(compare_n(n)) });
|
2020-09-24 19:59:20 +02:00
|
|
|
|
2020-09-25 23:25:49 +02:00
|
|
|
let alarm = &self.alarms.borrow(cs)[n];
|
|
|
|
alarm.timestamp.set(u64::MAX);
|
|
|
|
|
|
|
|
// Call after clearing alarm, so the callback can set another alarm.
|
2021-08-03 22:08:13 +02:00
|
|
|
|
|
|
|
// safety:
|
|
|
|
// - we can ignore the possiblity of `f` being unset (null) because of the safety contract of `allocate_alarm`.
|
|
|
|
// - other than that we only store valid function pointers into alarm.callback
|
|
|
|
let f: fn(*mut ()) = unsafe { mem::transmute(alarm.callback.get()) };
|
|
|
|
f(alarm.ctx.get());
|
|
|
|
}
|
2021-08-25 18:50:05 +02:00
|
|
|
}
|
2021-08-03 22:08:13 +02:00
|
|
|
|
2021-08-25 18:50:05 +02:00
|
|
|
impl Driver for RtcDriver {
|
|
|
|
fn now(&self) -> u64 {
|
|
|
|
// `period` MUST be read before `counter`, see comment at the top for details.
|
|
|
|
let period = self.period.load(Ordering::Relaxed);
|
|
|
|
compiler_fence(Ordering::Acquire);
|
|
|
|
let counter = rtc().counter.read().bits();
|
|
|
|
calc_now(period, counter)
|
|
|
|
}
|
|
|
|
|
|
|
|
unsafe fn allocate_alarm(&self) -> Option<AlarmHandle> {
|
2022-06-12 22:15:44 +02:00
|
|
|
let id = self.alarm_count.fetch_update(Ordering::AcqRel, Ordering::Acquire, |x| {
|
|
|
|
if x < ALARM_COUNT as u8 {
|
|
|
|
Some(x + 1)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
});
|
2021-08-03 22:08:13 +02:00
|
|
|
|
|
|
|
match id {
|
2021-08-25 18:50:05 +02:00
|
|
|
Ok(id) => Some(AlarmHandle::new(id)),
|
2021-08-03 22:08:13 +02:00
|
|
|
Err(_) => None,
|
2021-02-14 01:41:36 +01:00
|
|
|
}
|
2020-09-24 19:59:20 +02:00
|
|
|
}
|
|
|
|
|
2021-08-03 22:08:13 +02:00
|
|
|
fn set_alarm_callback(&self, alarm: AlarmHandle, callback: fn(*mut ()), ctx: *mut ()) {
|
2021-05-11 00:57:52 +02:00
|
|
|
critical_section::with(|cs| {
|
2021-08-03 22:08:13 +02:00
|
|
|
let alarm = self.get_alarm(cs, alarm);
|
|
|
|
|
2021-08-05 19:19:47 +02:00
|
|
|
alarm.callback.set(callback as *const ());
|
2021-08-03 22:08:13 +02:00
|
|
|
alarm.ctx.set(ctx);
|
2020-09-25 23:25:49 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-10-24 08:17:43 +02:00
|
|
|
fn set_alarm(&self, alarm: AlarmHandle, timestamp: u64) -> bool {
|
2021-05-11 00:57:52 +02:00
|
|
|
critical_section::with(|cs| {
|
2022-10-24 08:17:43 +02:00
|
|
|
let n = alarm.id() as _;
|
|
|
|
let alarm = self.get_alarm(cs, alarm);
|
|
|
|
alarm.timestamp.set(timestamp);
|
|
|
|
|
2021-08-03 22:08:13 +02:00
|
|
|
let r = rtc();
|
2021-03-27 03:12:58 +01:00
|
|
|
|
2022-10-24 10:10:59 +02:00
|
|
|
let t = self.now();
|
|
|
|
if timestamp <= t {
|
|
|
|
// If alarm timestamp has passed the alarm will not fire.
|
|
|
|
// Disarm the alarm and return `false` to indicate that.
|
|
|
|
r.intenclr.write(|w| unsafe { w.bits(compare_n(n)) });
|
|
|
|
|
|
|
|
alarm.timestamp.set(u64::MAX);
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2021-02-15 01:01:45 +01:00
|
|
|
// If it hasn't triggered yet, setup it in the compare channel.
|
2021-08-03 22:08:13 +02:00
|
|
|
|
|
|
|
// Write the CC value regardless of whether we're going to enable it now or not.
|
|
|
|
// This way, when we enable it later, the right value is already set.
|
|
|
|
|
|
|
|
// nrf52 docs say:
|
|
|
|
// If the COUNTER is N, writing N or N+1 to a CC register may not trigger a COMPARE event.
|
|
|
|
// To workaround this, we never write a timestamp smaller than N+3.
|
|
|
|
// N+2 is not safe because rtc can tick from N to N+1 between calling now() and writing cc.
|
|
|
|
//
|
|
|
|
// It is impossible for rtc to tick more than once because
|
|
|
|
// - this code takes less time than 1 tick
|
|
|
|
// - it runs with interrupts disabled so nothing else can preempt it.
|
|
|
|
//
|
|
|
|
// This means that an alarm can be delayed for up to 2 ticks (from t+1 to t+3), but this is allowed
|
|
|
|
// by the Alarm trait contract. What's not allowed is triggering alarms *before* their scheduled time,
|
|
|
|
// and we don't do that here.
|
|
|
|
let safe_timestamp = timestamp.max(t + 3);
|
|
|
|
r.cc[n].write(|w| unsafe { w.bits(safe_timestamp as u32 & 0xFFFFFF) });
|
|
|
|
|
2020-09-24 23:26:24 +02:00
|
|
|
let diff = timestamp - t;
|
2020-09-24 19:59:20 +02:00
|
|
|
if diff < 0xc00000 {
|
2021-03-27 03:12:58 +01:00
|
|
|
r.intenset.write(|w| unsafe { w.bits(compare_n(n)) });
|
2020-09-24 19:59:20 +02:00
|
|
|
} else {
|
2021-02-15 01:01:45 +01:00
|
|
|
// If it's too far in the future, don't setup the compare channel yet.
|
|
|
|
// It will be setup later by `next_period`.
|
2021-03-27 03:12:58 +01:00
|
|
|
r.intenclr.write(|w| unsafe { w.bits(compare_n(n)) });
|
2020-09-24 19:59:20 +02:00
|
|
|
}
|
2022-10-24 08:17:43 +02:00
|
|
|
|
|
|
|
true
|
2020-09-24 19:59:20 +02:00
|
|
|
})
|
|
|
|
}
|
2020-09-25 23:38:42 +02:00
|
|
|
}
|
|
|
|
|
2021-08-03 22:08:13 +02:00
|
|
|
#[interrupt]
|
|
|
|
fn RTC1() {
|
2021-08-25 18:50:05 +02:00
|
|
|
DRIVER.on_interrupt()
|
2021-01-13 03:17:42 +01:00
|
|
|
}
|
|
|
|
|
2021-08-18 22:12:36 +02:00
|
|
|
pub(crate) fn init(irq_prio: crate::interrupt::Priority) {
|
2021-08-25 18:50:05 +02:00
|
|
|
DRIVER.init(irq_prio)
|
2020-09-24 19:59:20 +02:00
|
|
|
}
|