ax-runtime 0.12.1

Runtime library of ArceOS
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
use ax_task::time::{MonotonicDeadline, MonotonicInstant};

/// Absolute finite deadline accepted by the physical clockevent.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) struct ClockDeadline(MonotonicDeadline);

impl ClockDeadline {
    pub(crate) const fn from_nanos(deadline_ns: u64) -> Option<Self> {
        match MonotonicDeadline::from_nanos(deadline_ns) {
            Some(deadline) => Some(Self(deadline)),
            None => None,
        }
    }

    pub(crate) const fn from_monotonic(deadline: MonotonicDeadline) -> Self {
        Self(deadline)
    }

    pub(crate) const fn as_nanos(self) -> u64 {
        self.0.as_nanos()
    }

    pub(crate) const fn as_monotonic(self) -> MonotonicDeadline {
        self.0
    }
}

/// Lifecycle of the physical clockevent owned by the current CPU.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ClockEventPhase {
    Offline,
    Idle,
    Armed,
    Firing,
    /// An expired physical edge remains owned until IRQ-return rearm.
    Deferred,
}

/// Hardware action produced by one clockevent state transition.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ClockEventAction {
    None,
    Stop,
    Resume(ClockDeadline),
    Program(ClockDeadline),
}

/// Physical rearm ownership selected by the runtime integration layer.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ClockEventRearm {
    /// Reconcile the next edge in the firing transaction itself.
    #[cfg(test)]
    Immediate,
    /// Transfer rearm to the IRQ-return or scheduler-tail transaction.
    Deferred,
}

/// Move-only proof that one CPU lifecycle epoch owns a firing transaction.
#[derive(Debug, Eq, PartialEq)]
pub(crate) struct ClockEventFiringToken {
    cpu_epoch: u64,
    quiesce: ClockEventAction,
    logical_deadline_elapsed: bool,
    scheduler_deadline_elapsed: bool,
}

impl ClockEventFiringToken {
    pub(crate) const fn quiesce_action(&self) -> ClockEventAction {
        self.quiesce
    }
    pub(crate) const fn logical_deadline_elapsed(&self) -> bool {
        self.logical_deadline_elapsed
    }
    pub(crate) const fn scheduler_deadline_elapsed(&self) -> bool {
        self.scheduler_deadline_elapsed
    }
}

/// Result of claiming a physical timer interrupt edge.
#[derive(Debug, Eq, PartialEq)]
pub(crate) enum ClockEventIrqClaim {
    /// The edge has no live clockevent owner in this CPU epoch.
    Ignored,
    /// The armed epoch owns one bounded scheduler service transaction.
    Firing(ClockEventFiringToken),
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum SchedulerTickState {
    Running { next: ClockDeadline },
    Stopped { resume_from: Option<ClockDeadline> },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ClockEventDeviceState {
    Stopped,
    Started,
}

/// Single owner for every source merged into one physical per-CPU clockevent.
#[derive(Debug)]
pub(crate) struct LocalClockEvent {
    phase: ClockEventPhase,
    cpu_epoch: u64,
    scheduler_generation: u64,
    scheduler_deadline: Option<ClockDeadline>,
    runtime_deadline: Option<ClockDeadline>,
    scheduler_tick: SchedulerTickState,
    armed_deadline: Option<ClockDeadline>,
    device_state: ClockEventDeviceState,
}

impl LocalClockEvent {
    pub(crate) const fn offline() -> Self {
        Self {
            phase: ClockEventPhase::Offline,
            cpu_epoch: 0,
            scheduler_generation: 0,
            scheduler_deadline: None,
            runtime_deadline: None,
            scheduler_tick: SchedulerTickState::Stopped { resume_from: None },
            armed_deadline: None,
            device_state: ClockEventDeviceState::Stopped,
        }
    }

    pub(crate) fn online(&mut self, periodic: ClockDeadline) -> ClockEventAction {
        assert_eq!(
            self.phase,
            ClockEventPhase::Offline,
            "clockevent online transition requires the offline phase"
        );
        self.advance_cpu_epoch();
        self.scheduler_tick = SchedulerTickState::Running { next: periodic };
        self.phase = ClockEventPhase::Idle;
        self.reconcile_arm()
    }

    /// Stops the periodic scheduler tick before the owner CPU commits idle.
    pub(crate) fn stop_scheduler_tick_for_idle(&mut self) -> ClockEventAction {
        assert!(!matches!(
            self.phase,
            ClockEventPhase::Offline | ClockEventPhase::Firing | ClockEventPhase::Deferred
        ));
        let SchedulerTickState::Running { next } = self.scheduler_tick else {
            return ClockEventAction::None;
        };
        self.scheduler_tick = SchedulerTickState::Stopped {
            resume_from: Some(next),
        };
        self.reconcile_arm()
    }

    /// Restarts the scheduler tick after idle work becomes runnable.
    pub(crate) fn restart_scheduler_tick_after_idle(
        &mut self,
        now: MonotonicInstant,
        interval_ns: u64,
    ) -> ClockEventAction {
        assert!(!matches!(
            self.phase,
            ClockEventPhase::Offline | ClockEventPhase::Firing
        ));
        let SchedulerTickState::Stopped { resume_from } = self.scheduler_tick else {
            return ClockEventAction::None;
        };
        let next = match resume_from {
            Some(previous) => {
                crate::clock_event_runtime::next_periodic_deadline(previous, now, interval_ns)
            }
            None => crate::clock_event_runtime::initial_periodic_deadline(now, interval_ns),
        };
        self.scheduler_tick = SchedulerTickState::Running { next };
        if self.phase == ClockEventPhase::Deferred {
            // The timer IRQ that woke idle may still own a deferred rearm. Its
            // scheduler-tail/IRQ-return transaction will reconcile this newly
            // running tick exactly once before local IRQs are enabled.
            return ClockEventAction::None;
        }
        self.reconcile_arm()
    }

    pub(crate) fn take_offline(&mut self) -> ClockEventAction {
        if self.phase == ClockEventPhase::Offline {
            return ClockEventAction::None;
        }
        let must_stop = self.device_state == ClockEventDeviceState::Started;
        self.advance_cpu_epoch();
        self.phase = ClockEventPhase::Offline;
        {
            self.scheduler_deadline = None;
            self.runtime_deadline = None;
        }
        self.scheduler_tick = SchedulerTickState::Stopped { resume_from: None };
        self.armed_deadline = None;
        self.device_state = ClockEventDeviceState::Stopped;
        if must_stop {
            ClockEventAction::Stop
        } else {
            ClockEventAction::None
        }
    }
    pub(crate) fn publish_scheduler(
        &mut self,
        generation: u64,
        deadline: Option<MonotonicDeadline>,
    ) -> ClockEventAction {
        if generation <= self.scheduler_generation {
            return ClockEventAction::None;
        }
        self.scheduler_generation = generation;
        self.scheduler_deadline = deadline.map(ClockDeadline::from_monotonic);
        self.reconcile_scheduler_publication()
    }

    pub(crate) fn publish_runtime_deadline(
        &mut self,
        deadline: Option<MonotonicDeadline>,
    ) -> ClockEventAction {
        let deadline = deadline.map(ClockDeadline::from_monotonic);
        if self.runtime_deadline == deadline {
            return ClockEventAction::None;
        }
        self.runtime_deadline = deadline;
        self.reconcile_scheduler_publication()
    }

    /// Claims a physical timer edge for this CPU lifecycle epoch.
    ///
    /// Every edge observed while armed starts one hrtimer-style firing
    /// transaction. Logical expiry is decided by the scheduler using its own
    /// clock; an early or stale hardware edge therefore completes normally
    /// and reprograms the still-earliest absolute deadline exactly once.
    pub(crate) fn claim_irq_with_device_quiesce(
        &mut self,
        now: MonotonicInstant,
        device_quiesce_required: bool,
    ) -> ClockEventIrqClaim {
        match self.phase {
            ClockEventPhase::Offline | ClockEventPhase::Idle | ClockEventPhase::Firing => {
                return ClockEventIrqClaim::Ignored;
            }
            ClockEventPhase::Deferred => {
                return ClockEventIrqClaim::Ignored;
            }
            ClockEventPhase::Armed => {}
        }
        let _armed = self
            .armed_deadline
            .expect("armed clockevent must retain its physical deadline");
        assert_eq!(
            self.device_state,
            ClockEventDeviceState::Started,
            "an armed clockevent must own an observable physical source"
        );
        let logical_deadline_elapsed = self.has_immediate_work(now);
        let scheduler_deadline_elapsed = self
            .runtime_deadline
            .is_some_and(|deadline| now.reached(deadline.as_monotonic()));
        if scheduler_deadline_elapsed {
            // Linux removes the expired hrtick from the active hrtimer base
            // before running its callback. The scheduler will publish the
            // next rq-owned runtime edge, if any, before IRQs are restored.
            self.runtime_deadline = None;
        }
        self.armed_deadline = None;
        if device_quiesce_required {
            self.device_state = ClockEventDeviceState::Stopped;
        }
        self.phase = ClockEventPhase::Firing;
        ClockEventIrqClaim::Firing(ClockEventFiringToken {
            cpu_epoch: self.cpu_epoch,
            quiesce: if device_quiesce_required {
                ClockEventAction::Stop
            } else {
                ClockEventAction::None
            },
            logical_deadline_elapsed,
            scheduler_deadline_elapsed,
        })
    }

    #[cfg(test)]
    pub(crate) fn claim_irq(&mut self, now: MonotonicInstant) -> ClockEventIrqClaim {
        self.claim_irq_with_device_quiesce(now, true)
    }

    /// Advances periodic accounting without producing a scheduling decision.
    ///
    /// A periodic clockevent is only one physical wakeup source. Whether the
    /// current thread must be preempted remains an ax-task policy decision.
    pub(crate) fn advance_periodic(&mut self, now: MonotonicInstant, interval_ns: u64) -> bool {
        let SchedulerTickState::Running { next } = &mut self.scheduler_tick else {
            return false;
        };
        let current = *next;
        if !now.reached(current.as_monotonic()) {
            return false;
        }
        *next = crate::clock_event_runtime::next_periodic_deadline(current, now, interval_ns);
        true
    }

    pub(crate) fn finish_firing(
        &mut self,
        token: ClockEventFiringToken,
        rearm: ClockEventRearm,
    ) -> ClockEventAction {
        if token.cpu_epoch != self.cpu_epoch {
            return ClockEventAction::None;
        }
        assert_eq!(
            self.phase,
            ClockEventPhase::Firing,
            "clockevent finish requires a firing transaction"
        );
        match rearm {
            #[cfg(test)]
            ClockEventRearm::Immediate => {
                self.phase = ClockEventPhase::Idle;
                self.reconcile_arm()
            }
            ClockEventRearm::Deferred => {
                // Match Linux's TIF_HRTIMER_REARM transaction: the expired
                // comparator has left the active base while IRQs stay
                // disabled. Scheduler/IRQ return reconciles the latest logical
                // minimum exactly once before enabling IRQs.
                self.phase = ClockEventPhase::Deferred;
                ClockEventAction::None
            }
        }
    }

    /// Completes a deferred firing transaction before local IRQs are enabled.
    pub(crate) fn finish_deferred_rearm(&mut self) -> ClockEventAction {
        if self.phase != ClockEventPhase::Deferred {
            return ClockEventAction::None;
        }
        self.phase = ClockEventPhase::Idle;
        self.reconcile_arm()
    }

    #[cfg(test)]
    pub(crate) const fn phase(&self) -> ClockEventPhase {
        self.phase
    }

    #[cfg(test)]
    pub(crate) const fn cpu_epoch(&self) -> u64 {
        self.cpu_epoch
    }

    #[cfg(test)]
    pub(crate) const fn scheduler_generation(&self) -> u64 {
        self.scheduler_generation
    }

    #[cfg(test)]
    pub(crate) const fn scheduler_deadline(&self) -> Option<ClockDeadline> {
        self.scheduler_deadline
    }

    #[cfg(test)]
    pub(crate) const fn armed_deadline(&self) -> Option<ClockDeadline> {
        self.armed_deadline
    }
    pub(crate) fn has_immediate_work(&self, now: MonotonicInstant) -> bool {
        self.selected_deadline()
            .is_some_and(|deadline| now.reached(deadline.as_monotonic()))
    }

    fn selected_deadline(&self) -> Option<ClockDeadline> {
        let scheduler_tick = match self.scheduler_tick {
            SchedulerTickState::Running { next } => Some(next),
            SchedulerTickState::Stopped { .. } => None,
        };
        [
            scheduler_tick,
            self.scheduler_deadline,
            self.runtime_deadline,
        ]
        .into_iter()
        .flatten()
        .min()
    }

    fn reconcile_arm(&mut self) -> ClockEventAction {
        self.reconcile_arm_with_early_edge(false)
    }

    /// Reconciles a scheduler hrtimer publication without moving an already
    /// armed physical edge later.
    ///
    /// Linux updates the logical hrtimer expiry on a context switch, but only
    /// reprograms the local clockevent immediately when the new expiry is
    /// earlier. An obsolete earlier comparator is harmless: its IRQ observes
    /// that no logical deadline is due and rearms the new minimum. Keeping it
    /// avoids an APIC write on the common Fair-to-Fair switch path.
    fn reconcile_scheduler_publication(&mut self) -> ClockEventAction {
        self.reconcile_arm_with_early_edge(true)
    }

    fn reconcile_arm_with_early_edge(&mut self, keep_earlier_armed: bool) -> ClockEventAction {
        match self.phase {
            ClockEventPhase::Offline | ClockEventPhase::Firing => {
                return ClockEventAction::None;
            }
            ClockEventPhase::Deferred => return ClockEventAction::None,
            ClockEventPhase::Idle | ClockEventPhase::Armed => {}
        }
        let selected = self.selected_deadline();
        if let Some(armed) = self.armed_deadline {
            match selected {
                Some(deadline) if deadline == armed => return ClockEventAction::None,
                Some(deadline) if keep_earlier_armed && armed < deadline => {
                    return ClockEventAction::None;
                }
                Some(deadline) => {
                    self.armed_deadline = Some(deadline);
                    self.phase = ClockEventPhase::Armed;
                    return ClockEventAction::Program(deadline);
                }
                None => {
                    self.armed_deadline = None;
                    self.phase = ClockEventPhase::Idle;
                    self.device_state = ClockEventDeviceState::Stopped;
                    return ClockEventAction::Stop;
                }
            }
        }

        match selected {
            Some(deadline) => {
                self.armed_deadline = Some(deadline);
                self.phase = ClockEventPhase::Armed;
                if self.device_state == ClockEventDeviceState::Stopped {
                    self.device_state = ClockEventDeviceState::Started;
                    ClockEventAction::Resume(deadline)
                } else {
                    ClockEventAction::Program(deadline)
                }
            }
            None => {
                self.phase = ClockEventPhase::Idle;
                if self.device_state == ClockEventDeviceState::Started {
                    self.device_state = ClockEventDeviceState::Stopped;
                    ClockEventAction::Stop
                } else {
                    ClockEventAction::None
                }
            }
        }
    }

    fn advance_cpu_epoch(&mut self) {
        self.cpu_epoch = self
            .cpu_epoch
            .checked_add(1)
            .expect("clockevent CPU lifecycle epoch exhausted");
    }
}

#[cfg(test)]
mod single_task_tests {
    use ax_task::time::MonotonicInstant;

    use super::{
        ClockDeadline, ClockEventAction, ClockEventIrqClaim, ClockEventPhase, ClockEventRearm,
        LocalClockEvent,
    };

    fn deadline(nanos: u64) -> ClockDeadline {
        ClockDeadline::from_nanos(nanos).unwrap()
    }

    fn instant(nanos: u64) -> MonotonicInstant {
        MonotonicInstant::from_nanos(nanos).unwrap()
    }

    #[test]
    fn host_clockevent_exercises_the_single_task_lifecycle() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(event.phase(), ClockEventPhase::Offline);
        assert_eq!(event.cpu_epoch(), 0);
        assert_eq!(event.armed_deadline(), None);
        assert_eq!(event.claim_irq(instant(0)), ClockEventIrqClaim::Ignored);

        assert_eq!(
            event.online(deadline(100)),
            ClockEventAction::Resume(deadline(100))
        );
        assert_eq!(event.phase(), ClockEventPhase::Armed);
        assert_eq!(event.cpu_epoch(), 1);
        assert_eq!(event.armed_deadline(), Some(deadline(100)));
        assert!(event.advance_periodic(instant(100), 25));

        let firing = match event.claim_irq(instant(100)) {
            ClockEventIrqClaim::Firing(firing) => firing,
            claim => panic!("armed clockevent was not claimed: {claim:?}"),
        };
        assert_eq!(event.phase(), ClockEventPhase::Firing);
        assert_eq!(
            event.finish_firing(firing, ClockEventRearm::Immediate),
            ClockEventAction::Resume(deadline(125))
        );
        assert_eq!(event.phase(), ClockEventPhase::Armed);
        assert_eq!(event.armed_deadline(), Some(deadline(125)));

        assert_eq!(event.take_offline(), ClockEventAction::Stop);
        assert_eq!(event.take_offline(), ClockEventAction::None);
        assert_eq!(event.phase(), ClockEventPhase::Offline);
        assert_eq!(event.armed_deadline(), None);
    }
}

#[cfg(test)]
mod tests {
    use ax_task::time::{MonotonicDeadline, MonotonicInstant};

    use super::{
        ClockDeadline, ClockEventAction, ClockEventDeviceState, ClockEventFiringToken,
        ClockEventIrqClaim, ClockEventPhase, ClockEventRearm, LocalClockEvent,
    };

    fn deadline(nanos: u64) -> ClockDeadline {
        ClockDeadline::from_nanos(nanos).unwrap()
    }

    fn instant(nanos: u64) -> MonotonicInstant {
        MonotonicInstant::from_nanos(nanos).unwrap()
    }

    fn scheduler_deadline(nanos: u64) -> MonotonicDeadline {
        MonotonicDeadline::from_nanos(nanos).unwrap()
    }

    fn fire_due(event: &mut LocalClockEvent, now_ns: u64) -> ClockEventFiringToken {
        match event.claim_irq(instant(now_ns)) {
            ClockEventIrqClaim::Firing(token) => token,
            claim => panic!("due clockevent was not claimed: {claim:?}"),
        }
    }

    #[test]
    fn values_outside_linux_ktime_are_not_physical_deadlines() {
        assert_eq!(ClockDeadline::from_nanos(u64::MAX), None);
        assert_eq!(
            ClockDeadline::from_nanos(ax_task::time::KTIME_MAX_NANOS),
            Some(deadline(ax_task::time::KTIME_MAX_NANOS))
        );
    }

    #[test]
    fn zero_is_a_valid_already_due_physical_deadline() {
        assert_eq!(ClockDeadline::from_nanos(0), Some(deadline(0)));
    }

    #[test]
    fn offline_stops_the_device_and_allows_a_fresh_online_cycle() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(100)),
            ClockEventAction::Resume(deadline(100))
        );
        assert_eq!(event.take_offline(), ClockEventAction::Stop);
        assert_eq!(event.phase(), ClockEventPhase::Offline);
        assert_eq!(event.armed_deadline(), None);
        assert_eq!(
            event.online(deadline(200)),
            ClockEventAction::Resume(deadline(200))
        );
    }

    #[test]
    fn stale_irq_after_reonline_cannot_fire_the_new_cpu_epoch_early() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(100)),
            ClockEventAction::Resume(deadline(100))
        );
        assert_eq!(event.take_offline(), ClockEventAction::Stop);
        assert_eq!(
            event.online(deadline(200)),
            ClockEventAction::Resume(deadline(200))
        );

        // A stale physical edge enters the same firing transaction as any
        // other hrtimer edge. Since no logical deadline is due, finish
        // reprograms the new epoch's still-earliest deadline.
        let firing = match event.claim_irq(instant(150)) {
            ClockEventIrqClaim::Firing(firing) => firing,
            claim => panic!("armed edge was not claimed: {claim:?}"),
        };
        assert_eq!(
            event.finish_firing(firing, ClockEventRearm::Immediate),
            ClockEventAction::Resume(deadline(200))
        );
        assert_eq!(event.phase(), ClockEventPhase::Armed);
        assert_eq!(event.armed_deadline(), Some(deadline(200)));
    }

    #[test]
    fn old_firing_token_cannot_commit_across_an_offline_cycle() {
        let mut event = LocalClockEvent::offline();
        event.online(deadline(100));
        let old_epoch = event.cpu_epoch();
        let firing = fire_due(&mut event, 100);

        assert_eq!(event.take_offline(), ClockEventAction::None);
        event.online(deadline(200));
        assert!(event.cpu_epoch() > old_epoch);

        assert_eq!(
            event.finish_firing(firing, ClockEventRearm::Immediate),
            ClockEventAction::None
        );
        assert_eq!(event.phase(), ClockEventPhase::Armed);
        assert_eq!(event.armed_deadline(), Some(deadline(200)));
    }

    #[test]
    fn idle_entry_removes_the_scheduler_tick_from_physical_selection() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(100)),
            ClockEventAction::Resume(deadline(100))
        );
        assert_eq!(
            event.publish_scheduler(1, Some(scheduler_deadline(1_000)),),
            ClockEventAction::None
        );

        assert_eq!(
            event.stop_scheduler_tick_for_idle(),
            ClockEventAction::Program(deadline(1_000))
        );
        assert_eq!(event.armed_deadline(), Some(deadline(1_000)));
    }

    #[test]
    fn idle_exit_restarts_the_tick_on_its_original_phase() {
        let mut event = LocalClockEvent::offline();
        event.online(deadline(100));
        assert_eq!(event.stop_scheduler_tick_for_idle(), ClockEventAction::Stop);

        assert_eq!(
            event.restart_scheduler_tick_after_idle(instant(149), 25),
            ClockEventAction::Resume(deadline(150))
        );
        assert_eq!(event.armed_deadline(), Some(deadline(150)));
    }

    #[test]
    fn repeated_idle_iteration_keeps_the_scheduler_tick_stopped() {
        let mut event = LocalClockEvent::offline();
        event.online(deadline(100));
        assert_eq!(event.stop_scheduler_tick_for_idle(), ClockEventAction::Stop);
        assert_eq!(event.stop_scheduler_tick_for_idle(), ClockEventAction::None);
        assert_eq!(event.phase(), ClockEventPhase::Idle);
        assert_eq!(event.armed_deadline(), None);
    }

    #[test]
    fn stale_scheduler_generation_cannot_cross_an_offline_cycle() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.publish_scheduler(7, Some(scheduler_deadline(90)),),
            ClockEventAction::None
        );
        assert_eq!(
            event.online(deadline(100)),
            ClockEventAction::Resume(deadline(90))
        );
        assert_eq!(event.take_offline(), ClockEventAction::Stop);
        assert_eq!(
            event.publish_scheduler(6, Some(scheduler_deadline(50)),),
            ClockEventAction::None
        );
        assert_eq!(
            event.online(deadline(200)),
            ClockEventAction::Resume(deadline(200))
        );
        assert_eq!(event.scheduler_generation(), 7);
        assert_eq!(event.scheduler_deadline(), None);
    }

    #[test]
    #[should_panic(expected = "finite monotonic clock domain")]
    fn periodic_overflow_is_a_fatal_clock_domain_violation() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(ax_task::time::KTIME_MAX_NANOS - 5)),
            ClockEventAction::Resume(deadline(ax_task::time::KTIME_MAX_NANOS - 5))
        );
        let _firing = fire_due(&mut event, ax_task::time::KTIME_MAX_NANOS - 1);
        assert!(event.advance_periodic(instant(ax_task::time::KTIME_MAX_NANOS - 1), 10));
    }

    #[test]
    fn later_live_scheduler_deadline_keeps_a_future_earlier_slice_edge() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(500)),
            ClockEventAction::Resume(deadline(500))
        );
        assert_eq!(
            event.publish_scheduler(1, Some(scheduler_deadline(300)),),
            ClockEventAction::Program(deadline(300))
        );
        assert!(
            !event.has_immediate_work(instant(250)),
            "the obsolete slice edge must still be reprogrammable"
        );

        assert_eq!(
            event.publish_scheduler(2, Some(scheduler_deadline(400)),),
            ClockEventAction::None,
            "a later current-task expiry must not move the physical edge later"
        );
        assert_eq!(event.scheduler_deadline(), Some(deadline(400)));
        assert_eq!(event.armed_deadline(), Some(deadline(300)));
    }

    #[test]
    fn later_scheduler_deadline_keeps_the_earlier_physical_edge_until_it_fires() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(500)),
            ClockEventAction::Resume(deadline(500))
        );
        assert_eq!(
            event.publish_scheduler(1, Some(scheduler_deadline(300)),),
            ClockEventAction::Program(deadline(300))
        );

        assert_eq!(
            event.publish_scheduler(2, Some(scheduler_deadline(400)),),
            ClockEventAction::None,
            "Linux keeps an already armed earlier hrtimer edge instead of moving it later"
        );
        assert_eq!(event.scheduler_deadline(), Some(deadline(400)));
        assert_eq!(event.armed_deadline(), Some(deadline(300)));

        let firing = fire_due(&mut event, 300);
        assert!(
            !firing.logical_deadline_elapsed(),
            "the retained edge must not claim a later logical deadline"
        );
        assert_eq!(
            event.finish_firing(firing, ClockEventRearm::Immediate),
            ClockEventAction::Resume(deadline(400))
        );
        assert_eq!(event.armed_deadline(), Some(deadline(400)));
    }

    #[test]
    fn later_logical_minimum_waits_for_the_earlier_armed_edge() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(500)),
            ClockEventAction::Resume(deadline(500))
        );
        assert_eq!(
            event.publish_scheduler(1, Some(scheduler_deadline(300)),),
            ClockEventAction::Program(deadline(300))
        );
        assert_eq!(
            event.publish_scheduler(2, Some(scheduler_deadline(400)),),
            ClockEventAction::None
        );
        assert_eq!(event.publish_scheduler(3, None), ClockEventAction::None);
        assert_eq!(event.armed_deadline(), Some(deadline(300)));
    }

    #[test]
    fn retained_early_edge_rearms_the_later_live_deadline() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(500)),
            ClockEventAction::Resume(deadline(500))
        );
        assert_eq!(
            event.publish_scheduler(1, Some(scheduler_deadline(300)),),
            ClockEventAction::Program(deadline(300))
        );
        assert!(
            event.has_immediate_work(instant(350)),
            "the programmed comparator is already elapsed before IRQ entry"
        );

        assert_eq!(
            event.publish_scheduler(2, Some(scheduler_deadline(400)),),
            ClockEventAction::None,
            "the elapsed edge is retained as an early hrtimer wakeup"
        );
        assert_eq!(event.armed_deadline(), Some(deadline(300)));

        // The retained earlier edge is an early firing for the new logical
        // minimum and must rearm that deadline without consuming it.
        let firing = fire_due(&mut event, 350);
        assert_eq!(
            event.finish_firing(firing, ClockEventRearm::Immediate),
            ClockEventAction::Resume(deadline(400))
        );
        assert_eq!(event.armed_deadline(), Some(deadline(400)));
    }

    #[test]
    fn stopped_to_armed_and_reprogram_are_distinct_device_actions() {
        let mut event = LocalClockEvent::offline();
        let start = event.online(deadline(500));
        let reprogram = event.publish_scheduler(1, Some(scheduler_deadline(300)));

        assert_eq!(start, ClockEventAction::Resume(deadline(500)));
        assert_eq!(reprogram, ClockEventAction::Program(deadline(300)));
    }

    #[test]
    fn removing_the_only_deadline_stops_the_obsolete_physical_edge() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(1_000)),
            ClockEventAction::Resume(deadline(1_000))
        );
        assert_eq!(event.stop_scheduler_tick_for_idle(), ClockEventAction::Stop);
        assert_eq!(
            event.publish_scheduler(1, Some(scheduler_deadline(300)),),
            ClockEventAction::Resume(deadline(300))
        );
        assert_eq!(event.publish_scheduler(2, None), ClockEventAction::Stop);
        assert_eq!(event.phase(), ClockEventPhase::Idle);
        assert_eq!(event.armed_deadline(), None);
        assert_eq!(event.claim_irq(instant(300)), ClockEventIrqClaim::Ignored);
    }

    #[test]
    fn stale_generation_is_ignored() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.publish_scheduler(7, Some(scheduler_deadline(200)),),
            ClockEventAction::None
        );
        assert_eq!(
            event.publish_scheduler(6, Some(scheduler_deadline(100)),),
            ClockEventAction::None
        );
        assert_eq!(event.scheduler_generation(), 7);
        assert_eq!(event.scheduler_deadline(), Some(deadline(200)));
    }

    #[test]
    fn firing_merges_updates_and_programs_exactly_once_at_finish() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(500)),
            ClockEventAction::Resume(deadline(500))
        );
        let firing = fire_due(&mut event, 500);
        assert_eq!(event.phase(), ClockEventPhase::Firing);
        assert_eq!(
            event.publish_scheduler(1, Some(scheduler_deadline(450)),),
            ClockEventAction::None
        );
        assert_eq!(
            event.publish_scheduler(2, Some(scheduler_deadline(250)),),
            ClockEventAction::None
        );
        assert_eq!(
            event.finish_firing(firing, ClockEventRearm::Immediate),
            ClockEventAction::Resume(deadline(250))
        );
        assert_eq!(event.phase(), ClockEventPhase::Armed);
    }

    #[test]
    fn periodic_advance_is_merged_with_scheduler_deadline() {
        let mut event = LocalClockEvent::offline();
        event.online(deadline(100));
        let firing = fire_due(&mut event, 100);
        assert!(!firing.scheduler_deadline_elapsed());
        assert!(event.advance_periodic(instant(100), 25));
        event.publish_scheduler(1, Some(scheduler_deadline(140)));
        assert_eq!(
            event.finish_firing(firing, ClockEventRearm::Immediate),
            ClockEventAction::Resume(deadline(125))
        );
    }

    #[test]
    fn simultaneous_periodic_and_scheduler_expiry_programs_one_replacement() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(100)),
            ClockEventAction::Resume(deadline(100))
        );
        assert_eq!(
            event.publish_runtime_deadline(Some(scheduler_deadline(100))),
            ClockEventAction::None
        );
        assert_eq!(
            event.publish_scheduler(1, Some(scheduler_deadline(100)),),
            ClockEventAction::None
        );

        let firing = fire_due(&mut event, 100);
        assert!(firing.scheduler_deadline_elapsed());
        assert!(event.advance_periodic(instant(100), 25));
        assert_eq!(event.publish_scheduler(2, None), ClockEventAction::None);

        assert_eq!(
            event.finish_firing(firing, ClockEventRearm::Immediate),
            ClockEventAction::Resume(deadline(125))
        );
        assert_eq!(event.armed_deadline(), Some(deadline(125)));
    }

    #[test]
    fn non_runtime_timer_expiry_does_not_claim_runtime_hrtick() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(500)),
            ClockEventAction::Resume(deadline(500))
        );
        assert_eq!(
            event.publish_runtime_deadline(Some(scheduler_deadline(300))),
            ClockEventAction::Program(deadline(300))
        );
        assert_eq!(
            event.publish_scheduler(1, Some(scheduler_deadline(100))),
            ClockEventAction::Program(deadline(100))
        );

        let firing = fire_due(&mut event, 100);
        assert!(firing.logical_deadline_elapsed());
        assert!(
            !firing.scheduler_deadline_elapsed(),
            "a non-runtime timer edge must not claim the later runtime hrtick"
        );
    }

    #[test]
    fn deferred_rearm_keeps_the_physical_edge_owned_until_irq_return() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(500)),
            ClockEventAction::Resume(deadline(500))
        );
        assert_eq!(
            event.publish_scheduler(1, Some(scheduler_deadline(100)),),
            ClockEventAction::Program(deadline(100))
        );

        let firing = fire_due(&mut event, 100);
        assert_eq!(
            event.finish_firing(firing, ClockEventRearm::Deferred),
            ClockEventAction::None,
            "multitask IRQ return must retain a deferred physical rearm owner"
        );
        assert_eq!(event.phase(), ClockEventPhase::Deferred);
        assert_eq!(event.armed_deadline(), None);

        assert_eq!(
            event.publish_scheduler(2, Some(scheduler_deadline(400)),),
            ClockEventAction::None,
            "logical publication cannot commit hardware before scheduler tail"
        );
        assert_eq!(event.phase(), ClockEventPhase::Deferred);
        assert_eq!(event.armed_deadline(), None);
        assert_eq!(
            event.finish_deferred_rearm(),
            ClockEventAction::Resume(deadline(400))
        );
        assert_eq!(event.phase(), ClockEventPhase::Armed);
        assert_eq!(event.armed_deadline(), Some(deadline(400)));
    }

    #[test]
    fn idle_exit_restarts_a_stopped_tick_during_deferred_rearm() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(100)),
            ClockEventAction::Resume(deadline(100))
        );
        assert_eq!(
            event.publish_scheduler(1, Some(scheduler_deadline(100)),),
            ClockEventAction::None
        );
        assert_eq!(event.stop_scheduler_tick_for_idle(), ClockEventAction::None);

        let firing = fire_due(&mut event, 100);
        assert_eq!(event.publish_scheduler(2, None), ClockEventAction::None);
        assert_eq!(
            event.finish_firing(firing, ClockEventRearm::Deferred),
            ClockEventAction::None
        );
        assert_eq!(event.phase(), ClockEventPhase::Deferred);

        assert_eq!(
            event.restart_scheduler_tick_after_idle(instant(100), 25),
            ClockEventAction::None,
            "the deferred owner must perform the sole physical rearm"
        );
        assert_eq!(
            event.finish_deferred_rearm(),
            ClockEventAction::Resume(deadline(125))
        );
        assert_eq!(event.armed_deadline(), Some(deadline(125)));
    }

    #[test]
    fn firing_quiesces_the_level_source_before_deferred_rearm() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(100)),
            ClockEventAction::Resume(deadline(100))
        );

        let firing = fire_due(&mut event, 100);
        assert_eq!(
            event.device_state,
            ClockEventDeviceState::Stopped,
            "an acknowledged level clockevent must be unobservable before controller EOI"
        );
        assert_eq!(
            event.finish_firing(firing, ClockEventRearm::Deferred),
            ClockEventAction::None
        );
        assert_eq!(
            event.finish_deferred_rearm(),
            ClockEventAction::Resume(deadline(100)),
            "deferred rearm must reactivate the quiesced source"
        );
    }

    #[test]
    fn early_irq_uses_one_firing_transaction_and_reprograms_once() {
        let mut event = LocalClockEvent::offline();
        assert_eq!(
            event.online(deadline(500)),
            ClockEventAction::Resume(deadline(500))
        );
        assert_eq!(
            event.publish_scheduler(1, Some(scheduler_deadline(100)),),
            ClockEventAction::Program(deadline(100))
        );

        let firing = match event.claim_irq(instant(50)) {
            ClockEventIrqClaim::Firing(firing) => firing,
            claim => panic!("armed edge was not claimed: {claim:?}"),
        };
        assert_eq!(
            event.finish_firing(firing, ClockEventRearm::Immediate),
            ClockEventAction::Resume(deadline(100))
        );
        assert_eq!(event.phase(), ClockEventPhase::Armed);
        assert_eq!(event.armed_deadline(), Some(deadline(100)));
    }

    #[test]
    fn idle_entry_stops_the_edge_and_ignores_a_residual_irq() {
        let mut event = LocalClockEvent::offline();
        event.online(deadline(500));
        assert_eq!(event.stop_scheduler_tick_for_idle(), ClockEventAction::Stop);
        assert_eq!(event.phase(), ClockEventPhase::Idle);
        assert_eq!(event.armed_deadline(), None);
        assert_eq!(event.claim_irq(instant(100)), ClockEventIrqClaim::Ignored);
    }

    #[test]
    fn overdue_scheduler_deadline_remains_immediate_until_firing_reconciles_it() {
        let mut event = LocalClockEvent::offline();
        event.online(deadline(500));
        assert_eq!(
            event.publish_scheduler(1, Some(scheduler_deadline(90)),),
            ClockEventAction::Program(deadline(90))
        );
        assert!(event.has_immediate_work(instant(100)));

        let firing = fire_due(&mut event, 100);
        assert_eq!(event.publish_scheduler(2, None), ClockEventAction::None);
        assert_eq!(
            event.finish_firing(firing, ClockEventRearm::Immediate),
            ClockEventAction::Resume(deadline(500))
        );
        assert!(!event.has_immediate_work(instant(100)));
    }
}