Skip to main content

ch32_hal/embassy/
time_driver_systick.rs

1//! SysTick-based time driver.
2
3use core::cell::RefCell;
4use core::sync::atomic::{AtomicU32, Ordering};
5
6use critical_section::CriticalSection;
7use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
8use embassy_sync::blocking_mutex::Mutex;
9use embassy_time_driver::Driver;
10use embassy_time_queue_utils::Queue;
11use pac::systick::vals;
12use qingke::interrupt::Priority;
13use qingke_rt::interrupt;
14
15use crate::pac;
16
17#[interrupt(core)]
18fn SysTick() {
19    DRIVER.on_interrupt();
20}
21
22pub struct SystickDriver {
23    cnt_per_tick: AtomicU32,
24    // floor((2^64 - 1) / cnt_per_tick), low word then high word. `now()` divides by multiplying
25    // with it: a 64-bit division is a software routine on RV32, and its run time depends on the count.
26    reciprocal: [AtomicU32; 2],
27    queue: Mutex<CriticalSectionRawMutex, RefCell<Queue>>,
28}
29
30embassy_time_driver::time_driver_impl!(static DRIVER: SystickDriver = SystickDriver {
31    cnt_per_tick: AtomicU32::new(1), // avoid div by zero
32    reciprocal: [AtomicU32::new(u32::MAX), AtomicU32::new(u32::MAX)],
33    queue: Mutex::new(RefCell::new(Queue::new()))
34});
35
36impl SystickDriver {
37    fn init(&'static self, _cs: critical_section::CriticalSection) {
38        let r = &crate::pac::SYSTICK;
39        let hclk = crate::rcc::clocks().hclk.0 as u64;
40
41        let cnt_per_second = hclk / 8; // HCLK/8
42        let cnt_per_tick = cnt_per_second / embassy_time_driver::TICK_HZ;
43
44        assert!(cnt_per_tick > 0, "SysTick runs slower than TICK_HZ");
45        self.cnt_per_tick.store(cnt_per_tick as u32, Ordering::Relaxed);
46        let reciprocal = reciprocal(cnt_per_tick as u32);
47        self.reciprocal[0].store(reciprocal as u32, Ordering::Relaxed);
48        self.reciprocal[1].store((reciprocal >> 32) as u32, Ordering::Relaxed);
49
50        r.ctlr().write(|w| {
51            // Everything else is set to default (0)
52            w.set_init(true); // Initialize counter
53            w.set_ste(true); // Enable counter
54        });
55
56        // Write 0 to both halves of the compare register
57        r.cmph().write_value(0);
58        r.cmpl().write_value(0);
59
60        // Count value compare flag
61        r.sr().write(|w| w.set_cntif(false)); // clear
62
63        // Configration: Upcount, No reload, HCLK/8 as clock source
64        r.ctlr().modify(|w| {
65            w.set_mode(vals::Mode::UPCOUNT); // Counter mode
66            w.set_stre(false); // Auto reload count enable bit
67            w.set_stclk(vals::Stclk::HCLK_DIV8); // Counter system clock sourse selection bit
68        });
69    }
70
71    fn on_interrupt(&self) {
72        let r = &crate::pac::SYSTICK;
73        // Count value compare flag
74        r.sr().write(|w| w.set_cntif(false)); // clear IF
75
76        critical_section::with(|cs| {
77            self.trigger_alarm(cs);
78        });
79    }
80
81    #[inline]
82    fn raw_cnt(&self) -> u64 {
83        let r = crate::pac::SYSTICK;
84        loop {
85            let high = r.cnth().read();
86            let low = r.cntl().read();
87            if r.cnth().read() == high {
88                return (u64::from(high) << 32) | u64::from(low);
89            }
90        }
91    }
92
93    fn trigger_alarm(&self, cs: CriticalSection) {
94        let mut next = self.queue.borrow(cs).borrow_mut().next_expiration(self.raw_cnt());
95        while !self.set_alarm(cs, next) {
96            next = self.queue.borrow(cs).borrow_mut().next_expiration(self.raw_cnt());
97        }
98    }
99
100    fn set_alarm(&self, _cs: CriticalSection, next_alarm_cnt: u64) -> bool {
101        let r = &crate::pac::SYSTICK;
102
103        // TODO move this to schedule_wake
104        if next_alarm_cnt <= self.raw_cnt() {
105            // If alarm timestamp has passed the alarm will not fire.
106            // Disarm the alarm and return `false` to indicate that.
107            return false;
108        }
109
110        // Counter interrupt enable control bit
111        r.cmph().write_value((next_alarm_cnt >> 32) as u32);
112        r.cmpl().write_value((next_alarm_cnt) as u32);
113        r.ctlr().modify(|w| w.set_stie(true));
114        r.sr().write(|w| w.set_cntif(false));
115
116        if next_alarm_cnt <= self.raw_cnt() {
117            // If alarm timestamp has passed the alarm will not fire.
118            // Disarm the alarm and return `false` to indicate that.
119            r.ctlr().modify(|w| w.set_stie(false));
120            r.sr().write(|w| w.set_cntif(false));
121            return false;
122        }
123
124        true
125    }
126}
127
128impl Driver for SystickDriver {
129    // Out of line: with LTO, the reciprocal multiply can otherwise be copied into
130    // `Instant::now()` call sites, about 80 bytes each on RV32.
131    #[inline(never)]
132    fn now(&self) -> u64 {
133        let cnt_per_tick = self.cnt_per_tick.load(Ordering::Relaxed) as u64;
134        let reciprocal = u64::from(self.reciprocal[1].load(Ordering::Relaxed)) << 32
135            | u64::from(self.reciprocal[0].load(Ordering::Relaxed));
136        let cnt = self.raw_cnt();
137        // The reciprocal is rounded down, so this is the quotient or one less.
138        let ticks = mul_high(cnt, reciprocal);
139        if cnt - ticks * cnt_per_tick >= cnt_per_tick {
140            ticks + 1
141        } else {
142            ticks
143        }
144    }
145
146    fn schedule_wake(&self, ticks: u64, waker: &core::task::Waker) {
147        let cnt_per_tick = self.cnt_per_tick.load(Ordering::Relaxed) as u64;
148        critical_section::with(|cs| {
149            let mut queue = self.queue.borrow(cs).borrow_mut();
150
151            if queue.schedule_wake(ticks * cnt_per_tick, waker) {
152                let mut next = queue.next_expiration(self.raw_cnt());
153                while !self.set_alarm(cs, next) {
154                    next = queue.next_expiration(self.raw_cnt());
155                }
156            }
157        })
158    }
159}
160
161/// floor((2^64 - 1) / divisor), by long division: once, at init, without the 64-bit division routine.
162fn reciprocal(divisor: u32) -> u64 {
163    let divisor = u64::from(divisor);
164    let (mut quotient, mut remainder) = (0u64, 0u64);
165    for _ in 0..64 {
166        remainder = remainder << 1 | 1;
167        quotient <<= 1;
168        if remainder >= divisor {
169            remainder -= divisor;
170            quotient |= 1;
171        }
172    }
173    quotient
174}
175
176/// The high 64 bits of the 128-bit product, from 32-bit multiplications.
177fn mul_high(a: u64, b: u64) -> u64 {
178    let (a1, a0) = (a >> 32, a & 0xffff_ffff);
179    let (b1, b0) = (b >> 32, b & 0xffff_ffff);
180    let middle = ((a0 * b0) >> 32) + ((a1 * b0) & 0xffff_ffff) + ((a0 * b1) & 0xffff_ffff);
181    a1 * b1 + ((a1 * b0) >> 32) + ((a0 * b1) >> 32) + (middle >> 32)
182}
183
184pub(crate) fn init(cs: CriticalSection) {
185    DRIVER.init(cs);
186    use qingke_rt::CoreInterrupt;
187
188    // enable interrupt
189    unsafe {
190        qingke::pfic::set_priority(CoreInterrupt::SysTick as u8, Priority::P15 as u8);
191        qingke::pfic::enable_interrupt(CoreInterrupt::SysTick as u8);
192    }
193}