rusty_rtos_kernel-core 0.3.3

The pure no_std core of rusty_rtos_kernel: types, traits and algorithms with no CPU, no allocator and no operating system. forbid(unsafe).
Documentation
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
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
//! `timers.c`: software timers and the daemon task that runs them.
//!
//! A software timer is not an interrupt and not a thread. It is an entry on
//! one of two sorted lists, and a task — the daemon, `Tmr Svc` — that
//! blocks on a queue until either a command arrives or the head of the list
//! is due. Everything a caller does to a timer is a *message*: start, stop,
//! reset, change period, delete. Nothing touches the lists but the daemon.
//!
//! That indirection is the whole design, and it is why the trace has a
//! `TIMER_COMMAND_SEND` line for every call and a `TIMER_EXPIRED` line only
//! when the daemon gets round to it.
//!
//! Two things this kernel spells differently from the C, both because it
//! has no pointers:
//!
//! * the command queue carries an *index* into a ring of commands rather
//!   than a struct, so the queue keeps the length, the blocking and the
//!   full behaviour the trace depends on while the payload lives beside it;
//! * a callback is a small number the application's hook switches on,
//!   rather than a function pointer. `pvTimerID` rides along with it.

use rusty_rtos_core::config::Config;
use rusty_rtos_core::error::{Error, Result};
use rusty_rtos_core::handle::{TaskHandle, TimerHandle};
use rusty_rtos_core::hooks::TickHook;
use rusty_rtos_core::isr::Woken;
use rusty_rtos_core::list::ListId;
use rusty_rtos_core::port::Port;
use rusty_rtos_core::trace::{Event, Trace};

use crate::kernel::{Kernel, OwedTrace};
use crate::name::Name;
use crate::queue::{Position, Ready, Wait};

/// How many `DaemonTaskMessage_t`s the ring beside the timer queue holds.
///
/// The C's queue carries the structs themselves; this one carries indices
/// into here, so the queue keeps the length, the blocking and the
/// full behaviour a trace depends on while the payload lives beside it.
/// [`Config::validate`] refuses a `TIMER_QUEUE_LENGTH` larger than this,
/// for the same reason it bounds the notification arrays.
pub const MAX_TIMER_COMMANDS: usize = 32;

/// `tmrSTATUS_IS_ACTIVE`.
pub(crate) const STATUS_ACTIVE: u8 = 0x01;
/// `tmrSTATUS_IS_AUTORELOAD`.
pub(crate) const STATUS_AUTORELOAD: u8 = 0x04;

/// The command ids, exactly as `timers.h` numbers them — the numbering is
/// load-bearing, because `xTimerGenericCommandFromTask` refuses anything at
/// or above [`Command::FIRST_FROM_ISR`] and the from-ISR half refuses
/// anything below it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Command {
    /// `tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR`.
    ExecuteCallbackFromIsr,
    /// `tmrCOMMAND_EXECUTE_CALLBACK`.
    ExecuteCallback,
    /// `tmrCOMMAND_START`.
    Start,
    /// `tmrCOMMAND_RESET`.
    Reset,
    /// `tmrCOMMAND_STOP`.
    Stop,
    /// `tmrCOMMAND_CHANGE_PERIOD`.
    ChangePeriod,
    /// `tmrCOMMAND_DELETE`.
    Delete,
    /// `tmrCOMMAND_START_FROM_ISR`.
    StartFromIsr,
    /// `tmrCOMMAND_RESET_FROM_ISR`.
    ResetFromIsr,
    /// `tmrCOMMAND_STOP_FROM_ISR`.
    StopFromIsr,
    /// `tmrCOMMAND_CHANGE_PERIOD_FROM_ISR`.
    ChangePeriodFromIsr,
}

impl Command {
    /// `tmrFIRST_FROM_ISR_COMMAND`.
    pub const FIRST_FROM_ISR: i32 = 6;

    /// The number `timers.h` gives it, which is what the trace prints.
    #[must_use]
    pub const fn id(self) -> i32 {
        match self {
            Self::ExecuteCallbackFromIsr => -2,
            Self::ExecuteCallback => -1,
            Self::Start => 1,
            Self::Reset => 2,
            Self::Stop => 3,
            Self::ChangePeriod => 4,
            Self::Delete => 5,
            Self::StartFromIsr => 6,
            Self::ResetFromIsr => 7,
            Self::StopFromIsr => 8,
            Self::ChangePeriodFromIsr => 9,
        }
    }

    #[inline]
    const fn is_from_isr(self) -> bool {
        self.id() >= Self::FIRST_FROM_ISR
    }

    const fn is_start_or_reset(self) -> bool {
        matches!(
            self,
            Self::Start | Self::StartFromIsr | Self::Reset | Self::ResetFromIsr
        )
    }

    const fn is_stop(self) -> bool {
        matches!(self, Self::Stop | Self::StopFromIsr)
    }

    const fn is_change_period(self) -> bool {
        matches!(self, Self::ChangePeriod | Self::ChangePeriodFromIsr)
    }
}

/// One `DaemonTaskMessage_t`, kept beside the queue rather than in it.
#[derive(Debug, Clone, Copy)]
pub struct Message {
    /// Which command this is.
    pub command: Command,
    /// `xMessageValue` for a timer command; `ulParameter2` for a pended
    /// function call.
    pub(crate) value: u64,
    /// The timer the command is for, if it is a timer command.
    pub(crate) timer: TimerHandle,
    /// `pvParameter1` of a pended function call.
    pub(crate) param1: u64,
    /// Which pended function, for the hook to switch on.
    pub(crate) function: u16,
}

impl Default for Message {
    fn default() -> Self {
        Self {
            command: Command::Stop,
            value: 0,
            timer: TimerHandle::NULL,
            param1: 0,
            function: 0,
        }
    }
}

/// A `u64` held as two `u32`s, so it does not force eight-byte alignment.
///
/// `Timer` lives in an arena, and an arena slot pays its value's ALIGNMENT as
/// padding around the generation beside it. `Timer`'s fields sum to 36 bytes,
/// but two `u64`s aligned the struct to 8 and rounded the slot to 48. Aligned
/// to 4 it is 40 -- the same as the `Timer_t` the C allocates.
///
/// The public API still takes and answers `u64`; only the storage is split.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg(target_pointer_width = "32")]
pub(crate) struct Split64 {
    lo: u32,
    hi: u32,
}

/// On a 64-bit host a `u64` IS one register, so splitting it is pure cost:
/// every read pays a shift and an or to put back something the machine was
/// holding whole. Measured on `bench/sb-ir`, `StreamBufferDemo` **149,452,276
/// against 139,479,427** -- 7.2 % of the oracle, for a representation that
/// exists to help a machine the oracle is not.
///
/// This is STORAGE, not arithmetic: `new` and `get` are lossless and every
/// value computed from them is identical on both widths, so the conformance
/// corpus proves the same behaviour either way. The layout already differs by
/// pointer width (`usize` is four bytes on the targets and eight here), so
/// this adds no new axis of divergence.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg(not(target_pointer_width = "32"))]
pub(crate) struct Split64 {
    whole: u64,
}

#[cfg(target_pointer_width = "32")]
impl Split64 {
    /// Split a `u64`.
    pub(crate) const fn new(value: u64) -> Self {
        Self {
            lo: (value & 0xFFFF_FFFF) as u32,
            hi: (value >> 32) as u32,
        }
    }

    /// Put it back together.
    pub(crate) const fn get(self) -> u64 {
        (self.hi as u64) << 32 | self.lo as u64
    }
}

#[cfg(not(target_pointer_width = "32"))]
impl Split64 {
    /// Keep it whole.
    pub(crate) const fn new(value: u64) -> Self {
        Self { whole: value }
    }

    /// Hand it back.
    pub(crate) const fn get(self) -> u64 {
        self.whole
    }
}

/// One software timer: a `Timer_t` without the pointers.
#[derive(Debug, Clone, Copy, Default)]
pub struct Timer {
    pub(crate) name: Name,
    /// `xTimerPeriodInTicks`.
    pub(crate) period: Split64,
    /// `pvTimerID`.
    pub(crate) id: Split64,
    /// Which callback the application's hook should run.
    pub(crate) callback: u16,
    /// `ucStatus`.
    pub(crate) status: u8,
}

impl<
    C: Config,
    P: Port,
    T: Trace,
    H,
    const TASKS: usize,
    const ITEMS: usize,
    const LISTS: usize,
    const QUEUES: usize,
    const SLOTS: usize,
    const BUFFERS: usize,
    const BYTES: usize,
    const TIMERS: usize,
    const GROUPS: usize,
    const TIMER_CMDS: usize,
> Kernel<C, P, T, H, TASKS, ITEMS, LISTS, QUEUES, SLOTS, BUFFERS, BYTES, TIMERS, GROUPS, TIMER_CMDS>
where
    H: TickHook<Self>,
{
    /// `pxCurrentTimerList` and `pxOverflowTimerList`, as list ids. They sit
    /// after the ready lists and the four task lists, before the queues'.
    pub(crate) fn timer_list(&self) -> ListId {
        let base = C::MAX_PRIORITIES.saturating_add(4);
        base.saturating_add(u8::from(self.timers_swapped))
    }

    pub(crate) fn overflow_timer_list(&self) -> ListId {
        let base = C::MAX_PRIORITIES.saturating_add(4);
        base.saturating_add(u8::from(!self.timers_swapped))
    }

    /// The list item a timer sorts by. Task items come first, then one per
    /// timer.
    pub(crate) fn timer_item(timer: TimerHandle) -> u16 {
        (TASKS.saturating_mul(2) as u16).saturating_add(timer.index() as u16)
    }

    // ---------------------------------------------------------- creating --

    /// `xTimerCreate`.
    ///
    /// `callback` names which of the application's timer callbacks this
    /// timer runs; `id` is `pvTimerID`.
    ///
    /// # Errors
    /// [`Error::Full`] when the timer arena is full;
    /// [`Error::InvalidArgument`] for a zero period, which the C asserts on.
    pub fn timer_create(
        &mut self,
        name: &str,
        period: u64,
        auto_reload: bool,
        id: u64,
        callback: u16,
    ) -> Result<TimerHandle> {
        if period == 0 {
            return Err(Error::InvalidArgument);
        }
        // `pvPortMalloc( sizeof( Timer_t ) )` comes first.
        self.account_for_allocation();
        let status = if auto_reload { STATUS_AUTORELOAD } else { 0 };
        let handle = self
            .timers
            .try_insert(Timer {
                // A timer keeps the *pointer* to its name in the C, so it
                // is never truncated the way a task's is. `Oneshot Timer`
                // is thirteen characters and `configMAX_TASK_NAME_LEN` is
                // twelve.
                name: Name::new(name, crate::NAME_CAPACITY),
                period: Split64::new(period),
                id: Split64::new(id),
                callback,
                status,
            })
            .map_err(|_| Error::Full)?;
        // `prvInitialiseNewTimer` opens with `prvCheckForValidListAndQueue`.
        self.check_for_valid_list_and_queue()?;
        let tick = self.tick;
        // Gated, as its sibling `trace_command_send` already was: a sink that
        // never reads a name pays for neither the resolve nor the copy of the
        // whole `Name`. And the `as_str` is gated TOO, not just the resolve --
        // turning even a default `Name` into a `&str` calls
        // `core::str::from_utf8`, which is 534 bytes of validation this
        // kernel links for no other reason.
        let name = if T::WANTS_NAMES {
            self.timers
                .resolve(handle)
                .map(|t| t.name)
                .unwrap_or_default()
        } else {
            Name::default()
        };
        self.note_exits();
        self.trace.event(
            tick,
            Event::TimerCreate {
                timer: handle,
                name: if T::WANTS_NAMES { name.as_str() } else { "" },
            },
        );
        Ok(handle)
    }

    /// `prvCheckForValidListAndQueue`: make the command queue if no timer
    /// has made it yet, inside one critical section either way.
    ///
    /// The C makes it lazily, on the first `xTimerCreate` — which for
    /// `TimerDemo` is *before the scheduler starts*, so the queue is the
    /// first object in the trace and not the third. Everything the create
    /// does happens inside the outer section, so the whole thing is one
    /// outermost exit whether or not it built anything.
    ///
    /// # Errors
    /// As [`Kernel::queue_create`].
    // Out of line at BOTH callers: win 29, -8 B of flash and 2 fewer rv32
    // instructions, against `andi` +1.
    //
    // This said "A3: ONE caller in the linked kernel, so this pays a prologue
    // and epilogue for a single call" and carried `#[inline(always)]`. The
    // caller count was wrong -- `timer.rs` and `kernel.rs` both call it -- so
    // A3 never applied, and at two callers `always` DUPLICATES an 86-byte body
    // rather than moving it. Found by auditing every inline rationale in the
    // kernel against the actual census, which is the third wrong or
    // contradictory inline rationale found on 2026-09-25.
    #[inline(never)]
    pub(crate) fn check_for_valid_list_and_queue(&mut self) -> Result<()> {
        self.enter_critical();
        let result = if self.timer_queue.is_null() {
            match self.queue_create(C::TIMER_QUEUE_LENGTH) {
                Ok(queue) => {
                    self.timer_queue = queue;
                    Ok(())
                }
                Err(e) => Err(e),
            }
        } else {
            Ok(())
        };
        self.exit_critical();
        result
    }

    /// `pvTimerGetTimerID`.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn timer_id(&mut self, timer: TimerHandle) -> Result<u64> {
        // The C wraps this in a critical section.
        self.enter_critical();
        let id = self.timers.resolve(timer).map(|t| t.id.get());
        self.exit_critical();
        id
    }

    /// `vTimerSetTimerID`.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn timer_set_id(&mut self, timer: TimerHandle, id: u64) -> Result<()> {
        self.enter_critical();
        let result = self.timers.resolve_mut(timer).map(|t| {
            t.id = Split64::new(id);
        });
        self.exit_critical();
        result
    }

    /// `xTimerGetPeriod`.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn timer_period(&self, timer: TimerHandle) -> Result<u64> {
        self.timers.resolve(timer).map(|t| t.period.get())
    }

    /// `xTimerIsTimerActive`.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn timer_is_active(&mut self, timer: TimerHandle) -> Result<bool> {
        self.enter_critical();
        let active = self
            .timers
            .resolve(timer)
            .map(|t| (t.status & STATUS_ACTIVE) != 0);
        self.exit_critical();
        active
    }

    /// `xTimerGetExpiryTime`.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn timer_expiry_time(&self, timer: TimerHandle) -> Result<u64> {
        self.timers.resolve(timer)?;
        self.lists.value(Self::timer_item(timer))
    }

    /// `xTimerGetReloadMode`.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn timer_auto_reload(&mut self, timer: TimerHandle) -> Result<bool> {
        self.enter_critical();
        let auto = self
            .timers
            .resolve(timer)
            .map(|t| (t.status & STATUS_AUTORELOAD) != 0);
        self.exit_critical();
        auto
    }

    /// `vTimerSetReloadMode`.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn timer_set_auto_reload(&mut self, timer: TimerHandle, auto: bool) -> Result<()> {
        self.enter_critical();
        let result = self.timers.resolve_mut(timer).map(|t| {
            if auto {
                t.status |= STATUS_AUTORELOAD;
            } else {
                t.status &= !STATUS_AUTORELOAD;
            }
        });
        self.exit_critical();
        result
    }

    // --------------------------------------------------- sending commands --

    /// `xTimerGenericCommandFromTask`.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn timer_command(
        &mut self,
        timer: TimerHandle,
        command: Command,
        value: u64,
        ticks: u64,
    ) -> Result<Wait<bool>> {
        // The retry of a command that blocked on a full queue sends what its
        // first pass built. `xTimerStart` and `xTimerReset` read the tick
        // count ONCE, before the send, and the C carries that sample in the
        // message through the block; reading the clock again here made the
        // command time late by however long the task waited, and the timer
        // expire that much late. The API differential found it with the
        // daemon below a task (two cores, step 4015: blocked, a tick, then
        // the retry). The first pass's frame on the command queue is what
        // says this is a retry.
        let caller = self.cur();
        let retry = self.waiting_on(caller, self.timer_queue);
        let value = if retry { self.held(caller) } else { value };
        let message = Message {
            command,
            value,
            timer,
            ..Message::default()
        };
        // The C refuses a from-ISR command here and still traces the send.
        if command.is_from_isr() {
            self.trace_command_send(timer, command, value);
            return Ok(Ready(false));
        }
        // `if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )` — before
        // the scheduler runs, a command may not block.
        let ticks = if self.is_running() { ticks } else { 0 };
        // `caller` is also who to trace against. The C runs
        // `traceTIMER_COMMAND_SEND` on the line after `xQueueSendToBack`, so a
        // send that made the daemon ready switches away first and the line
        // runs when this task has the CPU back — after the `TASK_SWITCHED_IN`
        // that returns it.
        // `traceTIMER_COMMAND_SEND` fires whatever the send returned — and
        // a full queue is the *point* of TimerDemo's first test, which
        // starts exactly as many timers as the queue holds and then
        // requires the next one to fail.
        match self.post_timer_message(message, ticks) {
            Ok(Wait::Blocked) => {
                self.hold(caller, value);
                Ok(Wait::Blocked)
            }
            Ok(Ready(ok)) => {
                self.trace_command_send_for(caller, timer, command, value);
                Ok(Ready(ok))
            }
            Err(Error::Full) => {
                self.trace_command_send_for(caller, timer, command, value);
                Ok(Ready(false))
            }
            Err(e) => Err(e),
        }
    }

    /// `xTimerStart`.
    ///
    /// # Errors
    /// As [`Kernel::timer_command`].
    pub fn timer_start(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
        let now = self.tick;
        self.timer_command(timer, Command::Start, now, ticks)
    }

    /// `xTimerStop`.
    ///
    /// # Errors
    /// As [`Kernel::timer_command`].
    pub fn timer_stop(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
        self.timer_command(timer, Command::Stop, 0, ticks)
    }

    /// `xTimerReset`.
    ///
    /// # Errors
    /// As [`Kernel::timer_command`].
    pub fn timer_reset(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
        let now = self.tick;
        self.timer_command(timer, Command::Reset, now, ticks)
    }

    /// `xTimerChangePeriod`.
    ///
    /// A period of zero is refused. The C asserts against one, which on this
    /// harness ends the run; refusing is the same answer without ending it,
    /// and it matters because a zero-period auto-reload timer would reload
    /// for ever without the clock moving.
    ///
    /// # Errors
    /// [`Error::InvalidArgument`] for a zero period; otherwise as
    /// [`Kernel::timer_command`].
    pub fn timer_change_period(
        &mut self,
        timer: TimerHandle,
        period: u64,
        ticks: u64,
    ) -> Result<Wait<bool>> {
        if period == 0 {
            return Err(Error::InvalidArgument);
        }
        self.timer_command(timer, Command::ChangePeriod, period, ticks)
    }

    /// `xTimerDelete`.
    ///
    /// # Errors
    /// As [`Kernel::timer_command`].
    pub fn timer_delete(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
        self.timer_command(timer, Command::Delete, 0, ticks)
    }

    /// `xTimerStartFromISR`.
    ///
    /// # Errors
    /// As [`Kernel::timer_command_from_isr`].
    pub fn timer_start_from_isr(&mut self, timer: TimerHandle) -> Result<(bool, Woken)> {
        let now = self.tick_count_from_isr();
        self.timer_command_from_isr(timer, Command::StartFromIsr, now)
    }

    /// `xTimerStopFromISR`.
    ///
    /// # Errors
    /// As [`Kernel::timer_command_from_isr`].
    pub fn timer_stop_from_isr(&mut self, timer: TimerHandle) -> Result<(bool, Woken)> {
        self.timer_command_from_isr(timer, Command::StopFromIsr, 0)
    }

    /// `xTimerResetFromISR`.
    ///
    /// # Errors
    /// As [`Kernel::timer_command_from_isr`].
    pub fn timer_reset_from_isr(&mut self, timer: TimerHandle) -> Result<(bool, Woken)> {
        let now = self.tick_count_from_isr();
        self.timer_command_from_isr(timer, Command::ResetFromIsr, now)
    }

    /// `xTimerChangePeriodFromISR`.
    ///
    /// # Errors
    /// As [`Kernel::timer_command_from_isr`].
    pub fn timer_change_period_from_isr(
        &mut self,
        timer: TimerHandle,
        period: u64,
    ) -> Result<(bool, Woken)> {
        self.timer_command_from_isr(timer, Command::ChangePeriodFromIsr, period)
    }

    /// `xTimerGenericCommandFromISR`: the raw command, value and all.
    ///
    /// Prefer the four wrappers above. They exist because the C's public
    /// from-ISR API does not let a caller choose the value: a start or a
    /// reset always carries `xTaskGetTickCountFromISR()`. A value from
    /// somewhere else is a *command time* the daemon will believe, and a
    /// command time far enough in the future makes `prvReloadTimer` reload
    /// without ever landing in the future — a loop the C has too, and
    /// reaches the same way.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn timer_command_from_isr(
        &mut self,
        timer: TimerHandle,
        command: Command,
        value: u64,
    ) -> Result<(bool, Woken)> {
        if !command.is_from_isr() || (command.is_change_period() && value == 0) {
            self.trace_command_send(timer, command, value);
            return Ok((false, Woken::NO));
        }
        let message = Message {
            command,
            value,
            timer,
            ..Message::default()
        };
        let (ok, woken) = self.post_timer_message_from_isr(message)?;
        self.trace_command_send(timer, command, value);
        Ok((ok, woken))
    }

    /// `xTimerPendFunctionCall`: run `function` on the daemon task.
    ///
    /// # Errors
    /// As the queue send.
    pub fn timer_pend_function_call(
        &mut self,
        function: u16,
        param1: u64,
        param2: u64,
        ticks: u64,
    ) -> Result<Wait<bool>> {
        let message = Message {
            command: Command::ExecuteCallback,
            value: param2,
            timer: TimerHandle::NULL,
            param1,
            function,
        };
        // `tracePEND_FUNC_CALL` is not one of the harness's hooks, so this
        // says nothing on either side.
        self.post_timer_message(message, ticks)
    }

    /// `xTimerPendFunctionCallFromISR`.
    ///
    /// This is how `xEventGroupSetBitsFromISR` does its work: an interrupt
    /// cannot walk an event group's waiting list, so it hands the job to
    /// the daemon.
    ///
    /// # Errors
    /// As the queue send.
    pub fn timer_pend_function_call_from_isr(
        &mut self,
        function: u16,
        param1: u64,
        param2: u64,
    ) -> Result<(bool, Woken)> {
        let message = Message {
            command: Command::ExecuteCallbackFromIsr,
            value: param2,
            timer: TimerHandle::NULL,
            param1,
            function,
        };
        self.post_timer_message_from_isr(message)
    }

    fn trace_command_send(&mut self, timer: TimerHandle, command: Command, value: u64) {
        // Nothing to say, so nothing to build. `trace_failure_or_owe` returns
        // at once for a sink that emits nothing, but the forty-byte
        // `OwedTrace::TimerCommandSend` is assembled at THIS call site before
        // the call, and a `Name` copy with it.
        if !T::EMITS {
            return;
        }
        let tick = self.tick;
        // A sink that never reads a name pays for neither the resolve nor
        // the copy of the whole `Name` that goes with it.
        let name = if T::WANTS_NAMES {
            self.timers
                .resolve(timer)
                .map(|t| t.name)
                .unwrap_or_default()
        } else {
            Name::default()
        };
        self.note_exits();
        self.trace.event(
            tick,
            Event::TimerCommandSend {
                timer,
                // Gated for the same reason the resolve above is: `as_str` on
                // even a default `Name` reaches `core::str::from_utf8`.
                name: if T::WANTS_NAMES { name.as_str() } else { "" },
                command: command.id(),
                value,
            },
        );
    }

    /// The same line, but owed to `caller` if the send has already handed
    /// the CPU to the daemon.
    fn trace_command_send_for(
        &mut self,
        caller: TaskHandle,
        timer: TimerHandle,
        command: Command,
        value: u64,
    ) {
        // Nothing to say, so nothing to build. `trace_failure_or_owe` returns
        // at once for a sink that emits nothing, but the forty-byte
        // `OwedTrace::TimerCommandSend` is assembled at THIS call site before
        // the call, and a `Name` copy with it.
        if !T::EMITS {
            return;
        }
        // A sink that never reads a name pays for neither the resolve nor
        // the copy of the whole `Name` that goes with it.
        let name = if T::WANTS_NAMES {
            self.timers
                .resolve(timer)
                .map(|t| t.name)
                .unwrap_or_default()
        } else {
            Name::default()
        };
        self.trace_failure_or_owe(
            caller,
            OwedTrace::TimerCommandSend {
                timer,
                name,
                command: command.id(),
                value,
            },
        );
    }

    /// Put a message in the ring and its index on the queue.
    fn post_timer_message(&mut self, message: Message, ticks: u64) -> Result<Wait<bool>> {
        let slot = self.stage_timer_message(message);
        match self.send_generic_outlined(self.timer_queue, slot, ticks, Position::Back)? {
            Wait::Blocked => Ok(Wait::Blocked),
            Ready(()) => {
                self.commit_timer_message();
                Ok(Ready(true))
            }
        }
    }

    fn post_timer_message_from_isr(&mut self, message: Message) -> Result<(bool, Woken)> {
        let slot = self.stage_timer_message(message);
        match self.queue_send_from_isr(self.timer_queue, slot) {
            Ok(woken) => {
                self.commit_timer_message();
                Ok((true, woken))
            }
            Err(Error::Full) => Ok((false, Woken::NO)),
            Err(e) => Err(e),
        }
    }

    /// Write the message into the slot the next accepted send will use, and
    /// answer with that slot — the index the queue will carry.
    ///
    /// The C caller holds its `DaemonTaskMessage_t` on its own stack, so a
    /// send the queue refuses simply loses it and no other message is
    /// harmed. Here the message lives in a ring the queue carries indices
    /// into, and the queue's indices are always the run ending just before
    /// this pointer, so the slot it names is free exactly when the queue
    /// has room. When it has none the send cannot be accepted either, and
    /// writing would overwrite a message the daemon has not read yet — the
    /// oldest one, which is the next it will read.
    fn stage_timer_message(&mut self, message: Message) -> u64 {
        let slot = self.timer_message_next;
        if self.timer_queue_has_room() {
            if let Some(cell) = self.timer_messages.get_mut(slot) {
                *cell = message;
            }
        }
        slot as u64
    }

    /// The queue took the index, so the message it points at belongs to the
    /// queue until the daemon reads it.
    fn commit_timer_message(&mut self) {
        self.timer_message_next = self
            .timer_message_next
            .saturating_add(1)
            .checked_rem(C::TIMER_QUEUE_LENGTH)
            .unwrap_or(0);
    }

    /// `uxQueueSpacesAvailable( xTimerQueue ) > 0`, without its critical
    /// section — this is the kernel reading its own queue, not a task
    /// asking, so it must cost no sim time.
    fn timer_queue_has_room(&self) -> bool {
        self.queues
            .resolve(self.timer_queue)
            .is_ok_and(|q| q.waiting < q.length)
    }

    // ----------------------------------------------------- the daemon task --

    /// `prvGetNextExpireTime`: when the head of the current list is due, and
    /// whether there is a head at all.
    pub fn timer_next_expire(&self) -> (u64, bool) {
        let list = self.timer_list();
        let empty = self.lists.is_empty(list).unwrap_or(true);
        if empty {
            (0, true)
        } else {
            (self.lists.head_value(list).unwrap_or(0), false)
        }
    }

    /// Whether `pxOverflowTimerList` is empty, which is the second half of
    /// the daemon's "may I wait for ever?" test.
    #[must_use]
    pub fn overflow_timer_list_is_empty(&self) -> bool {
        self.lists
            .is_empty(self.overflow_timer_list())
            .unwrap_or(true)
    }

    /// `prvSampleTimeNow`: the tick, and whether reading it swapped the two
    /// timer lists because it wrapped.
    ///
    /// # Errors
    /// As the list operations.
    pub fn timer_sample_time_now(&mut self) -> Result<(u64, bool)> {
        let now = self.tick;
        let switched = now < self.timer_last_time;
        if switched {
            self.switch_timer_lists()?;
        }
        self.timer_last_time = now;
        Ok((now, switched))
    }

    /// `prvSwitchTimerLists`: everything left on the current list has
    /// expired, so run it, then swap.
    fn switch_timer_lists(&mut self) -> Result<()> {
        while !self.lists.is_empty_of(self.timer_list()) {
            let next = self.lists.head_value(self.timer_list()).unwrap_or(0);
            self.process_expired_timer(next, Self::MAX_DELAY)?;
        }
        self.timers_swapped = !self.timers_swapped;
        Ok(())
    }

    /// `prvProcessExpiredTimer`: take the head off, reload it if it is an
    /// auto-reload, and run its callback.
    ///
    /// # Errors
    /// As the list operations.
    pub fn process_expired_timer(&mut self, expire_at: u64, now: u64) -> Result<()> {
        let list = self.timer_list();
        let Ok(Some(item)) = self.lists.head(list) else {
            return Ok(());
        };
        // Take it off *first*, whatever it turns out to be. `prvSwitchTimerLists`
        // loops until this list is empty, so an item this cannot resolve —
        // a timer deleted while its entry was still queued — would spin
        // here for ever if the removal came after the lookup.
        let _ = self.lists.unlink(item);
        let Some(timer) = self.timer_of_item(item) else {
            return Ok(());
        };
        let auto = self
            .timers
            .resolve(timer)
            .map(|t| (t.status & STATUS_AUTORELOAD) != 0)
            .unwrap_or(false);
        if auto {
            self.reload_timer(timer, expire_at, now)?;
        } else if let Ok(t) = self.timers.resolve_mut(timer) {
            t.status &= !STATUS_ACTIVE;
        }
        self.fire_timer(timer);
        Ok(())
    }

    /// `prvReloadTimer`: put it back on the list one period later, and keep
    /// firing while that period has already gone by.
    fn reload_timer(&mut self, timer: TimerHandle, expired_at: u64, now: u64) -> Result<()> {
        let mut expired_at = expired_at;
        loop {
            // A period of zero cannot reach here — `timer_create` and
            // `timer_change_period` both refuse one — but the loop only
            // terminates because the expiry advances, so it says so.
            let period = self
                .timers
                .resolve(timer)
                .map(|t| t.period.get())
                .unwrap_or(1)
                .max(1);
            let next = expired_at.wrapping_add(period) & Self::MAX_DELAY;
            if !self.insert_timer_in_active_list(timer, next, now, expired_at)? {
                return Ok(());
            }
            expired_at = next;
            self.fire_timer(timer);
        }
    }

    /// The callback itself, through the application's hook.
    fn fire_timer(&mut self, timer: TimerHandle) {
        let (name, callback, id) = match self.timers.resolve(timer) {
            Ok(t) => (t.name, t.callback, t.id.get()),
            Err(_) => return,
        };
        let tick = self.tick;
        self.note_exits();
        self.trace.event(
            tick,
            Event::TimerExpired {
                timer,
                name: name.as_str(),
            },
        );
        H::timer(self, timer, callback, id);
    }

    /// `prvInsertTimerInActiveList`: `true` when the timer is already due
    /// and the daemon should run it now rather than wait for it.
    ///
    /// # Errors
    /// As the list operations.
    pub fn insert_timer_in_active_list(
        &mut self,
        timer: TimerHandle,
        expiry: u64,
        now: u64,
        command_time: u64,
    ) -> Result<bool> {
        let item = Self::timer_item(timer);
        // `remove` is its own guard: it answers `NotActive` for an item
        // in no list, and the container test read the same node to learn
        // what `remove` was about to say. Same fold as `suspend` and
        // `add_current_task_to_delayed_list`.
        let _ = self.lists.unlink(item);
        self.lists.set_value(item, expiry)?;
        let period = self
            .timers
            .resolve(timer)
            .map(|t| t.period.get())
            .unwrap_or(1);
        if expiry <= now {
            if now.wrapping_sub(command_time) & Self::MAX_DELAY >= period {
                return Ok(true);
            }
            let list = self.overflow_timer_list();
            self.lists.insert(list, item, expiry)?;
        } else {
            if now < command_time && expiry >= command_time {
                return Ok(true);
            }
            let list = self.timer_list();
            self.lists.insert(list, item, expiry)?;
        }
        Ok(false)
    }

    /// `prvProcessReceivedCommands`: drain the queue, one command per call.
    ///
    /// The C loops until the queue is empty; a kernel with no stacks does
    /// one and says whether there is more, because a callback in the middle
    /// of that loop can block and the daemon has to be able to come back.
    ///
    /// # The block time is not a convenience
    ///
    /// `ticks` is how long the daemon is willing to WAIT on the queue, and
    /// passing zero has a consequence beyond promptness: a daemon that
    /// polls is never on the queue's receive list, so a task posting a
    /// command finds no waiter to remove and `queue_send_generic` does not
    /// call `port_yield`. The daemon is higher priority and still does not
    /// run, because nothing asked for a switch.
    ///
    /// That is visible from the C. `TimerDemo.c` stops a timer and asserts
    /// on the next line that it is inactive, and its comment says it may:
    /// "this will appear to happen immediately to this task because this
    /// task is running at a priority below the timer service task". With a
    /// polling daemon the assertion fails, and nothing else in the corpus
    /// notices.
    ///
    /// So a caller acting as the daemon should pass what
    /// `prvProcessTimerOrBlockTask` computes — the time to the next expiry,
    /// or the maximum delay when no timer is active. Zero is correct only
    /// for a caller that is draining the queue rather than serving it, such
    /// as a trace-exact state machine that schedules the wait itself.
    ///
    /// # Errors
    /// As the queue receive.
    pub fn process_one_timer_command(&mut self, ticks: u64) -> Result<Wait<bool>> {
        match self.timer_receive_command(ticks)? {
            Wait::Blocked => Ok(Wait::Blocked),
            Ready(None) => Ok(Ready(false)),
            Ready(Some(message)) => {
                self.timer_execute_command(message)?;
                Ok(Ready(true))
            }
        }
    }

    /// The first half of [`Kernel::process_one_timer_command`]: the
    /// `xQueueReceive` of `prvProcessReceivedCommands`'s loop: the message,
    /// for [`Kernel::timer_execute_command`], or `None` for an empty queue.
    ///
    /// A COPY of the message, as the C copies it into the daemon's local
    /// `xMessage`: the receive frees the ring slot it sat in, and a post
    /// between the two halves -- the tick hook's, say -- can reuse it.
    ///
    /// The halves are separate for a daemon that has to stop BETWEEN them.
    /// On two cores the receive is a top-level call that leaves a critical
    /// section, so it ends the daemon's turn (the two-core contract), and
    /// what the command then does -- a callback, the `vPortFree` a delete
    /// costs -- happens in the turns after. One call for both put the
    /// daemon a turn ahead of the C (two-core `TaskNotify`, a delete).
    ///
    /// # Errors
    /// As the queue receive.
    pub fn timer_receive_command(&mut self, ticks: u64) -> Result<Wait<Option<Message>>> {
        match self.queue_receive(self.timer_queue, ticks) {
            Ok(Ready(slot)) => Ok(Ready(Some(
                self.timer_messages
                    .get(slot as usize)
                    .copied()
                    .unwrap_or_default(),
            ))),
            Ok(Wait::Blocked) => Ok(Wait::Blocked),
            Err(_) => Ok(Ready(None)),
        }
    }

    /// The second half of [`Kernel::process_one_timer_command`]: carry out
    /// the command [`Kernel::timer_receive_command`] took.
    ///
    /// # Errors
    /// As the list operations.
    pub fn timer_execute_command(&mut self, message: Message) -> Result<()> {
        if message.command.id() < 0 {
            // A pended function call: the daemon just runs it.
            H::pended(self, message.function, message.param1, message.value);
            return Ok(());
        }

        let timer = message.timer;
        if self.timers.resolve(timer).is_err() {
            return Ok(());
        }
        let item = Self::timer_item(timer);
        // `remove` is its own guard: it answers `NotActive` for an item
        // in no list, and the container test read the same node to learn
        // what `remove` was about to say. Same fold as `suspend` and
        // `add_current_task_to_delayed_list`.
        let _ = self.lists.unlink(item);
        // `traceTIMER_COMMAND_RECEIVED` is not one of the harness's hooks.
        let (now, _switched) = self.timer_sample_time_now()?;

        if message.command.is_start_or_reset() {
            if let Ok(t) = self.timers.resolve_mut(timer) {
                t.status |= STATUS_ACTIVE;
            }
            let period = self
                .timers
                .resolve(timer)
                .map(|t| t.period.get())
                .unwrap_or(1);
            let expiry = message.value.wrapping_add(period) & Self::MAX_DELAY;
            if self.insert_timer_in_active_list(timer, expiry, now, message.value)? {
                let auto = self
                    .timers
                    .resolve(timer)
                    .map(|t| (t.status & STATUS_AUTORELOAD) != 0)
                    .unwrap_or(false);
                if auto {
                    self.reload_timer(timer, expiry, now)?;
                } else if let Ok(t) = self.timers.resolve_mut(timer) {
                    t.status &= !STATUS_ACTIVE;
                }
                self.fire_timer(timer);
            }
        } else if message.command.is_stop() {
            if let Ok(t) = self.timers.resolve_mut(timer) {
                t.status &= !STATUS_ACTIVE;
            }
        } else if message.command.is_change_period() {
            if let Ok(t) = self.timers.resolve_mut(timer) {
                t.status |= STATUS_ACTIVE;
                t.period = Split64::new(message.value);
            }
            let period = self
                .timers
                .resolve(timer)
                .map(|t| t.period.get())
                .unwrap_or(1);
            let expiry = now.wrapping_add(period) & Self::MAX_DELAY;
            let _ = self.insert_timer_in_active_list(timer, expiry, now, now)?;
        } else if message.command == Command::Delete {
            let _ = self.timers.discard(timer);
            // `vPortFree( pxTimer )`, which every `heap_N.c` wraps in
            // `vTaskSuspendAll` / `xTaskResumeAll` exactly as it wraps
            // malloc -- so a delete costs one outermost critical-section
            // exit, which under the sim contract is one unit of time,
            // while emitting no trace line at all (this harness defines no
            // `traceTIMER_DELETE`).
            //
            // `queue_delete` and `event_group_delete` both carry this
            // note; the timer command was the third object with a free and
            // the one that had not been told. `TaskNotify` is the scenario
            // that finds it -- it is the first in the corpus to delete a
            // timer -- and it showed up exactly as the other two did:
            // every event agreed and the exit column was one short from
            // the first delete onwards.
            self.account_for_allocation();
        }
        Ok(())
    }

    /// Which timer a list item belongs to.
    fn timer_of_item(&self, item: u16) -> Option<TimerHandle> {
        let base = TASKS.saturating_mul(2) as u16;
        let index = item.checked_sub(base)?;
        self.timers.handle_at(index)
    }
}

// ================================================================ tests ==

/// `timer.rs` had no unit test at all, and three of its APIs are also ones
/// no conformance scenario reaches (`docs/HOLES.md`, H2 and H3).
///
/// Every test here quotes the `timers.c` line it pins, and pins **the C's
/// contract** rather than this kernel's behaviour.
///
/// The theme is that the timer API is a COMMAND QUEUE. Every mutator
/// returns "the command was queued", not "the thing happened", and the
/// queries read state the daemon has not updated yet. That is the single
/// most surprising thing about this API and no scenario in the corpus
/// isolates it, because a scenario always lets the daemon run.
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use rusty_rtos_core::config::Config;
    use rusty_rtos_core::hooks::NoTickHook;

    use crate::queue::Wait;
    use crate::system::tests::{NoTrace, TestConfig, TestPort};

    /// Three tasks (idle, the timer daemon, one spare), one queue for the
    /// timer commands, and room for two timers.
    type K = crate::Kernel<
        TestConfig,
        TestPort,
        NoTrace,
        NoTickHook,
        3,
        { crate::list_slots_for(3, 2, crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0)) },
        { crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0) },
        1,
        2,
        0,
        0,
        2,
        0,
        { <TestConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
    >;

    /// A started kernel with the daemon PARKED, so a queued command stays
    /// queued until a test asks for it to be processed.
    fn started() -> K {
        let mut k = K::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
        let h = k.start_scheduler().expect("start");
        k.suspend(Some(h.timer)).expect("park the daemon");
        k
    }

    /// `xTimerStart` queues a command; it does not start a timer.
    ///
    /// `prvProcessReceivedCommands` is where the flag is actually set:
    ///
    /// ```c
    /// case tmrCOMMAND_START:
    ///     ...
    ///     pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE;
    /// ```
    ///
    /// so `pdPASS` from `xTimerStart` means "the daemon has been told", and
    /// `xTimerIsTimerActive` keeps saying pdFALSE until the daemon runs. A
    /// caller that starts a timer and immediately asks whether it is active
    /// gets "no", correctly.
    #[test]
    fn a_start_only_queues_and_the_timer_is_not_active_until_it_is_processed() {
        let mut k = started();
        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
        assert_eq!(k.timer_is_active(t), Ok(false), "created dormant");

        assert_eq!(
            k.timer_start(t, 0),
            Ok(Wait::Ready(true)),
            "the COMMAND was accepted"
        );
        assert_eq!(
            k.timer_is_active(t),
            Ok(false),
            "and the timer is still not running: the daemon has not run"
        );

        k.process_one_timer_command(0).expect("the daemon runs");
        assert_eq!(k.timer_is_active(t), Ok(true), "now it is running");
    }

    /// `xTimerGetPeriod`:
    ///
    /// ```c
    /// return pxTimer->xTimerPeriodInTicks;
    /// ```
    ///
    /// a plain field read -- and the field is written by the DAEMON:
    ///
    /// ```c
    /// case tmrCOMMAND_CHANGE_PERIOD:
    ///     pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue;
    /// ```
    ///
    /// So between `xTimerChangePeriod` returning pdPASS and the daemon
    /// running, `xTimerGetPeriod` answers the OLD period. Two calls that
    /// look like a setter and its getter, and they disagree.
    #[test]
    fn the_period_is_the_old_one_until_a_change_is_processed() {
        let mut k = started();
        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
        assert_eq!(k.timer_period(t), Ok(10));

        assert_eq!(k.timer_change_period(t, 25, 0), Ok(Wait::Ready(true)));
        assert_eq!(
            k.timer_period(t),
            Ok(10),
            "the setter returned pdPASS and the getter still says 10"
        );

        k.process_one_timer_command(0).expect("the daemon runs");
        assert_eq!(k.timer_period(t), Ok(25));
        assert_eq!(
            k.timer_is_active(t),
            Ok(true),
            "and a change period STARTS a dormant timer, which is the C's rule"
        );
    }

    /// `xTimerGetExpiryTime`:
    ///
    /// ```c
    /// xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) );
    /// return xReturn;
    /// ```
    ///
    /// An unconditional list-item read. **Nothing checks that the timer is
    /// active**, so on a dormant one this answers whatever the item was
    /// last left holding, and the return type cannot say "not running".
    ///
    /// The only correct use is gated on `xTimerIsTimerActive`, and that is
    /// what this pins -- so that a future caller reads it here rather than
    /// discovering it from a wrong wake-up.
    #[test]
    fn expiry_time_is_an_unguarded_list_read_and_needs_is_active_first() {
        let mut k = started();
        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");

        // Dormant: the call SUCCEEDS and the answer means nothing.
        assert!(
            k.timer_expiry_time(t).is_ok(),
            "it answers happily for a timer that was never started"
        );
        assert_eq!(
            k.timer_is_active(t),
            Ok(false),
            "and this is the only call that says the answer is meaningless"
        );

        k.timer_start(t, 0).expect("queue the start");
        k.process_one_timer_command(0).expect("the daemon runs");

        assert_eq!(k.timer_is_active(t), Ok(true));
        assert_eq!(
            k.timer_expiry_time(t),
            Ok(k.tick_count().wrapping_add(10)),
            "now it is now-plus-the-period, and now it means something"
        );
    }

    /// `vTimerSetReloadMode`:
    ///
    /// ```c
    /// taskENTER_CRITICAL();
    /// if( xAutoReload != pdFALSE ) { pxTimer->ucStatus |=  tmrSTATUS_IS_AUTORELOAD; }
    /// else                         { pxTimer->ucStatus &= ~tmrSTATUS_IS_AUTORELOAD; }
    /// taskEXIT_CRITICAL();
    /// ```
    ///
    /// The odd one out: it is NOT a queued command, it writes the flag
    /// directly. So unlike every other mutator in this file it takes effect
    /// at once -- and it does not reschedule anything, so a running timer
    /// keeps the expiry it already has and the new mode applies from the
    /// next expiry on.
    #[test]
    fn set_auto_reload_is_immediate_and_reschedules_nothing() {
        let mut k = started();
        let t = k.timer_create("t", 10, false, 0, 0).expect("a one-shot");
        assert_eq!(k.timer_auto_reload(t), Ok(false));

        k.timer_start(t, 0).expect("queue the start");
        k.process_one_timer_command(0).expect("the daemon runs");
        let expiry = k.timer_expiry_time(t).expect("an expiry");

        // No daemon round trip, unlike start/stop/change-period.
        k.timer_set_auto_reload(t, true).expect("set");
        assert_eq!(
            k.timer_auto_reload(t),
            Ok(true),
            "immediate: this one is not a queued command"
        );
        assert_eq!(
            k.timer_expiry_time(t),
            Ok(expiry),
            "and it moved nothing: the pending expiry is untouched"
        );
        assert_eq!(k.timer_is_active(t), Ok(true));
    }

    /// The id is the caller's own storage and the kernel never reads it.
    /// `TimerDemo` uses it to count callbacks, which is the only reason it
    /// has any coverage at all.
    #[test]
    fn the_id_is_the_callers_and_round_trips() {
        let mut k = started();
        let t = k.timer_create("t", 10, false, 7, 0).expect("a timer");
        assert_eq!(k.timer_id(t), Ok(7), "the creation id");
        k.timer_set_id(t, 0xdead_beef).expect("set");
        assert_eq!(k.timer_id(t), Ok(0xdead_beef));

        // And it survives the daemon, because no command touches it.
        k.timer_start(t, 0).expect("queue the start");
        k.process_one_timer_command(0).expect("the daemon runs");
        assert_eq!(k.timer_id(t), Ok(0xdead_beef));
    }

    /// The command queue is finite, and a full one is reported as `pdFAIL`
    /// from a call whose name suggests it did something.
    ///
    /// `TestConfig` declares `configTIMER_QUEUE_LENGTH` of one, so the
    /// second command with no block time has nowhere to go. It is the same
    /// answer a caller gets on a busy system, where it is a race rather
    /// than an arithmetic certainty -- which is why it is worth pinning
    /// somewhere it is certain.
    #[test]
    fn a_full_command_queue_refuses_without_erroring() {
        let mut k = started();
        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");

        assert_eq!(k.timer_start(t, 0), Ok(Wait::Ready(true)), "queued");
        assert_eq!(
            k.timer_stop(t, 0),
            Ok(Wait::Ready(false)),
            "refused: the queue is full and the block time is zero"
        );
        assert_eq!(
            k.timer_is_active(t),
            Ok(false),
            "neither command has run yet"
        );

        k.process_one_timer_command(0).expect("drain the start");
        assert_eq!(k.timer_is_active(t), Ok(true), "the start, not the stop");
    }
    /// The ISR halves queue exactly like the task halves do, and are just
    /// as deferred -- `xTimerStartFromISR` is
    /// `xTimerGenericCommandFromISR( ..., tmrCOMMAND_START_FROM_ISR, ... )`
    /// and the daemon is still the only thing that sets the flag.
    ///
    /// What differs is the block time: an ISR cannot wait, so there is no
    /// ticks argument and a full queue is reported at once.
    #[test]
    fn a_start_from_isr_is_queued_and_not_active_until_processed() {
        let mut k = started();
        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");

        let (queued, _woken) = k.timer_start_from_isr(t).expect("isr");
        assert!(queued, "the command was accepted");
        assert_eq!(
            k.timer_is_active(t),
            Ok(false),
            "and the timer is not running: the daemon has not run"
        );

        k.process_one_timer_command(0).expect("the daemon runs");
        assert_eq!(k.timer_is_active(t), Ok(true));
    }

    /// A stop from an interrupt, likewise deferred -- and it takes effect
    /// only when the daemon reaches it, so between the two the timer is
    /// still running and can still expire.
    #[test]
    fn a_stop_from_isr_leaves_the_timer_running_until_the_daemon_reaches_it() {
        let mut k = started();
        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
        k.timer_start(t, 0).expect("queue the start");
        k.process_one_timer_command(0)
            .expect("the daemon starts it");
        assert_eq!(k.timer_is_active(t), Ok(true));

        let (queued, _woken) = k.timer_stop_from_isr(t).expect("isr");
        assert!(queued);
        assert_eq!(
            k.timer_is_active(t),
            Ok(true),
            "STILL RUNNING: an interrupt asked, and nothing has answered yet"
        );

        k.process_one_timer_command(0).expect("the daemon stops it");
        assert_eq!(k.timer_is_active(t), Ok(false));
    }

    /// `xTimerChangePeriodFromISR` carries its value the same way, and the
    /// period is the daemon's to write.
    #[test]
    fn a_change_period_from_isr_carries_its_value_through_the_queue() {
        let mut k = started();
        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");

        let (queued, _woken) = k.timer_change_period_from_isr(t, 40).expect("isr");
        assert!(queued);
        assert_eq!(k.timer_period(t), Ok(10), "not yet");

        k.process_one_timer_command(0).expect("the daemon runs");
        assert_eq!(k.timer_period(t), Ok(40));
        assert_eq!(
            k.timer_is_active(t),
            Ok(true),
            "and a change period starts a dormant timer, from an ISR too"
        );
    }

    /// `xTimerResetFromISR` restarts the countdown from NOW, which is the
    /// whole point of it -- a reset on a running timer must move the
    /// expiry, not leave it where it was.
    #[test]
    fn a_reset_from_isr_moves_the_expiry_forward() {
        let mut k = started();
        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
        k.timer_start(t, 0).expect("queue the start");
        k.process_one_timer_command(0)
            .expect("the daemon starts it");
        let first = k.timer_expiry_time(t).expect("an expiry");

        for _ in 0..3_u32 {
            k.tick_from_isr();
        }

        let (queued, _woken) = k.timer_reset_from_isr(t).expect("isr");
        assert!(queued);
        k.process_one_timer_command(0)
            .expect("the daemon resets it");

        assert_eq!(
            k.timer_expiry_time(t),
            Ok(first.wrapping_add(3)),
            "the countdown restarted from the tick the reset was taken at"
        );
    }

    /// `xTimerPendFunctionCall` rides the same queue as the timer commands
    /// -- it is a way to run something in task context that an interrupt
    /// asked for, and it competes with real timer work for queue slots.
    ///
    /// `TestConfig` gives the queue one slot, so this pins the competition
    /// rather than assuming it.
    #[test]
    fn a_pended_function_call_competes_for_the_same_queue() {
        let mut k = started();
        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");

        assert_eq!(
            k.timer_pend_function_call(1, 2, 3, 0),
            Ok(Wait::Ready(true)),
            "the callback is queued"
        );
        assert_eq!(
            k.timer_start(t, 0),
            Ok(Wait::Ready(false)),
            "and now a timer start has nowhere to go"
        );

        k.process_one_timer_command(0).expect("drain the callback");
        assert_eq!(
            k.timer_start(t, 0),
            Ok(Wait::Ready(true)),
            "with the slot free again the start is accepted"
        );
    }

    /// The ISR half of the same call, which is how
    /// `xEventGroupSetBitsFromISR` reaches the daemon.
    #[test]
    fn a_pended_function_call_from_isr_queues_without_blocking() {
        let mut k = started();
        let (queued, _woken) = k.timer_pend_function_call_from_isr(1, 2, 3).expect("isr");
        assert!(queued, "queued");

        let (queued, _woken) = k.timer_pend_function_call_from_isr(4, 5, 6).expect("isr");
        assert!(
            !queued,
            "and the second is refused at once: an interrupt cannot wait"
        );
    }

    /// The from-ISR entry refuses what the C `configASSERT`s
    /// (`xTimerGenericCommandFromISR`): a task-level command, and a change
    /// of period to zero. Refused means traced, answered false, and nothing
    /// queued for the daemon (plan P5: `||` -> `&&` survived every oracle,
    /// which never makes the call the C cannot answer).
    #[test]
    fn the_isr_entry_refuses_a_task_command_and_a_zero_period() {
        use rusty_rtos_core::isr::Woken;
        let mut k = started();
        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
        for (command, value) in [
            (super::Command::Start, 0),
            (super::Command::ChangePeriodFromIsr, 0),
        ] {
            assert_eq!(
                k.timer_command_from_isr(t, command, value),
                Ok((false, Woken::NO)),
                "{command:?} {value} must be refused"
            );
            assert_eq!(
                k.process_one_timer_command(0),
                Ok(Wait::Ready(false)),
                "{command:?} {value} reached the daemon's queue"
            );
        }
        // And a good one still goes through.
        assert_eq!(
            k.timer_command_from_isr(t, super::Command::ChangePeriodFromIsr, 5),
            Ok((true, Woken::NO))
        );
    }

    /// `Split64` is storage: `new` then `get` is the identity, a high word
    /// included. On a 64-bit host it is one `u64` and this is trivial; at
    /// the targets' width (`--target i686-pc-windows-msvc`) it is two words,
    /// and a value past 2^32 is the only thing that tells the halves apart
    /// (plan P5: `<<` -> `>>` lived, because every stored tick fits 32 bits).
    #[test]
    fn a_split_value_comes_back_whole() {
        for value in [
            0,
            1,
            0xFFFF_FFFF,
            0x1_0000_0000,
            0x0123_4567_89AB_CDEF,
            u64::MAX,
        ] {
            assert_eq!(super::Split64::new(value).get(), value, "{value:#x}");
        }
    }
}