rusty_rtos_kernel-core 0.2.0

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
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
//! `queue.c`: the queue, and the semaphore and mutex built on it.
//!
//! In FreeRTOS a semaphore *is* a queue with a zero-size item, and a mutex
//! is that plus a holder and priority inheritance. Kairos keeps the same
//! shape, because the trace does: a semaphore give fires `QUEUE_SEND` and a
//! mutex take fires `QUEUE_RECEIVE`, and a conformance diff would notice
//! any tidier arrangement.
//!
//! # A blocking call with no stack to block on
//!
//! `xQueueReceive( q, &v, 100 )` blocks: the C task stops inside the call,
//! and when it is woken it loops back to the top, re-checks the queue, and
//! either returns the item or blocks again. This kernel has no stack to
//! suspend, so the loop is turned inside out — a blocking call returns
//! [`Blocked`] and the caller invokes it again, unchanged, when it next
//! runs:
//!
//! ```ignore
//! // in a task body, at some `pc`:
//! match k.queue_receive(q, 100)? {
//!     Blocked => {}                 // stay at this pc; the kernel parked us
//!     Ready(value) => { ...; self.pc = next; }
//! }
//! ```
//!
//! The task is off the ready list when `Blocked` comes back, so the runner
//! will not step it again until the kernel wakes it — which is exactly when
//! the C thread would have resumed. What the C keeps on its stack across
//! the block (the timeout, the remaining ticks, whether inheritance
//! happened) this kernel keeps in the TCB, in [`Wait`], because that *is*
//! the stack frame.

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

use crate::kernel::{Kernel, OwedTrace, QueueResume};

/// What a blocking call answers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Wait<T> {
    /// The kernel parked the calling task. Leave the program counter where
    /// it is and make the same call again when the task next runs.
    Blocked,
    /// The call completed.
    Ready(T),
}

pub use Wait::{Blocked, Ready};

/// Where an item goes (`xCopyPosition`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Position {
    /// `queueSEND_TO_BACK`.
    Back,
    /// `queueSEND_TO_FRONT`.
    Front,
    /// `queueOVERWRITE`: write to the front of a length-one queue whether
    /// or not it already holds something, and leave the message count
    /// where it was rather than raising it.
    Overwrite,
}

/// What a queue is underneath (`ucQueueType`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    // ORDER IS LOAD-BEARING, and only for the two predicates below. The kinds
    // that carry data are first and the two mutex kinds are last, so
    // `carries_data` and `is_mutex` are each a range the compiler can test
    // with one comparison instead of two. Nothing reads a discriminant, so
    // the order carries no other meaning.
    /// A queue of values.
    Queue,
    /// A queue set: a queue whose items are the handles of the queues in
    /// it. `xQueueSelectFromSet` is a receive from this one.
    Set,
    /// A binary or counting semaphore: a queue with a zero-size item, so
    /// only the count matters.
    Semaphore,
    /// A mutex: a one-deep semaphore with a holder and priority
    /// inheritance.
    Mutex,
    /// A recursive mutex: as above, and the holder may take it again.
    RecursiveMutex,
}

impl Kind {
    /// `uxItemSize == 0`: semaphores and mutexes carry a count, not data.
    pub(crate) const fn carries_data(self) -> bool {
        matches!(self, Self::Queue | Self::Set)
    }

    /// The two mutex kinds, which inherit priority.
    pub(crate) const fn is_mutex(self) -> bool {
        matches!(self, Self::Mutex | Self::RecursiveMutex)
    }
}

/// One queue: the C `Queue_t` minus the byte pointers. Storage is a range
/// of the kernel's shared slot pool, and the read and write cursors follow
/// C's `pcReadFrom` / `pcWriteTo` exactly — `pcReadFrom` points at the item
/// last read, which is what makes `queueSEND_TO_FRONT` a single step back.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Queue {
    pub(crate) base: usize,
    /// `uxLength`.
    pub(crate) length: usize,
    /// `uxMessagesWaiting`.
    pub(crate) waiting: usize,
    /// `pcReadFrom`, as an index: the item last read.
    pub(crate) read_from: usize,
    /// `pcWriteTo`, as an index: where the next back-send writes.
    pub(crate) write_to: usize,
    pub(crate) kind: Kind,
    /// `u.xSemaphore.xMutexHolder`.
    pub(crate) holder: TaskHandle,
    /// `u.xSemaphore.uxRecursiveCallCount`.
    pub(crate) recursions: u32,
    /// `cTxLock`: [`UNLOCKED`] when no task holds the queue locked;
    /// otherwise how many sends an interrupt made while it was locked, and
    /// therefore how many receivers `prvUnlockQueue` still owes a wake-up.
    pub(crate) tx_lock: i8,
    /// `cRxLock`, the same for receives and the tasks waiting to send.
    pub(crate) rx_lock: i8,
    /// `pxQueueSetContainer`: the set this queue belongs to, if any. An
    /// item arriving here is announced there.
    pub(crate) set_container: QueueHandle,
}

/// `queueUNLOCKED`.
pub(crate) const UNLOCKED: i8 = -1;
/// `queueLOCKED_UNMODIFIED`.
pub(crate) const LOCKED_UNMODIFIED: i8 = 0;

impl Queue {
    pub(crate) const fn new(base: usize, length: usize, kind: Kind) -> Self {
        Self {
            base,
            length,
            waiting: 0,
            // `xQueueGenericReset`: pcReadFrom = pcHead + (length - 1) * itemSize.
            read_from: length.saturating_sub(1),
            write_to: 0,
            kind,
            holder: TaskHandle::NULL,
            recursions: 0,
            tx_lock: UNLOCKED,
            rx_lock: UNLOCKED,
            set_container: QueueHandle::NULL,
        }
    }
}

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,
> Kernel<C, P, T, H, TASKS, ITEMS, LISTS, QUEUES, SLOTS, BUFFERS, BYTES, TIMERS, GROUPS>
where
    H: TickHook<Self>,
{
    // ------------------------------------------------------------ create --

    /// `xQueueCreate`.
    ///
    /// # Errors
    /// [`Error::Full`] when the queue arena or the shared slot pool is
    /// exhausted; [`Error::InvalidArgument`] for a zero length.
    pub fn queue_create(&mut self, length: usize) -> Result<QueueHandle> {
        self.new_queue(length, Kind::Queue)
    }

    /// `vQueueDelete`, and `vSemaphoreDelete`, which the C defines as the
    /// same function.
    ///
    /// # It traces nothing and still costs time
    ///
    /// `vQueueDelete` takes no critical section of its own — but it ends in
    /// `vPortFree( pxQueue )`, and every `heap_N.c` wraps free 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 `traceQUEUE_DELETE`).
    ///
    /// `AbortDelay`'s remake left the deletes out on the reasoning that an
    /// event-less call cannot move the trace. Every event still agreed and
    /// the exit column was one short from the first delete onwards. The
    /// sibling `event_group_delete` already carried this note; the queue
    /// had no delete at all.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn queue_delete(&mut self, queue: QueueHandle) -> Result<()> {
        self.queues.resolve(queue)?;
        let _ = self.queues.remove(queue);
        // `vPortFree( pxQueue )`.
        self.account_for_allocation();
        Ok(())
    }

    /// `xSemaphoreCreateBinary`: a one-deep semaphore, created empty.
    ///
    /// # Errors
    /// As [`Kernel::queue_create`].
    pub fn semaphore_create_binary(&mut self) -> Result<QueueHandle> {
        self.new_queue(1, Kind::Semaphore)
    }

    /// `xSemaphoreCreateCounting`.
    ///
    /// # Errors
    /// As [`Kernel::queue_create`]; [`Error::InvalidArgument`] if the
    /// initial count exceeds the maximum.
    pub fn semaphore_create_counting(&mut self, max: usize, initial: usize) -> Result<QueueHandle> {
        if initial > max {
            return Err(Error::InvalidArgument);
        }
        let handle = self.new_queue(max, Kind::Semaphore)?;
        if let Ok(q) = self.queues.resolve_mut(handle) {
            q.waiting = initial;
        }
        Ok(handle)
    }

    /// `xSemaphoreCreateMutex`: created **available**, unlike a semaphore.
    ///
    /// # Errors
    /// As [`Kernel::queue_create`].
    pub fn mutex_create(&mut self) -> Result<QueueHandle> {
        self.new_mutex(Kind::Mutex)
    }

    /// `xSemaphoreCreateRecursiveMutex`.
    ///
    /// # Errors
    /// As [`Kernel::queue_create`].
    pub fn mutex_create_recursive(&mut self) -> Result<QueueHandle> {
        self.new_mutex(Kind::RecursiveMutex)
    }

    fn new_mutex(&mut self, kind: Kind) -> Result<QueueHandle> {
        let handle = self.new_queue(1, kind)?;
        // `prvInitialiseMutex` gives the mutex once so it starts available,
        // and it does so through `xQueueGenericSend` — which fires
        // `traceQUEUE_SEND`. A mutex therefore has a `QUEUE_SEND` line
        // immediately after its `QUEUE_CREATE`, before any task exists.
        let _ = self.queue_send_generic(handle, 0, 0, Position::Back)?;
        Ok(handle)
    }

    fn new_queue(&mut self, length: usize, kind: Kind) -> Result<QueueHandle> {
        if length == 0 {
            return Err(Error::InvalidArgument);
        }
        // A zero-item-size queue needs no storage; only real queues do.
        let slots = if kind.carries_data() { length } else { 0 };
        let base = self.slots_used;
        let end = base.checked_add(slots).ok_or(Error::Full)?;
        if end > SLOTS {
            return Err(Error::Full);
        }
        let handle = self
            .queues
            .try_insert(Queue::new(base, length, kind))
            .map_err(|_| Error::Full)?;
        self.slots_used = end;
        // `xQueueGenericCreate` takes the queue and its storage from the
        // heap before it initialises anything.
        self.account_for_allocation();
        // `xQueueGenericReset` runs in a critical section before
        // `traceQUEUE_CREATE` fires at the end of `prvInitialiseNewQueue`.
        self.enter_critical();
        self.exit_critical();
        let tick = self.tick;
        self.trace.note_exits(self.port.exits());
        self.trace.event(
            tick,
            Event::QueueCreate {
                queue: handle,
                name: "",
                length,
            },
        );
        Ok(handle)
    }

    // ----------------------------------------------------------- getters --

    /// `uxQueueMessagesWaiting`, which takes a critical section.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn queue_messages_waiting(&mut self, queue: QueueHandle) -> Result<usize> {
        self.enter_critical();
        let n = self.queues.resolve(queue).map(|q| q.waiting);
        self.exit_critical();
        n
    }

    /// `xQueueIsQueueFullFromISR`, which takes NO critical section.
    ///
    /// The C compares `uxMessagesWaiting` against `uxLength` and returns,
    /// with nothing around it — it is meant to be called from an interrupt,
    /// where a critical section would be the wrong thing. That is why this
    /// takes `&self` and [`Kernel::queue_messages_waiting`] takes `&mut
    /// self`: the borrow is the proof that this one cannot charge the
    /// clock, and on the sim a charged section is a sixteenth of a tick.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn queue_is_full_from_isr(&self, queue: QueueHandle) -> Result<bool> {
        self.queues.resolve(queue).map(|q| q.waiting == q.length)
    }

    /// `uxSemaphoreGetCount`, which is the same thing.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn semaphore_count(&mut self, semaphore: QueueHandle) -> Result<usize> {
        self.queue_messages_waiting(semaphore)
    }

    /// `xSemaphoreGetMutexHolderFromISR`, which is
    /// `xQueueGetMutexHolderFromISR`: the same answer, read without a
    /// critical section because an ISR is already inside one.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn mutex_holder_from_isr(&mut self, mutex: QueueHandle) -> Result<TaskHandle> {
        self.queues.resolve(mutex).map(|q| q.holder)
    }

    /// `xSemaphoreGetMutexHolder`, which takes a critical section.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn mutex_holder(&mut self, mutex: QueueHandle) -> Result<TaskHandle> {
        self.enter_critical();
        let holder = self.queues.resolve(mutex).map(|q| q.holder);
        self.exit_critical();
        holder
    }

    // -------------------------------------------------------------- send --

    /// `xQueueSend` / `xQueueSendToBack`.
    ///
    /// # Errors
    /// [`Error::Full`] when the block time expires with the queue still
    /// full; [`Error::Gone`] for a stale handle.
    pub fn queue_send(&mut self, queue: QueueHandle, value: u64, ticks: u64) -> Result<Wait<()>> {
        self.queue_send_generic(queue, value, ticks, Position::Back)
    }

    /// `xQueueReset`, which is `xQueueGenericReset( q, pdFALSE )`: empty
    /// the queue and unlock it, waking one waiting sender if there is one.
    ///
    /// The event lists survive — only a brand-new queue re-initialises
    /// those — so a task blocked on this queue stays blocked, and the one
    /// woken here is woken because the reset made room.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn queue_reset(&mut self, queue: QueueHandle) -> Result<()> {
        self.enter_critical();
        let result = (|| {
            let length = self.queues.resolve(queue)?.length;
            {
                let q = self.queues.resolve_mut(queue)?;
                q.waiting = 0;
                q.write_to = 0;
                q.read_from = length.saturating_sub(1);
                q.rx_lock = UNLOCKED;
                q.tx_lock = UNLOCKED;
            }
            let senders = Self::queue_send_list(queue);
            if self.lists.is_empty(senders) == Ok(false) && self.remove_from_event_list(senders)? {
                // queueYIELD_IF_USING_PREEMPTION(), inside the section.
                self.port_yield();
            }
            Ok(())
        })();
        self.exit_critical();
        result
    }

    /// `uxQueueSpacesAvailable`: how many more items would fit.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn queue_spaces_available(&mut self, queue: QueueHandle) -> Result<usize> {
        self.enter_critical();
        let spaces = self
            .queues
            .resolve(queue)
            .map(|q| q.length.wrapping_sub(q.waiting));
        self.exit_critical();
        spaces
    }

    // --------------------------------------------------- queue sets --
    //
    // A queue set is a queue whose items are the handles of the queues in
    // it. Nothing is *moved* into the set: an item arriving on a member
    // queue puts that queue's handle on the set, and the task that wakes on
    // the set reads the handle and then reads the member queue itself. So a
    // set holds an announcement, not the data — which is why adding a queue
    // that already has items in it is refused, and why the two counts would
    // otherwise drift apart forever.

    /// `xQueueCreateSet`: a set that can hold `length` announcements.
    ///
    /// # Errors
    /// As [`Kernel::queue_create`].
    pub fn queue_create_set(&mut self, length: usize) -> Result<QueueHandle> {
        self.new_queue(length, Kind::Set)
    }

    /// `xQueueAddToSet`.
    ///
    /// `false` is the C's `pdFAIL`: the target is not a set, the queue is
    /// already in one, or it has items waiting that the set never saw.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn queue_add_to_set(&mut self, queue: QueueHandle, set: QueueHandle) -> Result<bool> {
        self.enter_critical();
        let result = (|| {
            if self.queues.resolve(set)?.kind != Kind::Set {
                return Ok(false);
            }
            let member = self.queues.resolve(queue)?;
            if member.set_container != QueueHandle::NULL || member.waiting != 0 {
                return Ok(false);
            }
            self.queues.resolve_mut(queue)?.set_container = set;
            Ok(true)
        })();
        self.exit_critical();
        result
    }

    /// `xQueueRemoveFromSet`.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn queue_remove_from_set(&mut self, queue: QueueHandle, set: QueueHandle) -> Result<bool> {
        // Both refusals are tested OUTSIDE the section and only the removal
        // itself is inside it, which is what the C does -- and it is NOT
        // what `xQueueAddToSet` does, three functions up, where the whole
        // body including both refusals is inside one section. The asymmetry
        // is upstream's and it is load-bearing here: a failing remove costs
        // the clock nothing, and `QueueSet`'s setup makes one deliberately,
        // to prove a queue cannot be removed from a set it is not in.
        // Charging for it put a tick one event early, 30 lines in.
        let member = *self.queues.resolve(queue)?;
        if member.set_container != set || member.waiting != 0 {
            return Ok(false);
        }
        self.enter_critical();
        let result = self
            .queues
            .resolve_mut(queue)
            .map(|q| q.set_container = QueueHandle::NULL);
        self.exit_critical();
        result?;
        Ok(true)
    }

    /// `xQueueSelectFromSet`: which member queue has something on it.
    ///
    /// The C is one line — `xQueueReceive( xQueueSet, &xReturn, xTicksToWait )`
    /// — so this blocks, traces and costs exactly what a receive does, and
    /// `None` is the C's `NULL`.
    ///
    /// # Errors
    /// As [`Kernel::queue_receive`].
    pub fn queue_select_from_set(
        &mut self,
        set: QueueHandle,
        ticks: u64,
    ) -> Result<Wait<Option<QueueHandle>>> {
        match self.queue_receive(set, ticks) {
            Ok(Blocked) => Ok(Blocked),
            Ok(Ready(raw)) => {
                let handle = QueueHandle::from_raw(u32::try_from(raw).unwrap_or(0));
                Ok(Ready((handle != QueueHandle::NULL).then_some(handle)))
            }
            Err(Error::Empty) => Ok(Ready(None)),
            Err(e) => Err(e),
        }
    }

    /// `xQueueSelectFromSetFromISR`: which queue in `set` has data, from
    /// an interrupt.
    ///
    /// The C is three lines -- `xQueueReceiveFromISR` on the set itself,
    /// with a NULL handle meaning "none" -- because a set IS a queue of
    /// member handles. This is that, and it takes no critical section for
    /// the same reason the rest of the FromISR surface does not.
    ///
    /// # Errors
    /// [`Error::Gone`] for a stale handle.
    pub fn queue_select_from_set_from_isr(
        &mut self,
        set: QueueHandle,
    ) -> Result<Option<QueueHandle>> {
        match self.queue_receive_from_isr(set) {
            Ok((raw, _woken)) => {
                let handle = QueueHandle::from_raw(u32::try_from(raw).unwrap_or(0));
                Ok((handle != QueueHandle::NULL).then_some(handle))
            }
            // An empty set is "no queue has data", which is what the C's
            // NULL means; it is not a failure.
            Err(Error::Empty) => Ok(None),
            Err(e) => Err(e),
        }
    }

    /// `prvNotifyQueueSetContainer`: put `queue`'s handle on the set it
    /// belongs to. `true` when that woke a task that outranks the current
    /// one.
    fn notify_queue_set_container(&mut self, queue: QueueHandle) -> Result<bool> {
        let set = self.queues.resolve(queue)?.set_container;
        let container = *self.queues.resolve(set)?;
        if container.waiting >= container.length {
            // The C asserts this cannot happen and does nothing if it does.
            return Ok(false);
        }
        let tx_lock = container.tx_lock;
        let tick = self.tick;
        self.trace.note_exits(self.port.exits());
        // `traceQUEUE_SET_SEND` is `traceQUEUE_SEND` unless a port says
        // otherwise, and this port does not.
        self.trace.event(
            tick,
            Event::QueueSend {
                queue: set,
                name: "",
            },
        );
        let mut woke =
            self.copy_data_to_queue(set, &container, u64::from(queue.to_raw()), Position::Back)?;
        if tx_lock == UNLOCKED {
            let receivers = Self::queue_receive_list(set);
            if self.lists.is_empty(receivers) == Ok(false)
                && self.remove_from_event_list(receivers)?
            {
                woke = true;
            }
        } else {
            self.increment_tx_lock(set, tx_lock);
        }
        Ok(woke)
    }

    /// `xQueueOverwrite`: write to a length-one queue whether or not it
    /// already holds something.
    ///
    /// The C is `xQueueGenericSend( q, item, 0, queueOVERWRITE )` — a send
    /// with no block time, because a queue that is always writable can
    /// never make the caller wait.
    ///
    /// # Errors
    /// As [`Kernel::queue_send`].
    pub fn queue_overwrite(&mut self, queue: QueueHandle, value: u64) -> Result<Wait<()>> {
        self.queue_send_generic(queue, value, 0, Position::Overwrite)
    }

    // ------------------------------------------------------- from an ISR --
    //
    // The `FromISR` half of the API. Three things make it a different
    // animal from the task half, and all three are visible in a trace:
    //
    //   * It never blocks and never yields. It reports that a higher
    //     priority task woke, by returning a [`Woken`], and the interrupt
    //     decides what to do about it on the way out.
    //   * Its critical section is `portSET_INTERRUPT_MASK_FROM_ISR`, not
    //     `portENTER_CRITICAL`. On the Posix port both are empty, so a call
    //     here costs no sim time at all — which is exactly what the C does
    //     and therefore what a matching trace requires.
    //   * If a task has the queue locked it may not touch the event lists.
    //     It counts what it did in `cTxLock` / `cRxLock` instead, and
    //     `prvUnlockQueue` pays the wake-ups back when the task is done.

    /// `xQueueGenericSendFromISR`.
    ///
    /// # Errors
    /// [`Error::Full`] when the queue is full and this is not an overwrite;
    /// [`Error::Gone`] for a stale handle.
    pub fn queue_send_generic_from_isr(
        &mut self,
        queue: QueueHandle,
        value: u64,
        position: Position,
    ) -> Result<Woken> {
        let mask = self.port.enter_critical_from_isr();
        let result = self.send_from_isr_locked(queue, value, position);
        self.port.exit_critical_from_isr(mask);
        result
    }

    fn send_from_isr_locked(
        &mut self,
        queue: QueueHandle,
        value: u64,
        position: Position,
    ) -> Result<Woken> {
        let snapshot = *self.queues.resolve(queue)?;
        if snapshot.waiting >= snapshot.length && position != Position::Overwrite {
            // `traceQUEUE_SEND_FROM_ISR_FAILED` is not one of the harness's
            // hooks, so a full queue says nothing on either side.
            return Err(Error::Full);
        }
        let tx_lock = snapshot.tx_lock;
        let tick = self.tick;
        self.trace.note_exits(self.port.exits());
        self.trace
            .event(tick, Event::QueueSendFromIsr { queue, name: "" });
        let previously_waiting = snapshot.waiting;
        let _ = self.copy_data_to_queue(queue, &snapshot, value, position)?;
        let mut woken = Woken::NO;
        if tx_lock == UNLOCKED {
            if snapshot.set_container != QueueHandle::NULL {
                let overwrote = position == Position::Overwrite && previously_waiting > 0;
                if !overwrote && self.notify_queue_set_container(queue)? {
                    woken = Woken::YES;
                }
                return Ok(woken);
            }
            let receivers = Self::queue_receive_list(queue);
            if self.lists.is_empty(receivers) == Ok(false)
                && self.remove_from_event_list(receivers)?
            {
                woken = Woken::YES;
            }
        } else {
            self.increment_tx_lock(queue, tx_lock);
        }
        Ok(woken)
    }

    /// `xQueueSendToBackFromISR`.
    ///
    /// # Errors
    /// As [`Kernel::queue_send_generic_from_isr`].
    pub fn queue_send_from_isr(&mut self, queue: QueueHandle, value: u64) -> Result<Woken> {
        self.queue_send_generic_from_isr(queue, value, Position::Back)
    }

    /// `xQueueSendToFrontFromISR`.
    ///
    /// # Errors
    /// As [`Kernel::queue_send_generic_from_isr`].
    pub fn queue_send_to_front_from_isr(
        &mut self,
        queue: QueueHandle,
        value: u64,
    ) -> Result<Woken> {
        self.queue_send_generic_from_isr(queue, value, Position::Front)
    }

    /// `xQueueOverwriteFromISR`. Only for a queue of length one.
    ///
    /// # Errors
    /// As [`Kernel::queue_send_generic_from_isr`].
    pub fn queue_overwrite_from_isr(&mut self, queue: QueueHandle, value: u64) -> Result<Woken> {
        self.queue_send_generic_from_isr(queue, value, Position::Overwrite)
    }

    /// `xSemaphoreGiveFromISR`.
    ///
    /// # Errors
    /// As [`Kernel::queue_send_generic_from_isr`].
    pub fn semaphore_give_from_isr(&mut self, semaphore: QueueHandle) -> Result<Woken> {
        self.queue_send_generic_from_isr(semaphore, 0, Position::Back)
    }

    /// `xQueueReceiveFromISR`: the value, and whether a waiting sender that
    /// this made room for outranks the interrupted task.
    ///
    /// # Errors
    /// [`Error::Empty`] when the queue is empty; [`Error::Gone`] for a
    /// stale handle.
    pub fn queue_receive_from_isr(&mut self, queue: QueueHandle) -> Result<(u64, Woken)> {
        let mask = self.port.enter_critical_from_isr();
        let result = self.receive_from_isr_locked(queue);
        self.port.exit_critical_from_isr(mask);
        result
    }

    fn receive_from_isr_locked(&mut self, queue: QueueHandle) -> Result<(u64, Woken)> {
        let snapshot = *self.queues.resolve(queue)?;
        if snapshot.waiting == 0 {
            return Err(Error::Empty);
        }
        let rx_lock = snapshot.rx_lock;
        let tick = self.tick;
        self.trace.note_exits(self.port.exits());
        self.trace
            .event(tick, Event::QueueReceiveFromIsr { queue, name: "" });
        let value = self.copy_data_from_queue(queue, &snapshot, false)?;
        let mut woken = Woken::NO;
        if rx_lock == UNLOCKED {
            let senders = Self::queue_send_list(queue);
            if self.lists.is_empty(senders) == Ok(false) && self.remove_from_event_list(senders)? {
                woken = Woken::YES;
            }
        } else {
            self.increment_rx_lock(queue, rx_lock);
        }
        Ok((value, woken))
    }

    /// `xQueuePeekFromISR`: the head without removing it.
    ///
    /// It wakes nobody and traces nothing — the C has no hook for it —
    /// which is why it returns a bare value rather than a [`Woken`].
    ///
    /// # Errors
    /// [`Error::Empty`] when the queue is empty; [`Error::Gone`] for a
    /// stale handle.
    pub fn queue_peek_from_isr(&mut self, queue: QueueHandle) -> Result<u64> {
        let mask = self.port.enter_critical_from_isr();
        let result = match self.queues.resolve(queue) {
            Ok(q) if q.waiting > 0 => {
                let snapshot = *q;
                self.copy_data_from_queue(queue, &snapshot, true)
            }
            Ok(_) => Err(Error::Empty),
            Err(e) => Err(e),
        };
        self.port.exit_critical_from_isr(mask);
        result
    }

    /// `prvIncrementQueueTxLock`, capped at the task count as the C caps it.
    fn increment_tx_lock(&mut self, queue: QueueHandle, tx_lock: i8) {
        let tasks = self.task_count();
        if let Ok(q) = self.queues.resolve_mut(queue) {
            if i64::from(tx_lock) < tasks as i64 {
                q.tx_lock = tx_lock.saturating_add(1);
            }
        }
    }

    /// `prvIncrementQueueRxLock`.
    fn increment_rx_lock(&mut self, queue: QueueHandle, rx_lock: i8) {
        let tasks = self.task_count();
        if let Ok(q) = self.queues.resolve_mut(queue) {
            if i64::from(rx_lock) < tasks as i64 {
                q.rx_lock = rx_lock.saturating_add(1);
            }
        }
    }

    /// `xQueueSendToFront`.
    ///
    /// # Errors
    /// As [`Kernel::queue_send`].
    pub fn queue_send_to_front(
        &mut self,
        queue: QueueHandle,
        value: u64,
        ticks: u64,
    ) -> Result<Wait<()>> {
        self.queue_send_generic(queue, value, ticks, Position::Front)
    }

    /// `xSemaphoreGive`: a send with no data.
    ///
    /// # Errors
    /// [`Error::Full`] when the semaphore is already at its maximum count.
    pub fn semaphore_give(&mut self, semaphore: QueueHandle) -> Result<Wait<()>> {
        self.queue_send_generic(semaphore, 0, 0, Position::Back)
    }

    /// `xQueueGenericSend`, one pass of its `for(;;)`.
    ///
    /// # Errors
    /// [`Error::Full`] on timeout; [`Error::Gone`] for a stale handle.
    /// In line on purpose, for the same reason as
    /// [`Kernel::queue_take`]: seven instructions of prologue and ten of
    /// epilogue on every one of khot-ir's 48,000 sends, so that `xQueueSend`
    /// and its siblings could pass four arguments through unchanged. This
    /// one pays on every instrument, `kernel-ir` included.
    #[inline(always)]
    pub fn queue_send_generic(
        &mut self,
        queue: QueueHandle,
        value: u64,
        ticks: u64,
        position: Position,
    ) -> Result<Wait<()>> {
        let caller = self.current;
        // Resuming below the sampling exit, as the C's thread does. See
        // `Kernel::take_queue_resume`: the prologue has already run, and
        // repeating it would spend a second critical-section exit that the
        // C never spends.
        if self.take_queue_resume(caller) != QueueResume::No {
            // The send's only resume point is below its sampling exit: its
            // timed-out branch has nothing after `resume_all` that costs an
            // exit, so being switched away there changes no count.
            return self.queue_send_blocking(caller, queue);
        }
        self.enter_critical();
        let snapshot = match self.queues.resolve(queue) {
            Ok(q) => *q,
            Err(e) => {
                self.exit_critical();
                return Err(e);
            }
        };
        // The wait frame is set where the C sets it: `xQueueReceive` and
        // `xQueueGenericSend` call `vTaskInternalSetTimeOutState` only
        // after finding the queue unusable AND the block time non-zero,
        // guarded by `xEntryTimeSet`. Setting it up here instead meant
        // every *successful* call wrote a six-field frame and then had
        // `end_wait` wipe it on the way out.
        //
        // It also has to be after the resolve, so that a handle naming
        // nothing leaves the caller exactly as it found it -- which is
        // what `configASSERT( pxQueue )` means in the C.
        // `( uxMessagesWaiting < uxLength ) || ( xCopyPosition == queueOVERWRITE )`
        if snapshot.waiting < snapshot.length || position == Position::Overwrite {
            self.trace.note_exits(self.port.exits());
            let tick = self.tick;
            self.trace.event(tick, Event::QueueSend { queue, name: "" });
            let previously_waiting = snapshot.waiting;
            let yield_required = self.copy_data_to_queue(queue, &snapshot, value, position)?;
            if snapshot.set_container != QueueHandle::NULL {
                // A queue in a set announces the arrival there, not here.
                // An overwrite of an item that was already present is not an
                // arrival: the count did not change, so the set is not told.
                let overwrote = position == Position::Overwrite && previously_waiting > 0;
                if !overwrote && self.notify_queue_set_container(queue)? {
                    self.port_yield();
                }
                self.exit_critical();
                self.end_wait(caller);
                return Ok(Ready(()));
            }
            let receivers = Self::queue_receive_list(queue);
            let woke_higher = if self.lists.is_empty(receivers) == Ok(false) {
                self.remove_from_event_list(receivers)?
            } else {
                false
            };
            // queueYIELD_IF_USING_PREEMPTION(), inside the section.
            // `yield_required` first: it is false on every send that is
            // not a mutex give, and it is a local, so on the common path
            // the list is not read a second time at all. Both operands are
            // pure, so the order is free to choose. (The read cannot be
            // hoisted above the removal above it -- removing the last
            // waiter is exactly what changes the answer.)
            if woke_higher || (yield_required && self.lists.is_empty(receivers) != Ok(false)) {
                self.port_yield();
            }
            self.exit_critical();
            self.end_wait(caller);
            return Ok(Ready(()));
        }
        if let Err(e) = self.begin_wait(caller, queue, ticks) {
            self.exit_critical();
            return Err(e);
        }
        if self.remaining_ticks(caller) == 0 {
            self.exit_critical();
            self.trace_failure_or_owe(caller, OwedTrace::SendFailed(queue));
            self.end_wait(caller);
            return Err(Error::Full);
        }
        self.exit_critical();
        // That exit can release a tick, and a tick can switch this task
        // away. The C's thread stops INSIDE the exit, so everything below
        // runs when the task is scheduled again -- and names that task.
        if self.current != caller {
            self.set_queue_resume(caller, QueueResume::BelowSample);
            return Ok(Blocked);
        }
        self.queue_send_blocking(caller, queue)
    }

    /// Everything `xQueueGenericSend` does below its sampling exit.
    ///
    /// Split out so a call preempted at that exit re-enters here rather
    /// than at the top. See [`Kernel::take_queue_resume`].
    fn queue_send_blocking(&mut self, caller: TaskHandle, queue: QueueHandle) -> Result<Wait<()>> {
        self.suspend_all();
        self.lock_queue(queue);
        if self.check_for_timeout(caller) {
            self.unlock_queue(queue)?;
            let _ = self.resume_all();
            self.trace_failure_or_owe(caller, OwedTrace::SendFailed(queue));
            self.end_wait(caller);
            return Err(Error::Full);
        }
        if self.is_queue_full(queue) {
            self.trace.note_exits(self.port.exits());
            let tick = self.tick;
            self.trace
                .event(tick, Event::BlockingOnQueueSend { queue, name: "" });
            let ticks_left = self.remaining_ticks(caller);
            self.place_on_event_list(Self::queue_send_list(queue), ticks_left)?;
            self.unlock_queue(queue)?;
            if !self.resume_all() {
                self.yield_or_owe(caller);
            }
        } else {
            self.unlock_queue(queue)?;
            let _ = self.resume_all();
        }
        Ok(Blocked)
    }

    /// `prvCopyDataToQueue`; `true` when giving a mutex back lowered the
    /// giver's priority and a yield is therefore wanted.
    ///
    /// This resolves rather than taking the caller's snapshot, and
    /// [`Kernel::copy_data_from_queue`] does the opposite. That is not an
    /// inconsistency: both forms were measured on both helpers and they
    /// disagree, because the writer's caller does not keep its snapshot
    /// live across the call and the reader's does.
    ///
    /// In line on purpose. `queue_send_generic` is its only caller, and out
    /// of line it paid a call and a frame on all 48,000 sends to move one
    /// value into a slot the caller had already resolved. Its reader twin
    /// was already being inlined by LLVM; this one was over the size
    /// threshold and was not.
    #[inline(always)]
    fn copy_data_to_queue(
        &mut self,
        queue: QueueHandle,
        snapshot: &Queue,
        value: u64,
        position: Position,
    ) -> Result<bool> {
        // The snapshot comes from the caller, which has already resolved this
        // handle -- and nothing between that resolve and this call can reach
        // the arena. Resolving again here made every send pay for the same
        // four checks twice. `copy_data_from_queue` has always taken its
        // snapshot this way.
        let mut yield_required = false;
        // `prvCopyDataToQueue` counts the item in — except on an overwrite
        // of a queue that already held one, where it decrements first so
        // the increment cancels and the count stays where it was.
        //
        // Decided once, up here, so that each arm below can fold the count
        // into the resolve it is already making. Deciding it after the arms
        // is what forced a further resolve for one field.
        let counted = !(position == Position::Overwrite && snapshot.waiting > 0);
        if snapshot.kind.carries_data() {
            let (index, next_read, next_write) = match position {
                Position::Back => (
                    snapshot.write_to,
                    snapshot.read_from,
                    wrap_next(snapshot.write_to, snapshot.length),
                ),
                // Write at the item last read, then step back, so the next
                // read's pre-increment lands on it. An overwrite takes the
                // same path; only the message count differs.
                Position::Front | Position::Overwrite => (
                    snapshot.read_from,
                    wrap_prev(snapshot.read_from, snapshot.length),
                    snapshot.write_to,
                ),
            };
            // `base + index` is below `base + length`, which the geometry
            // put inside `SLOTS`; and the `get_mut` refuses anything it is
            // not, so nothing rests on the arithmetic either way.
            if let Some(slot) = self.slots.get_mut(snapshot.base.wrapping_add(index)) {
                *slot = value;
            }
            let q = self.queues.resolve_mut(queue)?;
            q.read_from = next_read;
            q.write_to = next_write;
            if counted {
                q.waiting = q.waiting.wrapping_add(1);
            }
        } else if snapshot.kind.is_mutex() {
            // Giving a mutex back: the holder drops any inherited
            // priority. The disinherit touches the holder's TCB, not this
            // queue, so the resolve after it is still the first one.
            yield_required = self.priority_disinherit(snapshot.holder)?;
            let q = self.queues.resolve_mut(queue)?;
            q.holder = TaskHandle::NULL;
            if counted {
                q.waiting = q.waiting.wrapping_add(1);
            }
        } else if counted {
            // A counting or binary semaphore: only the count moves.
            let q = self.queues.resolve_mut(queue)?;
            q.waiting = q.waiting.wrapping_add(1);
        }
        Ok(yield_required)
    }

    // ----------------------------------------------------------- receive --

    /// `xQueueReceive`.
    ///
    /// # Errors
    /// [`Error::Empty`] when the block time expires with the queue still
    /// empty; [`Error::Gone`] for a stale handle.
    pub fn queue_receive(&mut self, queue: QueueHandle, ticks: u64) -> Result<Wait<u64>> {
        self.queue_take::<false>(queue, ticks)
    }

    /// `xQueuePeek`: read the head without removing it.
    ///
    /// # Errors
    /// As [`Kernel::queue_receive`].
    pub fn queue_peek(&mut self, queue: QueueHandle, ticks: u64) -> Result<Wait<u64>> {
        self.queue_take::<true>(queue, ticks)
    }

    /// `xSemaphoreTake`, which is `xQueueSemaphoreTake`: a receive with no
    /// data, and — on a mutex — with priority inheritance while it waits.
    ///
    /// # Errors
    /// [`Error::Empty`] on timeout; [`Error::Gone`] for a stale handle.
    pub fn semaphore_take(&mut self, semaphore: QueueHandle, ticks: u64) -> Result<Wait<()>> {
        match self.queue_take::<false>(semaphore, ticks)? {
            Blocked => Ok(Blocked),
            Ready(_) => Ok(Ready(())),
        }
    }

    /// The shared body of `xQueueReceive`, `xQueuePeek` and
    /// `xQueueSemaphoreTake` — one pass of the C `for(;;)`.
    /// `PEEK` is a const because it is one at every call site: a receive
    /// passes `false`, a peek `true`, and a semaphore take `false`. As a
    /// parameter it cost an argument to set up and a branch at each of the
    /// ten places this function and its copy helper consult it.
    /// In line on purpose, into all three of `xQueueReceive`, `xQueuePeek`
    /// and `xSemaphoreTake`.
    ///
    /// Out of line it charged eight instructions of prologue and ten of
    /// epilogue to every take -- 48,000 of them in `khot-ir`, which is 7.6%
    /// of that instrument -- so that three wrappers could each hand it two
    /// arguments and return its result unchanged. LLVM declined on size; the
    /// frame is the reason to overrule that.
    ///
    /// The cost is stated rather than hidden: `kernel-ir` pays 214,804 for
    /// the larger wrappers. Splitting the body from the symbol does not
    /// recover it -- outlining at the semaphore site alone leaves `kernel-ir`
    /// 262,828 up and gives back 427,983 of `khot-ir`'s win, and outlining at
    /// the receive site leaves it 190,238 up and gives back 1,104,183 -- so
    /// the regression is the wrappers growing, not any one call site.
    #[inline(always)]
    fn queue_take<const PEEK: bool>(
        &mut self,
        queue: QueueHandle,
        ticks: u64,
    ) -> Result<Wait<u64>> {
        let caller = self.current;
        // Resuming below the sampling exit, as `queue_send_generic` does.
        // The snapshot is re-read rather than carried: nothing below uses
        // anything of it that a concurrent access could change, and the
        // read takes no critical section, so it costs the clock nothing.
        match self.take_queue_resume(caller) {
            QueueResume::No => {}
            QueueResume::BelowSample => {
                let snapshot = *self.queues.resolve(queue)?;
                return self.queue_take_blocking::<PEEK>(caller, queue, snapshot);
            }
            QueueResume::BelowTimedOutResume => {
                let snapshot = *self.queues.resolve(queue)?;
                return self.queue_take_timed_out::<PEEK>(caller, queue, snapshot);
            }
        }
        self.enter_critical();
        let snapshot = match self.queues.resolve(queue) {
            Ok(q) => *q,
            Err(e) => {
                self.exit_critical();
                return Err(e);
            }
        };
        // The wait frame is set where the C sets it: `xQueueReceive` and
        // `xQueueGenericSend` call `vTaskInternalSetTimeOutState` only
        // after finding the queue unusable AND the block time non-zero,
        // guarded by `xEntryTimeSet`. Setting it up here instead meant
        // every *successful* call wrote a six-field frame and then had
        // `end_wait` wipe it on the way out.
        //
        // It also has to be after the resolve, so that a handle naming
        // nothing leaves the caller exactly as it found it -- which is
        // what `configASSERT( pxQueue )` means in the C.
        if snapshot.waiting > 0 {
            let value = self.copy_data_from_queue(queue, &snapshot, PEEK)?;
            self.trace.note_exits(self.port.exits());
            let tick = self.tick;
            // `xQueuePeek` is its own function in the C with its own trace
            // macro; `xQueueSemaphoreTake` shares `xQueueReceive`'s.
            let event = if PEEK {
                Event::QueuePeek { queue, name: "" }
            } else {
                Event::QueueReceive { queue, name: "" }
            };
            self.trace.event(tick, event);
            if PEEK {
                // A PEEK wakes another *receiver*, not a sender: the item
                // is still there.
                let receivers = Self::queue_receive_list(queue);
                if self.lists.is_empty(receivers) == Ok(false)
                    && self.remove_from_event_list(receivers)?
                {
                    self.port_yield();
                }
            } else {
                if snapshot.kind.is_mutex() {
                    self.queues.resolve_mut(queue)?.holder = caller;
                    self.increment_mutexes_held(caller);
                }
                let senders = Self::queue_send_list(queue);
                if self.lists.is_empty(senders) == Ok(false)
                    && self.remove_from_event_list(senders)?
                {
                    self.port_yield();
                }
            }
            self.exit_critical();
            self.end_wait(caller);
            return Ok(Ready(value));
        }
        if let Err(e) = self.begin_wait(caller, queue, ticks) {
            self.exit_critical();
            return Err(e);
        }
        if self.remaining_ticks(caller) == 0 {
            self.exit_critical();
            // `traceQUEUE_PEEK_FAILED` is not one of the harness's hooks,
            // so a failed PEEK says nothing on either side.
            if !PEEK {
                self.trace_failure_or_owe(caller, OwedTrace::ReceiveFailed(queue));
            }
            self.end_wait(caller);
            return Err(Error::Empty);
        }
        self.exit_critical();
        // That exit can release a tick, and a tick can switch this task
        // away. The C's thread stops INSIDE the exit, so everything below
        // runs when the task is scheduled again -- and names that task.
        if self.current != caller {
            self.set_queue_resume(caller, QueueResume::BelowSample);
            return Ok(Blocked);
        }
        self.queue_take_blocking::<PEEK>(caller, queue, snapshot)
    }

    /// Everything `xQueueReceive` and `xQueuePeek` do below their sampling
    /// exit. See [`Kernel::take_queue_resume`].
    fn queue_take_blocking<const PEEK: bool>(
        &mut self,
        caller: TaskHandle,
        queue: QueueHandle,
        snapshot: Queue,
    ) -> Result<Wait<u64>> {
        self.suspend_all();
        self.lock_queue(queue);
        if self.check_for_timeout(caller) {
            self.unlock_queue(queue)?;
            let _ = self.resume_all();
            // `xTaskResumeAll` replays any tick that pended while the
            // scheduler was suspended, and replaying it can switch this task
            // away with `prvIsQueueEmpty` still to run. The C's thread stops
            // inside it; everything below runs when the task is next
            // scheduled. Without this, `prvIsQueueEmpty`'s section is spent
            // in the wrong window -- one exit, and IntQueue's 100,000-tick
            // run diverges at tick 16,260.
            if self.current != caller {
                self.set_queue_resume(caller, QueueResume::BelowTimedOutResume);
                return Ok(Blocked);
            }
            return self.queue_take_timed_out::<PEEK>(caller, queue, snapshot);
        }
        self.queue_take_locked::<PEEK>(caller, queue, snapshot)
    }

    /// `xQueueReceive` below the `xTaskResumeAll` of its timed-out branch.
    fn queue_take_timed_out<const PEEK: bool>(
        &mut self,
        caller: TaskHandle,
        queue: QueueHandle,
        snapshot: Queue,
    ) -> Result<Wait<u64>> {
        {
            if self.is_queue_empty(queue) {
                if snapshot.kind.is_mutex() && self.wait_inherited(caller) {
                    // `vTaskPriorityDisinheritAfterTimeout`: the holder
                    // keeps only what the still-waiting tasks justify.
                    self.enter_critical();
                    let highest = self.highest_waiting_priority(queue)?;
                    let holder = self.queues.resolve(queue).map(|q| q.holder)?;
                    self.priority_disinherit_after_timeout(holder, highest)?;
                    self.exit_critical();
                }
                if !PEEK {
                    self.trace_failure_or_owe(caller, OwedTrace::ReceiveFailed(queue));
                }
                self.end_wait(caller);
                return Err(Error::Empty);
            }
            Ok(Blocked)
        }
    }

    /// `xQueueReceive` below its timeout test, with the queue still locked.
    fn queue_take_locked<const PEEK: bool>(
        &mut self,
        caller: TaskHandle,
        queue: QueueHandle,
        snapshot: Queue,
    ) -> Result<Wait<u64>> {
        if self.is_queue_empty(queue) {
            let event = if PEEK {
                Event::BlockingOnQueuePeek { queue, name: "" }
            } else {
                Event::BlockingOnQueueReceive { queue, name: "" }
            };
            self.trace.note_exits(self.port.exits());
            let tick = self.tick;
            self.trace.event(tick, event);
            if snapshot.kind.is_mutex() {
                self.enter_critical();
                let holder = self.queues.resolve(queue).map(|q| q.holder)?;
                let inherited = self.priority_inherit(holder)?;
                self.exit_critical();
                if inherited {
                    self.set_wait_inherited(caller);
                }
            }
            let ticks_left = self.remaining_ticks(caller);
            self.place_on_event_list(Self::queue_receive_list(queue), ticks_left)?;
            self.unlock_queue(queue)?;
            if !self.resume_all() {
                self.yield_or_owe(caller);
            }
        } else {
            self.unlock_queue(queue)?;
            let _ = self.resume_all();
        }
        Ok(Blocked)
    }

    /// `prvCopyDataFromQueue`, with the peek variant putting the cursor
    /// back as `xQueuePeek` does.
    /// `prvCopyDataFromQueue`, over a snapshot its caller already took.
    ///
    /// Every caller resolves this queue to decide whether there is
    /// anything to read; this used to resolve it again to do the reading.
    /// The snapshot cannot be stale — nothing between the two touches this
    /// queue, and both are inside the same critical section.
    ///
    /// The same change to [`Kernel::copy_data_to_queue`] is **refused**,
    /// and the pair is why this bench exists: threading the snapshot into
    /// the writer is worth -245,389 Ir inside it and +211,717 in
    /// `queue_send_generic`, because a `&Queue` argument forces the
    /// caller's local to be addressable and it stops living in registers.
    /// Here the caller is `queue_take`, which keeps its snapshot alive
    /// across the call anyway, so there is no spill to pay for.
    fn copy_data_from_queue(
        &mut self,
        queue: QueueHandle,
        snapshot: &Queue,
        peek: bool,
    ) -> Result<u64> {
        if !snapshot.kind.carries_data() {
            if !peek {
                let q = self.queues.resolve_mut(queue)?;
                // Wrapping: all three callers reach here under
                // `waiting > 0`, and the doc above says the snapshot they
                // tested cannot be stale, so there is an item to take.
                q.waiting = q.waiting.wrapping_sub(1);
            }
            return Ok(0);
        }
        let next = wrap_next(snapshot.read_from, snapshot.length);
        let value = self
            .slots
            .get(snapshot.base.wrapping_add(next))
            .copied()
            .unwrap_or(0);
        // `xQueuePeek` saves and restores `pcReadFrom` — which is to
        // say it leaves it exactly as it found it. Writing it back stored
        // the value already there, and the resolve that reached it was a
        // whole handle validation for a no-op.
        if !peek {
            let q = self.queues.resolve_mut(queue)?;
            q.read_from = next;
            // Wrapping, for the same reason as the branch above.
            q.waiting = q.waiting.wrapping_sub(1);
        }
        Ok(value)
    }

    // ------------------------------------------------------ recursive mutex --

    /// `xSemaphoreTakeRecursive`.
    ///
    /// # Errors
    /// [`Error::Empty`] on timeout; [`Error::Gone`] for a stale handle.
    pub fn mutex_take_recursive(&mut self, mutex: QueueHandle, ticks: u64) -> Result<Wait<()>> {
        let caller = self.current;
        // One resolve reads the holder and counts the re-entry.
        // `resolve_mut` runs the same four checks and answers the same
        // errors, so asking twice only asked twice.
        {
            let q = self.queues.resolve_mut(mutex)?;
            if q.holder == caller {
                q.recursions = q.recursions.wrapping_add(1);
                return Ok(Ready(()));
            }
        }
        match self.semaphore_take(mutex, ticks)? {
            Blocked => Ok(Blocked),
            Ready(()) => {
                let q = self.queues.resolve_mut(mutex)?;
                q.recursions = q.recursions.wrapping_add(1);
                Ok(Ready(()))
            }
        }
    }

    /// `xSemaphoreGiveRecursive`.
    ///
    /// # Errors
    /// [`Error::NotActive`] when the caller does not hold the mutex.
    pub fn mutex_give_recursive(&mut self, mutex: QueueHandle) -> Result<()> {
        let caller = self.current;
        // One resolve, as in the take above.
        let remaining = {
            let q = self.queues.resolve_mut(mutex)?;
            if q.holder != caller {
                return Err(Error::NotActive);
            }
            q.recursions = q.recursions.saturating_sub(1);
            q.recursions
        };
        if remaining == 0 {
            let _ = self.semaphore_give(mutex)?;
        }
        Ok(())
    }

    // -------------------------------------------------------- queue locks --

    /// `prvLockQueue`: one critical section. The lock counters themselves
    /// only matter to an ISR, and the sim has none — but the section is
    /// where sim time passes, so it is here.
    /// `prvLockQueue`: stop interrupts taking tasks off this queue's event
    /// lists while a task walks them. An interrupt that finds the queue
    /// locked counts what it did instead, and [`Kernel::unlock_queue`] pays
    /// it back.
    fn lock_queue(&mut self, queue: QueueHandle) {
        self.enter_critical();
        if let Ok(q) = self.queues.resolve_mut(queue) {
            if q.rx_lock == UNLOCKED {
                q.rx_lock = LOCKED_UNMODIFIED;
            }
            if q.tx_lock == UNLOCKED {
                q.tx_lock = LOCKED_UNMODIFIED;
            }
        }
        self.exit_critical();
    }

    /// `prvUnlockQueue`: two critical sections, one per lock counter. The
    /// loops inside them wake tasks that an ISR queued while the lock was
    /// held, and on the sim there are none.
    /// `prvUnlockQueue`: two critical sections, one per lock count, each
    /// waking one task per send or receive an interrupt made while the
    /// queue was locked. The yields are *missed* yields — pended, not
    /// taken — because a task is walking the list.
    fn unlock_queue(&mut self, queue: QueueHandle) -> Result<()> {
        self.enter_critical();
        {
            // One resolve for both fields. They were two, and a resolve
            // is a null test, a bounds check, a generation compare and an
            // `Option` unwrap -- all of it repeated to reach the same slot.
            let (mut tx_lock, container) = self
                .queues
                .resolve(queue)
                .map_or((UNLOCKED, QueueHandle::NULL), |q| {
                    (q.tx_lock, q.set_container)
                });
            while tx_lock > LOCKED_UNMODIFIED {
                if container != QueueHandle::NULL {
                    if self.notify_queue_set_container(queue)? {
                        self.missed_yield();
                    }
                    // Wrapping: the loop runs only while this is above
                    // `LOCKED_UNMODIFIED`, so one off it stays in range.
                    tx_lock = tx_lock.wrapping_sub(1);
                    continue;
                }
                let receivers = Self::queue_receive_list(queue);
                if self.lists.is_empty(receivers) == Ok(true) {
                    break;
                }
                if self.remove_from_event_list(receivers)? {
                    self.missed_yield();
                }
                // Wrapping: bounded by the loop, as above.
                tx_lock = tx_lock.wrapping_sub(1);
            }
            if let Ok(q) = self.queues.resolve_mut(queue) {
                q.tx_lock = UNLOCKED;
            }
        }
        self.exit_critical();
        self.enter_critical();
        {
            let mut rx_lock = self
                .queues
                .resolve(queue)
                .map(|q| q.rx_lock)
                .unwrap_or(UNLOCKED);
            while rx_lock > LOCKED_UNMODIFIED {
                let senders = Self::queue_send_list(queue);
                if self.lists.is_empty(senders) == Ok(true) {
                    break;
                }
                if self.remove_from_event_list(senders)? {
                    self.missed_yield();
                }
                // Wrapping: bounded by the loop, as above.
                rx_lock = rx_lock.wrapping_sub(1);
            }
            if let Ok(q) = self.queues.resolve_mut(queue) {
                q.rx_lock = UNLOCKED;
            }
        }
        self.exit_critical();
        Ok(())
    }

    /// `vQueueWaitForMessageRestricted`: what the timer service task does
    /// when it has no timer to run — block on the command queue without
    /// suspending the scheduler.
    ///
    /// `wait_indefinitely` is the C third argument: when set the wait
    /// becomes `portMAX_DELAY` and the task goes to the suspended list
    /// rather than a delayed one. The queue locks around it are C's
    /// `prvLockQueue` and `prvUnlockQueue` — three critical sections, and
    /// therefore three sixteenths of a tick's worth of sim time.
    ///
    /// # Errors
    /// A list error surfaces as itself.
    pub fn wait_for_message_restricted(
        &mut self,
        queue: QueueHandle,
        ticks: u64,
        wait_indefinitely: bool,
    ) -> Result<()> {
        self.lock_queue(queue);
        let empty = self
            .queues
            .resolve(queue)
            .map(|q| q.waiting == 0)
            .unwrap_or(false);
        if empty {
            // vTaskPlaceOnEventListRestricted
            let current = self.current;
            let event = Self::event_item(current);
            self.lists
                .insert_end(Self::queue_receive_list(queue), event)?;
            let ticks = if wait_indefinitely {
                Self::MAX_DELAY
            } else {
                ticks
            };
            let wake_at = self.tick.wrapping_add(ticks) & Self::MAX_DELAY;
            self.trace_task(current, |task, name| Event::TaskDelayUntil {
                task,
                name,
                wake_at,
            });
            self.add_current_task_to_delayed_list(ticks, wait_indefinitely)?;
        }
        self.unlock_queue(queue)?;
        Ok(())
    }

    /// `prvIsQueueEmpty`, critical section and all — it is one of the
    /// four the blocking path spends, and therefore a sixteenth of a tick
    /// every four calls.
    fn is_queue_empty(&mut self, queue: QueueHandle) -> bool {
        self.enter_critical();
        let empty = self
            .queues
            .resolve(queue)
            .map(|q| q.waiting == 0)
            .unwrap_or(true);
        self.exit_critical();
        empty
    }

    /// `prvIsQueueFull`, likewise.
    fn is_queue_full(&mut self, queue: QueueHandle) -> bool {
        self.enter_critical();
        let full = self
            .queues
            .resolve(queue)
            .map(|q| q.waiting >= q.length)
            .unwrap_or(false);
        self.exit_critical();
        full
    }

    /// `prvGetHighestPriorityOfWaitToReceiveList`.
    fn highest_waiting_priority(&self, queue: QueueHandle) -> Result<u8> {
        let list = Self::queue_receive_list(queue);
        match self.lists.head(list)? {
            // The event item's value is `configMAX_PRIORITIES - priority`.
            Some(item) => {
                let value = self.lists.value(item)?;
                let max = u64::from(C::MAX_PRIORITIES);
                Ok(u8::try_from(max.saturating_sub(value)).unwrap_or(0))
            }
            None => Ok(0),
        }
    }
}

/// The next index in a ring of `length`.
const fn wrap_next(index: usize, length: usize) -> usize {
    // `wrapping_add`, and it is the SAME function, not an approximation
    // of it: at `usize::MAX` saturating yields `usize::MAX`, which is
    // `>= length`, so the caller gets 0 -- and wrapping yields 0, which is
    // `< length`, so the caller gets 0 as well. Every other index agrees
    // without argument.
    let next = index.wrapping_add(1);
    if next >= length { 0 } else { next }
}

/// The previous index in a ring of `length`.
const fn wrap_prev(index: usize, length: usize) -> usize {
    match index.checked_sub(1) {
        Some(prev) => prev,
        None => length.saturating_sub(1),
    }
}

/// The Rust face's raw surface: see [`crate::typed`].
///
/// Every method here is one of the kernel's own calls under another name.
/// The one that is not — [`Raw::raw_queue_has_room`] — is the kernel
/// reading its own queue rather than a task asking, so it takes no
/// critical section and costs no sim time, which is what lets the typed
/// face be free.
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,
> crate::typed::Raw
    for Kernel<C, P, T, H, TASKS, ITEMS, LISTS, QUEUES, SLOTS, BUFFERS, BYTES, TIMERS, GROUPS>
where
    H: TickHook<Self>,
{
    fn raw_queue_create(&mut self, length: usize) -> Result<QueueHandle> {
        self.queue_create(length)
    }

    fn raw_queue_send(&mut self, queue: QueueHandle, value: u64, ticks: u64) -> Result<Wait<()>> {
        self.queue_send(queue, value, ticks)
    }

    fn raw_queue_receive(&mut self, queue: QueueHandle, ticks: u64) -> Result<Wait<u64>> {
        self.queue_receive(queue, ticks)
    }

    fn raw_queue_messages_waiting(&mut self, queue: QueueHandle) -> Result<usize> {
        self.queue_messages_waiting(queue)
    }

    fn raw_queue_has_room(&self, queue: QueueHandle) -> bool {
        self.queues
            .resolve(queue)
            .is_ok_and(|q| q.waiting < q.length)
    }

    fn raw_in_isr(&self) -> bool {
        self.port.in_isr()
    }

    fn raw_queue_send_from_isr(&mut self, queue: QueueHandle, value: u64) -> Result<Woken> {
        self.queue_send_from_isr(queue, value)
    }

    fn raw_mutex_create(&mut self) -> Result<QueueHandle> {
        self.mutex_create()
    }

    fn raw_mutex_take(&mut self, mutex: QueueHandle, ticks: u64) -> Result<Wait<()>> {
        self.semaphore_take(mutex, ticks)
    }

    fn raw_mutex_give(&mut self, mutex: QueueHandle) -> Result<()> {
        self.semaphore_give(mutex).map(|_| ())
    }
}