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
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
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
//! `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, Default)]
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. `#[default]` so a free arena slot holds something
    /// real without unsafe; the ORDER above is untouched, and nothing reads
    /// a free slot.
    #[default]
    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, Default)]
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 {
    // A3: ONE caller, so the out-of-line body pays a prologue and epilogue for
    // a single call. Inlining moves the body rather than duplicating it.
    #[inline]
    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,
    const TIMER_CMDS: usize,
> Kernel<C, P, T, H, TASKS, ITEMS, LISTS, QUEUES, SLOTS, BUFFERS, BYTES, TIMERS, GROUPS, TIMER_CMDS>
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<()> {
        let q = *self.queues.resolve(queue)?;
        // Give the item storage back when it is the last thing allocated.
        //
        // `new_queue` bump-allocates from `slots_used` and, until
        // 2026-09-21, nothing ever lowered it: the DESCRIPTOR came back and
        // the storage did not, so a create/delete loop exhausted `SLOTS`
        // permanently. `AbortDelay` hits it after ~108 passes, which is how
        // it was found, and any application with a queue per connection or
        // per job hits it too.
        //
        // This is the same move `give_bytes` already makes for the byte
        // arena — that allocator exists because "a bump allocator would run
        // out in a few hundred ticks", and the identical argument applies
        // here and was simply never made.
        //
        // Deliberately the END-OF-ARENA case only, and not a free list.
        // The pattern that needs this is create-then-delete of the same
        // object, where the deleted extent IS the last one, and it is what
        // the corpus exercises. An out-of-order delete still strands its
        // slots; that wants the full `free_blocks` treatment and is a
        // larger change with more to prove.
        if q.kind.carries_data() {
            self.give_slots(q.base, q.length);
        }
        let _ = self.queues.discard(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)
    }

    /// `prvInitialiseMutex`: give the mutex once so it starts available.
    ///
    /// This goes through the general send for the same reason the C does — and
    /// the byte count is the argument. Until 2026-09-25 a private `prime_mutex`
    /// carried a hand-written copy of the send, specialised on the four
    /// constants supplied below, because inlining the general body here cost
    /// **534 bytes**. That defence was aimed at the wrong thing: the choice is
    /// not "specialise or inline", it is *which symbol to call*, and
    /// [`Self::send_generic_outlined`] — the A4 handle that already existed for
    /// the cold callers — costs a five-argument frame, not a body.
    ///
    /// Calling it instead and deleting the specialisation measured
    /// **−316 bytes** of flash (19,302 → 18,986), `mv` − 8, `slli` − 5,
    /// `andi` − 2 and 99 fewer rv32 instructions — every pin down, none up.
    /// `conform --all` stays at 26/26, which is what proves the trace is
    /// unchanged: one critical section, `QueueSend` at the same point, the same
    /// `exits`. A mutex therefore still shows a `QUEUE_SEND` line immediately
    /// after its `QUEUE_CREATE`, before any task exists.
    ///
    /// The law: a specialisation written to escape an unwanted INLINE is only
    /// worth its bytes if no out-of-line handle on the general body exists.
    /// Check for the handle first.
    fn new_mutex(&mut self, kind: Kind) -> Result<QueueHandle> {
        let handle = self.new_queue(1, kind)?;
        let _ = self.send_generic_outlined(handle, 0, 0, Position::Back)?;
        Ok(handle)
    }

    /// Take `length` slots: first fit from what deleted queues gave back,
    /// and only then from the untouched end.
    ///
    /// First fit rather than best fit for the same reason `take_bytes` uses
    /// it — the pattern that needs an allocator at all is create-then-delete
    /// of the *same size*, which first fit serves exactly and without
    /// fragmenting.
    fn take_slots(&mut self, length: usize) -> Option<usize> {
        if length == 0 {
            return Some(self.slots_used);
        }
        for i in 0..self.free_slot_count {
            let (base, free) = *self.free_slots.get(i)?;
            if free < length {
                continue;
            }
            if free == length {
                self.drop_free_slot(i);
            } else if let Some(slot) = self.free_slots.get_mut(i) {
                *slot = (base.saturating_add(length), free.wrapping_sub(length));
            }
            return Some(base);
        }
        let end = self.slots_used.checked_add(length)?;
        if end > SLOTS {
            return None;
        }
        let base = self.slots_used;
        self.slots_used = end;
        Some(base)
    }

    /// Give an extent back, coalescing with whichever neighbours touch it so
    /// the list cannot grow past one entry per hole.
    pub(crate) fn give_slots(&mut self, base: usize, length: usize) {
        if length == 0 {
            return;
        }
        let mut base = base;
        let mut length = length;
        let mut i = 0;
        while i < self.free_slot_count {
            let Some(&(other_base, other_len)) = self.free_slots.get(i) else {
                break;
            };
            if other_base.saturating_add(other_len) == base {
                base = other_base;
                length = length.saturating_add(other_len);
                self.drop_free_slot(i);
                continue;
            }
            if base.saturating_add(length) == other_base {
                length = length.saturating_add(other_len);
                self.drop_free_slot(i);
                continue;
            }
            i = i.wrapping_add(1);
        }
        // An extent at the very end goes back to the bump pointer instead of
        // the list, which is what keeps a create/delete loop free.
        if base.saturating_add(length) == self.slots_used {
            self.slots_used = base;
            return;
        }
        if let Some(slot) = self.free_slots.get_mut(self.free_slot_count) {
            *slot = (base, length);
            self.free_slot_count = self.free_slot_count.wrapping_add(1);
        }
    }

    fn drop_free_slot(&mut self, index: usize) {
        let last = self.free_slot_count.saturating_sub(1);
        if index < last {
            if let Some(&moved) = self.free_slots.get(last) {
                if let Some(slot) = self.free_slots.get_mut(index) {
                    *slot = moved;
                }
            }
        }
        self.free_slot_count = last;
    }

    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.take_slots(slots).ok_or(Error::Full)?;
        let handle = match self.queues.try_insert(Queue::new(base, length, kind)) {
            Ok(handle) => handle,
            Err(_) => {
                // The descriptor arena refused after the slots were taken,
                // so give them straight back rather than stranding them.
                self.give_slots(base, slots);
                return Err(Error::Full);
            }
        };
        // `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.note_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_of(senders) && 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.is_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.is_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.is_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.
    /// `#[cold]` because the call is GUARDED and reached from many sites on
    /// one hot path, which is the shape that pays: it lets LLVM keep the
    /// caller's frame setup out of the likely route. Measured on
    /// `riscv32-qemu-tick-work`, one attribute at a time.
    /// Worth queue -1 on its own.
    #[cold]
    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.note_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_of(receivers) && 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.send_generic_outlined(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.note_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 C::USE_QUEUE_SETS && !snapshot.set_container.is_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_of(receivers) && 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.note_exits();
        self.trace
            .event(tick, Event::QueueReceiveFromIsr { queue, name: "" });
        let value = self.copy_data_from_queue(
            queue,
            snapshot.kind,
            snapshot.base,
            snapshot.length,
            snapshot.read_from,
            false,
        )?;
        let mut woken = Woken::NO;
        if rx_lock == UNLOCKED {
            let senders = Self::queue_send_list(queue);
            if !self.lists.is_empty_of(senders) && 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.kind,
                    snapshot.base,
                    snapshot.length,
                    snapshot.read_from,
                    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) {
            // 32-bit throughout. This was `i64::from(lock) < tasks as i64`,
            // which is a SIXTY-FOUR-bit signed compare on a target whose
            // registers are 32 -- to order an `i8` against a task count. The
            // `< 0` arm is what makes the unsigned cast safe and is the
            // UNLOCKED sentinel's case, which cannot reach the increment.
            if tx_lock < 0 || (tx_lock as usize) < tasks {
                q.tx_lock = tx_lock.wrapping_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) {
            // 32-bit throughout. This was `i64::from(lock) < tasks as i64`,
            // which is a SIXTY-FOUR-bit signed compare on a target whose
            // registers are 32 -- to order an `i8` against a task count. The
            // `< 0` arm is what makes the unsigned cast safe and is the
            // UNLOCKED sentinel's case, which cannot reach the increment.
            if rx_lock < 0 || (rx_lock as usize) < tasks {
                q.rx_lock = rx_lock.wrapping_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.send_generic_outlined(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.send_generic_outlined(semaphore, 0, 0, Position::Back)
    }

    /// The out-of-line handle on [`Kernel::queue_send_generic`]'s body.
    ///
    /// One shared copy for the wrappers that are not on a measured hot row --
    /// `queue_send_to_front`, `queue_overwrite`, `semaphore_give` and the
    /// timer daemon's post. `queue_send` keeps the inlined body because
    /// `send_full`, `queue_roundtrip` and `block_cycle` all go through it and
    /// all three pay for the call.
    #[inline(never)]
    pub(crate) fn send_generic_outlined(
        &mut self,
        queue: QueueHandle,
        value: u64,
        ticks: u64,
        position: Position,
    ) -> Result<Wait<()>> {
        self.queue_send_generic(queue, value, ticks, position)
    }

    /// `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.
    ///
    /// **But only the HOT site wants it.** With the flash probe fixed so that
    /// real bodies link at all (2026-09-24), this was inlined at five places
    /// and cost about 1,666 bytes of duplicate.
    ///
    /// RE-PRICED 2026-09-25, because that figure was taken at FIVE inline sites
    /// and there is now one. Dropping the hint today measures:
    ///
    /// * flash **19,302 -> 18,704, i.e. -598 B**, with `mv` -31, `andi` -7,
    ///   `slli` -8 and 221 fewer instructions;
    /// * rv32 work rows **+118 instructions** over seven of them —
    ///   `queue_roundtrip` 122 -> 169, `block_cycle` 983 -> 1022,
    ///   `send_full` 36 -> 62, and +1 or +2 on four more.
    ///
    /// That is **5.07 bytes of flash per instruction**, a worse rate than the
    /// `queue_peek` trade declined at 7.3 and than the 10.7 this hint was
    /// originally kept at. So it stays — but the K3 flash row is the one
    /// FAILING its target while the work rows are absolutes with no C
    /// comparison, so if that priority ever inverts this is the single largest
    /// item in the send path and the numbers are here. `rusty-compiler-leverage` A4: a function has one
    /// body, so one inlining decision serves callers who want different
    /// things -- give it two names instead of averaging them.
    /// [`Kernel::send_generic_outlined`] is the out-of-line handle, and the
    /// four colder wrappers call that.
    #[cfg_attr(not(feature = "small"), inline(always))]
    #[cfg_attr(feature = "small", inline(never))]
    pub fn queue_send_generic(
        &mut self,
        queue: QueueHandle,
        value: u64,
        ticks: u64,
        position: Position,
    ) -> Result<Wait<()>> {
        let caller = self.cur();
        // 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.note_exits();
            let tick = self.tick;
            self.trace.event(tick, Event::QueueSend { queue, name: "" });
            // An emitting sink is a CALL here, and the whole snapshot was held
            // live across it -- seven fields spilled and reloaded on every
            // send. Read again after the call instead: nothing in the sink can
            // reach the arena, so it is the same value, and a re-resolve is
            // cheaper than the spills. A silent sink has no call, and keeps
            // the one read.
            let snapshot = if T::EMITS {
                match self.queues.resolve(queue) {
                    Ok(q) => *q,
                    Err(e) => {
                        self.exit_critical();
                        return Err(e);
                    }
                }
            } else {
                snapshot
            };
            let previously_waiting = snapshot.waiting;
            let yield_required = self.copy_data_to_queue(queue, &snapshot, value, position)?;
            if C::USE_QUEUE_SETS && !snapshot.set_container.is_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);
            // The C's `if( waiters ) { ... } else if( xYieldRequired )`: the
            // emptiness is answered ONCE, BEFORE a waiter is removed. With
            // waiters, only "the woken task outranks me" yields; the
            // disinherit's yield request is consulted only when there were
            // none. This used to re-read the list AFTER the removal, so
            // removing the only waiter made the list empty and a give that
            // disinherited AND woke a lower-priority task yielded where the
            // C does not (one core; on two the disinherit yields the core
            // itself). Found by the API differential, P1.3, step 4105.
            let had_receivers = !self.lists.is_empty_of(receivers);
            let woke_higher = if had_receivers {
                self.remove_from_event_list(receivers)?
            } else {
                false
            };
            // queueYIELD_IF_USING_PREEMPTION(), inside the section.
            if woke_higher || (yield_required && !had_receivers) {
                self.port_yield();
            }
            self.exit_critical();
            self.end_wait(caller);
            return Ok(Ready(()));
        }
        let remaining = self.begin_wait(caller, queue, ticks);
        if remaining.unwrap_or(0) == 0 {
            self.exit_critical();
            self.trace_failure_or_owe(caller, OwedTrace::SendFailed(queue));
            if remaining.is_some() {
                // A frame was written, so it has to be torn down. `None` means
                // `begin_wait` took its zero-block-time exit and wrote
                // nothing, and then `end_wait` is a provable no-op.
                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.cur() != 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`].
    #[cold]
    fn queue_send_blocking(&mut self, caller: TaskHandle, queue: QueueHandle) -> Result<Wait<()>> {
        self.suspend_all();
        self.lock_queue(queue);
        let left = self.check_for_timeout(caller);
        if left.is_none() {
            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.note_exits();
            let tick = self.tick;
            self.trace
                .event(tick, Event::BlockingOnQueueSend { queue, name: "" });
            // `check_for_timeout` above already resolved the TCB and wrote
            // this field; `remaining_ticks` resolved it a second time to read
            // it back.
            let ticks_left = left.map_or(0, core::num::NonZeroU64::get);
            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, at ALL THREE call sites.
    ///
    /// The rationale here used to say `queue_send_generic` was its only caller.
    /// That is no longer true — `queue_add_to_set` and
    /// `queue_send_generic_from_isr` call it too — so an A4 split was tried on
    /// 2026-09-25, keeping the hint for the hot caller and routing the cold ones
    /// through an out-of-line handle. It measured **+72 B of flash**, `mv` +12
    /// and 49 more instructions, and was reverted. `prime_mutex` was a fourth
    /// caller when that was measured; it was deleted later the same day (see
    /// [`Self::new_mutex`]) and the split was **re-tested at three callers**:
    /// **+6 B**, still a loss but only a twelfth of the old one. So ~66 of the
    /// original 72 bytes were `prime_mutex`'s own site — an A4 verdict can be
    /// carried almost entirely by ONE caller, which is why §9's re-test law
    /// exists. At three callers this is now a near-tie held by 6 bytes.
    ///
    /// The reason is worth keeping: the cold callers pass CONSTANT arguments
    /// (`Position::Back` from `queue_add_to_set`), so each inlined copy is
    /// SPECIALISED and folds well below the 138 bytes C's `prvCopyDataToQueue`
    /// occupies. Out of line they pay a five-argument frame and force
    /// `&snapshot` into memory, which costs more than the copies they remove.
    ///
    /// The hot reason also still stands: out of line it paid a call and a frame
    /// on all 48,000 sends of `bench/kernel-ir` to move one value into a slot
    /// the caller had already resolved.
    #[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.
            //
            // A silent sink writes the queue's fields FIRST: then nothing
            // stands between the caller's resolve and this one, they fold, and
            // the handle is not re-checked after the slot store, which LLVM
            // cannot prove misses the queue. With an emitting sink the trace
            // call already stands between them, and the reorder only cost
            // codegen (refuted R2: host +32,092).
            if !T::EMITS {
                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);
                }
            }
            if let Some(slot) = self.slots.get_mut(snapshot.base.wrapping_add(index)) {
                *slot = value;
            }
            if T::EMITS {
                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 --

    /// The out-of-line handle on [`Kernel::queue_take`]s body.
    ///
    /// `peek` was a `const PEEK: bool`, which gave the whole take chain TWO
    /// monomorphisations and three inlined copies of a ~600-byte body that no
    /// A4 split could share, because `<true>` and `<false>` are different
    /// functions. As a runtime flag there is one body to share.
    ///
    /// Only `semaphore_take` uses this handle. `queue_receive` and `queue_peek`
    /// keep the inlined body because all four of `recv_empty`, `peek_ok`,
    /// `queue_roundtrip` and `block_cycle` go through one or the other --
    /// routing `queue_peek` here cost `peek_ok` **45 -> 108**, which is what a
    /// call and a frame are worth on a row that short.
    #[inline(never)]
    fn take_outlined(&mut self, queue: QueueHandle, ticks: u64, peek: bool) -> Result<Wait<u64>> {
        self.queue_take(queue, ticks, peek)
    }

    /// `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(queue, ticks, false)
    }

    /// `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(queue, ticks, true)
    }

    /// `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.
    // A3: ONE caller, so the out-of-line body pays a prologue and epilogue for
    // a single call. Inlining moves the body rather than duplicating it.
    #[inline]
    pub fn semaphore_take(&mut self, semaphore: QueueHandle, ticks: u64) -> Result<Wait<()>> {
        match self.take_outlined(semaphore, ticks, false)? {
            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.
    #[cfg_attr(not(feature = "small"), inline(always))]
    #[cfg_attr(feature = "small", inline(never))]
    fn queue_take(&mut self, queue: QueueHandle, ticks: u64, peek: bool) -> Result<Wait<u64>> {
        let caller = self.cur();
        // 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 => {
                return self.queue_take_blocking(caller, queue, peek);
            }
            QueueResume::BelowTimedOutResume => {
                return self.queue_take_timed_out(queue, peek);
            }
        }
        self.enter_critical();
        // ONE resolve, mutable, for the whole fast path, reading only the
        // fields it uses. Two earlier shapes, both measured:
        //  - `*q`, the whole eleven-field descriptor copied to reach five of
        //    them: nine words of `usize` on rv32 with four dead on every
        //    successful receive, and more live fields than LLVM keeps in
        //    hand, so the function claimed callee-saved registers it had no
        //    use for;
        //  - the five fields read through `resolve`, then the item taken
        //    through `copy_data_from_queue`, which resolved the handle AGAIN
        //    to write `read_from` and `waiting` back. On rv32 LLVM merged the
        //    two at run time, but every inlined copy carried the second body
        //    (-242 B of flash, -395,353 kernel-ir), and on the Xtensa S3 the
        //    copy was an outlined call on every receive.
        // The blocking tail below still wants the whole descriptor and
        // re-resolves for it, outside the section and at no cost to the
        // clock, exactly as the resume arms above do.
        let q = match self.queues.resolve_mut(queue) {
            Ok(q) => q,
            Err(e) => {
                self.exit_critical();
                return Err(e);
            }
        };
        let (waiting, kind) = (q.waiting, q.kind);
        // 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 waiting > 0 {
            // `copy_data_from_queue`, in place, on the reference above.
            let value = if kind.carries_data() {
                let next = wrap_next(q.read_from, q.length);
                let value = self
                    .slots
                    .get(q.base.wrapping_add(next))
                    .copied()
                    .unwrap_or(0);
                if !peek {
                    q.read_from = next;
                    // Wrapping: `waiting > 0` was read under this section.
                    q.waiting = q.waiting.wrapping_sub(1);
                }
                value
            } else {
                if !peek {
                    q.waiting = q.waiting.wrapping_sub(1);
                }
                0
            };
            self.note_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_of(receivers) && self.remove_from_event_list(receivers)? {
                    self.port_yield();
                }
            } else {
                if 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_of(senders) && self.remove_from_event_list(senders)? {
                    self.port_yield();
                }
            }
            self.exit_critical();
            self.end_wait(caller);
            return Ok(Ready(value));
        }
        let remaining = self.begin_wait(caller, queue, ticks);
        if remaining.unwrap_or(0) == 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));
            }
            if remaining.is_some() {
                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.cur() != caller {
            self.set_queue_resume(caller, QueueResume::BelowSample);
            return Ok(Blocked);
        }
        self.queue_take_blocking(caller, queue, peek)
    }

    /// Everything `xQueueReceive` and `xQueuePeek` do below their sampling
    /// exit. See [`Kernel::take_queue_resume`].
    #[cold]
    fn queue_take_blocking(
        &mut self,
        caller: TaskHandle,
        queue: QueueHandle,
        peek: bool,
    ) -> Result<Wait<u64>> {
        // `kind` is read HERE rather than handed down from the caller, because
        // it is the one field of the descriptor that cannot change after
        // `new_queue` sets it -- so resolving it late reads the same byte, and
        // resolving it early only lengthened a live range across the hot
        // function's whole body.
        //
        // SINKING it below the timed-out branch -- which never reads it, and
        // whose callee resolves `kind` for itself -- removes a resolve from
        // that path and measured **+2 B** on 2026-09-25. Refuted: the resolve
        // is still emitted once at the later site and the branch around it grew
        // by more. Both paths are `#[cold]`, so there was no runtime case to
        // weigh against the bytes.
        let kind = self.queues.resolve(queue)?.kind;
        self.suspend_all();
        self.lock_queue(queue);
        let left = self.check_for_timeout(caller);
        if left.is_none() {
            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.cur() != caller {
                self.set_queue_resume(caller, QueueResume::BelowTimedOutResume);
                return Ok(Blocked);
            }
            return self.queue_take_timed_out(queue, peek);
        }
        // `left` is `Some` here, and it carries the block time
        // `check_for_timeout` has just written into the TCB.
        self.queue_take_locked(
            caller,
            queue,
            peek,
            kind,
            left.map_or(0, core::num::NonZeroU64::get),
        )
    }

    /// `xQueueReceive` below the `xTaskResumeAll` of its timed-out branch.
    /// `caller` is read here rather than passed, for the reason given on
    /// [`Kernel::queue_take_blocking`]: both call sites have already
    /// established that it is `self.cur()`.
    #[cold]
    fn queue_take_timed_out(&mut self, queue: QueueHandle, peek: bool) -> Result<Wait<u64>> {
        let caller = self.cur();
        // `kind` is read HERE rather than handed down from the caller,
        // because it is the one field of the descriptor that cannot change
        // after `new_queue` sets it -- so resolving it late reads the same
        // byte, and resolving it early only lengthened a live range across
        // the hot function's whole body.
        let kind = self.queues.resolve(queue)?.kind;
        {
            if self.is_queue_empty(queue) {
                if 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(
        &mut self,
        caller: TaskHandle,
        queue: QueueHandle,
        peek: bool,
        // The descriptor's `kind`, and ONLY that. All three of these
        // functions took the whole `Queue` by value -- thirty-six bytes on
        // rv32, copied at every hop of a three-deep chain -- to read
        // `kind.is_mutex()` twice. Nothing else of it was ever touched.
        kind: Kind,
        ticks_left: u64,
    ) -> Result<Wait<u64>> {
        // Both arms end the same way -- unlock, then resume -- and
        // `resume_all_inline` is exactly that: INLINE. Written as two arms it
        // was two copies of its body in one function. The sequence below is
        // the sequence both arms had, in the same order, because on the sim a
        // critical-section exit is the clock and reordering one is a
        // divergence.
        let was_empty = self.is_queue_empty(queue);
        if was_empty {
            let event = if peek {
                Event::BlockingOnQueuePeek { queue, name: "" }
            } else {
                Event::BlockingOnQueueReceive { queue, name: "" }
            };
            self.note_exits();
            let tick = self.tick;
            self.trace.event(tick, event);
            if 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();
                // Assigned, not latched: the C's `xInheritanceOccurred` is
                // whatever the LATEST block's inherit answered. Latching it
                // made a timeout disinherit after a re-block that inherited
                // nothing (API differential P1.4, two cores, step 2390: a
                // waiter lowered to priority 0 while it waited).
                self.set_wait_inherited(caller, inherited);
            }
            self.place_on_event_list(Self::queue_receive_list(queue), ticks_left)?;
        }
        self.unlock_queue(queue)?;
        let yielded = self.resume_all_inline();
        if was_empty && !yielded {
            self.yield_or_owe(caller);
        }
        Ok(Blocked)
    }

    /// `prvCopyDataFromQueue`, with the peek variant putting the cursor
    /// back as `xQueuePeek` does -- over fields its caller already read.
    ///
    /// 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,
        kind: Kind,
        base: usize,
        length: usize,
        read_from: usize,
        peek: bool,
    ) -> Result<u64> {
        if !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(read_from, length);
        let value = self
            .slots
            .get(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.cur();
        // 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.cur();
        // 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.wrapping_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.
    // In line at both callers (`rusty-compiler-leverage` A3): win 23, which
    // took this and `is_queue_empty`/`lock_queue`'s siblings together for
    // -48 B of flash. A two-caller body this small pays two frames for a
    // resolve and a critical section; `#[inline]` alone was declined.
    #[inline(always)]
    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.
            // The unlock is written on the SAME lookup that read the lock,
            // whenever the drain below is not going to run -- which is every
            // call where nothing was sent while the queue was held, i.e. the
            // common one. It used to take a second `resolve_mut` after the
            // loop to store a value already known here.
            let (tx_lock, container) = match self.queues.resolve_mut(queue) {
                Ok(q) => {
                    // The container is read only when queue sets exist. With
                    // `USE_QUEUE_SETS` false nothing ever writes `set_container`,
                    // so the const makes it a known NULL and the whole branch
                    // below folds -- the other two queue-set sites already put
                    // the const FIRST and this one tested the field first.
                    let read = (
                        q.tx_lock,
                        if C::USE_QUEUE_SETS {
                            q.set_container
                        } else {
                            QueueHandle::NULL
                        },
                    );
                    if read.0 <= LOCKED_UNMODIFIED {
                        q.tx_lock = UNLOCKED;
                    }
                    read
                }
                Err(_) => (UNLOCKED, QueueHandle::NULL),
            };
            if tx_lock > LOCKED_UNMODIFIED {
                self.unlock_drain::<false>(queue, tx_lock, container)?;
            }
        }
        self.exit_critical();
        self.enter_critical();
        {
            // Same trade as the tx half above.
            let rx_lock = match self.queues.resolve_mut(queue) {
                Ok(q) => {
                    let read = q.rx_lock;
                    if read <= LOCKED_UNMODIFIED {
                        q.rx_lock = UNLOCKED;
                    }
                    read
                }
                Err(_) => UNLOCKED,
            };
            if rx_lock > LOCKED_UNMODIFIED {
                self.unlock_drain::<true>(queue, rx_lock, QueueHandle::NULL)?;
            }
        }
        self.exit_critical();
        Ok(())
    }

    /// Either half of [`Kernel::unlock_queue`] when an interrupt used the
    /// queue while it was locked: wake one waiter per operation it made
    /// (`RX` false: receivers, for its sends; true: senders, for its
    /// receives), then unlock that half.
    ///
    /// Out of line because the loop is what makes `unlock_queue` CALL
    /// anything, and a body that calls saves six registers on entry. Nearly
    /// every unlock finds nothing to drain (BlockQ: all 21,490), and it was
    /// paying that frame for a loop it never ran.
    ///
    /// In line under `small`: out of line it is +232 B on the flash profile
    /// (17,776 -> 18,008), a speed trade that profile does not make. In line
    /// it is +8 B there (17,784), which is LLVM picking a different compare
    /// for the loop counter; three arrangements of the same loop read +8,
    /// +8 and +16, so the 8 is layout, not work.
    #[cfg_attr(not(feature = "small"), cold, inline(never))]
    #[cfg_attr(feature = "small", inline(always))]
    fn unlock_drain<const RX: bool>(
        &mut self,
        queue: QueueHandle,
        mut lock: i8,
        container: QueueHandle,
    ) -> Result<()> {
        while lock > LOCKED_UNMODIFIED {
            if !RX && C::USE_QUEUE_SETS && !container.is_null() {
                if C::USE_QUEUE_SETS && 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.
                lock = lock.wrapping_sub(1);
                continue;
            }
            let waiters = if RX {
                Self::queue_send_list(queue)
            } else {
                Self::queue_receive_list(queue)
            };
            if self.lists.is_empty_of(waiters) {
                break;
            }
            if self.remove_from_event_list(waiters)? {
                self.missed_yield();
            }
            // Wrapping: bounded by the loop, as above.
            lock = lock.wrapping_sub(1);
        }
        if let Ok(q) = self.queues.resolve_mut(queue) {
            if RX {
                q.rx_lock = UNLOCKED;
            } else {
                q.tx_lock = UNLOCKED;
            }
        }
        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.cur();
            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.
    // In line at both callers (`rusty-compiler-leverage` A3): win 23, which
    // took this and `is_queue_empty`/`lock_queue`'s siblings together for
    // -48 B of flash. A two-caller body this small pays two frames for a
    // resolve and a critical section; `#[inline]` alone was declined.
    #[inline(always)]
    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`.
///
/// Five instructions behind a call at six sites. `#[inline]` lets the ring
/// bound fold into the caller, which already knows it.
#[inline]
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`.
#[inline]
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,
    const TIMER_CMDS: usize,
> crate::typed::Raw
    for Kernel<
        C,
        P,
        T,
        H,
        TASKS,
        ITEMS,
        LISTS,
        QUEUES,
        SLOTS,
        BUFFERS,
        BYTES,
        TIMERS,
        GROUPS,
        TIMER_CMDS,
    >
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(|_| ())
    }
}

/// Plan P5: what the mutation survey found no oracle judging in this file --
/// the slot arena (Kairos storage; the C mallocs), the queue LOCK (which
/// only an interrupt landing while a task holds the queue can reach, and
/// the oracles deliver interrupts between calls), and a receive or peek
/// made on a semaphore through the queue API.
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use rusty_rtos_core::config::Config;
    use rusty_rtos_core::error::Error;
    use rusty_rtos_core::handle::{QueueHandle, TaskHandle};
    use rusty_rtos_core::hooks::NoTickHook;

    use super::{UNLOCKED, Wait};
    use crate::TaskState;
    use crate::system::tests::{NoTrace, TestConfig, TestPort};

    /// Room for the timer daemon's queue, a set and three queues, over
    /// thirty-two slots.
    type K = crate::Kernel<
        TestConfig,
        TestPort,
        NoTrace,
        NoTickHook,
        4,
        { crate::list_slots_for(4, 0, crate::lists_for(TestConfig::MAX_PRIORITIES, 5, 0)) },
        { crate::lists_for(TestConfig::MAX_PRIORITIES, 5, 0) },
        5,
        32,
        0,
        0,
        0,
        0,
        { <TestConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
    >;

    /// Eight slots and nothing else, to fill.
    type K8 = crate::Kernel<
        TestConfig,
        TestPort,
        NoTrace,
        NoTickHook,
        4,
        { crate::list_slots_for(4, 0, crate::lists_for(TestConfig::MAX_PRIORITIES, 3, 0)) },
        { crate::lists_for(TestConfig::MAX_PRIORITIES, 3, 0) },
        3,
        8,
        0,
        0,
        0,
        0,
        { <TestConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
    >;

    /// A started kernel in which `rx` (priority 2) is blocked receiving on
    /// an empty queue of sixteen, and `tx` (priority 1) runs.
    fn with_receiver() -> (K, QueueHandle, TaskHandle) {
        let mut k = K::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
        let q = k.queue_create(16).expect("a queue");
        let rx = k.create_task("rx", 2).expect("rx");
        k.create_task("tx", 1).expect("tx");
        let h = k.start_scheduler().expect("start");
        k.suspend(Some(h.timer)).expect("park the daemon");
        assert_eq!(k.current(), rx);
        assert_eq!(k.queue_receive(q, 10), Ok(Wait::Blocked));
        (k, q, rx)
    }

    fn tx_lock(k: &K, q: QueueHandle) -> i8 {
        k.queues.resolve(q).expect("the queue").tx_lock
    }

    /// `prvLockQueue` holds an interrupt's wake back until `prvUnlockQueue`:
    /// the interrupt only counts what it did. Two sends, because the first
    /// alone cannot tell the count from the `queueUNLOCKED` sentinel.
    #[test]
    fn an_interrupt_send_to_a_locked_queue_waits_for_the_unlock() {
        let (mut k, q, rx) = with_receiver();
        k.lock_queue(q);
        let _ = k.queue_send_from_isr(q, 7).expect("send");
        let _ = k.queue_send_from_isr(q, 8).expect("send");
        assert_eq!(
            k.task_state_get(rx),
            Ok(TaskState::Blocked),
            "the lock held the wake back"
        );
        assert_eq!(tx_lock(&k, q), 2, "and counted both sends");
        k.unlock_queue(q).expect("unlock");
        assert_eq!(
            k.task_state_get(rx),
            Ok(TaskState::Ready),
            "the unlock woke it"
        );
        assert_eq!(tx_lock(&k, q), UNLOCKED);
    }

    /// `prvUnlockQueue` wakes ONE waiter per send the lock held back, not
    /// every waiter: one interrupt send, two receivers blocked, one woken.
    ///
    /// The drain's `while lock > LOCKED_UNMODIFIED` as `>=` survived every
    /// oracle once the drain moved out of line (kernel 1ce2ac3): the guard
    /// before it means the loop is entered only above zero, so the mutant
    /// differs only at the tail -- one wake too many when a waiter is left.
    /// No test held back fewer sends than there were waiters.
    #[test]
    fn an_unlock_wakes_one_waiter_per_held_back_send() {
        let mut k = K::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
        let q = k.queue_create(16).expect("a queue");
        let first = k.create_task("rx1", 3).expect("rx1");
        let second = k.create_task("rx2", 2).expect("rx2");
        let h = k.start_scheduler().expect("start");
        k.suspend(Some(h.timer)).expect("park the daemon");
        assert_eq!(k.current(), first);
        assert_eq!(k.queue_receive(q, 10), Ok(Wait::Blocked));
        k.switch_context();
        assert_eq!(k.current(), second);
        assert_eq!(k.queue_receive(q, 10), Ok(Wait::Blocked));
        k.switch_context();
        k.lock_queue(q);
        let _ = k.queue_send_from_isr(q, 7).expect("send");
        assert_eq!(tx_lock(&k, q), 1, "one send held back");
        k.unlock_queue(q).expect("unlock");
        assert_eq!(
            k.task_state_get(first),
            Ok(TaskState::Ready),
            "the first waiter woke"
        );
        assert_eq!(
            k.task_state_get(second),
            Ok(TaskState::Blocked),
            "and only the first: one send, one wake"
        );
        assert_eq!(tx_lock(&k, q), UNLOCKED);
    }

    /// `prvIncrementQueueTxLock` / `RxLock` stop at the task count: there
    /// is no point waking more tasks than exist.
    #[test]
    fn the_lock_counts_stop_at_the_task_count() {
        let (mut k, q, _) = with_receiver();
        let tasks = k.task_count();
        k.lock_queue(q);
        for i in 0..tasks.saturating_add(3) {
            let _ = k.queue_send_from_isr(q, i as u64).expect("send");
        }
        assert_eq!(tx_lock(&k, q) as usize, tasks, "the send count is capped");
        k.unlock_queue(q).expect("unlock");

        k.lock_queue(q);
        for _ in 0..tasks.saturating_add(3) {
            let _ = k.queue_receive_from_isr(q).expect("receive");
        }
        let rx_lock = k.queues.resolve(q).expect("the queue").rx_lock;
        assert_eq!(rx_lock as usize, tasks, "and so is the receive count");
        k.unlock_queue(q).expect("unlock");
    }

    /// A send an interrupt made while the queue was locked is announced to
    /// its set by the unlock, not lost (`prvUnlockQueue`'s
    /// `prvNotifyQueueSetContainer`).
    #[test]
    fn an_unlock_announces_to_the_set_what_the_lock_held_back() {
        let mut k = K::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
        let set = k.queue_create_set(4).expect("a set");
        let q = k.queue_create(4).expect("a member");
        assert_eq!(k.queue_add_to_set(q, set), Ok(true));
        k.create_task("t", 1).expect("t");
        let h = k.start_scheduler().expect("start");
        k.suspend(Some(h.timer)).expect("park the daemon");

        k.lock_queue(q);
        let _ = k.queue_send_from_isr(q, 5).expect("send");
        assert_eq!(
            k.queue_select_from_set(set, 0),
            Ok(Wait::Ready(None)),
            "nothing announced while the lock holds"
        );
        k.unlock_queue(q).expect("unlock");
        assert_eq!(
            k.queue_select_from_set(set, 0),
            Ok(Wait::Ready(Some(q))),
            "the unlock announced the member"
        );
    }

    /// The slot arena refits a freed queue's slots exactly, so a
    /// create/delete loop of one length never runs out.
    #[test]
    fn the_slot_arena_refits_a_hole_of_the_same_length() {
        let mut k = K8::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
        let a = k.queue_create(4).expect("a");
        let _b = k.queue_create(4).expect("b fills the slots");
        assert_eq!(k.queue_create(1), Err(Error::Full));
        k.queue_delete(a).expect("delete");
        k.queue_create(4).expect("the hole refits exactly");
        assert_eq!(k.queue_create(1), Err(Error::Full));
    }

    /// `xQueueReceive` on a semaphore takes it and `xQueuePeek` does not:
    /// a semaphore carries no data, so the count is the item.
    #[test]
    fn receive_takes_a_semaphore_and_peek_leaves_it() {
        let (mut k, _, _) = with_receiver();
        let s = k.semaphore_create_binary().expect("a semaphore");
        k.semaphore_give(s).expect("give");
        assert_eq!(k.queue_peek(s, 0), Ok(Wait::Ready(0)));
        assert_eq!(k.semaphore_count(s), Ok(1), "a peek leaves it");
        assert_eq!(k.queue_receive(s, 0), Ok(Wait::Ready(0)));
        assert_eq!(k.semaphore_count(s), Ok(0), "a receive takes it");

        // And from an interrupt -- `xSemaphoreTakeFromISR` is exactly
        // `xQueueReceiveFromISR` on a semaphore.
        k.semaphore_give(s).expect("give");
        assert_eq!(k.queue_peek_from_isr(s), Ok(0));
        assert_eq!(k.semaphore_count(s), Ok(1), "an ISR peek leaves it");
        let _ = k.queue_receive_from_isr(s).expect("receive");
        assert_eq!(k.semaphore_count(s), Ok(0), "an ISR receive takes it");
    }

    /// `xTaskResumeAll` yields for a task the pending-ready list hands back
    /// only when it outranks the running one: an interrupt that wakes a
    /// LOWER-priority waiter under suspension costs no yield.
    #[test]
    fn resuming_with_a_lower_priority_task_pending_does_not_yield() {
        let mut k = K::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
        let sem = k.semaphore_create_binary().expect("a semaphore");
        let lo = k.create_task("lo", 1).expect("lo");
        let hi = k.create_task("hi", 2).expect("hi");
        let h = k.start_scheduler().expect("start");
        k.suspend(Some(h.timer)).expect("park the daemon");
        assert_eq!(k.current(), hi);
        k.delay(2).expect("hi steps aside");
        assert_eq!(k.current(), lo);
        assert_eq!(k.semaphore_take(sem, 100), Ok(Wait::Blocked));
        k.tick_from_isr();
        k.tick_from_isr();
        assert_eq!(k.current(), hi, "hi is back");

        k.suspend_all();
        let _ = k.semaphore_give_from_isr(sem).expect("give");
        assert!(!k.resume_all(), "lo does not outrank hi: no yield");
        assert_eq!(k.current(), hi);
    }
}