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
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
//! The scheduler: `tasks.c` and `queue.c` as a state machine over indices.
//!
//! Every public function here is a FreeRTOS API function, and its body
//! follows the C body statement for statement — including **where the
//! critical sections open and close**, because on the sim that is where
//! time passes (`ORACLES.md`, sim contract v1, rule 3), and including where
//! the `trace*` macros fire, because the order of those lines is the gate.
//!
//! The subtlety that costs a diff if you miss it: FreeRTOS yields from
//! *inside* the critical section in `vTaskResume`, `vTaskPrioritySet`,
//! `xTaskResumeAll` and the queue calls, and from *outside* it in
//! `vTaskSuspend` and `vTaskDelay`. Since `portYIELD()` on the Posix port
//! is itself a critical section, an inside yield nests (and counts one
//! outermost exit) where an outside yield counts two. Each site below says
//! which it is.
//!
//! Where the C has a `configASSERT`, this has an [`Error`]: the C kernel
//! stops the world on a bad handle, and the whole point of the remake is
//! that we do not.
use core::marker::PhantomData;
use rusty_rtos_core::arena::Arena;
use rusty_rtos_core::config::Config;
use rusty_rtos_core::error::{Error, Result};
use rusty_rtos_core::handle::{
EventGroup as EventGroupKind, EventGroupHandle, Queue as QueueKind, QueueHandle,
StreamBuffer as StreamKind, StreamBufferHandle, Task as TaskKind, TaskHandle,
Timer as TimerKind, TimerHandle,
};
use rusty_rtos_core::hooks::TickHook;
use rusty_rtos_core::isr::Woken;
use rusty_rtos_core::list::{ItemId, ListId, Lists};
use rusty_rtos_core::port::Port;
use rusty_rtos_core::priority::Priority;
use rusty_rtos_core::tick::TickWidth;
use rusty_rtos_core::trace::{Event, Trace};
use crate::events::EventGroup;
use crate::name::Name;
use crate::queue::Queue;
use crate::queue::Wait;
use crate::stream::StreamBuffer;
use crate::timer::{MAX_TIMER_COMMANDS, Message, Timer};
use crate::{OVERHEAD_LISTS, list_slots_for, lists_for};
/// A trace line owed by a task that was switched out before it could
/// emit one. Only the queue failure paths can owe one: they are the only
/// places FreeRTOS traces *after* leaving a critical section.
/// Why `vTaskSwitchContext` could not choose a task to run.
///
/// # Law 3: no silent failures
///
/// Every variant here was, until 2026-09-11, a bare `return` — the scheduler
/// declining to switch and saying nothing. Three of them are impossible in a
/// healthy kernel and the fourth is what the C asserts on
/// (`configASSERT( uxTopPriority )`), so reaching any of them means an
/// invariant has already broken somewhere else.
///
/// They cost a multi-flash hardware hunt on the day the Xtensa port first
/// ran a stacked task: every ready list had emptied, the kernel kept
/// quietly running whoever was current, and nothing said so. A counter and
/// a reason turn that into one printed line.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Stall {
/// The scheduler chose normally.
#[default]
None,
/// No ready task at ANY priority. The idle task keeps priority 0
/// non-empty, so reaching this means the idle task is gone — which is
/// exactly what `configASSERT( uxTopPriority )` fires on.
NoReadyTask,
/// A ready list refused to answer at all.
ListError,
/// The chosen priority's list had nothing to rotate to, having just
/// reported itself non-empty.
EmptyRotation,
/// The chosen list item named no live task.
UnknownTask,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum OwedTrace {
/// Nothing owed.
None,
/// `traceQUEUE_SEND_FAILED`.
SendFailed(QueueHandle),
/// `traceQUEUE_RECEIVE_FAILED`.
ReceiveFailed(QueueHandle),
/// `traceTIMER_COMMAND_SEND`, which the C runs on the line *after*
/// `xQueueSendToBack` — so a send that made the daemon ready traces
/// only once this task has the CPU back.
TimerCommandSend {
timer: TimerHandle,
name: Name,
command: i32,
value: u64,
},
/// `traceSTREAM_BUFFER_CREATE`, which the C runs after the
/// `pvPortMalloc` that made the buffer.
///
/// `heap_4` brackets that malloc with `vTaskSuspendAll` /
/// `xTaskResumeAll`, so a tick can land on its exit -- and the C's
/// thread then stops inside the allocator, with the trace still ahead
/// of it. Emitting it anyway puts the line in another task's run of the
/// trace. `StreamBufferDemo`'s echo client showed it at tick 429, one
/// line early and a whole task's work out of place.
StreamBufferCreate {
buffer: StreamBufferHandle,
is_message_buffer: bool,
},
/// `traceEVENT_GROUP_WAIT_BITS_END`, which the C runs after the
/// `xTaskResumeAll` that ends the wait — so a resume that switched away
/// traces once this task has the CPU back.
EventGroupWaitBitsEnd {
group: EventGroupHandle,
bits: u32,
timed_out: bool,
},
/// `prvAddNewTaskToReadyList`, the second half of `xTaskCreate`.
///
/// A create costs three outermost exits before it reaches this — two
/// `pvPortMalloc`s and the port's `pthread_create` section — and a tick
/// can land on any of them. The C is a real thread, so it simply stops
/// there and the new task is not on a ready list until the creator runs
/// again. This is that pause, and it is the only owed item that is not
/// purely a trace line: it carries the ready-list insertion too.
AddNewTaskToReadyList { task: TaskHandle, priority: u8 },
}
/// `eTaskState`: what a task is doing, derived from the list it is in
/// exactly as `eTaskGetState` derives it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskState {
/// The task `current` names.
Running,
/// On a ready list.
Ready,
/// On a delayed list, or on an event list with a timeout.
Blocked,
/// On the suspended list with no event pending.
Suspended,
/// The handle names no live task.
Deleted,
}
/// Where a preempted queue call has to start again.
///
/// A queue call has SEVERAL critical-section exits that can release a tick
/// and switch the caller away, and the C's thread resumes below whichever
/// one it stopped at. One marker is not enough to say which.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum QueueResume {
/// Nothing to resume; enter at the top.
#[default]
No,
/// Below the section that samples the queue, in the caller.
BelowSample,
/// Below the `xTaskResumeAll` of the TIMED-OUT branch, which is the one
/// `IntQueue` reaches at tick 16,260: the tick pended inside the
/// scheduler suspension is replayed there, and replaying it switches
/// the caller away with `prvIsQueueEmpty` still to run.
BelowTimedOutResume,
}
/// One task control block: the C `TCB_t` minus everything that is a
/// pointer. No stack, no TLS, no `pxTopOfStack`.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Tcb {
name: Name,
/// `uxPriority`, the possibly-inherited one the scheduler sorts by.
priority: u8,
/// `uxBasePriority`, what the task asked for.
base_priority: u8,
/// `uxMutexesHeld`: how many mutexes this task holds, which is what
/// decides whether giving one back may drop an inherited priority.
mutexes_held: u32,
/// The locals a blocking queue call keeps on the C stack across a
/// block. This kernel has no stack, so they live here — see
/// [`crate::queue`].
wait: WaitFrame,
/// `ulNotifiedValue[]`.
notified: [u32; MAX_NOTIFICATION_ENTRIES],
/// `ucNotifyState[]`.
notify_state: [NotifyState; MAX_NOTIFICATION_ENTRIES],
/// Whether a stream-buffer call this task made was preempted at the
/// critical-section exit that samples the buffer, and must resume
/// *after* that exit rather than repeat it.
stream_resume: bool,
/// Where a preempted queue call resumes. See [`QueueResume`].
///
/// `xQueueGenericSend` and `xQueueReceive` exit their sampling section
/// before suspending the scheduler to block, and THAT exit can release
/// a tick which switches the caller away. The C's thread stops inside
/// the exit; everything below it -- `traceBLOCKING_ON_QUEUE_SEND` and
/// `vTaskPlaceOnEventList` -- runs when the task is next scheduled, and
/// so names the right task. Without this marker the trace attributes
/// the block to whoever the tick switched TO, which `IntQueue` catches
/// at tick 5 and no other scenario reaches.
queue_resume: QueueResume,
/// Whether a blocking `xStreamBufferSend` has already run its
/// `vTaskSetTimeOutState`. See [`Kernel::take_stream_timed`].
stream_timed: bool,
/// Whether a stream-buffer call's notify wait has already finished.
/// See [`Kernel::take_stream_waited`].
stream_waited: bool,
/// The stack local that exit produced — `xBytesAvailable` on a receive,
/// `xSpace` on a send — kept because the frame it belonged to is gone.
stream_local: usize,
/// Whether this task has already blocked inside the notification wait
/// it is in. The C blocks inside `xTaskGenericNotifyWait`; a kernel
/// with no stacks returns `Blocked` and is called again, so it needs to
/// know the second call is a resumption rather than a fresh wait.
notify_blocked: bool,
/// The same, for the event-group wait this task is inside. Those two
/// functions have no retry loop — the C blocks once and then reads the
/// event item value — so the second call has to know it is the far side
/// of the switch and not a fresh wait.
event_blocked: bool,
}
/// How many notification slots a task has room for.
///
/// The C sizes its arrays from `configTASK_NOTIFICATION_ARRAY_ENTRIES`
/// directly. A `Config` is a type here and stable Rust cannot size an array
/// from one of its associated consts, so the arrays are the largest a
/// configuration may ask for and [`Config::validate`] refuses more. The
/// cost is a few bytes per task per unused slot; the alternative was a
/// tenth const generic on every kernel type.
pub const MAX_NOTIFICATION_ENTRIES: usize = 4;
/// `ucNotifyState[]`: what a task's notification slot is doing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum NotifyState {
/// `taskNOT_WAITING_NOTIFICATION`.
#[default]
NotWaiting,
/// `taskWAITING_NOTIFICATION`.
Waiting,
/// `taskNOTIFICATION_RECEIVED`.
Received,
}
/// `eNotifyAction`: what a notification does to the value already there.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum NotifyAction {
/// `eNoAction`: wake the task, leave the value alone.
#[default]
None,
/// `eSetBits`.
SetBits,
/// `eIncrement`.
Increment,
/// `eSetValueWithOverwrite`.
Overwrite,
/// `eSetValueWithoutOverwrite`: fails if one is already pending.
NoOverwrite,
}
/// What `xQueueGenericSend` and friends keep between passes of their
/// `for(;;)`: the queue being waited on, the ticks left, and the timeout
/// bookkeeping (`TimeOut_t`).
#[derive(Debug, Clone, Copy, Default)]
struct WaitFrame {
/// The queue this task is part-way through a blocking call on;
/// `TaskHandle::NULL`-equivalent when there is none.
queue: QueueHandle,
/// `xTicksToWait`, decremented by each `xTaskCheckForTimeOut`.
ticks: u64,
/// `xTimeOut.xTimeOnEntering`.
entering: u64,
/// `xTimeOut.xOverflowCount`.
overflows: u64,
/// `xEntryTimeSet`.
entry_set: bool,
/// `xInheritanceOccurred`.
inherited: bool,
}
/// What [`Kernel::start_scheduler`] created, so a runner can attach bodies.
#[derive(Debug, Clone, Copy)]
pub struct StartHandles {
/// The idle task.
pub idle: TaskHandle,
/// The timer service task.
pub timer: TaskHandle,
/// The timer command queue.
pub timer_queue: QueueHandle,
}
/// The scheduler.
///
/// `TASKS`, `ITEMS`, `LISTS`, `QUEUES`, `SLOTS`, `BUFFERS` and `BYTES` are
/// the geometry: how many tasks, list items, lists, queues, queue item
/// slots, stream buffers, and stream-buffer bytes this kernel has room
/// for. See the crate docs and [`items_for`] / [`lists_for`].
/// [`Kernel::new`] refuses a geometry that does not add up.
pub struct Kernel<
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,
> {
pub(crate) port: P,
pub(crate) trace: T,
pub(crate) tcbs: Arena<TaskKind, Tcb, TASKS>,
pub(crate) queues: Arena<QueueKind, Queue, QUEUES>,
pub(crate) lists: Lists<ITEMS, LISTS>,
pub(crate) slots: [u64; SLOTS],
pub(crate) buffers: Arena<StreamKind, StreamBuffer, BUFFERS>,
pub(crate) timers: Arena<TimerKind, Timer, TIMERS>,
pub(crate) groups: Arena<EventGroupKind, EventGroup, GROUPS>,
/// The ring of `DaemonTaskMessage_t`s the timer queue carries indices
/// into. It is exactly as long as the queue, so a message can only be
/// overwritten once the queue has already refused to hold its index.
pub(crate) timer_messages: [Message; MAX_TIMER_COMMANDS],
pub(crate) timer_message_next: usize,
/// Which of the two timer lists is `pxCurrentTimerList` right now.
pub(crate) timers_swapped: bool,
/// `xLastTime` in `prvSampleTimeNow`.
pub(crate) timer_last_time: u64,
/// `xTimerQueue`.
pub(crate) timer_queue: QueueHandle,
pub(crate) bytes: [u8; BYTES],
pub(crate) bytes_used: usize,
/// Blocks of the byte arena that a deleted stream buffer gave back,
/// as `(base, length)`, kept sorted and coalesced.
///
/// This is the one allocator in the kernel, and it exists because the
/// C's stream buffers are heap objects: `MessageBufferDemo`'s echo
/// server creates one and deletes it again on every loop, and a bump
/// allocator would run out in a few hundred ticks. At most `BUFFERS`
/// buffers can be alive, so at most `BUFFERS` holes can exist between
/// them, which is why the list is that long and cannot overflow.
pub(crate) free_blocks: [(usize, usize); BUFFERS],
pub(crate) free_count: usize,
pub(crate) slots_used: usize,
/// `pxCurrentTCB`.
pub(crate) current: TaskHandle,
/// `uxTopReadyPriority`.
top_ready_priority: u8,
/// `xTickCount`, masked to the configuration's tick width.
pub(crate) tick: u64,
/// `xPendedTicks`.
pended_ticks: u64,
/// `uxSchedulerSuspended`.
suspended_depth: u32,
/// `xSchedulerRunning`.
running: bool,
/// `xNextTaskUnblockTime`.
next_unblock_time: u64,
/// `xYieldPendings[0]`.
yield_pending: bool,
/// `uxCurrentNumberOfTasks`.
task_count: usize,
/// How many times the scheduler could not choose a task, and why the
/// FIRST time. See [`Stall`].
stalls: u32,
first_stall: Stall,
/// A task that deleted ITSELF and whose slot the idle task has not
/// reclaimed yet — the C's `xTasksWaitingTermination`, which only ever
/// holds the running task, because any other task is freed on the spot.
///
/// One slot is enough, and that is a property rather than a guess: a
/// self-deleting task is off every ready list and yields immediately, so
/// a second self-delete cannot happen until a switch has occurred, and
/// the switch is where this is reaped.
awaiting_reap: Option<TaskHandle>,
/// Which of the two delayed lists is `pxDelayedTaskList` right now.
delayed_swapped: bool,
/// `xNumOfOverflows`.
overflows: u64,
/// Which tasks have been switched in at least once. A task's first
/// switch-in is where a real port hands it a fresh stack, so the
/// outgoing task's open critical sections are abandoned there
/// (`Port::reset_nesting_for_first_start`).
started: [bool; TASKS],
/// A task that was switched out *in the middle of a kernel call* still
/// owes the tail of that call — in practice always the `portYIELD()`
/// that `vTaskDelay` and `vTaskSuspend` make after their critical
/// sections. On a real port the tail simply sits on the task's frozen
/// stack; here the stack is a program counter, so the debt is recorded
/// and paid by [`Kernel::resume_pending`] when the task runs again.
owes_yield: [bool; TASKS],
/// A trace line a task owes from a call it was switched out of.
///
/// `xQueueReceive`'s failure path is `taskEXIT_CRITICAL();
/// traceQUEUE_RECEIVE_FAILED( pxQueue ); return errQUEUE_EMPTY;` — and
/// if the tick that the exit released switches the task away, those two
/// lines sit on a stack that is not running. The C emits the trace when
/// the task resumes, so this kernel does too.
owed_trace: [OwedTrace; TASKS],
/// How many outermost critical-section exits a task owes the clock.
///
/// This is `uxSavedCriticalNesting` in the Posix port's
/// `prvSwitchThread` and then some. A thread stops at the switch; a
/// stackless call does not, so the abandoned frame runs on — closing
/// the sections it had open and, on some paths, opening one more. The
/// port tallies every exit that frame makes instead of counting it as
/// sim time, and the tally is paid here when the task runs again. That
/// is what puts a sim tick where the C one lands.
owed_exits: [u32; TASKS],
/// Does this task owe anything at all? A conservative hint: set by
/// every writer of the three fields above, cleared only by
/// [`Kernel::resume_pending`] once it has checked all three. Wrong in
/// the `true` direction costs one slow path; it is never wrong the
/// other way, because every writer raises it.
owes_anything: [bool; TASKS],
/// Does this task have a wait frame set?
///
/// A mirror of its `wait.entry_set`, so [`Kernel::end_wait`] can
/// answer "nothing to clear" -- which is almost every call -- without
/// resolving the TCB to find out. Two writers, the same two that move
/// the flag itself.
wait_set: [bool; TASKS],
/// The task whose abandoned frame is running right now, if any.
unwinding: Option<TaskHandle>,
/// `vApplicationTickHook`, held by value so it can borrow the kernel.
pub(crate) tick_hook: H,
/// `ucDelayAborted`: the task was pulled out of the Blocked state by
/// [`Kernel::abort_delay`] rather than by its own block time running
/// out, so it must not re-evaluate that block time and block again.
delay_aborted: [bool; TASKS],
_config: PhantomData<C>,
}
impl<
C: Config,
P: Port,
T: Trace,
H,
const TASKS: usize,
const ITEMS: usize,
const LISTS: usize,
const QUEUES: usize,
const SLOTS: usize,
const BUFFERS: usize,
const BYTES: usize,
const TIMERS: usize,
const GROUPS: usize,
> Kernel<C, P, T, H, TASKS, ITEMS, LISTS, QUEUES, SLOTS, BUFFERS, BYTES, TIMERS, GROUPS>
where
H: TickHook<Self>,
{
/// `portMAX_DELAY` at this configuration's tick width.
pub const MAX_DELAY: u64 = <C::Tick as TickWidth>::MAX;
// ------------------------------------------------------------ setup --
/// A kernel with no tasks, ready for [`Kernel::create_task`].
///
/// # Errors
/// [`Error::InvalidArgument`] if the configuration is invalid
/// ([`Config::validate`]), if the name capacity cannot hold
/// `MAX_TASK_NAME_LEN`, or if the const geometry does not match the
/// configuration: `ITEMS` must be [`items_for`]`(TASKS)` and `LISTS`
/// must be [`lists_for`]`(MAX_PRIORITIES, QUEUES)`.
pub fn new(port: P, trace: T) -> Result<Self>
where
H: Default,
{
Self::with_tick_hook(port, trace, H::default())
}
/// [`Kernel::new`] with `vApplicationTickHook` installed.
///
/// # Errors
/// As [`Kernel::new`].
pub fn with_tick_hook(port: P, trace: T, tick_hook: H) -> Result<Self> {
C::validate()?;
if ITEMS != list_slots_for(TASKS, TIMERS, LISTS)
|| LISTS != lists_for(C::MAX_PRIORITIES, QUEUES, GROUPS)
|| TASKS == 0
|| C::MAX_TASK_NAME_LEN > crate::NAME_CAPACITY
{
return Err(Error::InvalidArgument);
}
Ok(Self {
port,
trace,
tcbs: Arena::new(),
queues: Arena::new(),
lists: Lists::new(),
slots: [0; SLOTS],
slots_used: 0,
buffers: Arena::new(),
timers: Arena::new(),
groups: Arena::new(),
timer_messages: [Message::default(); MAX_TIMER_COMMANDS],
timer_message_next: 0,
timers_swapped: false,
timer_last_time: 0,
timer_queue: QueueHandle::NULL,
bytes: [0; BYTES],
bytes_used: 0,
free_blocks: [(0, 0); BUFFERS],
free_count: 0,
current: TaskHandle::NULL,
top_ready_priority: 0,
tick: C::INITIAL_TICK_COUNT,
pended_ticks: 0,
suspended_depth: 0,
running: false,
next_unblock_time: Self::MAX_DELAY,
yield_pending: false,
task_count: 0,
stalls: 0,
first_stall: Stall::None,
awaiting_reap: None,
delayed_swapped: false,
overflows: 0,
started: [false; TASKS],
owes_yield: [false; TASKS],
owed_exits: [0; TASKS],
owes_anything: [false; TASKS],
wait_set: [false; TASKS],
unwinding: None,
tick_hook,
delay_aborted: [false; TASKS],
owed_trace: [OwedTrace::None; TASKS],
_config: PhantomData,
})
}
/// The port, for a runner that needs its counters.
pub const fn port(&self) -> &P {
&self.port
}
/// The trace sink.
pub const fn trace(&self) -> &T {
&self.trace
}
/// The trace sink, mutably.
pub const fn trace_mut(&mut self) -> &mut T {
&mut self.trace
}
/// Take the trace sink back when the run is over, so a deliverable can
/// flush whatever it was writing to.
pub fn into_trace(self) -> T {
self.trace
}
/// `xNumOfOverflows`, for a scenario that reports counters.
#[must_use]
pub const fn overflows(&self) -> u64 {
self.overflows
}
// ------------------------------------------------------ list indices --
// `ListId` is a `u8` and `ItemId` a `u16` (the core's `list`): the
// whole scheduler addresses lists and items by small integers, which is
// what keeps a TCB free of pointers.
pub(crate) const fn ready_list(priority: u8) -> ListId {
priority
}
const fn delayed_list(&self) -> ListId {
if self.delayed_swapped {
C::MAX_PRIORITIES.saturating_add(1)
} else {
C::MAX_PRIORITIES
}
}
const fn overflow_delayed_list(&self) -> ListId {
if self.delayed_swapped {
C::MAX_PRIORITIES
} else {
C::MAX_PRIORITIES.saturating_add(1)
}
}
const fn pending_ready_list() -> ListId {
C::MAX_PRIORITIES.saturating_add(2)
}
const fn suspended_list() -> ListId {
C::MAX_PRIORITIES.saturating_add(3)
}
/// `xTasksWaitingToSend` of a queue.
pub(crate) fn queue_send_list(queue: QueueHandle) -> ListId {
let offset = u8::try_from(queue.index().saturating_mul(2)).unwrap_or(u8::MAX);
C::MAX_PRIORITIES
.saturating_add(u8::try_from(OVERHEAD_LISTS).unwrap_or(u8::MAX))
.saturating_add(offset)
}
/// `xTasksWaitingToReceive` of a queue.
pub(crate) fn queue_receive_list(queue: QueueHandle) -> ListId {
Self::queue_send_list(queue).saturating_add(1)
}
/// A task's `xStateListItem`: the task's own arena index.
pub(crate) const fn state_item(task: TaskHandle) -> ItemId {
task.index()
}
/// A task's `xEventListItem`: `TASKS` above its state item, so the two
/// never collide and either maps back to its task by arithmetic alone.
pub(crate) fn event_item(task: TaskHandle) -> ItemId {
Self::task_item_base().saturating_add(task.index())
}
fn task_item_base() -> ItemId {
u16::try_from(TASKS).unwrap_or(u16::MAX)
}
fn task_of_state_item(&self, item: ItemId) -> Result<TaskHandle> {
self.tcbs.handle_at(item).ok_or(Error::Gone)
}
fn task_of_event_item(&self, item: ItemId) -> Result<TaskHandle> {
let index = item
.checked_sub(Self::task_item_base())
.ok_or(Error::InvalidArgument)?;
self.tcbs.handle_at(index).ok_or(Error::Gone)
}
// ----------------------------------------------------------- getters --
/// `pxCurrentTCB`.
#[must_use]
pub const fn current(&self) -> TaskHandle {
self.current
}
/// `xTaskGetTickCount`.
#[must_use]
pub const fn tick_count(&self) -> u64 {
self.tick
}
/// `xSchedulerRunning`.
#[must_use]
pub const fn is_running(&self) -> bool {
self.running
}
/// `uxCurrentNumberOfTasks`.
#[must_use]
pub const fn task_count(&self) -> usize {
self.task_count
}
/// `uxSchedulerSuspended`, for a stepper reporting why a tick pended.
#[must_use]
pub const fn scheduler_suspended(&self) -> u32 {
self.suspended_depth
}
/// `xPendedTicks`, likewise.
#[must_use]
pub const fn pended_ticks(&self) -> u64 {
self.pended_ticks
}
/// The item ids in `priority`'s ready list, in order, into `out`.
///
/// Returns how many were written. The companion to
/// [`Kernel::ready_cursor`]: when a ready task is never chosen, the
/// cursor says whether the rotation moved and this says what it was
/// moving THROUGH.
pub fn ready_items(&self, priority: u8, out: &mut [u16]) -> usize {
let mut n = 0;
for item in self.lists.iter(Self::ready_list(priority)) {
let Some(slot) = out.get_mut(n) else {
break;
};
*slot = item;
n = n.wrapping_add(1);
}
n
}
/// Where the round-robin cursor sits in `priority`'s ready list.
///
/// A diagnostic, paired with [`Kernel::ready_len`]: a ready task that
/// is never chosen is either not in the list the scheduler looks at,
/// or the cursor is not moving. These two answer both halves.
#[must_use]
pub fn ready_cursor(&self, priority: u8) -> u16 {
self.lists
.cursor_of(Self::ready_list(priority))
.unwrap_or(0)
}
/// The live handle in arena slot `index`, if that slot holds a task.
///
/// The generation is the point: a bare index names a SLOT, and a slot
/// outlives the tasks that occupy it, so an index is not a task. This
/// answers the handle, which is.
///
/// It exists so a diagnostic can walk every task without knowing any
/// of their names -- `task_get_handle` needs the name it is looking
/// for, and a crash report is exactly the case where you do not have
/// one.
#[must_use]
pub fn task_at(&self, index: usize) -> Option<TaskHandle> {
let index = u16::try_from(index).ok()?;
self.tcbs.handle_at(index)
}
/// A task's name.
///
/// # Errors
/// [`Error::Gone`] for a stale or null handle.
pub fn name_of(&self, task: TaskHandle) -> Result<Name> {
self.tcbs.resolve(task).map(|t| t.name)
}
/// `uxTaskPriorityGet`. `None` means the current task, as in C.
///
/// # Errors
/// [`Error::Gone`] for a stale handle.
pub fn priority_of(&self, task: Option<TaskHandle>) -> Result<u8> {
let h = task.unwrap_or(self.current);
self.tcbs.resolve(h).map(|t| t.priority)
}
pub(crate) fn current_priority(&self) -> u8 {
self.priority_of(None).unwrap_or(0)
}
/// `uxTaskPriorityGet`: the C API, which takes a critical section.
///
/// The distinction matters: on the sim a critical-section exit is where
/// time passes, so reading a priority through the API costs a tick
/// sixteen calls later, exactly as it does in C
/// (`portBASE_TYPE_ENTER_CRITICAL` is `taskENTER_CRITICAL` on the Posix
/// port). The kernel's own reads use the field directly, as C's do.
///
/// # Errors
/// [`Error::Gone`] for a stale handle.
pub fn task_priority_get(&mut self, task: Option<TaskHandle>) -> Result<u8> {
self.enter_critical();
let result = self.priority_of(task);
self.exit_critical();
result
}
/// `eTaskGetState`: the C API, which takes a critical section for any
/// task but the running one.
///
/// # Errors
/// A list error surfaces as itself.
pub fn task_state_get(&mut self, task: TaskHandle) -> Result<TaskState> {
if task == self.current {
return Ok(TaskState::Running);
}
self.enter_critical();
let result = self.state_of(task);
self.exit_critical();
result
}
/// `eTaskGetState`, derived from the list the task is in.
///
/// # Errors
/// A list error surfaces as itself.
pub fn state_of(&self, task: TaskHandle) -> Result<TaskState> {
if !self.tcbs.contains(task) {
return Ok(TaskState::Deleted);
}
if task == self.current {
return Ok(TaskState::Running);
}
let Some(list) = self.lists.container(Self::state_item(task))? else {
return Ok(TaskState::Deleted);
};
if list == Self::suspended_list() {
if self.lists.container(Self::event_item(task))?.is_some() {
return Ok(TaskState::Blocked);
}
// A task blocked indefinitely on a notification is in the
// suspended list and on no event list at all, so the C scans
// the notification array before it calls such a task suspended.
// Miss this and a stream buffer's reader looks suspended to
// `eTaskGetState` while it is plainly waiting.
let waiting_notification = self
.tcbs
.resolve(task)
.map(|t| {
t.notify_state
.iter()
.take(C::NOTIFICATION_ARRAY_ENTRIES)
.any(|s| *s == NotifyState::Waiting)
})
.unwrap_or(false);
return Ok(if waiting_notification {
TaskState::Blocked
} else {
TaskState::Suspended
});
}
if list == self.delayed_list() || list == self.overflow_delayed_list() {
return Ok(TaskState::Blocked);
}
Ok(TaskState::Ready)
}
/// How many tasks sit on a priority's ready list — what the idle task
/// checks before yielding (`configIDLE_SHOULD_YIELD`).
///
/// # Errors
/// [`Error::InvalidPriority`] for a priority outside the configuration.
pub fn ready_len(&self, priority: u8) -> Result<usize> {
if priority >= C::MAX_PRIORITIES {
return Err(Error::InvalidPriority);
}
self.lists.len(Self::ready_list(priority))
}
/// Record that the scheduler could not choose.
///
/// Counts every occurrence and keeps the FIRST reason: the first is the
/// diagnosis and the rest are consequences.
fn note_stall(&mut self, why: Stall) {
self.stalls = self.stalls.saturating_add(1);
if self.first_stall == Stall::None {
self.first_stall = why;
}
}
/// How many times the scheduler could not choose a task.
///
/// **Non-zero means an invariant broke.** A healthy kernel never stalls:
/// the idle task is always ready. A firmware that prints this alongside
/// its own counters turns a hang into a sentence.
#[must_use]
pub const fn stalls(&self) -> u32 {
self.stalls
}
/// Why the scheduler first failed to choose. [`Stall::None`] if it never
/// has.
#[must_use]
pub const fn first_stall(&self) -> Stall {
self.first_stall
}
// ------------------------------------------------------------ tracing --
pub(crate) fn trace_task<F>(&mut self, task: TaskHandle, make: F)
where
F: for<'a> FnOnce(TaskHandle, &'a str) -> Event<'a>,
{
// `tcbs` and `trace` are different fields, so the name can be read
// where it lives rather than copied onto the stack to end a borrow
// that never had to end.
//
// A sink that never reads the name pays for neither the lookup nor
// the UTF-8 validation that turning one into a `&str` costs.
let Self {
tcbs,
trace,
port,
tick,
..
} = self;
let name = if T::WANTS_NAMES {
tcbs.get(task).map(|t| t.name.as_str()).unwrap_or("")
} else {
""
};
let tick = *tick;
trace.note_exits(port.exits());
trace.event(tick, make(task, name));
}
pub(crate) fn priority_value(raw: u8) -> Priority {
Priority::new(raw, C::MAX_PRIORITIES).unwrap_or(Priority::IDLE)
}
// --------------------------------------------------- critical section --
/// What `pvPortMalloc` costs in sim time on a heap-backed C kernel:
/// `vTaskSuspendAll()` around the allocation, then `xTaskResumeAll()`,
/// whose critical section is one outermost exit.
///
/// This kernel allocates nothing, so the call is the whole of it. On a
/// configuration with [`Config::DYNAMIC_ALLOCATION`] off it compiles
/// away to nothing at all.
pub(crate) fn account_for_allocation(&mut self) {
if C::DYNAMIC_ALLOCATION {
self.suspend_all();
let _ = self.resume_all();
}
}
/// `taskENTER_CRITICAL()`.
pub fn enter_critical(&mut self) {
self.port.enter_critical();
}
/// `taskEXIT_CRITICAL()`.
///
/// On the sim this is where time passes: the port raises a tick on
/// every sixteenth outermost exit and the kernel takes it here, which
/// is exactly where the C kernel's `SIGALRM` handler would have run.
///
/// NOT in line, though it is three statements called 118,640 times in
/// a 20,000-tick `StreamBufferDemo`. `#[inline(always)]` was measured:
/// it saves that scenario 210,292 and costs `BlockQ` 200,912 and
/// `GenQTest` 280,540, for a net loss of 271,962 over six scenarios.
/// Whatever the hot sites gain, the switch-heavy ones lose more.
pub fn exit_critical(&mut self) {
self.port.exit_critical();
if self.port.take_pending_tick() {
self.tick_on_exit();
}
}
/// The tick as [`Kernel::exit_critical`] reaches it, deliberately out of
/// line.
///
/// `exit_critical` is inlined into every queue walker and every demo
/// step, and the tick is its rare arm -- 8,000 of 48,000 sends in
/// `khot-ir` raise one, and 38,013 ticks across 18 scenarios in
/// `kernel-ir`. Left in line it put `increment_tick` and
/// `switch_context` inside all of those frames.
///
/// Taking it out is worth 233,207 on `kernel-ir` and costs the four
/// kernel micro-instruments 9,650 between them, which is about what one
/// extra call layer costs at their call counts.
///
/// The other half was refuted: `#[inline(always)]` on
/// [`Kernel::tick_from_isr`] itself costs `khot-ir` 178,245 while saving
/// the three lighter instruments 82,642, and stacked on top of this
/// outlining it still costs `khot-ir` 12,001, `ksched-ir` 7,555 and
/// `kipc-ir` 2,000 for nothing `kernel-ir` did not already have. So the
/// body keeps LLVM's own choice and only this call site is pinned.
#[inline(never)]
fn tick_on_exit(&mut self) {
self.tick_from_isr();
}
/// `vPortSystemTickHandler`: the tick, from interrupt context.
///
/// A silicon port calls this from its timer interrupt. The sim reaches
/// it from [`Kernel::exit_critical`] -- through [`Kernel::tick_on_exit`],
/// which is where the reason for this attribute is written down -- and
/// from the idle hook.
pub fn tick_from_isr(&mut self) {
self.port.set_in_tick_entry(true);
self.port.count_tick();
// The C handler bumps `uxCriticalNesting` by hand and drops it the
// same way — a raw `--`, never `vPortExitCritical` — so the bump is
// invisible to the exit count and to anything that unwinds later.
// Modelling it as a real critical section would invent an exit at
// every tick that caused a switch.
if self.increment_tick() {
self.switch_context();
}
self.port.set_in_tick_entry(false);
}
/// The idle hook's tick, `vPortKairosTick()` on the C side: a critical
/// section around one unconditional tick. The enclosing section counts
/// toward rule 3 exactly as the C one does.
pub fn idle_hook_tick(&mut self) {
self.enter_critical();
self.tick_from_isr();
self.exit_critical();
}
// ---- tickless idle --------------------------------------------------
/// `tskIDLE_PRIORITY`.
const IDLE_PRIORITY: u8 = 0;
/// `prvGetExpectedIdleTime`: how long nothing is due, in ticks.
///
/// Zero whenever the answer would be unsafe to sleep on -- something
/// above the idle priority is running, another idle-priority task is
/// ready to share the slice, or a higher-priority task is ready. The
/// last of those cannot happen with preemption on, and the C keeps the
/// test anyway because a cooperative build reaches it.
fn expected_idle_time(&self) -> u64 {
// The C spells these as three arms so each carries its own reason;
// they answer zero alike, so here they are one short-circuit chain
// in the same order:
//
// - something above the idle priority is running;
// - another idle-priority task is ready to share the slice, so the
// very next tick has to be processed;
// - a higher-priority task is ready, which only a cooperative
// build can reach and which the C tests for anyway.
let due = self.current_priority() > Self::IDLE_PRIORITY
|| self.ready_len(Self::IDLE_PRIORITY).unwrap_or(0) > 1
|| self.top_ready_priority > Self::IDLE_PRIORITY;
if due {
0
} else {
self.next_unblock_time.saturating_sub(self.tick)
}
}
/// `vTaskStepTick`: wind the tick count forward over a suppressed period.
///
/// Note this does *not* call the tick hook for each stepped tick, which
/// is the C's own note and the reason a tickless trace has no heartbeat
/// in it.
///
/// The C `configASSERT`s that the jump does not pass the next unblock
/// time. This clamps instead: a port that overslept is a port bug, and
/// winding the clock past a task's wake would lose the wake entirely,
/// where losing the extra sleep is recoverable. `forbid(unsafe)` buys
/// nothing if the kernel panics on a misbehaving port.
///
/// Landing exactly on the next unblock time leaves the last tick pended
/// rather than stepped, so `increment_tick` runs it when the scheduler
/// resumes and the delayed task is woken by the same code that would
/// have woken it.
pub fn step_tick(&mut self, ticks_to_jump: u64) {
let room = self.next_unblock_time.saturating_sub(self.tick);
let mut jump = ticks_to_jump.min(room);
if self.tick.saturating_add(jump) == self.next_unblock_time && jump > 0 {
self.pended_ticks = self.pended_ticks.saturating_add(1);
jump = jump.saturating_sub(1);
}
self.tick = self.tick.wrapping_add(jump) & Self::MAX_DELAY;
}
/// The `configUSE_TICKLESS_IDLE` block of `prvIdleTask`.
///
/// Compiled away entirely when the configuration leaves tickless idle
/// off, which is the default and is why every existing scenario is
/// byte-identical with this in the tree.
///
/// The shape is the C's, including the part that looks redundant: the
/// expected idle time is sampled once WITHOUT the scheduler suspended,
/// and again with it. The first answer is not necessarily valid and the
/// C takes it anyway, because suspending and resuming the scheduler on
/// every pass of the idle task costs more than a sample that is
/// sometimes wasted.
pub fn idle_suppress_ticks(&mut self) {
if !C::USE_TICKLESS_IDLE {
return;
}
if self.expected_idle_time() < C::EXPECTED_IDLE_TIME_BEFORE_SLEEP {
return;
}
self.suspend_all();
let expected = self.expected_idle_time();
if expected >= C::EXPECTED_IDLE_TIME_BEFORE_SLEEP {
let tick = self.tick;
self.trace.note_exits(self.port.exits());
self.trace.event(tick, Event::LowPowerIdleBegin);
let slept = self.port.suppress_ticks_and_sleep(expected);
self.step_tick(slept);
let tick = self.tick;
self.trace.note_exits(self.port.exits());
self.trace.event(tick, Event::LowPowerIdleEnd);
}
let _ = self.resume_all();
}
/// `portYIELD()` as the Posix port spells it: a critical section around
/// the context switch, so a tick raised during it lands on the way out.
pub(crate) fn port_yield(&mut self) {
self.enter_critical();
self.port.count_yield();
if P::COMMITS_SWITCH {
// A STACKED port. Raise its switching exception and leave
// `current` where it is: the exception will call
// `switch_context` itself, so the decision and the register
// swap happen together and nothing runs in between as a task
// the kernel has already moved on from.
//
// The exception cannot fire yet -- `exit_critical` below is
// what unmasks -- so the kernel is consistent at the moment it
// is taken.
self.port.yield_now();
} else {
// A STACKLESS kernel: moving `current` IS the switch, because
// no task owns a stack. This is the path every corpus
// architecture takes, and it is unchanged.
self.switch_context();
}
self.exit_critical();
}
/// `taskYIELD()` from a task body (the idle task's yield).
pub fn task_yield(&mut self) {
self.port_yield();
}
// -------------------------------------------------------- task create --
/// `xTaskCreate`.
///
/// # Errors
/// [`Error::Full`] when the task arena is full (the C
/// `errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY`).
pub fn create_task(&mut self, name: &str, priority: u8) -> Result<TaskHandle> {
let caller = self.current;
// configASSERT( uxPriority < configMAX_PRIORITIES ), then C clamps.
let priority = priority.min(C::MAX_PRIORITIES.saturating_sub(1));
// `prvCreateTask` takes the stack and then the TCB from the heap
// before anything is initialised — `portSTACK_GROWTH` is negative on
// the oracle's port, which fixes that order — and `pvPortMallocStack`
// *is* `pvPortMalloc` with the MPU wrappers off. On heap_3 each one
// suspends the scheduler, so a create costs two outermost exits.
//
// Every scenario before `death` created its tasks BEFORE
// `vTaskStartScheduler`, and the sim port counts no exits there (the
// C patch counts only on a FreeRTOS thread), so this cost was
// invisible to the whole corpus. `death` is the first scenario that
// creates a task with the scheduler running, and the first that can
// tell the difference.
self.account_for_allocation();
self.account_for_allocation();
let tcb = Tcb {
name: Name::new(name, C::MAX_TASK_NAME_LEN),
priority,
base_priority: priority,
mutexes_held: 0,
wait: WaitFrame::default(),
notified: [0; MAX_NOTIFICATION_ENTRIES],
notify_state: [NotifyState::NotWaiting; MAX_NOTIFICATION_ENTRIES],
notify_blocked: false,
event_blocked: false,
stream_resume: false,
queue_resume: QueueResume::No,
stream_timed: false,
stream_waited: false,
stream_local: 0,
};
let handle = match self.tcbs.try_insert(tcb) {
Ok(h) => h,
Err(_) => {
let tick = self.tick;
self.trace.note_exits(self.port.exits());
self.trace.event(tick, Event::TaskCreateFailed);
return Err(Error::Full);
}
};
// The event item sorts by `configMAX_PRIORITIES - uxPriority`, so a
// higher-priority task waits nearer the head of an event list.
let event_value = u64::from(C::MAX_PRIORITIES.saturating_sub(priority));
self.lists
.set_value(Self::event_item(handle), event_value)?;
// `prvInitialiseNewTask` ends by calling `pxPortInitialiseStack`,
// which on the oracle's Posix port wraps `pthread_create` in a
// critical section — one more exit, and a PORT cost rather than a
// kernel one, which is why it has a flag of its own.
if C::PORT_STACK_INIT_CRITICAL {
self.enter_critical();
self.exit_critical();
}
// Any of the three exits above can release a tick that switches the
// creator out. In the C the creator is a thread and simply STOPS
// there: `prvAddNewTaskToReadyList` has not run, so the new task is
// on no ready list and `traceTASK_CREATE` has not fired. Running it
// now would put both events on the wrong side of the switch — which
// is precisely how `death` first diverged.
if self.current != caller {
if let Some(slot) = self.owed_trace.get_mut(usize::from(caller.index())) {
*slot = OwedTrace::AddNewTaskToReadyList {
task: handle,
priority,
};
}
self.owe(caller);
return Ok(handle);
}
self.add_new_task_to_ready_list(handle, priority)?;
Ok(handle)
}
/// `prvAddNewTaskToReadyList`.
fn add_new_task_to_ready_list(&mut self, task: TaskHandle, priority: u8) -> Result<()> {
self.enter_critical();
{
self.task_count = self.task_count.wrapping_add(1);
if self.current.is_null() {
self.current = task;
} else if !self.running {
// `<=`, so the last-created task of the highest priority is
// the one that runs first.
if self.current_priority() <= priority {
self.current = task;
}
}
self.trace_task(task, |task, name| Event::TaskCreate {
task,
name,
priority: Self::priority_value(priority),
});
self.add_task_to_ready_list(task)?;
}
self.exit_critical();
// taskYIELD_IF_USING_PREEMPTION(), outside the section.
if self.running && C::USE_PREEMPTION && self.current_priority() < priority {
self.port_yield();
}
Ok(())
}
/// `prvAddTaskToReadyList`.
/// Returns `Result<()>`, and that is a measured decision, not an
/// oversight.
///
/// Its two hot callers -- the tick's wake loop and the pending-ready
/// drain -- resolve the SAME TCB again on the next line for the SAME
/// field, to ask whether the woken task outranks the running one. Having
/// this hand the priority back instead costs **+3.69% on kdelay-ir and
/// +3.10% on ksched-ir**.
///
/// Wrapping it -- narrow signature for the eleven callers that ignore the
/// value, a wide inner for the two that want it -- does NOT help: that
/// measured bit-for-bit identical to the unwrapped version on all four
/// arms, because LLVM inlines through the wrapper and propagates the wide
/// return anyway.
///
/// The likely mechanism is the tail call. At `Result<()>` this function
/// ends by handing back `insert_end`'s own result; at `Result<u8>` it has
/// to capture that result, test it, and build a new one, at every site.
pub(crate) fn add_task_to_ready_list(&mut self, task: TaskHandle) -> Result<()> {
let priority = self.tcbs.resolve(task)?.priority;
self.trace_task(task, |task, name| Event::MovedTaskToReadyState {
task,
name,
});
// taskRECORD_READY_PRIORITY
if priority > self.top_ready_priority {
self.top_ready_priority = priority;
}
self.lists
.insert_end(Self::ready_list(priority), Self::state_item(task))
}
// ---------------------------------------------------- scheduler start --
/// `vTaskStartScheduler`, minus the part that never returns.
///
/// Creates the idle task, the timer command queue and the timer service
/// task, fires `TASK_SWITCHED_IN` for whichever task will run first and
/// then `STARTING_SCHEDULER`, and returns the handles so the runner can
/// attach their bodies.
///
/// # Errors
/// As [`Kernel::create_task`].
pub fn start_scheduler(&mut self) -> Result<StartHandles> {
let idle = self.create_task("IDLE", 0)?;
// `xTimerCreateTimerTask` opens with `prvCheckForValidListAndQueue`,
// which makes the command queue only if no `xTimerCreate` has made
// it already.
self.check_for_valid_list_and_queue()?;
let timer_queue = self.timer_queue;
let timer = self.create_task("Tmr Svc", C::TIMER_TASK_PRIORITY)?;
self.next_unblock_time = Self::MAX_DELAY;
self.running = true;
self.tick = C::INITIAL_TICK_COUNT;
self.port.scheduler_started();
// `vPortStartFirstTask` runs the first task through the same
// first-start path as every other.
let current = self.current;
self.note_first_start(current);
self.trace_task(current, |task, name| Event::TaskSwitchedIn { task, name });
let tick = self.tick;
self.trace.note_exits(self.port.exits());
self.trace.event(tick, Event::StartingScheduler);
Ok(StartHandles {
idle,
timer,
timer_queue,
})
}
// -------------------------------------------------------- the switch --
/// `vTaskSwitchContext`.
pub fn switch_context(&mut self) {
if self.suspended_depth != 0 {
self.yield_pending = true;
return;
}
self.yield_pending = false;
let current = self.current;
self.trace_task(current, |task, name| Event::TaskSwitchedOut { task, name });
// taskSELECT_HIGHEST_PRIORITY_TASK
let mut top = self.top_ready_priority;
loop {
match self.lists.is_empty(Self::ready_list(top)) {
Ok(false) => break,
Ok(true) => {
if top == 0 {
// The C `configASSERT( uxTopPriority )`. The idle
// task keeps priority 0 non-empty, so reaching here
// means it is gone. The kernel keeps the current
// task rather than indexing out of range -- and now
// SAYS so, because carrying on quietly is how this
// costs an afternoon on a board.
self.note_stall(Stall::NoReadyTask);
return;
}
// At least 1: the arm above returns at zero.
top = top.wrapping_sub(1);
}
Err(_) => {
self.note_stall(Stall::ListError);
return;
}
}
}
let Ok(Some(item)) = self.lists.next_round_robin(Self::ready_list(top)) else {
self.note_stall(Stall::EmptyRotation);
return;
};
let Ok(next) = self.task_of_state_item(item) else {
self.note_stall(Stall::UnknownTask);
return;
};
self.top_ready_priority = top;
if next != current {
self.hand_over(current, next);
}
self.current = next;
self.trace_task(next, |task, name| Event::TaskSwitchedIn { task, name });
}
// ----------------------------------------------------------- the tick --
/// Pay whatever the running task still owes from a call it was
/// preempted inside. The runner calls this before stepping a body;
/// `true` means work was done and the current task may have changed
/// again, so nothing else should be assumed.
#[inline(always)]
pub fn resume_pending(&mut self) -> bool {
// The fast path, in line at the runner's one call site.
//
// `Runner::step_once` asks this before every step -- 214,488 times
// in a 20,000-tick `StreamBufferDemo` -- and the answer is "nothing
// owed" almost every time. Two loads and two branches decide it,
// and out of line they cost a call and a frame as well.
//
// The two tests are the entry conditions of the two things the
// body does: `settle_unwind` returns at once unless `unwinding` is
// set, and the rest returns at once unless this task owes
// something. Neither is duplicated -- the cold half still runs
// both in full.
if self.unwinding.is_none()
&& !self
.owes_anything
.get(usize::from(self.current.index()))
.copied()
.unwrap_or(true)
{
return false;
}
self.resume_pending_cold()
}
/// Everything [`Kernel::resume_pending`] does when something IS owed.
///
/// Out of line on purpose: it is reached on a small fraction of steps,
/// and inlining it would put the whole `OwedTrace` match at the hot
/// site. Same body/symbol split the trace sink's `num` measured.
#[inline(never)]
fn resume_pending_cold(&mut self) -> bool {
self.settle_unwind();
let index = usize::from(self.current.index());
// One load and one test for the overwhelmingly common case. The
// combined check below is the fallback, and it is what clears the hint
// -- so a hint left standing costs one slow path and then goes away.
if !self.owes_anything.get(index).copied().unwrap_or(true) {
return false;
}
// Almost every call answers "nothing owed", and the sequence below
// reaches that answer in three stages -- a compare, a match over
// `OwedTrace`, then another compare -- each reachable only after the
// one before. The same three loads, but one branch instead of three.
if self.owed_exits.get(index).copied().unwrap_or(0) == 0
&& matches!(
self.owed_trace.get(index).copied(),
Some(OwedTrace::None) | None
)
&& self.owes_yield.get(index).copied() != Some(true)
{
if let Some(flag) = self.owes_anything.get_mut(index) {
*flag = false;
}
return false;
}
// First the stack unwinds — the sections the task had open when it
// was switched out, and whatever its abandoned frame opened after
// that — and only then does the statement after the yield run.
// Reversing the two moves every tick.
let owed = self.owed_exits.get(index).copied().unwrap_or(0);
if owed > 0 {
if let Some(slot) = self.owed_exits.get_mut(index) {
*slot = 0;
}
// One counted exit each: the tally is already in outermost
// exits, so replaying it as nesting would lose the sections the
// tail opened and closed on its own.
for _ in 0..owed {
self.enter_critical();
self.exit_critical();
// A replayed exit can release a tick that switches this
// task straight back out. The rest of the loop is then the
// tail of *this* frame, which the port tallies and the next
// resume pays — so there is nothing to unwind by hand.
}
return true;
}
// Then the line the abandoned frame had not reached yet.
match self.owed_trace.get(index).copied() {
Some(OwedTrace::SendFailed(queue)) => {
if let Some(slot) = self.owed_trace.get_mut(index) {
*slot = OwedTrace::None;
}
let tick = self.tick;
self.trace.note_exits(self.port.exits());
self.trace
.event(tick, Event::QueueSendFailed { queue, name: "" });
return true;
}
Some(OwedTrace::ReceiveFailed(queue)) => {
if let Some(slot) = self.owed_trace.get_mut(index) {
*slot = OwedTrace::None;
}
let tick = self.tick;
self.trace.note_exits(self.port.exits());
self.trace
.event(tick, Event::QueueReceiveFailed { queue, name: "" });
return true;
}
Some(OwedTrace::EventGroupWaitBitsEnd {
group,
bits,
timed_out,
}) => {
if let Some(slot) = self.owed_trace.get_mut(index) {
*slot = OwedTrace::None;
}
let tick = self.tick;
self.trace.note_exits(self.port.exits());
self.trace.event(
tick,
Event::EventGroupWaitBitsEnd {
group,
bits,
timed_out,
},
);
return true;
}
Some(OwedTrace::StreamBufferCreate {
buffer,
is_message_buffer,
}) => {
if let Some(slot) = self.owed_trace.get_mut(index) {
*slot = OwedTrace::None;
}
let tick = self.tick;
self.trace.note_exits(self.port.exits());
self.trace.event(
tick,
Event::StreamBufferCreate {
buffer,
is_message_buffer,
},
);
return true;
}
Some(OwedTrace::TimerCommandSend {
timer,
name,
command,
value,
}) => {
if let Some(slot) = self.owed_trace.get_mut(index) {
*slot = OwedTrace::None;
}
let tick = self.tick;
self.trace.note_exits(self.port.exits());
self.trace.event(
tick,
Event::TimerCommandSend {
timer,
name: name.as_str(),
command,
value,
},
);
return true;
}
Some(OwedTrace::AddNewTaskToReadyList { task, priority }) => {
if let Some(slot) = self.owed_trace.get_mut(index) {
*slot = OwedTrace::None;
}
let _ = self.add_new_task_to_ready_list(task, priority);
return true;
}
Some(OwedTrace::None) | None => {}
}
if self.owes_yield.get(index).copied() != Some(true) {
return false;
}
if let Some(flag) = self.owes_yield.get_mut(index) {
*flag = false;
}
self.port_yield();
true
}
/// Collect the tally of an abandoned frame that has finished running.
///
/// The frame runs to its end before control comes back to the runner,
/// so this is called once, at the top of [`Kernel::resume_pending`],
/// which is the first thing the runner does.
fn settle_unwind(&mut self) {
// Nothing to settle is the common case by a wide margin, and `take()`
// writes `None` back even then -- a store, on every call, to clear a
// slot that was already clear. Peeking first leaves the store for the
// calls that actually have something to clear.
if self.unwinding.is_none() {
return;
}
let Some(task) = self.unwinding.take() else {
return;
};
let owed = self.port.end_unwind();
if let Some(slot) = self.owed_exits.get_mut(usize::from(task.index())) {
// Accumulate: a replay that is itself interrupted leaves the
// rest of its own loop as a tail, and that tail is more of the
// same debt.
*slot = slot.saturating_add(owed);
}
if owed > 0 {
self.owe(task);
}
}
/// Emit a queue failure line now, or owe it if a tick switched the
/// caller out of the call that was about to emit it.
/// In line on purpose, at all seven call sites. It is reached 46,671
/// times in kernel-ir and every one of them paid a call and a frame to
/// choose between two events the caller had already decided between.
#[inline(always)]
pub(crate) fn trace_failure_or_owe(&mut self, caller: TaskHandle, owed: OwedTrace) {
if self.current == caller {
let tick = self.tick;
self.trace.note_exits(self.port.exits());
match owed {
OwedTrace::SendFailed(queue) => self
.trace
.event(tick, Event::QueueSendFailed { queue, name: "" }),
OwedTrace::ReceiveFailed(queue) => self
.trace
.event(tick, Event::QueueReceiveFailed { queue, name: "" }),
OwedTrace::StreamBufferCreate {
buffer,
is_message_buffer,
} => self.trace.event(
tick,
Event::StreamBufferCreate {
buffer,
is_message_buffer,
},
),
OwedTrace::TimerCommandSend {
timer,
name,
command,
value,
} => self.trace.event(
tick,
Event::TimerCommandSend {
timer,
name: name.as_str(),
command,
value,
},
),
OwedTrace::EventGroupWaitBitsEnd {
group,
bits,
timed_out,
} => self.trace.event(
tick,
Event::EventGroupWaitBitsEnd {
group,
bits,
timed_out,
},
),
// Not reachable through this function: `create_task` owes
// its second half directly, because that half is not a
// trace line — it inserts into a ready list — and it must
// run INSIDE the section this one has already left.
OwedTrace::AddNewTaskToReadyList { .. } | OwedTrace::None => {}
}
return;
}
if let Some(slot) = self.owed_trace.get_mut(usize::from(caller.index())) {
*slot = owed;
}
self.owe(caller);
}
/// Raise the hint that `task` owes something.
///
/// Called by every writer of `owed_trace`, `owes_yield` and `owed_exits`.
/// Missing one would let `resume_pending` skip work that was really owed,
/// which the conformance differential would show as a missing trace line.
fn owe(&mut self, task: TaskHandle) {
if let Some(flag) = self.owes_anything.get_mut(usize::from(task.index())) {
*flag = true;
}
}
/// Record that `task` was preempted before the `portYIELD()` at the end
/// of the call it is inside.
pub(crate) fn owe_yield(&mut self, task: TaskHandle) {
if let Some(flag) = self.owes_yield.get_mut(usize::from(task.index())) {
*flag = true;
}
self.owe(task);
}
/// Hand the CPU from `outgoing` to `incoming`: what `prvSwitchThread`
/// does to `uxCriticalNesting`.
///
/// Everything the outgoing task's call still does from here belongs to
/// that task at the time it runs again, so the port stops counting the
/// frame's exits as sim time and starts tallying them;
/// [`Kernel::settle_unwind`] collects the tally once the frame has
/// finished. A task being switched in for the first time has a fresh
/// stack and owes nothing.
fn hand_over(&mut self, outgoing: TaskHandle, incoming: TaskHandle) {
// A tail that switches again is still the first frame's tail: the
// code after the second switch is on the same abandoned stack.
if self.unwinding.is_none() {
self.unwinding = Some(outgoing);
self.port.begin_unwind();
}
let index = usize::from(incoming.index());
if let Some(flag) = self.started.get_mut(index) {
if !*flag {
*flag = true;
if let Some(slot) = self.owed_exits.get_mut(index) {
*slot = 0;
}
if let Some(flag) = self.owes_yield.get_mut(index) {
*flag = false;
}
if let Some(slot) = self.owed_trace.get_mut(index) {
*slot = OwedTrace::None;
}
}
}
}
/// Mark a task as having run, without a hand-over: the first task the
/// scheduler starts has no predecessor.
fn note_first_start(&mut self, task: TaskHandle) {
if let Some(flag) = self.started.get_mut(usize::from(task.index())) {
*flag = true;
}
}
/// `xTaskIncrementTick`; `true` when a context switch is required.
pub fn increment_tick(&mut self) -> bool {
let tick = self.tick;
self.trace.note_exits(self.port.exits());
self.trace.event(tick, Event::TaskIncrementTick { tick });
let mut switch_required = false;
if self.suspended_depth == 0 {
let next = self.tick.wrapping_add(1) & Self::MAX_DELAY;
self.tick = next;
if next == 0 {
self.switch_delayed_lists();
}
if next >= self.next_unblock_time {
switch_required = self.wake_due_tasks(next);
}
// `!switch_required` first: when the tick already woke a
// task, this can only set what is already set, and asking
// costs a TCB resolve for the running priority plus a list
// read. Setting a `true` to `true` is not worth either.
if C::USE_PREEMPTION
&& C::USE_TIME_SLICING
&& !switch_required
&& self
.lists
.len(Self::ready_list(self.current_priority()))
.unwrap_or(0)
> 1
{
switch_required = true;
}
// The C guards this site with `xPendedTicks == 0`, so a hook
// does not fire again for each tick being unwound by
// `xTaskResumeAll`. It sits after the time-slicing test and
// before the yield-pending one, and a `FromISR` call inside it
// can set `yield_pending`, so the order is load-bearing.
if self.pended_ticks == 0 {
self.run_tick_hook();
}
if C::USE_PREEMPTION && self.yield_pending {
switch_required = true;
}
} else {
self.pended_ticks = self.pended_ticks.wrapping_add(1);
// "The tick hook gets called at regular intervals, even if the
// scheduler is locked" — and here with no guard, because this
// tick is being pended rather than unwound.
self.run_tick_hook();
}
switch_required
}
// ------------------------------------------- task notifications --
//
// A notification is the lightest thing a task can block on: no object,
// no event list, just a slot in the TCB and the delayed list. That is
// why the stream buffers use one rather than a queue, and why waking a
// task this way is a list move rather than an event-list walk.
/// `xTaskGenericNotifyWait`.
///
/// `true` is `pdTRUE`: a notification was received. `Blocked` means the
/// caller must call again — the C blocks inside this function, and a
/// kernel with no stacks returns instead.
///
/// # Errors
/// [`Error::InvalidArgument`] for an index past the configured array.
pub fn notify_wait(
&mut self,
index: usize,
clear_on_entry: u32,
clear_on_exit: u32,
ticks: u64,
) -> Result<Wait<(bool, u32)>> {
if index >= C::NOTIFICATION_ARRAY_ENTRIES {
return Err(Error::InvalidArgument);
}
let caller = self.current;
let state = self.notify_state_of(caller, index);
if state != NotifyState::Received && ticks > 0 && !self.notify_blocked(caller) {
self.suspend_all();
self.enter_critical();
let mut should_block = false;
if self.notify_state_of(caller, index) != NotifyState::Received {
if let Ok(tcb) = self.tcbs.resolve_mut(caller) {
if let Some(slot) = tcb.notified.get_mut(index) {
*slot &= !clear_on_entry;
}
if let Some(slot) = tcb.notify_state.get_mut(index) {
*slot = NotifyState::Waiting;
}
}
should_block = true;
}
self.exit_critical();
if should_block {
let tick = self.tick;
self.trace.note_exits(self.port.exits());
self.trace_task(caller, |task, name| Event::TaskNotifyWaitBlock {
task,
name,
index,
});
let _ = tick;
self.add_current_task_to_delayed_list(ticks, true)?;
}
let already_yielded = self.resume_all();
if should_block && !already_yielded {
if self.current == caller {
self.port_yield();
} else {
self.owe_yield(caller);
}
}
// The C blocks here; this kernel comes back and is called again.
self.set_notify_blocked(caller, true);
return Ok(Wait::Blocked);
}
self.set_notify_blocked(caller, false);
self.enter_critical();
self.trace.note_exits(self.port.exits());
self.trace_task(caller, |task, name| Event::TaskNotifyWait {
task,
name,
index,
});
let value = self.notified_value_of(caller, index);
let received = self.notify_state_of(caller, index) == NotifyState::Received;
if let Ok(tcb) = self.tcbs.resolve_mut(caller) {
if received {
if let Some(slot) = tcb.notified.get_mut(index) {
*slot &= !clear_on_exit;
}
}
if let Some(slot) = tcb.notify_state.get_mut(index) {
*slot = NotifyState::NotWaiting;
}
}
self.exit_critical();
Ok(Wait::Ready((received, value)))
}
/// `ulTaskGenericNotifyTake`: the notification used as a lightweight
/// counting semaphore — block until the value is non-zero, then either
/// zero it or decrement it by one.
///
/// This is the half of the notification API the kernel was missing.
/// `notify_wait` waits on *bits*; this waits on a *count*, and the two
/// are separate calls in the C with their own trace events. Its
/// partner, `xTaskNotifyGive`, needs no method of its own: the C
/// defines it as `xTaskGenericNotify( .., 0, eIncrement, NULL )` and
/// it traces as an ordinary notify, so
/// `notify(task, index, 0, NotifyAction::Increment)` already is it.
///
/// # The shape, and why it is not `notify_wait`'s
///
/// The C blocks on `ulNotifiedValue == 0`, **not** on the notify
/// state, and it does no clear-on-entry. Both halves run on the way
/// out: `traceTASK_NOTIFY_TAKE` fires whether or not the call ever
/// blocked, which is what makes a take that finds a count already
/// waiting still emit one line.
///
/// This kernel has no stack, so the block is a return: the first call
/// answers [`Wait::Blocked`] and the caller is entered again when the
/// scheduler runs it, taking the second half. `notify_wait_pending`
/// answers for this call too — a task is only ever inside one of the
/// two.
///
/// # Errors
/// [`Error::InvalidArgument`] for an index past the configured array.
pub fn notify_take(
&mut self,
index: usize,
clear_on_exit: bool,
ticks: u64,
) -> Result<Wait<u32>> {
if index >= C::NOTIFICATION_ARRAY_ENTRIES {
return Err(Error::InvalidArgument);
}
let caller = self.current;
if self.notified_value_of(caller, index) == 0 && ticks > 0 && !self.notify_blocked(caller) {
self.suspend_all();
self.enter_critical();
let mut should_block = false;
// Re-checked inside the section, as the C does: a notify from
// an ISR between the two reads would otherwise be lost.
if self.notified_value_of(caller, index) == 0 {
if let Ok(tcb) = self.tcbs.resolve_mut(caller) {
if let Some(slot) = tcb.notify_state.get_mut(index) {
*slot = NotifyState::Waiting;
}
}
should_block = true;
}
self.exit_critical();
if should_block {
// The C traces BEFORE it adds itself to the delayed list.
self.trace.note_exits(self.port.exits());
self.trace_task(caller, |task, name| Event::TaskNotifyTakeBlock {
task,
name,
index,
});
self.add_current_task_to_delayed_list(ticks, true)?;
}
let already_yielded = self.resume_all();
if should_block && !already_yielded {
if self.current == caller {
self.port_yield();
} else {
self.owe_yield(caller);
}
}
self.set_notify_blocked(caller, true);
return Ok(Wait::Blocked);
}
self.set_notify_blocked(caller, false);
self.enter_critical();
self.trace.note_exits(self.port.exits());
self.trace_task(caller, |task, name| Event::TaskNotifyTake {
task,
name,
index,
});
let value = self.notified_value_of(caller, index);
if let Ok(tcb) = self.tcbs.resolve_mut(caller) {
if value != 0 {
if let Some(slot) = tcb.notified.get_mut(index) {
// Guarded by `value != 0` above, so the saturation
// never fires; it is here because the workspace forbids
// bare arithmetic, and a decrement is exactly the place
// an unguarded one would wrap.
*slot = if clear_on_exit {
0
} else {
value.saturating_sub(1)
};
}
}
if let Some(slot) = tcb.notify_state.get_mut(index) {
*slot = NotifyState::NotWaiting;
}
}
self.exit_critical();
Ok(Wait::Ready(value))
}
/// `xTaskGetHandle`: the task registered under `name`.
///
/// # It is not free, and that is the point
///
/// The C walks every ready list, then the delayed lists, then the
/// suspended and waiting-termination lists, all inside
/// `vTaskSuspendAll` / `xTaskResumeAll` — and `xTaskResumeAll` takes a
/// critical section. So a lookup that emits **no trace event** still
/// costs **one critical-section exit**, which under the sim contract is
/// one unit of time.
///
/// That is why this exists rather than a scenario keeping the handle it
/// was given at creation. `AbortDelay`'s remake did exactly that, on the
/// reasoning that a lookup emitting no event could not change the trace,
/// and the corpus caught it: every event still agreed and the
/// exit column was one short at the first block.
///
/// The arena is searched instead of five lists, which cannot change the
/// answer — a live task is in exactly one of them — and does not change
/// the accounting either, because the cost is the suspend/resume pair.
///
/// # Errors
/// [`Error::Gone`] when no live task carries that name.
pub fn task_get_handle(&mut self, name: &str) -> Result<TaskHandle> {
self.suspend_all();
let mut found = None;
for index in 0..u16::try_from(self.tcbs.capacity()).unwrap_or(u16::MAX) {
let Some(handle) = self.tcbs.handle_at(index) else {
continue;
};
if self
.tcbs
.resolve(handle)
.is_ok_and(|tcb| tcb.name.as_str() == name)
{
found = Some(handle);
break;
}
}
let _ = self.resume_all();
found.ok_or(Error::Gone)
}
/// `xTaskGenericNotify`.
///
/// # Errors
/// [`Error::InvalidArgument`] for a bad index; [`Error::Gone`] for a
/// stale handle.
pub fn notify(
&mut self,
task: TaskHandle,
index: usize,
value: u32,
action: NotifyAction,
) -> Result<bool> {
if index >= C::NOTIFICATION_ARRAY_ENTRIES {
return Err(Error::InvalidArgument);
}
self.enter_critical();
let result = self.notify_locked(task, index, value, action, false);
self.exit_critical();
result.map(|(ok, _)| ok)
}
/// `xTaskGenericNotifyFromISR`: the same, without a critical section
/// that costs anything, and putting a woken task on the pending-ready
/// list when the scheduler is suspended.
///
/// # Errors
/// As [`Kernel::notify`].
pub fn notify_from_isr(
&mut self,
task: TaskHandle,
index: usize,
value: u32,
action: NotifyAction,
) -> Result<(bool, Woken)> {
if index >= C::NOTIFICATION_ARRAY_ENTRIES {
return Err(Error::InvalidArgument);
}
let mask = self.port.enter_critical_from_isr();
let result = self.notify_locked(task, index, value, action, true);
self.port.exit_critical_from_isr(mask);
result.map(|(ok, woken)| (ok, if woken { Woken::YES } else { Woken::NO }))
}
/// `xTaskGenericNotify` with its `pulPreviousNotificationValue`
/// out-parameter filled: `xTaskNotifyAndQuery`.
///
/// It exists because the answer has to come out of the SAME critical
/// section as the notification. Reading [`Kernel::notify_value`] first
/// and then notifying yields the same two numbers and costs a second
/// critical section -- and on the sim a critical-section exit is a
/// tick opportunity, so the extra one moves the tick and the trace
/// stops matching the C. `TaskNotify.c` calls this eleven times.
///
/// # Errors
/// As [`Kernel::notify`].
pub fn notify_and_query(
&mut self,
task: TaskHandle,
index: usize,
value: u32,
action: NotifyAction,
) -> Result<(bool, u32)> {
if index >= C::NOTIFICATION_ARRAY_ENTRIES {
return Err(Error::InvalidArgument);
}
self.enter_critical();
let previous = self
.tcbs
.resolve(task)
.map(|tcb| tcb.notified.get(index).copied().unwrap_or(0));
let result = self.notify_locked(task, index, value, action, false);
self.exit_critical();
Ok((result?.0, previous?))
}
/// `xTaskGenericNotifyAndQueryFromISR`.
///
/// # Errors
/// As [`Kernel::notify`].
pub fn notify_and_query_from_isr(
&mut self,
task: TaskHandle,
index: usize,
value: u32,
action: NotifyAction,
) -> Result<(bool, u32, Woken)> {
if index >= C::NOTIFICATION_ARRAY_ENTRIES {
return Err(Error::InvalidArgument);
}
let mask = self.port.enter_critical_from_isr();
let previous = self
.tcbs
.resolve(task)
.map(|tcb| tcb.notified.get(index).copied().unwrap_or(0));
let result = self.notify_locked(task, index, value, action, true);
self.port.exit_critical_from_isr(mask);
let (ok, woken) = result?;
Ok((ok, previous?, if woken { Woken::YES } else { Woken::NO }))
}
/// The body both notify paths share.
fn notify_locked(
&mut self,
task: TaskHandle,
index: usize,
value: u32,
action: NotifyAction,
from_isr: bool,
) -> Result<(bool, bool)> {
let original = self.notify_state_of(task, index);
let mut ok = true;
{
let tcb = self.tcbs.resolve_mut(task)?;
if let Some(slot) = tcb.notify_state.get_mut(index) {
*slot = NotifyState::Received;
}
if let Some(slot) = tcb.notified.get_mut(index) {
match action {
NotifyAction::SetBits => *slot |= value,
NotifyAction::Increment => *slot = slot.wrapping_add(1),
NotifyAction::Overwrite => *slot = value,
NotifyAction::NoOverwrite => {
if original == NotifyState::Received {
ok = false;
} else {
*slot = value;
}
}
NotifyAction::None => {}
}
}
}
// `traceTASK_NOTIFY` is hooked; `traceTASK_NOTIFY_FROM_ISR` is not,
// so an interrupt's notification says nothing on either side.
if !from_isr {
self.trace.note_exits(self.port.exits());
self.trace_task(task, |t, name| Event::TaskNotify {
task: t,
name,
index,
});
}
let mut woke_higher = false;
if original == NotifyState::Waiting {
let item = Self::state_item(task);
if from_isr && self.suspended_depth != 0 {
let _ = self.lists.remove(Self::event_item(task));
let value = self.lists.value(Self::event_item(task))?;
self.lists
.insert(Self::pending_ready_list(), Self::event_item(task), value)?;
} else {
if self.lists.container(item)?.is_some() {
let _ = self.lists.remove(item);
}
self.add_task_to_ready_list(task)?;
}
let woken = self.tcbs.resolve(task).map(|t| t.priority).unwrap_or(0);
if woken > self.current_priority() {
woke_higher = true;
if from_isr {
// The C sets `xYieldPendings[ 0 ]` here as well as
// reporting the wake through the caller's flag — so an
// interrupt that discards the flag still gets the
// switch, on the way out of `xTaskIncrementTick`. That
// is why the tick hook runs before the yield-pending
// test and not after it.
self.yield_pending = true;
} else {
// taskYIELD_ANY_CORE_IF_USING_PREEMPTION, inside the
// section.
self.port_yield();
}
}
}
Ok((ok, woke_higher))
}
/// `xTaskGenericNotifyStateClear`. `None` is the calling task.
///
/// # Errors
/// As [`Kernel::notify`].
pub fn notify_state_clear(&mut self, task: Option<TaskHandle>, index: usize) -> Result<bool> {
if index >= C::NOTIFICATION_ARRAY_ENTRIES {
return Err(Error::InvalidArgument);
}
let target = task.unwrap_or(self.current);
self.enter_critical();
let cleared = self.notify_state_of(target, index) == NotifyState::Received;
if cleared {
if let Ok(tcb) = self.tcbs.resolve_mut(target) {
if let Some(slot) = tcb.notify_state.get_mut(index) {
*slot = NotifyState::NotWaiting;
}
}
}
self.exit_critical();
Ok(cleared)
}
/// `ulNotifiedValue[ index ]` for a task. `None` is the calling task.
///
/// The C reaches this through `xTaskNotifyAndQuery`, which hands back
/// the value a notification is about to REPLACE, and through
/// `ulTaskNotifyValueClear`. Neither could be implemented without it:
/// `xTaskNotifyAndQuery` is `xTaskGenericNotify` with a
/// `pulPreviousNotificationValue` out-parameter, and `TaskNotify.c:373`
/// asserts on what comes back. The field existed; only the way to read
/// it was missing, which is the kind of gap a C ABI finds and a Rust
/// face never does.
///
/// # Errors
/// `InvalidArgument` if `index` is outside the notification array, or
/// the resolve error if the handle is stale.
pub fn notify_value(&mut self, task: Option<TaskHandle>, index: usize) -> Result<u32> {
if index >= C::NOTIFICATION_ARRAY_ENTRIES {
return Err(Error::InvalidArgument);
}
let target = task.unwrap_or(self.current);
self.enter_critical();
let value = self
.tcbs
.resolve(target)
.map(|tcb| tcb.notified.get(index).copied().unwrap_or(0));
self.exit_critical();
value
}
/// `ulTaskGenericNotifyValueClear`: clear `bits` in the task's
/// notification value and answer what it was BEFORE the clear.
///
/// # Errors
/// As [`Kernel::notify_value`].
pub fn notify_value_clear(
&mut self,
task: Option<TaskHandle>,
index: usize,
bits: u32,
) -> Result<u32> {
if index >= C::NOTIFICATION_ARRAY_ENTRIES {
return Err(Error::InvalidArgument);
}
let target = task.unwrap_or(self.current);
self.enter_critical();
let before = match self.tcbs.resolve_mut(target) {
Ok(tcb) => match tcb.notified.get_mut(index) {
Some(slot) => {
let was = *slot;
*slot &= !bits;
Ok(was)
}
None => Err(Error::InvalidArgument),
},
Err(e) => Err(e),
};
self.exit_critical();
before
}
/// Whether `task` is part-way through a notification wait — it blocked
/// once and has not yet run the half of `xTaskGenericNotifyWait` that
/// happens when a task wakes.
///
/// A caller that blocks on a notification needs this: the C's wait
/// returns *after* the wake, so its second half always runs, and a
/// stackless caller that decided not to block again would otherwise
/// skip it and leave the slot marked as received for ever.
#[must_use]
pub fn notify_wait_pending(&self, task: TaskHandle) -> bool {
self.notify_blocked(task)
}
/// Whether `task` has a stream-buffer call to resume, and the local it
/// left behind. Taking it clears the marker.
pub(crate) fn take_stream_resume(&mut self, task: TaskHandle) -> Option<usize> {
let tcb = self.tcbs.resolve_mut(task).ok()?;
if !tcb.stream_resume {
return None;
}
tcb.stream_resume = false;
Some(tcb.stream_local)
}
/// Remember where a preempted stream-buffer call has to start again.
pub(crate) fn set_stream_resume(&mut self, task: TaskHandle, local: usize) {
if let Ok(tcb) = self.tcbs.resolve_mut(task) {
tcb.stream_resume = true;
tcb.stream_local = local;
}
}
/// Whether `task` has a queue call to resume below its sampling exit.
/// Taking it clears the marker.
pub(crate) fn take_queue_resume(&mut self, task: TaskHandle) -> QueueResume {
let Ok(tcb) = self.tcbs.resolve_mut(task) else {
return QueueResume::No;
};
let resume = tcb.queue_resume;
tcb.queue_resume = QueueResume::No;
resume
}
/// Remember that a queue call was preempted at its sampling exit.
///
/// No local travels with it, unlike [`Kernel::set_stream_resume`]: the C
/// re-reads the queue under `prvLockQueue` on the other side of the
/// exit, so there is nothing sampled to carry.
pub(crate) fn set_queue_resume(&mut self, task: TaskHandle, at: QueueResume) {
if let Ok(tcb) = self.tcbs.resolve_mut(task) {
tcb.queue_resume = at;
}
}
/// Has this task's blocking send already paid for `vTaskSetTimeOutState`?
///
/// A one-shot, like [`Kernel::take_stream_resume`], and for the same
/// reason: `vTaskSetTimeOutState`'s own exit can release a tick and
/// switch the caller away, and the C's thread then resumes **below** it,
/// in the sampling loop. Running it again on re-entry would spend a
/// second exit the C never spends -- which is a sixteenth of a tick, and
/// `StreamBufferDemo`'s echo client hit it at tick 419.
pub(crate) fn take_stream_timed(&mut self, task: TaskHandle) -> bool {
let Ok(tcb) = self.tcbs.resolve_mut(task) else {
return false;
};
let was = tcb.stream_timed;
tcb.stream_timed = false;
was
}
/// Remember that the timeout state is set and must not be set again.
pub(crate) fn set_stream_timed(&mut self, task: TaskHandle) {
if let Ok(tcb) = self.tcbs.resolve_mut(task) {
tcb.stream_timed = true;
}
}
/// Has this task's stream-buffer call already finished its wait?
///
/// The other half of [`Kernel::take_stream_resume`]. A call can be
/// preempted at two different exits, and the two resume in different
/// places: at the SAMPLING exit the C goes on to block, and at the
/// WAIT's own exit it goes on to move the bytes and trace them. Without
/// this the second case is indistinguishable from the first, and a call
/// that had already waited would wait again.
pub(crate) fn take_stream_waited(&mut self, task: TaskHandle) -> bool {
let Ok(tcb) = self.tcbs.resolve_mut(task) else {
return false;
};
let was = tcb.stream_waited;
tcb.stream_waited = false;
was
}
/// Remember that the wait is done and only the transfer is left.
pub(crate) fn set_stream_waited(&mut self, task: TaskHandle) {
if let Ok(tcb) = self.tcbs.resolve_mut(task) {
tcb.stream_waited = true;
}
}
fn notify_blocked(&self, task: TaskHandle) -> bool {
self.tcbs
.resolve(task)
.map(|t| t.notify_blocked)
.unwrap_or(false)
}
fn set_notify_blocked(&mut self, task: TaskHandle, blocked: bool) {
if let Ok(tcb) = self.tcbs.resolve_mut(task) {
tcb.notify_blocked = blocked;
}
}
fn notify_state_of(&self, task: TaskHandle, index: usize) -> NotifyState {
self.tcbs
.resolve(task)
.ok()
.and_then(|t| t.notify_state.get(index).copied())
.unwrap_or(NotifyState::NotWaiting)
}
fn notified_value_of(&self, task: TaskHandle, index: usize) -> u32 {
self.tcbs
.resolve(task)
.ok()
.and_then(|t| t.notified.get(index).copied())
.unwrap_or(0)
}
/// `xTaskGetTickCountFromISR`.
///
/// No critical section, exactly as `xTaskGetTickCount` takes none: the
/// Posix port sets `portTICK_TYPE_IS_ATOMIC`, so reading the count is
/// a single load on both sides and costs no sim time.
#[must_use]
pub const fn tick_count_from_isr(&self) -> u64 {
self.tick
}
/// `vTaskMissedYield`: a yield that could not be taken where it was
/// asked for — because a task is walking an event list, or because the
/// scheduler is suspended — and must happen on the way out instead.
pub(crate) fn missed_yield(&mut self) {
self.yield_pending = true;
}
/// `vApplicationTickHook()`, when `configUSE_TICK_HOOK` is 1.
///
/// The hook is copied out, run, and the result stored: that is what
/// lets it borrow the kernel mutably while the kernel owns it. A hook
/// that reads the kernel's own copy of itself therefore sees the value
/// from before this call.
fn run_tick_hook(&mut self) {
if !C::USE_TICK_HOOK {
return;
}
let hook = self.tick_hook;
self.tick_hook = hook.tick(self);
}
/// The tick hook, as it now stands.
///
/// A scenario's `xAre...StillRunning()` reads the status its interrupt
/// half latched, so the owner of the kernel needs to see it.
pub const fn tick_hook(&self) -> &H {
&self.tick_hook
}
/// The tick hook, to install or reset one after construction.
pub const fn tick_hook_mut(&mut self) -> &mut H {
&mut self.tick_hook
}
/// The wake loop inside `xTaskIncrementTick`.
// Out of line: this walks the delayed list and runs only when a tick
// reaches the next unblock time, but `increment_tick` runs on EVERY tick
// and was carrying a frame sized for the walk regardless.
#[inline(never)]
fn wake_due_tasks(&mut self, now: u64) -> bool {
let mut switch_required = false;
// Hoisted: see the note at the bottom of the loop.
let running = if C::USE_PREEMPTION {
self.current_priority()
} else {
0
};
loop {
let delayed = self.delayed_list();
if self.lists.is_empty(delayed) != Ok(false) {
self.next_unblock_time = Self::MAX_DELAY;
return switch_required;
}
let Ok(Some(item)) = self.lists.head(delayed) else {
self.next_unblock_time = Self::MAX_DELAY;
return switch_required;
};
let Ok(wake_at) = self.lists.value(item) else {
return switch_required;
};
if now < wake_at {
self.next_unblock_time = wake_at;
return switch_required;
}
let Ok(task) = self.task_of_state_item(item) else {
return switch_required;
};
let _ = self.lists.remove(item);
if self
.lists
.container(Self::event_item(task))
.unwrap_or(None)
.is_some()
{
let _ = self.lists.remove(Self::event_item(task));
}
if self.add_task_to_ready_list(task).is_err() {
return switch_required;
}
// `!switch_required` FIRST, and the running priority read once
// for the whole drain.
//
// Both of these cost a TCB resolve -- a generation check, a
// bounds check and an `Option` -- and this loop runs once per
// task the tick wakes. `self.current` cannot move while the
// drain is running (nothing here switches), so the running
// priority is a loop invariant that was being re-derived on
// every lap. And once a switch is already required, asking again
// can only set a `true` to `true`, which is not worth the
// resolve it costs -- the same reasoning `increment_tick`
// already applies one level up.
if C::USE_PREEMPTION && !switch_required {
let woken = self.tcbs.resolve(task).map(|t| t.priority).unwrap_or(0);
if woken > running {
switch_required = true;
}
}
}
}
/// `taskSWITCH_DELAYED_LISTS()`.
// Out of line for the same reason: the overflow swap happens when the
// tick count wraps, which is once in a very long while.
#[inline(never)]
fn switch_delayed_lists(&mut self) {
self.delayed_swapped = !self.delayed_swapped;
self.overflows = self.overflows.wrapping_add(1);
self.reset_next_task_unblock_time();
}
/// `prvResetNextTaskUnblockTime`.
fn reset_next_task_unblock_time(&mut self) {
let delayed = self.delayed_list();
self.next_unblock_time = self.lists.head_value(delayed).unwrap_or(Self::MAX_DELAY);
}
// ------------------------------------------------------------- delay --
/// `vTaskDelay`.
///
/// # Errors
/// A list error surfaces as itself.
pub fn delay(&mut self, ticks: u64) -> Result<()> {
let caller = self.current;
let mut already_yielded = false;
if ticks > 0 {
self.suspend_all();
{
let current = self.current;
self.trace_task(current, |task, name| Event::TaskDelay { task, name, ticks });
self.add_current_task_to_delayed_list(ticks, false)?;
}
already_yielded = self.resume_all();
}
// taskYIELD_WITHIN_API(), outside any critical section — unless a
// tick switched us out somewhere above, in which case this line is
// on a stack that is not running, and runs when the task does.
if !already_yielded {
if self.current == caller {
self.port_yield();
} else {
self.owe_yield(caller);
}
}
Ok(())
}
/// `xTaskAbortDelay`: pull a task out of the Blocked state early.
///
/// `true` is `pdPASS` — the task really was blocked and is now ready.
/// A task that was not blocked is left alone and `false` comes back,
/// which is the C's `pdFAIL`.
///
/// The shape matters as much as the effect: the whole thing runs with
/// the scheduler suspended, the event list is touched inside a critical
/// section of its own because an interrupt can reach it, and a yield
/// that the higher priority of the woken task calls for is *pended*
/// rather than taken, so it happens on the way out of `xTaskResumeAll`.
///
/// # Errors
/// [`Error::Gone`] for a stale handle.
pub fn abort_delay(&mut self, task: TaskHandle) -> Result<bool> {
if !self.tcbs.contains(task) {
return Err(Error::Gone);
}
self.suspend_all();
// eTaskGetState: a critical section of its own on any task but the
// running one, and the running one is never Blocked.
let blocked = self.task_state_get(task)? == TaskState::Blocked;
if !blocked {
let _ = self.resume_all();
return Ok(false);
}
let item = Self::state_item(task);
// `remove` is its own guard, as above.
let _ = self.lists.remove(item);
self.enter_critical();
{
let event = Self::event_item(task);
// `remove` answers `NotActive` when the item is in no list, so
// it is its own guard -- and `is_ok` is exactly "something was
// removed", which is what the flag below depends on.
if self.lists.remove(event).is_ok() {
if let Some(flag) = self.delay_aborted.get_mut(usize::from(task.index())) {
*flag = true;
}
}
}
self.exit_critical();
self.add_task_to_ready_list(task)?;
// configUSE_PREEMPTION, one core: pend the yield rather than take
// it, so it lands where `xTaskResumeAll` puts it.
let woken = self.tcbs.resolve(task).map(|t| t.priority).unwrap_or(0);
if woken > self.current_priority() {
self.yield_pending = true;
}
let _ = self.resume_all();
Ok(true)
}
/// `prvAddCurrentTaskToDelayedList`.
pub(crate) fn add_current_task_to_delayed_list(
&mut self,
ticks: u64,
can_block_indefinitely: bool,
) -> Result<()> {
let now = self.tick;
let current = self.current;
// About to enter a delayed list, so the abort flag is cleared here
// and can only be seen set by a task that really was aborted.
if let Some(flag) = self.delay_aborted.get_mut(usize::from(current.index())) {
*flag = false;
}
let item = Self::state_item(current);
// `uxListRemove` already answers `NotActive` for an item that is
// in no list, and both it and the container test are one read of
// the same node — so asking first was reading it twice. This is
// the running task's state item, so it is in the ready list and
// the test passed anyway.
let _ = self.lists.remove(item);
if ticks == Self::MAX_DELAY && can_block_indefinitely {
self.lists.insert_end(Self::suspended_list(), item)?;
return Ok(());
}
let wake_at = now.wrapping_add(ticks) & Self::MAX_DELAY;
// `vListInsert` sets the item's value from the one it sorts by, so
// both arms below write `wake_at` themselves. Setting it here as
// well was a second lookup of the same item to store the same
// number into it.
if wake_at < now {
self.trace_task(current, |task, name| {
Event::MovedTaskToOverflowDelayedList { task, name }
});
let list = self.overflow_delayed_list();
self.lists.insert(list, item, wake_at)?;
} else {
self.trace_task(current, |task, name| Event::MovedTaskToDelayedList {
task,
name,
});
let list = self.delayed_list();
// ---- append, when the wake time says we may ------------------
//
// `vListInsert` walks from the head until it finds a larger
// value, so a delayed list `n` deep costs `n` steps -- and this
// function is the single largest consumer of the blocking
// workload, most of it that walk.
//
// The walk is almost always finding the same answer: the END.
// `wake_at` is `now + ticks` and `now` only increases, so tasks
// blocking with comparable timeouts produce ASCENDING wake times
// and belong after everything already there.
//
// `insert_sorted` takes that shortcut, and it asks this caller
// for exactly ONE thing: that the list is already sorted. The
// delayed list is, because it is only ever built by sorted
// inserts and by this append -- so its last item carries its
// largest value.
//
// The other two promises this call site used to make are gone
// into the list, where they are written once instead of at
// every future call site: the `>=` tie rule, and the fact that
// `insert_end` only appends while the cursor is at the marker.
// Both were silent when wrong. See `ListsOf::insert_sorted`,
// and `ListsOf::is_sorted` for checking the one that is left.
self.lists.insert_sorted(list, item, wake_at)?;
if wake_at < self.next_unblock_time {
self.next_unblock_time = wake_at;
}
}
Ok(())
}
// --------------------------------------------------- suspend / resume --
/// `vTaskSuspend`. `None` suspends the calling task.
///
/// # Errors
/// [`Error::Gone`] for a stale handle.
pub fn suspend(&mut self, task: Option<TaskHandle>) -> Result<()> {
let caller = self.current;
let target = task.unwrap_or(caller);
self.enter_critical();
{
if !self.tcbs.contains(target) {
self.exit_critical();
return Err(Error::Gone);
}
self.trace_task(target, |task, name| Event::TaskSuspend { task, name });
let item = Self::state_item(target);
// `remove` is its own guard: it answers `NotActive` for an item
// in no list, and the result was discarded either way.
let _ = self.lists.remove(item);
let event = Self::event_item(target);
if self.lists.container(event)?.is_some() {
let _ = self.lists.remove(event);
}
self.lists.insert_end(Self::suspended_list(), item)?;
// `vTaskSuspend`, `tasks.c`:
//
// ```c
// if( pxTCB->ucNotifyState[ x ] == taskWAITING_NOTIFICATION )
// {
// /* The task was blocked to wait for a notification, but
// * is now suspended, so no notification was received. */
// pxTCB->ucNotifyState[ x ] = taskNOT_WAITING_NOTIFICATION;
// }
// ```
//
// Not tidying: `eTaskGetState` calls a task on the suspended
// list BLOCKED rather than SUSPENDED if any of its notification
// slots is still waiting, so leaving the flag set makes a
// suspended task report as blocked for ever.
// `TaskNotify.c:498` asserts exactly that, in a timer callback
// that suspends a task which is waiting for a notification --
// and a task that reports the wrong state there is a task the
// rest of that test never resumes correctly.
if let Ok(tcb) = self.tcbs.resolve_mut(target) {
for slot in &mut tcb.notify_state {
if *slot == NotifyState::Waiting {
*slot = NotifyState::NotWaiting;
}
}
}
}
self.exit_critical();
// A second, separate critical section — two outermost exits, which
// is what the C does and therefore what the tick count depends on.
if self.running {
self.enter_critical();
self.reset_next_task_unblock_time();
self.exit_critical();
}
if target == caller {
if self.running {
// portYIELD_WITHIN_API(), outside the section.
if self.current == caller {
self.port_yield();
} else {
self.owe_yield(caller);
}
} else if self.lists.len(Self::suspended_list()).unwrap_or(0) != self.task_count {
self.switch_context();
}
}
Ok(())
}
/// `vTaskResume`.
///
/// # Errors
/// [`Error::Gone`] for a stale handle.
pub fn resume(&mut self, task: TaskHandle) -> Result<()> {
if task == self.current || task.is_null() {
return Ok(());
}
if !self.tcbs.contains(task) {
return Err(Error::Gone);
}
self.enter_critical();
{
if self.task_is_suspended(task)? {
self.trace_task(task, |task, name| Event::TaskResume { task, name });
let _ = self.lists.remove(Self::state_item(task));
self.add_task_to_ready_list(task)?;
// taskYIELD_ANY_CORE_IF_USING_PREEMPTION: inside the
// section, and only when the resumed task outranks the
// running one.
let resumed = self.tcbs.resolve(task)?.priority;
if C::USE_PREEMPTION && self.current_priority() < resumed {
self.port_yield();
}
}
}
self.exit_critical();
Ok(())
}
/// `prvTaskIsTaskSuspended`: on the suspended list, not on the pending
/// ready list, and not waiting on an event.
fn task_is_suspended(&self, task: TaskHandle) -> Result<bool> {
if self.lists.container(Self::state_item(task))? != Some(Self::suspended_list()) {
return Ok(false);
}
let event_list = self.lists.container(Self::event_item(task))?;
if event_list == Some(Self::pending_ready_list()) {
return Ok(false);
}
Ok(event_list.is_none())
}
// -------------------------------------------------------- priorities --
/// `vTaskDelete`. `None` deletes the calling task.
///
/// # Two paths, and the C picks between them for a reason
///
/// Deleting *another* task frees its TCB on the spot. Deleting the
/// **running** task cannot: the caller is still executing out of it. The
/// C parks such a task on `xTasksWaitingTermination` and lets the idle
/// task reclaim it, which is what `prvCheckTasksWaitingTermination` is
/// for — so [`Kernel::check_tasks_waiting_termination`] is where the
/// deferred half lands here, called from the idle body at the same point
/// in the same loop.
///
/// # The frees are outside the critical section, and they cost exits
///
/// `prvDeleteTCB` runs **after** `taskEXIT_CRITICAL()` and frees twice —
/// `vPortFreeStack( pxStack )` then `vPortFree( pxTCB )`. On the oracle's
/// heap every free suspends the scheduler, so a delete is one exit for
/// its own section plus two for the frees, in that order. Folding the
/// frees into the section, or forgetting them, moves every later tick.
///
/// # Errors
/// [`Error::Gone`] for a stale handle.
pub fn task_delete(&mut self, task: Option<TaskHandle>) -> Result<()> {
// `prvGetTCBFromHandle`: NULL is the calling task.
let target = task.unwrap_or(self.current);
self.tcbs.resolve(target)?;
self.enter_critical();
// `uxListRemove( &( pxTCB->xStateListItem ) )`. The C follows this
// with `taskRESET_READY_PRIORITY`, which is an EMPTY MACRO under the
// oracle's `configUSE_PORT_OPTIMISED_TASK_SELECTION 0` — there is no
// priority bitmap to clear, and `vTaskSwitchContext` rediscovers the
// top priority by walking down. Nothing to model.
let state = Self::state_item(target);
if matches!(self.lists.container(state), Ok(Some(_))) {
let _ = self.lists.remove(state);
}
// `if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )`
// — a task blocked on a queue is on two lists, and both must let go.
let event = Self::event_item(target);
if matches!(self.lists.container(event), Ok(Some(_))) {
let _ = self.lists.remove(event);
}
// `uxTaskNumber++` is not modelled: it exists so kernel-aware
// debuggers can tell the task lists changed, and nothing the trace
// records reads it.
// `xSchedulerRunning != pdFALSE && taskTASK_IS_RUNNING_OR_SCHEDULED_
// _TO_YIELD( pxTCB )`, which at `configNUMBER_OF_CORES 1` is exactly
// `pxTCB == pxCurrentTCB`.
let defer = self.running && target == self.current;
if defer {
// `vListInsertEnd( &xTasksWaitingTermination, ... )` and
// `++uxDeletedTasksWaitingCleanUp`. The count is NOT decremented
// here — the idle task does that when it reaps.
self.awaiting_reap = Some(target);
self.trace_task(target, |task, name| Event::TaskDelete { task, name });
} else {
self.task_count = self.task_count.saturating_sub(1);
self.trace_task(target, |task, name| Event::TaskDelete { task, name });
self.reset_next_task_unblock_time();
}
self.exit_critical();
// `if( xDeleteTCBInIdleTask != pdTRUE ) { prvDeleteTCB( pxTCB ); }`,
// outside the section.
if !defer {
self.delete_tcb(target);
}
// `taskYIELD_WITHIN_API()`. The C guards this with
// `xSchedulerRunning && pxTCB == pxCurrentTCB`, which is the same
// condition that chose the deferred path.
if defer {
self.port_yield();
}
Ok(())
}
/// `prvDeleteTCB`: two frees, and on the oracle's heap each one suspends
/// the scheduler, so each is one outermost exit.
fn delete_tcb(&mut self, task: TaskHandle) {
// `vPortFreeStack( pxTCB->pxStack )`.
self.account_for_allocation();
// `vPortFree( pxTCB )`.
self.account_for_allocation();
let _ = self.tcbs.remove(task);
// The index is now free for reuse, so mark the task UNSTARTED.
//
// The C frees the TCB and a later `xTaskCreate` gets fresh memory,
// so a new task cannot inherit anything. Our arena hands back the
// same index, and the per-index bookkeeping — owed exits, an owed
// yield, an owed trace line — is keyed on that index, not on the
// TCB. Without this a task deleted while it still owed the tail of
// a call bequeaths that debt to its successor, and the successor
// pays an exit it never incurred: exactly how `death`'s second
// cycle first diverged, one exit early, 1,100 lines after the first
// cycle had matched perfectly.
//
// Clearing this ONE flag is the whole fix, and deliberately so.
// `hand_over` already empties all three of those on a task's first
// switch-in, and a reused index is a first switch-in again. Zeroing
// them here as well would work and would be worse: two places that
// must agree about what a fresh task owes, and a gate that cannot
// catch either one being dropped because the other still covers it.
if let Some(slot) = self.started.get_mut(usize::from(task.index())) {
*slot = false;
}
}
/// `prvCheckTasksWaitingTermination`, called from the idle task.
///
/// # This must cost NOTHING when nothing is pending
///
/// The C's body is `while( uxDeletedTasksWaitingCleanUp > 0 )`, so an
/// idle loop with no deleted task takes no critical section and pays no
/// exit. That is what lets this be wired into the idle body without
/// disturbing a single scenario in the corpus — and it is the property
/// the corpus is checking when it stays byte-identical.
///
/// At most one task can be pending: only the *running* task defers, and
/// it yields before it can return, so a second deferred delete cannot
/// happen until this has run.
pub fn check_tasks_waiting_termination(&mut self) {
let Some(task) = self.awaiting_reap else {
return;
};
// The C takes the section per reaped task, decrements both counts
// inside it, and calls `prvDeleteTCB` outside.
self.enter_critical();
self.awaiting_reap = None;
self.task_count = self.task_count.saturating_sub(1);
self.exit_critical();
self.delete_tcb(task);
}
/// `vTaskPrioritySet`. `None` is the calling task. /// `vTaskPrioritySet`. `None` is the calling task.
///
/// # Errors
/// [`Error::Gone`] for a stale handle.
pub fn set_priority(&mut self, task: Option<TaskHandle>, new_priority: u8) -> Result<()> {
let new_priority = new_priority.min(C::MAX_PRIORITIES.saturating_sub(1));
let target = task.unwrap_or(self.current);
let mut yield_required = false;
self.enter_critical();
{
if !self.tcbs.contains(target) {
self.exit_critical();
return Err(Error::Gone);
}
self.trace_task(target, |task, name| Event::TaskPrioritySet {
task,
name,
priority: Self::priority_value(new_priority),
});
let base = self.tcbs.resolve(target)?.base_priority;
if base != new_priority {
if new_priority > base {
if target != self.current && new_priority > self.current_priority() {
yield_required = true;
}
} else if target == self.current {
yield_required = true;
}
let used_on_entry = self.tcbs.resolve(target)?.priority;
{
let tcb = self.tcbs.resolve_mut(target)?;
if tcb.base_priority == tcb.priority || new_priority > tcb.priority {
tcb.priority = new_priority;
}
tcb.base_priority = new_priority;
}
let event_value = u64::from(C::MAX_PRIORITIES.saturating_sub(new_priority));
self.lists
.set_value(Self::event_item(target), event_value)?;
let item = Self::state_item(target);
if self.lists.container(item)? == Some(Self::ready_list(used_on_entry)) {
let _ = self.lists.remove(item);
self.add_task_to_ready_list(target)?;
}
// taskYIELD_TASK_CORE_IF_USING_PREEMPTION: inside the
// section.
if yield_required && C::USE_PREEMPTION {
self.port_yield();
}
}
}
self.exit_critical();
Ok(())
}
// ------------------------------------------------- scheduler suspend --
/// `vTaskSuspendAll`.
pub fn suspend_all(&mut self) {
self.suspended_depth = self.suspended_depth.wrapping_add(1);
}
/// Move everything an ISR readied onto the ready lists.
///
/// Out of line because it is the rare half of [`Kernel::resume_all`]: the
/// pending list is empty on essentially every call, and inlining this made
/// every one of those calls carry a frame sized for the walk.
#[inline(never)]
fn drain_pending_ready(&mut self) {
let mut moved_any = false;
while self.lists.is_empty(Self::pending_ready_list()) == Ok(false) {
let Ok(Some(item)) = self.lists.head(Self::pending_ready_list()) else {
break;
};
let Ok(task) = self.task_of_event_item(item) else {
break;
};
let _ = self.lists.remove(Self::event_item(task));
let _ = self.lists.remove(Self::state_item(task));
if self.add_task_to_ready_list(task).is_err() {
break;
}
moved_any = true;
let woken = self.tcbs.resolve(task).map(|t| t.priority).unwrap_or(0);
if woken > self.current_priority() {
self.yield_pending = true;
}
}
if moved_any {
self.reset_next_task_unblock_time();
}
}
/// Run the ticks that landed while the scheduler was suspended.
///
/// Out of line for the same reason as its sibling: `pended_ticks` is zero
/// on essentially every call.
#[inline(never)]
fn unwind_pended_ticks(&mut self) {
let mut pended = self.pended_ticks;
while pended > 0 {
if self.increment_tick() {
self.yield_pending = true;
}
pended = pended.saturating_sub(1);
}
self.pended_ticks = 0;
}
/// `xTaskResumeAll`; `true` when it yielded on the caller's behalf.
#[inline(always)]
pub fn resume_all(&mut self) -> bool {
let mut already_yielded = false;
self.enter_critical();
{
self.suspended_depth = self.suspended_depth.saturating_sub(1);
if self.suspended_depth == 0 && self.task_count > 0 {
if self.lists.is_empty(Self::pending_ready_list()) == Ok(false) {
self.drain_pending_ready();
}
if self.pended_ticks > 0 {
self.unwind_pended_ticks();
}
if self.yield_pending {
if C::USE_PREEMPTION {
already_yielded = true;
}
// taskYIELD_TASK_CORE_IF_USING_PREEMPTION: inside the
// section.
self.port_yield();
}
}
}
self.exit_critical();
already_yielded
}
// ------------------------------------------- the blocking-call frame --
/// Start (or continue) a blocking call's `for(;;)`.
///
/// The first pass records the block time and the entry timestamp, the
/// way `xEntryTimeSet` / `vTaskInternalSetTimeOutState` do; later
/// passes leave the running total alone, because the `ticks` the caller
/// passes is the original block time and the kernel is holding what is
/// left of it.
pub(crate) fn begin_wait(
&mut self,
task: TaskHandle,
queue: QueueHandle,
ticks: u64,
) -> Result<()> {
let tick = self.tick;
let overflows = self.overflows;
let Ok(tcb) = self.tcbs.resolve_mut(task) else {
// A queue call made before the scheduler started, from what the
// C would call `main()`: there is no task to keep a frame for,
// and such a call never blocks — `xSemaphoreGive` on a fresh
// semaphore is the usual one.
return Ok(());
};
if tcb.wait.queue != queue || !tcb.wait.entry_set {
tcb.wait = WaitFrame {
queue,
ticks,
entering: tick,
overflows,
entry_set: true,
inherited: false,
};
}
// The frame is set either way on this path -- either it was written
// just now, or it was already this queue's.
if let Some(flag) = self.wait_set.get_mut(usize::from(task.index())) {
*flag = true;
}
Ok(())
}
/// The call finished, one way or the other.
pub(crate) fn end_wait(&mut self, task: TaskHandle) {
// Almost every call arrives with no frame to clear, and the mirror
// says so in one byte where resolving the TCB to read `entry_set`
// cost an arena lookup. Out of range reads as SET, so an impossible
// index still takes the slow path below.
let at = usize::from(task.index());
if !self.wait_set.get(at).copied().unwrap_or(true) {
return;
}
if let Some(flag) = self.wait_set.get_mut(at) {
*flag = false;
}
if let Ok(tcb) = self.tcbs.resolve_mut(task) {
// Now that the frame is only set on the path that blocks, most
// calls reach here with nothing to clear, and this was writing
// a default frame over a default frame. `entry_set` is the
// sentinel the C calls `xEntryTimeSet`, and it is the first
// thing set — `inherited` is only reached far inside the
// blocking path, so it cannot be true while this is false.
if tcb.wait.entry_set {
tcb.wait = WaitFrame::default();
}
}
}
/// `xTicksToWait` as it now stands.
pub(crate) fn remaining_ticks(&self, task: TaskHandle) -> u64 {
self.tcbs.resolve(task).map(|t| t.wait.ticks).unwrap_or(0)
}
/// `xInheritanceOccurred`.
pub(crate) fn wait_inherited(&self, task: TaskHandle) -> bool {
self.tcbs
.resolve(task)
.map(|t| t.wait.inherited)
.unwrap_or(false)
}
pub(crate) fn set_wait_inherited(&mut self, task: TaskHandle) {
if let Ok(tcb) = self.tcbs.resolve_mut(task) {
tcb.wait.inherited = true;
}
}
/// `xTaskCheckForTimeOut`: `true` when the block time has run out.
/// Takes a critical section, as the C does, and charges the elapsed
/// time against what is left.
pub(crate) fn check_for_timeout(&mut self, task: TaskHandle) -> bool {
self.enter_critical();
// An aborted delay is not the same as a time out, but it has the
// same result: stop waiting.
if self.delay_aborted.get(usize::from(task.index())).copied() == Some(true) {
if let Some(flag) = self.delay_aborted.get_mut(usize::from(task.index())) {
*flag = false;
}
self.exit_critical();
return true;
}
let now = self.tick;
let overflows = self.overflows;
let result = match self.tcbs.resolve_mut(task) {
Ok(tcb) => {
let elapsed = now.wrapping_sub(tcb.wait.entering) & Self::MAX_DELAY;
if tcb.wait.ticks == Self::MAX_DELAY {
// An indefinite block never times out.
false
} else if overflows != tcb.wait.overflows && now >= tcb.wait.entering {
tcb.wait.ticks = 0;
true
} else if elapsed < tcb.wait.ticks {
tcb.wait.ticks = tcb.wait.ticks.saturating_sub(elapsed);
tcb.wait.entering = now;
tcb.wait.overflows = overflows;
false
} else {
tcb.wait.ticks = 0;
true
}
}
Err(_) => true,
};
self.exit_critical();
result
}
/// `vTaskPlaceOnUnorderedEventList`: the item value carries the
/// condition rather than the priority, so the item goes on the end and
/// the list is never sorted.
///
/// `taskEVENT_LIST_ITEM_VALUE_IN_USE` is not set here the way the C
/// sets it. The C needs it because the same `ListItem_t` is a
/// priority-ordered event item the rest of the time and the flag says
/// which; the value is only ever read back by the event-group code,
/// which masks the control byte off, so setting it would change
/// nothing but the arithmetic in the doc comment.
pub(crate) fn place_on_unordered_event_list(
&mut self,
list: ListId,
value: u64,
ticks: u64,
) -> Result<()> {
let item = Self::event_item(self.current);
self.lists.set_value(item, value)?;
self.lists.insert_end(list, item)?;
self.add_current_task_to_delayed_list(ticks, true)
}
/// `vTaskRemoveFromUnorderedEventList`: write the answer into the item
/// value, then wake the task.
///
/// Unlike `xTaskRemoveFromEventList` this always goes straight to the
/// ready list. It is only ever called with the scheduler suspended —
/// `xEventGroupSetBits` holds it across the whole walk — and the C
/// still bypasses the pending-ready list, because the value it just
/// wrote is the task's return value and a second pass would overwrite
/// it.
pub(crate) fn remove_from_unordered_event_list(
&mut self,
item: ItemId,
value: u64,
) -> Result<()> {
self.lists.set_value(item, value)?;
let task = self.task_of_event_item(item)?;
let _ = self.lists.remove(item);
let _ = self.lists.remove(Self::state_item(task));
self.add_task_to_ready_list(task)?;
if self.tcbs.resolve(task)?.priority > self.current_priority() {
self.yield_pending = true;
}
Ok(())
}
/// `uxTaskResetEventItemValue`: read the answer the unblocker left, and
/// put the item back to the priority order an ordinary event list wants.
pub(crate) fn reset_event_item_value(&mut self, task: TaskHandle) -> Result<u64> {
let item = Self::event_item(task);
let value = self.lists.value(item)?;
let priority = self.tcbs.resolve(task)?.priority;
self.lists
.set_value(item, u64::from(C::MAX_PRIORITIES.saturating_sub(priority)))?;
Ok(value)
}
/// Whether `task` is resuming an event-group wait rather than starting
/// one. Taking it clears the marker.
pub(crate) fn take_event_resume(&mut self, task: TaskHandle) -> bool {
match self.tcbs.resolve_mut(task) {
Ok(tcb) if tcb.event_blocked => {
tcb.event_blocked = false;
true
}
_ => false,
}
}
/// Mark that `task` blocked inside an event-group wait, so the call it
/// is inside resumes rather than restarts.
pub(crate) fn set_event_resume(&mut self, task: TaskHandle) {
if let Ok(tcb) = self.tcbs.resolve_mut(task) {
tcb.event_blocked = true;
}
}
/// `vTaskPlaceOnEventList`: sorted by priority, then blocked.
pub(crate) fn place_on_event_list(&mut self, list: ListId, ticks: u64) -> Result<()> {
let current = self.current;
let item = Self::event_item(current);
// The item keeps the value its call set; reading it out only to
// hand it back made the list read the item twice and write it once
// for no change.
self.lists.insert_keeping_value(list, item)?;
self.add_current_task_to_delayed_list(ticks, true)
}
/// Take the trailing `portYIELD()` now, or owe it if a tick already
/// switched us out of this call.
pub(crate) fn yield_or_owe(&mut self, caller: TaskHandle) {
if self.current == caller {
self.port_yield();
} else {
self.owe_yield(caller);
}
}
/// `pvTaskIncrementMutexHeldCount`.
pub(crate) fn increment_mutexes_held(&mut self, task: TaskHandle) {
if let Ok(tcb) = self.tcbs.resolve_mut(task) {
tcb.mutexes_held = tcb.mutexes_held.wrapping_add(1);
}
}
// ------------------------------------------------ priority inheritance --
/// `xTaskPriorityInherit`: lift the mutex holder to the waiter's
/// priority. `true` when the holder is (or already was) lifted, which
/// is what the waiter remembers so it can undo it on a timeout.
pub(crate) fn priority_inherit(&mut self, holder: TaskHandle) -> Result<bool> {
if holder.is_null() || !self.tcbs.contains(holder) {
return Ok(false);
}
let waiter_priority = self.current_priority();
let (holder_priority, holder_base) = {
let tcb = self.tcbs.resolve(holder)?;
(tcb.priority, tcb.base_priority)
};
if holder_priority >= waiter_priority {
// Already at least as urgent; the waiter still records that the
// holder is running above its base, if it is.
return Ok(holder_base < waiter_priority);
}
let event_value = u64::from(C::MAX_PRIORITIES.saturating_sub(waiter_priority));
self.lists
.set_value(Self::event_item(holder), event_value)?;
let item = Self::state_item(holder);
if self.lists.container(item)? == Some(Self::ready_list(holder_priority)) {
let _ = self.lists.remove(item);
self.tcbs.resolve_mut(holder)?.priority = waiter_priority;
self.add_task_to_ready_list(holder)?;
} else {
self.tcbs.resolve_mut(holder)?.priority = waiter_priority;
}
self.trace_task(holder, |task, name| Event::TaskPriorityInherit {
task,
name,
priority: Self::priority_value(waiter_priority),
});
Ok(true)
}
/// `xTaskPriorityDisinherit`: giving the mutex back drops the
/// inherited priority. `true` when a yield is wanted.
pub(crate) fn priority_disinherit(&mut self, holder: TaskHandle) -> Result<bool> {
if holder.is_null() {
return Ok(false);
}
// One lookup where there were three: `contains` asked the arena
// whether the holder is there, `resolve` asked again to read its
// three fields, and `resolve_mut` asked a third time to put one back
// -- with nothing but a subtraction in between. A holder the arena
// does not have still answers `Ok(false)`, which is what `contains`
// was for.
let (priority, base, remaining) = match self.tcbs.resolve_mut(holder) {
Ok(tcb) => {
let remaining = tcb.mutexes_held.saturating_sub(1);
tcb.mutexes_held = remaining;
(tcb.priority, tcb.base_priority, remaining)
}
Err(_) => return Ok(false),
};
if priority == base || remaining != 0 {
return Ok(false);
}
let item = Self::state_item(holder);
if self.lists.remove(item).is_err() {
return Ok(false);
}
self.trace_task(holder, |task, name| Event::TaskPriorityDisinherit {
task,
name,
priority: Self::priority_value(base),
});
{
let tcb = self.tcbs.resolve_mut(holder)?;
tcb.priority = base;
}
let event_value = u64::from(C::MAX_PRIORITIES.saturating_sub(base));
self.lists
.set_value(Self::event_item(holder), event_value)?;
self.add_task_to_ready_list(holder)?;
Ok(true)
}
/// `vTaskPriorityDisinheritAfterTimeout`: a waiter gave up, so the
/// holder keeps only what the tasks still waiting justify.
pub(crate) fn priority_disinherit_after_timeout(
&mut self,
holder: TaskHandle,
highest_waiting: u8,
) -> Result<()> {
if holder.is_null() || !self.tcbs.contains(holder) {
return Ok(());
}
let (priority, base, held) = {
let tcb = self.tcbs.resolve(holder)?;
(tcb.priority, tcb.base_priority, tcb.mutexes_held)
};
if priority == base || held != 1 {
return Ok(());
}
let target = if highest_waiting > base {
highest_waiting
} else {
base
};
if priority == target {
return Ok(());
}
self.trace_task(holder, |task, name| Event::TaskPriorityDisinherit {
task,
name,
priority: Self::priority_value(target),
});
self.tcbs.resolve_mut(holder)?.priority = target;
let event_value = u64::from(C::MAX_PRIORITIES.saturating_sub(target));
self.lists
.set_value(Self::event_item(holder), event_value)?;
let item = Self::state_item(holder);
if self.lists.container(item)? == Some(Self::ready_list(priority)) {
let _ = self.lists.remove(item);
self.add_task_to_ready_list(holder)?;
}
Ok(())
}
// ------------------------------------------------------- delay until --
/// `xTaskDelayUntil`: wake at `*previous_wake + period`, whatever the
/// task did in between. `false` when the deadline has already passed,
/// in which case nothing blocks — exactly as the C returns `pdFALSE`.
///
/// # Errors
/// A list error surfaces as itself.
pub fn delay_until(&mut self, previous_wake: &mut u64, period: u64) -> Result<bool> {
let caller = self.current;
let mut should_delay = false;
self.suspend_all();
{
let now = self.tick;
let wake_at = previous_wake.wrapping_add(period) & Self::MAX_DELAY;
if now < *previous_wake {
// The tick count overflowed since the last wake.
if wake_at < *previous_wake && wake_at > now {
should_delay = true;
}
} else if wake_at < *previous_wake || wake_at > now {
should_delay = true;
}
*previous_wake = wake_at;
if should_delay {
self.trace_task(caller, |task, name| Event::TaskDelayUntil {
task,
name,
wake_at,
});
let ticks = wake_at.wrapping_sub(now) & Self::MAX_DELAY;
self.add_current_task_to_delayed_list(ticks, false)?;
}
}
if !self.resume_all() {
self.yield_or_owe(caller);
}
Ok(should_delay)
}
/// `xTaskRemoveFromEventList`; `true` when the woken task outranks the
/// running one and a yield is therefore required.
pub(crate) fn remove_from_event_list(&mut self, list: ListId) -> Result<bool> {
let Some(item) = self.lists.head(list)? else {
return Ok(false);
};
let task = self.task_of_event_item(item)?;
let _ = self.lists.remove(item);
if self.suspended_depth == 0 {
let _ = self.lists.remove(Self::state_item(task));
self.add_task_to_ready_list(task)?;
} else {
self.lists.insert_end(Self::pending_ready_list(), item)?;
}
let woken = self.tcbs.resolve(task)?.priority;
if woken > self.current_priority() {
self.yield_pending = true;
return Ok(true);
}
Ok(false)
}
}
// ================================================================ tests ==
/// `kernel.rs` is corpus-oracled BY DESIGN (`docs/HOLES.md` H3), and these
/// do not change that. They exist for the mutants that survived BOTH
/// oracles — measured, 80 of 415 viable — because the corpus and the unit
/// suite each cannot reach them:
///
/// * the corpus runs `PosixDemoConfig` for 2,000 ticks, so the TICK
/// OVERFLOW arms of `delay_until` never execute. Nine survivors sat
/// there, and the only way to reach them is to choose a
/// `previous_wake` near the maximum rather than to simulate 2^32 ticks;
/// * the diagnostic accessors (`task_at`, `ready_items`, `ready_cursor`)
/// and the geometry guard in `with_tick_hook` are called by no scenario
/// at all — they are also on H2's list of APIs with no differential, so
/// two independent methods agree on the same surface.
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use rusty_rtos_core::config::Config;
use rusty_rtos_core::hooks::NoTickHook;
use crate::system::tests::{NoTrace, TestConfig, TestPort};
type K = crate::Kernel<
TestConfig,
TestPort,
NoTrace,
NoTickHook,
4,
{ crate::list_slots_for(4, 0, crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0)) },
{ crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0) },
1,
1,
0,
0,
0,
0,
>;
fn kernel() -> K {
K::new(TestPort::default(), NoTrace).expect("the declared geometry adds up")
}
/// A kernel with one task of our own running, so the calls that act on
/// "the current task" have one.
fn running() -> K {
let mut k = kernel();
k.create_task("t", 1).expect("a task");
let h = k.start_scheduler().expect("start");
k.suspend(Some(h.timer)).expect("park the daemon");
for _ in 0..50_u32 {
if k.name_of(k.current()).expect("a name").as_str() == "t" {
return k;
}
k.switch_context();
}
panic!("the task never reached the CPU");
}
/// `vTaskDelayUntil` with no overflow: a deadline still ahead delays,
/// and one already passed does NOT.
///
/// ```c
/// else if( ( xTimeIncrement > ( xConstTickCount - *pxPreviousWakeTime ) ) ... )
/// ```
///
/// The second half is the one that matters and the one a naive test
/// misses: a task that overran its period must NOT sleep a whole extra
/// one, it must return immediately and say it did not delay.
#[test]
fn delay_until_skips_a_deadline_that_has_already_passed() {
let mut k = running();
// now is 0; the deadline is 20 ticks away, so it delays.
let mut previous = 0_u64;
assert_eq!(k.delay_until(&mut previous, 20), Ok(true));
assert_eq!(previous, 20, "the wake time advances by the period");
// Run the clock well past the next deadline.
for _ in 0..60_u32 {
k.tick_from_isr();
}
// now is 60 and the deadline was 40: already gone.
let mut previous = 20_u64;
assert_eq!(
k.delay_until(&mut previous, 20),
Ok(false),
"the period was overrun, so it must not sleep another one"
);
assert_eq!(
previous, 40,
"and the wake time STILL advances, or the task never catches up"
);
}
/// The tick-overflow arm, which the corpus cannot reach in 2,000 ticks.
///
/// ```c
/// if( xConstTickCount < *pxPreviousWakeTime ) {
/// if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) )
/// ```
///
/// Both halves are needed: the wake time must have wrapped TOO, and it
/// must still be ahead of the wrapped-around now. Reaching it needs a
/// `previous_wake` near the maximum, not 2^32 ticks of simulation.
#[test]
fn delay_until_handles_a_wake_time_that_wrapped_with_the_tick() {
let mut k = running();
let max = K::MAX_DELAY;
// A few ticks, so `now` is small and positive.
for _ in 0..5_u32 {
k.tick_from_isr();
}
// previous_wake sits just below the maximum; the period carries the
// wake time over the top, to 9. now is 5, so 9 is still ahead.
let mut previous = max.wrapping_sub(10);
assert_eq!(
k.delay_until(&mut previous, 20),
Ok(true),
"wrapped, and still in the future: it must delay"
);
assert_eq!(previous, 9, "the wake time wrapped with the tick");
// Same wrap, but the wake time is already behind a larger now.
let mut k = running();
for _ in 0..40_u32 {
k.tick_from_isr();
}
let mut previous = max.wrapping_sub(10);
assert_eq!(
k.delay_until(&mut previous, 20),
Ok(false),
"wrapped, and now is already past it: it must NOT delay"
);
}
/// `task_at` walks the arena by SLOT, which is how a debugger or a
/// health check enumerates tasks without holding handles.
#[test]
fn task_at_enumerates_live_slots_and_stops_at_the_end() {
let mut k = kernel();
let a = k.create_task("a", 1).expect("a task");
assert_eq!(k.task_at(0), Some(a), "slot zero is the first task");
assert_eq!(
k.task_at(usize::from(u16::MAX)),
None,
"past the arena is None, not a handle"
);
assert_eq!(
k.task_at(usize::from(u16::MAX) + 1),
None,
"and an index that does not even fit a u16 is None, not a panic"
);
}
/// `ready_items` fills the caller's buffer and answers how many it
/// wrote, stopping at the buffer's end rather than running past it.
#[test]
fn ready_items_fills_what_it_can_and_counts_what_it_filled() {
let mut k = kernel();
k.create_task("a", 1).expect("a");
k.create_task("b", 1).expect("b");
let mut out = [0_u16; 8];
let n = k.ready_items(1, &mut out);
assert_eq!(n, 2, "two tasks are ready at priority 1");
// A buffer too small must be filled to its end and no further.
let mut small = [0_u16; 1];
assert_eq!(
k.ready_items(1, &mut small),
1,
"it wrote one, because one is all there was room for"
);
// An empty priority writes nothing.
let mut out = [0_u16; 8];
assert_eq!(k.ready_items(0, &mut out), 0);
}
/// `ready_cursor` is the diagnostic that answers "did the round robin
/// move", so it must report the list it was asked about.
#[test]
fn ready_cursor_reports_the_list_it_was_asked_about() {
let mut k = kernel();
k.create_task("a", 1).expect("a");
k.create_task("b", 1).expect("b");
let before = k.ready_cursor(1);
k.switch_context();
let after = k.ready_cursor(1);
assert_ne!(after, before, "a switch moved the cursor at priority 1");
assert_eq!(
k.ready_cursor(0),
k.ready_cursor(0),
"and an untouched priority answers the same thing twice"
);
}
/// `with_tick_hook`'s geometry guard, which is the only thing standing
/// between a mis-declared kernel and a silently wrong one.
///
/// `ITEMS` and `LISTS` are derived constants; if a caller writes them
/// by hand and gets them wrong, every list index is off. The guard
/// refuses, and these are the arms of it.
#[test]
fn the_geometry_guard_refuses_a_kernel_that_does_not_add_up() {
// ITEMS too small for the declared tasks and timers.
type WrongItems = crate::Kernel<
TestConfig,
TestPort,
NoTrace,
NoTickHook,
4,
// Legal as a geometry — a power of two above `LISTS` — but not
// the derived value, which is 32. A grosser error (2 slots for
// 12 lists) is now a COMPILE error in `SIZES_FIT`, so it cannot
// be used to exercise the runtime guard any more. That the
// check moved earlier is the improvement; this keeps the later
// one honest.
16,
{ crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0) },
1,
1,
0,
0,
0,
0,
>;
assert!(
WrongItems::new(TestPort::default(), NoTrace).is_err(),
"ITEMS must be list_slots_for(TASKS, TIMERS, LISTS)"
);
// LISTS not derived from the priorities, queues and groups.
type WrongLists = crate::Kernel<
TestConfig,
TestPort,
NoTrace,
NoTickHook,
4,
// Correct for the two lists declared below, so the refusal
// below is attributable to `LISTS` and nothing else.
{ crate::list_slots_for(4, 0, 2) },
2,
1,
1,
0,
0,
0,
0,
>;
assert!(
WrongLists::new(TestPort::default(), NoTrace).is_err(),
"LISTS must be lists_for(MAX_PRIORITIES, QUEUES, GROUPS)"
);
// A kernel with no room for a single task.
type NoTasks = crate::Kernel<
TestConfig,
TestPort,
NoTrace,
NoTickHook,
0,
{ crate::list_slots_for(0, 0, crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0)) },
{ crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0) },
1,
1,
0,
0,
0,
0,
>;
assert!(
NoTasks::new(TestPort::default(), NoTrace).is_err(),
"TASKS == 0 cannot even hold the idle task"
);
// And the geometry that DOES add up is accepted, or the three
// assertions above would pass for the wrong reason.
assert!(K::new(TestPort::default(), NoTrace).is_ok());
}
/// `prvGetExpectedIdleTime`, arm one: something above the idle
/// priority is running, so there is no window to sleep through.
///
/// The three arms are a short-circuit chain and each is separately
/// constructible, which is how they get pinned one at a time. A `>`
/// turned `>=` in any of them would let the kernel sleep through work
/// that is ready NOW.
#[test]
fn expected_idle_time_is_zero_while_anything_outranks_the_idle_task() {
let mut k = kernel();
k.create_task("hi", 1).expect("a task above idle");
k.start_scheduler().expect("start");
assert!(
k.current_priority() > 0,
"the task above idle is the one running"
);
assert_eq!(
k.expected_idle_time(),
0,
"something outranks idle, so the window is zero"
);
}
/// Arm two: another task shares the idle priority, so the very next
/// tick has to be processed to give it its slice.
#[test]
fn expected_idle_time_is_zero_when_another_idle_task_wants_the_slice() {
let mut k = kernel();
k.create_task("a", 0).expect("a task AT the idle priority");
k.start_scheduler().expect("start");
assert!(
k.ready_len(0).unwrap_or(0) > 1,
"the idle task and ours are both ready at priority 0"
);
assert_eq!(
k.expected_idle_time(),
0,
"a shared slice cannot be slept through"
);
}
/// And with none of the three arms true, the window is the time to the
/// next unblock -- which is the number the whole tickless feature
/// rests on.
#[test]
fn expected_idle_time_is_the_window_to_the_next_unblock() {
let mut k = running();
k.delay(30).expect("park our task for thirty ticks");
// Only the idle task is ready now, and nothing outranks it.
assert_eq!(k.current_priority(), 0, "the idle task is running");
assert_eq!(k.ready_len(0).unwrap_or(0), 1, "and it is alone at zero");
assert_eq!(
k.expected_idle_time(),
30,
"so the port may sleep right up to the next unblock"
);
}
/// `ulTaskNotifyValueClear`'s reader half, and `xTaskNotifyAndQuery`'s:
/// it answers the slot it was ASKED for, for the task it was asked
/// about.
///
/// Pinned with a value that is neither 0 nor 1, because those are what
/// the surviving mutants replaced it with.
#[test]
fn notify_value_answers_the_slot_it_was_asked_for() {
use crate::kernel::NotifyAction;
let mut k = running();
let me = k.current();
k.notify(me, 0, 0xabcd_1234, NotifyAction::Overwrite)
.expect("notify");
assert_eq!(
k.notify_value(Some(me), 0),
Ok(0xabcd_1234),
"the value that was set, not zero and not one"
);
assert_eq!(
k.notify_value(None, 0),
Ok(0xabcd_1234),
"None means the CURRENT task"
);
assert!(
k.notify_value(Some(me), TestConfig::NOTIFICATION_ARRAY_ENTRIES)
.is_err(),
"an index past the configured array is an error, not a zero"
);
}
/// `delay_until`'s BOUNDARIES, which is where the four mutants that
/// survived both oracles live.
///
/// Each comparison in it has an edge the ordinary tests never touch,
/// and each edge is reachable once you notice that `previous_wake` is
/// a CALLER variable and the period may be zero:
///
/// | line | comparison | the edge |
/// |---|---|---|
/// | 3228 | `wake_at < *previous_wake` | equal, via a period of 0 |
/// | 3228 | `wake_at > now` | equal, by ticking to the wake time |
/// | 3231 | `wake_at < *previous_wake` | equal, via a period of 0 |
///
/// All three answers must be "do not delay". A `<=` or a `>=` in any of
/// them turns a zero-length wait into a full period of sleep.
#[test]
fn delay_until_does_not_delay_on_any_of_its_boundaries() {
let max = K::MAX_DELAY;
// (1) OVERFLOW arm, period zero: the wake time equals the previous
// one, so there is nothing to wait for.
let mut k = running();
for _ in 0..5_u32 {
k.tick_from_isr();
}
let mut previous = max.wrapping_sub(10);
assert_eq!(
k.delay_until(&mut previous, 0),
Ok(false),
"a period of zero is not a period of MAX_DELAY"
);
// (2) OVERFLOW arm, wake time exactly equal to now: already due.
// (max - 10) + 20 wraps to 9, so tick to 9.
let mut k = running();
for _ in 0..9_u32 {
k.tick_from_isr();
}
let mut previous = max.wrapping_sub(10);
assert_eq!(
previous.wrapping_add(20) & max,
9,
"the wake time wraps to 9"
);
assert_eq!(
k.delay_until(&mut previous, 20),
Ok(false),
"the wrapped wake time is NOW, so it is not in the future"
);
// (3) NON-overflow arm, period zero with now already at the wake
// time: neither disjunct holds.
let mut k = running();
for _ in 0..10_u32 {
k.tick_from_isr();
}
let mut previous = 10_u64;
assert_eq!(
k.delay_until(&mut previous, 0),
Ok(false),
"nothing to wait for, and no period to sleep"
);
assert_eq!(previous, 10, "and the wake time does not move");
}
/// The tick-wrap bookkeeping, which `xTaskIncrementTick` runs once
/// every `MAX_DELAY + 1` ticks.
///
/// Neither oracle can reach it: the corpus runs 2,000 ticks and the
/// unit suite does not wrap either, so every mutation of it survived
/// both. It is a private `fn` and this module is inside `kernel.rs`,
/// so the test calls it directly rather than trying to simulate 2^32
/// ticks — which is the right answer when the trigger is unreachable
/// but the behaviour is not.
#[test]
fn switching_the_delayed_lists_flips_the_pair_and_counts_the_wrap() {
let mut k = running();
let swapped = k.delayed_swapped;
let overflows = k.overflows;
k.switch_delayed_lists();
assert_ne!(
k.delayed_swapped, swapped,
"the delayed and overflow lists change places"
);
assert_eq!(
k.overflows,
overflows.wrapping_add(1),
"and the wrap is counted, because `overflows` is how a trace \
tells one epoch from the next"
);
k.switch_delayed_lists();
assert_eq!(k.delayed_swapped, swapped, "flipping twice is the identity");
assert_eq!(k.overflows, overflows.wrapping_add(2));
}
/// `prvResetNextTaskUnblockTime`, which the wrap calls: after the swap
/// the next unblock time has to be recomputed from the list that is
/// NOW the delayed one.
///
/// That list is empty immediately after a wrap, so the answer must be
/// `MAX_DELAY` — a stale value from the old list would make the
/// kernel think a task is due and spin, or sleep through one that is.
#[test]
fn switching_the_delayed_lists_recomputes_the_next_unblock_time() {
let mut k = running();
let due = k.tick_count().wrapping_add(30);
k.delay(30).expect("park our task on the delayed list");
assert_eq!(k.next_unblock_time, due, "the parked task is what is next");
k.switch_delayed_lists();
assert_eq!(
k.next_unblock_time,
u64::MAX,
"the list that is now 'delayed' is empty, so nothing is due"
);
}
/// The sentinel for "nothing is due" is NOT the same value in the two
/// places this kernel writes it, and this pins both.
///
/// `new()` starts it at `MAX_DELAY` -- the tick mask, and what the C's
/// `portMAX_DELAY` is. `reset_next_task_unblock_time` instead takes
/// `head_value` of an empty list, which answers `ListsOf::MAX_VALUE`
/// = `u64::MAX`, so the `unwrap_or(MAX_DELAY)` beside it never fires
/// for emptiness.
///
/// Neither is reachable as a tick, because the tick is masked to
/// `MAX_DELAY`, so no scheduling decision can tell them apart and the
/// corpus is green either way. It IS visible to the tickless path:
/// `expected_idle_time` answers `next_unblock_time - tick`, which is
/// the window the port is handed, and the two sentinels differ there
/// by four billion.
///
/// Recorded rather than changed: making them agree is an owner
/// decision, because `expected_idle_time` feeds a port and any change
/// to it moves what a tickless build asks for.
#[test]
fn the_nothing_is_due_sentinel_differs_between_init_and_reset() {
let k = kernel();
assert_eq!(
k.next_unblock_time,
K::MAX_DELAY,
"a fresh kernel uses the tick mask, which is the C's portMAX_DELAY"
);
let mut k = running();
k.reset_next_task_unblock_time();
assert_eq!(
k.next_unblock_time,
u64::MAX,
"and a reset over an empty list uses the LIST's maximum instead"
);
assert_ne!(
K::MAX_DELAY,
u64::MAX,
"the two are genuinely different values, or this test is vacuous"
);
}
/// The stream-buffer resume flag is a ONE-SHOT: the take clears it, so
/// a second take answers None. A `take` that did not clear would let a
/// blocked reader wake twice on one send.
#[test]
fn a_stream_resume_is_taken_once_and_then_gone() {
let mut k = running();
let me = k.current();
assert_eq!(k.take_stream_resume(me), None, "nothing set yet");
k.set_stream_resume(me, 7);
assert_eq!(k.take_stream_resume(me), Some(7), "the value that was set");
assert_eq!(k.take_stream_resume(me), None, "and it is consumed");
}
/// `vTaskMissedYield`: a yield asked for while the scheduler is
/// suspended has to be remembered, or it is simply lost.
#[test]
fn a_missed_yield_is_remembered_rather_than_dropped() {
let mut k = running();
k.yield_pending = false;
k.missed_yield();
assert!(
k.yield_pending,
"the yield survives until something can act on it"
);
}
}