1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
// SPDX-License-Identifier: Apache-2.0
use core::sync::atomic::{AtomicU32, Ordering};
#[cfg(test)]
use core::sync::atomic::AtomicBool;
#[cfg(feature = "embedded-hal")]
const NANOS_PER_SECOND: u128 = 1_000_000_000;
/// A 64-bit timer based on SysTick.
///
/// Stores wraparounds in 2 32-bit atomics. Scales the systick counts
/// to arbitrary frequency.
pub struct Timer {
inner_wraps: AtomicU32, // Counts SysTick interrupts (lower 32 bits)
outer_wraps: AtomicU32, // Counts overflows of inner_wraps (upper 32 bits)
reload_value: u32, // SysTick reload value (max 2^24 - 1)
#[cfg(feature = "embedded-hal")]
systick_freq: u64, // Input SysTick frequency in Hz
tick_hz: u64, // Output frequency in Hz
multiplier: u64, // Precomputed for scaling cycles to ticks
shift: u32, // Precomputed for scaling efficiency
#[cfg(test)]
current_systick: AtomicU32,
#[cfg(test)]
after_v1_hook: Option<fn(&Timer)>, // injected nested call site
#[cfg(test)]
pendst_is_pending: AtomicBool, // emulated SCB->ICSR PENDSTSET bit
}
impl Timer {
fn stable_cycle_snapshot(&self) -> (u64, u64) {
let reload = self.reload_value as u64;
loop {
// The order of these reads is critical to preventing race conditions.
// 1. Read the high-level state (wrap counters).
let in1 = self.inner_wraps.load(Ordering::SeqCst) as u64;
let out1 = self.outer_wraps.load(Ordering::SeqCst) as u64;
let wraps_pre = (out1 << 32) | in1;
// 2. Read the low-level hardware value.
let val_before = self.get_syst() as u64;
// 3. Re-read the high-level state to detect if an ISR ran during our reads.
let in2 = self.inner_wraps.load(Ordering::SeqCst) as u64;
let out2 = self.outer_wraps.load(Ordering::SeqCst) as u64;
let wraps_post = (out2 << 32) | in2;
// If the wrap counters changed, an ISR ran. Our snapshot is inconsistent,
// so we must loop again to get a clean read.
if wraps_pre != wraps_post {
continue;
}
// If we're here, the wrap counters are stable, but we need to handle the race
// where PendST could have flipped after wraps_pre but before wraps_post.
// Re-sample both PendST and VAL now that we know the counters are consistent.
let is_pending = self.is_systick_pending_internal();
let val_after = self.get_syst() as u64;
// Double-check that no ISR ran during our PendST/VAL re-sampling.
let in3 = self.inner_wraps.load(Ordering::SeqCst) as u64;
let out3 = self.outer_wraps.load(Ordering::SeqCst) as u64;
let wraps_final = (out3 << 32) | in3;
if wraps_final != wraps_pre {
// Wrap counters changed during our final reads - loop again
continue;
}
// Now we have a truly stable snapshot. Determine if a wrap occurred:
// 1. PendST is set (hardware detected a wrap)
// 2. VAL increased (SysTick counts down, so increase means wrap occurred)
let wrap_occurred = is_pending || val_after > val_before;
//
// KEY DESIGN DECISION: This +1 compensation handles exactly ONE missed wrap.
// If the ISR is starved for 2+ wrap periods, we get monotonic violations.
let (wraps_u64, final_val) = if wrap_occurred {
// A wrap occurred after we read wraps_pre. Use the post-wrap VAL reading.
(wraps_pre + 1, val_after)
} else {
// No wrap occurred. Use the most recent VAL reading for consistency.
(wraps_pre, val_after)
};
// Return the cycle snapshot as wrap count and current VAL-derived low part.
return (wraps_u64, reload - final_val);
}
}
/// SysTick handler.
///
/// Call this from the SysTick interrupt handler.
pub fn systick_handler(&self) {
// Increment inner_wraps and check for overflow
let inner = self.inner_wraps.load(Ordering::Relaxed);
// Check for overflow (inner was u32::MAX)
// Store the incremented value
self.inner_wraps
.store(inner.wrapping_add(1), Ordering::SeqCst);
if inner == u32::MAX {
// Increment outer_wraps
let outer = self.outer_wraps.load(Ordering::Relaxed).wrapping_add(1);
self.outer_wraps.store(outer, Ordering::SeqCst);
}
}
/// Robust `now()` (VAL-jump tie-breaker, no COUNTFLAG dependency).
///
/// ## Design: One-Wrap Compensation via PendST Detection
/// This implementation is designed to handle exactly **one missed SysTick wrap**.
///
/// **How it works:**
/// 1. Uses PendST bit to detect when the SysTick ISR is pending (hardware wrapped but ISR hasn't run)
/// 2. If PendST is set, adds +1 to the wrap count to compensate for the missed wrap
/// 3. This allows monotonic time even when the ISR is delayed by up to one full wrap period
///
/// **Design limit:**
/// If the SysTick ISR is starved for MORE than one complete wrap period, this compensation
/// becomes insufficient and monotonic violations occur. The ISR starvation detection logic
/// in `diagnose_timing_violation()` identifies these as catastrophic "N+1 missed wraps".
pub fn now(&self) -> u64 {
let reload = self.reload_value as u64;
let (wraps_u64, low_part) = self.stable_cycle_snapshot();
// Calculate final time.
let reload_plus_1 = reload + 1;
// If cycles computation would overflow u64, use u128 path from the start
if wraps_u64 > (u64::MAX - low_part) / reload_plus_1 {
let cycles128 = (wraps_u64 as u128) * (reload_plus_1 as u128) + (low_part as u128);
let ticks128 = cycles128 * (self.multiplier as u128);
return (ticks128 >> self.shift) as u64;
}
let total_cycles = wraps_u64 * reload_plus_1 + low_part;
// Scale to ticks.
let (result, mul_overflow) = total_cycles.overflowing_mul(self.multiplier);
if mul_overflow {
let wide = (total_cycles as u128) * (self.multiplier as u128);
return (wide >> self.shift) as u64;
}
result >> self.shift
}
/// Returns the current SysTick counter value.
pub fn get_syst(&self) -> u32 {
#[cfg(test)]
return self.current_systick.load(Ordering::SeqCst);
#[cfg(all(not(test), feature = "cortex-m"))]
return cortex_m::peripheral::SYST::get_current();
#[cfg(all(not(test), not(feature = "cortex-m")))]
panic!("This module requires the cortex-m crate to be available");
}
/// Returns the SysTick reload value configured for this timer.
pub const fn reload_value(&self) -> u32 {
self.reload_value
}
/// Returns the output tick frequency in Hz.
pub const fn tick_hz(&self) -> u64 {
self.tick_hz
}
#[cfg(feature = "embedded-hal")]
fn delay_cycles_from_ns(&self, ns: u32) -> u64 {
if ns == 0 || self.systick_freq == 0 {
return 0;
}
let ticks = (((ns as u128) * (self.systick_freq as u128)) + (NANOS_PER_SECOND - 1))
/ NANOS_PER_SECOND;
ticks.min(u64::MAX as u128) as u64
}
#[cfg(feature = "embedded-hal")]
fn current_cycles_wrapping(&self) -> u64 {
let reload_plus_1 = self.reload_value as u64 + 1;
let (wraps_u64, low_part) = self.stable_cycle_snapshot();
wraps_u64.wrapping_mul(reload_plus_1).wrapping_add(low_part)
}
#[cfg(feature = "embedded-hal")]
/// Blocking delay helper.
///
/// Requires the underlying SysTick timer to be started and actively
/// advancing. If the hardware counter is stalled, this loop will not
/// complete.
fn delay_cycles_blocking(&self, cycles: u64) {
if cycles == 0 {
return;
}
let start = self.current_cycles_wrapping();
while self.current_cycles_wrapping().wrapping_sub(start) < cycles {
core::hint::spin_loop();
}
}
/// Internal method to check if the SysTick interrupt is pending.
fn is_systick_pending_internal(&self) -> bool {
#[cfg(test)]
return self.pendst_is_pending.load(Ordering::SeqCst);
#[cfg(all(not(test), feature = "cortex-m"))]
return cortex_m::peripheral::SCB::is_pendst_pending();
#[cfg(all(not(test), not(feature = "cortex-m")))]
return false; // Or panic, depending on desired behavior without cortex-m
}
/// Checks if the SysTick interrupt is pending (diagnostic method).
#[cfg(feature = "diagnostics")]
pub fn is_systick_pending(&self) -> bool {
self.is_systick_pending_internal()
}
// Figure out a shift that leads to less precision loss
const fn compute_shift(tick_hz: u64, systick_freq: u64) -> u32 {
let mut shift = 32;
let mut multiplier = (tick_hz << shift) / systick_freq;
while multiplier == 0 && shift < 64 {
shift += 1;
multiplier = (tick_hz << shift) / systick_freq;
}
shift
}
/// Creates a new timer that converts SysTick cycles to ticks at a specified frequency.
///
/// # Arguments
///
/// * `tick_hz` - The desired output frequency in Hz (e.g., 1000 for millisecond ticks)
/// * `reload_value` - The SysTick reload value. Must be between 1 and 2^24-1.
/// This determines how many cycles occur between interrupts.
/// * `systick_freq` - The frequency of the SysTick counter in Hz (typically CPU frequency)
///
/// # Panics
///
/// * If `reload_value` is 0 or greater than 2^24-1 (16,777,215)
/// * If `systick_freq` is 0
///
/// # Examples
///
/// ```
/// # use systick_timer::Timer;
/// // Create a millisecond-resolution timer on a 48MHz CPU with reload value of 47,999
/// let timer = Timer::new(1000, 47_999, 48_000_000);
/// ```
pub const fn new(tick_hz: u64, reload_value: u32, systick_freq: u64) -> Self {
if reload_value > (1 << 24) - 1 {
panic!("Reload value too large");
}
if reload_value == 0 {
panic!("Reload value cannot be 0");
}
if systick_freq == 0 {
panic!("SysTick frequency cannot be 0");
}
// Use a shift to maintain precision and keep multiplier within u64
let shift = Self::compute_shift(tick_hz, systick_freq);
let multiplier = (tick_hz << shift) / systick_freq;
Timer {
inner_wraps: AtomicU32::new(0),
outer_wraps: AtomicU32::new(0),
reload_value,
#[cfg(feature = "embedded-hal")]
systick_freq,
tick_hz,
multiplier,
shift,
#[cfg(test)]
current_systick: AtomicU32::new(0),
#[cfg(test)]
after_v1_hook: None,
#[cfg(test)]
pendst_is_pending: AtomicBool::new(false),
}
}
/// Call this if you haven't already started the timer.
#[cfg(feature = "cortex-m")]
pub fn start(&self, syst: &mut cortex_m::peripheral::SYST) {
syst.set_clock_source(cortex_m::peripheral::syst::SystClkSource::Core);
syst.set_reload(self.reload_value);
syst.clear_current();
syst.enable_interrupt();
syst.enable_counter();
}
/// Check if a time difference indicates ISR starvation beyond design limits.
///
/// This timer implementation compensates for exactly one missed SysTick wrap using
/// the PendST bit detection mechanism. If the SysTick ISR is starved longer than
/// one complete wrap period, monotonic violations will occur.
///
/// Returns `Some(total_missed_wraps)` if the backwards jump matches the pattern of
/// ISR starvation (N+1 total missed wraps). Returns `None` for other timing issues.
#[cfg(feature = "diagnostics")]
pub fn diagnose_timing_violation(
&self,
current_time: u64,
previous_time: u64,
systick_freq: u64,
) -> Option<u32> {
if current_time >= previous_time {
return None; // Not a backwards jump
}
let backwards_jump = previous_time - current_time;
let wrap_period_ns = ((self.reload_value as u64 + 1) * 1_000_000_000) / systick_freq;
// Convert backwards_jump from ticks to nanoseconds for comparison
// backwards_jump is in ticks scaled by tick_hz
let backwards_jump_ns = (backwards_jump * 1_000_000_000) / self.tick_hz;
// Check if backwards jump is close to N complete wrap periods
// If so, this indicates N+1 total missed wraps (since PendST already compensated for 1)
for observed_periods in 1..=3 {
let expected_jump = observed_periods * wrap_period_ns;
let tolerance = wrap_period_ns / 100; // 1% tolerance
if backwards_jump_ns >= expected_jump.saturating_sub(tolerance)
&& backwards_jump_ns <= expected_jump + tolerance
{
return Some(observed_periods as u32 + 1); // +1 because PendST compensated for first wrap
}
}
None
}
}
impl Timer {
// -------- test-only helpers ----------
#[cfg(test)]
pub fn set_syst(&self, value: u32) {
debug_assert!(
value <= self.reload_value,
"set_syst: value {} exceeds reload {}",
value,
self.reload_value
);
self.current_systick.store(value, Ordering::SeqCst);
}
#[cfg(test)]
pub fn set_after_v1_hook(&mut self, hook: Option<fn(&Timer)>) {
self.after_v1_hook = hook;
}
#[cfg(test)]
pub fn set_pendst_pending(&self, val: bool) {
self.pendst_is_pending.store(val, Ordering::SeqCst);
}
}
#[cfg(feature = "embedded-hal")]
/// Busy-wait delay implementation backed by SysTick progress.
///
/// Callers must start the timer with [`Timer::start`] before using this trait.
/// If SysTick is not running, delay calls will not complete.
impl embedded_hal::delay::DelayNs for Timer {
fn delay_ns(&mut self, ns: u32) {
let cycles = self.delay_cycles_from_ns(ns);
self.delay_cycles_blocking(cycles);
}
}
#[cfg(feature = "embedded-hal")]
/// Busy-wait delay implementation backed by SysTick progress.
///
/// Callers must start the timer with [`Timer::start`] before using this trait.
/// If SysTick is not running, delay calls will not complete.
impl embedded_hal::delay::DelayNs for &Timer {
fn delay_ns(&mut self, ns: u32) {
let cycles = self.delay_cycles_from_ns(ns);
self.delay_cycles_blocking(cycles);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn test_zero_systick_freq() {
Timer::new(1000, 5, 0);
}
#[test]
fn test_timer_new() {
let timer = Timer::new(1000, 5, 12_000);
timer.inner_wraps.store(4, Ordering::Relaxed); // 4 interrupts = 24 cycles
timer.set_syst(3); // Start of next period
assert_eq!(timer.now(), 2); // Should be ~2 ticks
}
#[test]
fn test_compute_shift() {
assert_eq!(Timer::compute_shift(1000, 12_000), 32);
// This ratio overflows 32bit, so we shift
assert_eq!(Timer::compute_shift(3, 16_000_000_000), 33);
}
#[cfg(feature = "embedded-hal")]
#[test]
fn test_delay_cycles_from_ns_rounds_up() {
let timer = Timer::new(1_000_000, 5, 8_000_000);
assert_eq!(timer.delay_cycles_from_ns(0), 0);
assert_eq!(timer.delay_cycles_from_ns(1), 1);
assert_eq!(timer.delay_cycles_from_ns(125), 1);
assert_eq!(timer.delay_cycles_from_ns(126), 2);
}
#[cfg(feature = "embedded-hal")]
#[test]
fn test_delay_cycles_from_ns_saturates() {
let timer = Timer {
inner_wraps: AtomicU32::new(0),
outer_wraps: AtomicU32::new(0),
reload_value: 5,
systick_freq: u64::MAX,
tick_hz: 1,
multiplier: 0,
shift: 0,
current_systick: AtomicU32::new(0),
after_v1_hook: None,
pendst_is_pending: AtomicBool::new(false),
};
assert_eq!(timer.delay_cycles_from_ns(u32::MAX), u64::MAX);
}
#[cfg(feature = "embedded-hal")]
#[test]
fn test_delay_ns_trait_for_timer_accepts_zero_delay() {
let mut timer = Timer::new(1_000_000, 5, 1_000_000);
embedded_hal::delay::DelayNs::delay_ns(&mut timer, 0);
}
#[cfg(feature = "embedded-hal")]
#[test]
fn test_delay_ns_trait_for_timer_reference_accepts_zero_delay() {
let timer = Timer::new(1_000_000, 5, 1_000_000);
let mut delay = &timer;
embedded_hal::delay::DelayNs::delay_ns(&mut delay, 0);
}
#[cfg(feature = "embedded-hal")]
#[test]
fn test_delay_ns_waits_full_duration_from_partial_tick_phase() {
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
fn advance_one_cycle(timer: &Timer, reload: u32) {
let current = timer.get_syst();
if current == 0 {
timer.systick_handler();
timer.set_syst(reload);
} else {
timer.set_syst(current - 1);
}
}
const RELOAD: u32 = 9;
let timer = Arc::new(Timer::new(1, RELOAD, 10));
timer.set_syst(1);
let done = Arc::new(AtomicBool::new(false));
let timer_for_thread = Arc::clone(&timer);
let done_for_thread = Arc::clone(&done);
let handle = thread::spawn(move || {
let mut delay = &*timer_for_thread;
embedded_hal::delay::DelayNs::delay_ns(&mut delay, 1_000_000_000);
done_for_thread.store(true, AtomicOrdering::SeqCst);
});
thread::sleep(Duration::from_millis(10));
assert!(!done.load(AtomicOrdering::SeqCst));
for _ in 0..9 {
advance_one_cycle(&timer, RELOAD);
thread::sleep(Duration::from_millis(1));
}
assert!(!done.load(AtomicOrdering::SeqCst));
advance_one_cycle(&timer, RELOAD);
thread::sleep(Duration::from_millis(10));
assert!(done.load(AtomicOrdering::SeqCst));
handle.join().unwrap();
}
#[test]
fn test_timer_initial_state() {
let timer = Timer::new(1000, 5, 12_000);
assert_eq!(timer.now(), 0);
}
struct TestTimer<const RELOAD: u32> {
timer: Timer,
}
impl<const RELOAD: u32> TestTimer<RELOAD> {
fn new(tick_hz: u64, systick_freq: u64) -> Self {
Self {
timer: Timer::new(tick_hz, RELOAD, systick_freq),
}
}
fn interrupt(&mut self) {
self.timer.systick_handler();
self.timer.set_syst(RELOAD);
}
fn set_tick(&mut self, tick: u32) -> u64 {
assert!(tick <= RELOAD);
self.timer.set_syst(tick);
self.timer.now()
}
}
#[test]
fn test_timer_matching_rates() {
let mut timer = TestTimer::<5>::new(1000, 1000);
assert_eq!(timer.set_tick(5), 0);
assert_eq!(timer.set_tick(4), 1);
assert_eq!(timer.set_tick(0), 5);
timer.interrupt();
assert_eq!(timer.set_tick(5), 6);
}
#[test]
fn test_timer_tick_rate_2x() {
let mut timer = TestTimer::<5>::new(2000, 1000);
assert_eq!(timer.set_tick(5), 0);
assert_eq!(timer.set_tick(4), 2);
assert_eq!(timer.set_tick(0), 10);
timer.interrupt();
assert_eq!(timer.set_tick(5), 12);
timer.interrupt();
assert_eq!(timer.set_tick(5), 24);
}
#[test]
fn test_systick_rate_2x() {
let mut timer = TestTimer::<5>::new(1000, 2000);
assert_eq!(timer.set_tick(5), 0);
assert_eq!(timer.set_tick(4), 0);
assert_eq!(timer.set_tick(3), 1);
assert_eq!(timer.set_tick(2), 1);
assert_eq!(timer.set_tick(0), 2);
timer.interrupt();
assert_eq!(timer.set_tick(5), 3);
timer.interrupt();
assert_eq!(timer.set_tick(5), 6);
}
#[test]
fn test_outer_wraps_wrapping() {
let mut timer = TestTimer::<5>::new(1000, 1000);
// Set up for outer_wraps overflow
timer.timer.inner_wraps.store(u32::MAX, Ordering::Relaxed);
timer.timer.outer_wraps.store(u32::MAX, Ordering::Relaxed);
timer.timer.set_syst(5);
// One more interrupt should wrap outer_wraps
timer.interrupt();
// Should still count correctly despite wrapping
// With matching rates, we expect total_cycles * (1000/1000) ticks
assert_eq!(timer.set_tick(5), ((1u128 << 64) * 1000 / 1000) as u64);
}
#[test]
fn test_extreme_rates() {
// Test with very high tick rate vs systick rate (1000:1)
let mut timer = TestTimer::<5>::new(1_000_000, 1000);
assert_eq!(timer.set_tick(5), 0);
timer.interrupt(); // One interrupt = 6 cycles, each cycle = 1000 ticks
assert_eq!(timer.set_tick(5), 6000); // 6 cycles * 1000 ticks/cycle
// Test with very low tick rate vs systick rate (1:1000)
let mut timer = TestTimer::<5>::new(1000, 1_000_000);
// With 1000:1 ratio and reload of 5 (6 cycles per interrupt)
// We need (1_000_000/1000 * 6) = 6000 cycles for 6 ticks
// So we need 1000 interrupts for 6 ticks
for _ in 0..1000 {
timer.interrupt();
}
assert_eq!(timer.set_tick(5), 5); // Should get 5 complete ticks
}
#[test]
fn test_boundary_conditions() {
// Test with minimum reload value
let mut timer = TestTimer::<1>::new(1000, 1000);
assert_eq!(timer.set_tick(1), 0);
assert_eq!(timer.set_tick(0), 1);
timer.interrupt();
assert_eq!(timer.set_tick(1), 2);
// Test with maximum reload value
let mut timer = TestTimer::<0xFFFFFF>::new(1000, 1000);
assert_eq!(timer.set_tick(0xFFFFFF), 0);
assert_eq!(timer.set_tick(0xFFFF00), 255);
assert_eq!(timer.set_tick(0), 0xFFFFFF);
}
#[test]
fn test_partial_tick_accuracy() {
// With matching rates, test partial periods
let mut timer = TestTimer::<100>::new(1000, 1000);
assert_eq!(timer.set_tick(100), 0); // Start of period
assert_eq!(timer.set_tick(75), 25); // 25% through period = 25 ticks
assert_eq!(timer.set_tick(50), 50); // 50% through period = 50 ticks
assert_eq!(timer.set_tick(25), 75); // 75% through period = 75 ticks
assert_eq!(timer.set_tick(0), 100); // End of period = 100 ticks
}
#[test]
fn test_interrupt_race() {
let mut timer = TestTimer::<5>::new(1000, 1000);
timer.interrupt();
timer.timer.set_syst(3);
let t1 = timer.timer.now();
timer.interrupt();
let t2 = timer.timer.now();
assert!(t2 > t1); // Monotonicity
}
#[test]
fn test_rapid_interrupts() {
let mut timer = TestTimer::<5>::new(1000, 1000);
// With matching rates, each interrupt = 6 cycles = 6 ticks
for _ in 0..10 {
timer.interrupt();
}
// 10 interrupts * 6 cycles/interrupt * (1000/1000) = 60 ticks
assert_eq!(timer.set_tick(5), 60);
// At position 2, we're 3 cycles in = 3 more ticks
assert_eq!(timer.set_tick(2), 63);
}
#[test]
fn test_u64_overflow_scenario() {
// Timer configuration from the real application:
// TICK_RESOLUTION: 10_000_000 (tick_hz)
// reload_value: 0xFFFFFF (16,777,215)
// systick_freq: 100_000_000
let timer = Timer::new(10_000_000, 0xFFFFFF, 100_000_000);
let total_interrupts = 2560u64;
let outer = (total_interrupts >> 32) as u32;
let inner = total_interrupts as u32;
timer.outer_wraps.store(outer, Ordering::Relaxed);
timer.inner_wraps.store(inner, Ordering::Relaxed);
// This call should take the u128 fallback path.
let expected_ticks = 4_296_645_011;
assert_eq!(timer.now(), expected_ticks);
}
#[test]
fn test_monotonicity_around_wrap() {
const RELOAD: u32 = 100;
let timer = Timer::new(1_000, RELOAD, 1_000);
// 1. Time right before the wrap
timer.set_syst(1);
let t1 = timer.now();
// 2. Simulate the hardware wrap:
// - The ISR has NOT run yet, but the pending bit is set.
timer.set_syst(RELOAD);
timer.set_pendst_pending(true);
// 3. Time right after the wrap
let t2 = timer.now();
// The key assertion: time must not go backward.
// The new logic reads the COUNTFLAG and virtually adds a wrap,
// preventing the non-monotonic jump.
assert!(
t2 >= t1,
"Timer is not monotonic: t1 was {}, t2 was {}",
t1,
t2
);
// For sanity, let's check the values.
// t1 should be close to the end of a period.
// t2 should be at the beginning of the *next* period.
assert_eq!(t1, 99);
assert_eq!(t2, 101);
}
#[test]
fn test_monotonicity_between_interrupts() {
const RELOAD: u32 = 100;
let timer = Timer::new(1_000, RELOAD, 1_000);
// Set the counter to the reload value, no wraps yet.
timer.set_syst(RELOAD);
let t1 = timer.now();
// Simulate time passing by decrementing the hardware counter.
timer.set_syst(RELOAD / 2);
let t2 = timer.now();
// Decrement again.
timer.set_syst(0);
let t3 = timer.now();
// Assert that time is always moving forward.
assert!(t2 > t1, "t2 ({}) should be > t1 ({})", t2, t1);
assert!(t3 > t2, "t3 ({}) should be > t2 ({})", t3, t2);
// Also check the specific values for correctness.
assert_eq!(t1, 0);
assert_eq!(t2, 50);
assert_eq!(t3, 100);
}
const RELOAD: u32 = 100; // small for easy arithmetic; period = 101 cycles
#[test]
fn test_monotonicity_with_starved_isr() {
// This test simulates the "hardest path" scenario:
// 1. A wrap occurs, setting the PENDST bit.
// 2. The SysTick ISR is "starved" by a higher-priority interrupt and does not run.
// 3. Multiple calls to now() are made from the higher-priority context.
// 4. All calls must see the pending wrap and report monotonic time.
let timer = Timer::new(1_000, RELOAD, 1_000); // 1 tick per cycle
// State 1: Right before a wrap.
timer.set_syst(1);
let t1 = timer.now();
assert_eq!(t1, 100 - 1);
// State 2: Hardware wraps, ISR is pended but does not run.
// We manually simulate this state.
timer.set_pendst_pending(true);
timer.set_syst(RELOAD - 10); // Timer has wrapped and counted down a bit.
// First call to now() after the wrap. It must see the pending bit.
let t2 = timer.now();
let expected_t2 = (0 + 1) * (RELOAD as u64 + 1) + (RELOAD as u64 - (RELOAD as u64 - 10));
assert_eq!(t2, expected_t2);
assert!(
t2 > t1,
"Time must advance after wrap. t1={}, t2={}",
t1,
t2
);
// State 3: More time passes, ISR is still starved.
timer.set_syst(RELOAD - 20);
// Second call to now(). It must still see the pending bit.
let t3 = timer.now();
let expected_t3 = (0 + 1) * (RELOAD as u64 + 1) + (RELOAD as u64 - (RELOAD as u64 - 20));
assert_eq!(t3, expected_t3);
assert!(
t3 > t2,
"Time must advance even if ISR is starved. t2={}, t3={}",
t2,
t3
);
// State 4: The ISR finally runs, clearing the pending bit and incrementing wraps.
timer.set_pendst_pending(false);
timer.systick_handler(); // This increments inner_wraps to 1.
// Third call to now(). It should now use the updated wrap counter.
let t4 = timer.now();
let expected_t4 = 1 * (RELOAD as u64 + 1) + (RELOAD as u64 - (RELOAD as u64 - 20));
assert_eq!(t4, expected_t4);
assert_eq!(
t4, t3,
"Time should be consistent after ISR runs. t3={}, t4={}",
t3, t4
);
}
// The old tests for value-jump and COUNTFLAG are no longer relevant
// as the core logic has been replaced. The new test above provides
// superior coverage for the most critical race condition.
}
#[cfg(test)]
mod stress_test;