time: replace dyn clock/alarm with a global Driver trait

This commit is contained in:
Dario Nieuwenhuis
2021-08-03 22:08:13 +02:00
parent a4c0ee6df7
commit 0ea6a2d890
47 changed files with 663 additions and 814 deletions

View File

@ -23,6 +23,8 @@ compile_error!("No chip feature activated. You must activate exactly one of the
pub(crate) mod fmt;
pub(crate) mod util;
mod time_driver;
pub mod buffered_uarte;
pub mod gpio;
pub mod gpiote;
@ -32,7 +34,6 @@ pub mod pwm;
#[cfg(feature = "nrf52840")]
pub mod qspi;
pub mod rng;
pub mod rtc;
#[cfg(not(feature = "nrf52820"))]
pub mod saadc;
pub mod spim;
@ -160,7 +161,10 @@ pub fn init(config: config::Config) -> Peripherals {
while r.events_lfclkstarted.read().bits() == 0 {}
// Init GPIOTE
crate::gpiote::init(config.gpiote_interrupt_priority);
gpiote::init(config.gpiote_interrupt_priority);
// init RTC time driver
time_driver::init();
peripherals
}

View File

@ -1,13 +1,17 @@
use core::cell::Cell;
use core::sync::atomic::{compiler_fence, AtomicU32, Ordering};
use core::sync::atomic::{compiler_fence, AtomicU32, AtomicU8, Ordering};
use core::{mem, ptr};
use critical_section::CriticalSection;
use embassy::interrupt::InterruptExt;
use embassy::time::Clock;
use embassy::util::{CriticalSectionMutex as Mutex, Unborrow};
use embassy::interrupt::{Interrupt, InterruptExt};
use embassy::time::driver::{AlarmHandle, Driver};
use embassy::util::CriticalSectionMutex as Mutex;
use crate::interrupt::Interrupt;
use crate::interrupt;
use crate::pac;
use crate::{interrupt, peripherals};
fn rtc() -> &'static pac::rtc0::RegisterBlock {
unsafe { &*pac::RTC1::ptr() }
}
// RTC timekeeping works with something we call "periods", which are time intervals
// of 2^23 ticks. The RTC counter value is 24 bits, so one "overflow cycle" is 2 periods.
@ -57,46 +61,45 @@ mod test {
struct AlarmState {
timestamp: Cell<u64>,
callback: Cell<Option<(fn(*mut ()), *mut ())>>,
// This is really a Option<(fn(*mut ()), *mut ())>
// but fn pointers aren't allowed in const yet
callback: Cell<*const ()>,
ctx: Cell<*mut ()>,
}
unsafe impl Send for AlarmState {}
impl AlarmState {
fn new() -> Self {
const fn new() -> Self {
Self {
timestamp: Cell::new(u64::MAX),
callback: Cell::new(None),
callback: Cell::new(ptr::null()),
ctx: Cell::new(ptr::null_mut()),
}
}
}
const ALARM_COUNT: usize = 3;
pub struct RTC<T: Instance> {
rtc: T,
irq: T::Interrupt,
struct State {
/// Number of 2^23 periods elapsed since boot.
period: AtomicU32,
alarm_count: AtomicU8,
/// Timestamp at which to fire alarm. u64::MAX if no alarm is scheduled.
alarms: Mutex<[AlarmState; ALARM_COUNT]>,
}
unsafe impl<T: Instance> Send for RTC<T> {}
unsafe impl<T: Instance> Sync for RTC<T> {}
const ALARM_STATE_NEW: AlarmState = AlarmState::new();
static STATE: State = State {
period: AtomicU32::new(0),
alarm_count: AtomicU8::new(0),
alarms: Mutex::new([ALARM_STATE_NEW; ALARM_COUNT]),
};
impl<T: Instance> RTC<T> {
pub fn new(rtc: T, irq: T::Interrupt) -> Self {
Self {
rtc,
irq,
period: AtomicU32::new(0),
alarms: Mutex::new([AlarmState::new(), AlarmState::new(), AlarmState::new()]),
}
}
pub fn start(&'static self) {
let r = self.rtc.regs();
impl State {
fn init(&'static self) {
let r = rtc();
r.cc[3].write(|w| unsafe { w.bits(0x800000) });
r.intenset.write(|w| {
@ -111,17 +114,11 @@ impl<T: Instance> RTC<T> {
// Wait for clear
while r.counter.read().bits() != 0 {}
self.irq.set_handler(|ptr| unsafe {
let this = &*(ptr as *const () as *const Self);
this.on_interrupt();
});
self.irq.set_handler_context(self as *const _ as *mut _);
self.irq.unpend();
self.irq.enable();
unsafe { interrupt::RTC1::steal() }.enable();
}
fn on_interrupt(&self) {
let r = self.rtc.regs();
let r = rtc();
if r.events_ovrflw.read().bits() == 1 {
r.events_ovrflw.write(|w| w);
self.next_period();
@ -144,7 +141,7 @@ impl<T: Instance> RTC<T> {
fn next_period(&self) {
critical_section::with(|cs| {
let r = self.rtc.regs();
let r = rtc();
let period = self.period.fetch_add(1, Ordering::Relaxed) + 1;
let t = (period as u64) << 23;
@ -152,38 +149,77 @@ impl<T: Instance> RTC<T> {
let alarm = &self.alarms.borrow(cs)[n];
let at = alarm.timestamp.get();
let diff = at - t;
if diff < 0xc00000 {
r.cc[n].write(|w| unsafe { w.bits(at as u32 & 0xFFFFFF) });
if at < t + 0xc00000 {
// just enable it. `set_alarm` has already set the correct CC val.
r.intenset.write(|w| unsafe { w.bits(compare_n(n)) });
}
}
})
}
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)
}
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) }
}
fn trigger_alarm(&self, n: usize, cs: CriticalSection) {
let r = self.rtc.regs();
let r = rtc();
r.intenclr.write(|w| unsafe { w.bits(compare_n(n)) });
let alarm = &self.alarms.borrow(cs)[n];
alarm.timestamp.set(u64::MAX);
// Call after clearing alarm, so the callback can set another alarm.
if let Some((f, ctx)) = alarm.callback.get() {
f(ctx);
// 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());
}
fn allocate_alarm(&self) -> Option<AlarmHandle> {
let id = self
.alarm_count
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |x| {
if x < ALARM_COUNT as u8 {
Some(x + 1)
} else {
None
}
});
match id {
Ok(id) => Some(unsafe { AlarmHandle::new(id) }),
Err(_) => None,
}
}
fn set_alarm_callback(&self, n: usize, callback: fn(*mut ()), ctx: *mut ()) {
fn set_alarm_callback(&self, alarm: AlarmHandle, callback: fn(*mut ()), ctx: *mut ()) {
critical_section::with(|cs| {
let alarm = &self.alarms.borrow(cs)[n];
alarm.callback.set(Some((callback, ctx)));
let alarm = self.get_alarm(cs, alarm);
// safety: it's OK to transmute a fn pointer into a raw pointer
let callback_ptr: *const () = unsafe { mem::transmute(callback) };
alarm.callback.set(callback_ptr);
alarm.ctx.set(ctx);
})
}
fn set_alarm(&self, n: usize, timestamp: u64) {
fn set_alarm(&self, alarm: AlarmHandle, timestamp: u64) {
critical_section::with(|cs| {
let alarm = &self.alarms.borrow(cs)[n];
let n = alarm.id() as _;
let alarm = self.get_alarm(cs, alarm);
alarm.timestamp.set(timestamp);
let t = self.now();
@ -194,25 +230,30 @@ impl<T: Instance> RTC<T> {
return;
}
let r = self.rtc.regs();
let r = rtc();
// If it hasn't triggered yet, setup it in the compare channel.
// 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) });
let diff = timestamp - t;
if diff < 0xc00000 {
// 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) });
r.intenset.write(|w| unsafe { w.bits(compare_n(n)) });
} else {
// If it's too far in the future, don't setup the compare channel yet.
@ -221,74 +262,34 @@ impl<T: Instance> RTC<T> {
}
})
}
}
pub fn alarm0(&'static self) -> Alarm<T> {
Alarm { n: 0, rtc: self }
struct RtcDriver;
embassy::time_driver_impl!(RtcDriver);
impl Driver for RtcDriver {
fn now() -> u64 {
STATE.now()
}
pub fn alarm1(&'static self) -> Alarm<T> {
Alarm { n: 1, rtc: self }
unsafe fn allocate_alarm() -> Option<AlarmHandle> {
STATE.allocate_alarm()
}
pub fn alarm2(&'static self) -> Alarm<T> {
Alarm { n: 2, rtc: self }
fn set_alarm_callback(alarm: AlarmHandle, callback: fn(*mut ()), ctx: *mut ()) {
STATE.set_alarm_callback(alarm, callback, ctx)
}
fn set_alarm(alarm: AlarmHandle, timestamp: u64) {
STATE.set_alarm(alarm, timestamp)
}
}
impl<T: Instance> embassy::time::Clock for RTC<T> {
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 = self.rtc.regs().counter.read().bits();
calc_now(period, counter)
}
#[interrupt]
fn RTC1() {
STATE.on_interrupt()
}
pub struct Alarm<T: Instance> {
n: usize,
rtc: &'static RTC<T>,
pub(crate) fn init() {
STATE.init()
}
impl<T: Instance> embassy::time::Alarm for Alarm<T> {
fn set_callback(&self, callback: fn(*mut ()), ctx: *mut ()) {
self.rtc.set_alarm_callback(self.n, callback, ctx);
}
fn set(&self, timestamp: u64) {
self.rtc.set_alarm(self.n, timestamp);
}
fn clear(&self) {
self.rtc.set_alarm(self.n, u64::MAX);
}
}
mod sealed {
use super::*;
pub trait Instance {
fn regs(&self) -> &pac::rtc0::RegisterBlock;
}
}
macro_rules! impl_instance {
($type:ident, $irq:ident) => {
impl sealed::Instance for peripherals::$type {
fn regs(&self) -> &pac::rtc0::RegisterBlock {
unsafe { &*pac::$type::ptr() }
}
}
impl Instance for peripherals::$type {
type Interrupt = interrupt::$irq;
}
};
}
/// Implemented by all RTC instances.
pub trait Instance: Unborrow<Target = Self> + sealed::Instance + 'static {
/// The interrupt associated with this RTC instance.
type Interrupt: Interrupt;
}
impl_instance!(RTC0, RTC0);
impl_instance!(RTC1, RTC1);
#[cfg(any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840"))]
impl_instance!(RTC2, RTC2);