oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
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
//! Tests of `oscall::io::linux`: io_uring.
//!
//! Whether there is an io_uring to test is up to the environment: an
//! emulator may not pass the system calls on (qemu-user: `ENOSYS`), the
//! system call filter of a container refuses them (Docker's default one:
//! `EPERM`), an administrator can switch it off (`kernel.io_uring_disabled`:
//! `EPERM`), and an old kernel charges the queues to a locked memory limit
//! a container sets low (`ENOMEM`). A test that cannot have a ring says so
//! (`skipped: ...`) and passes. `OSCALL_REQUIRE_IO_URING=1` makes that a
//! failure: CI sets it where io_uring is known to work (the Linux runners
//! themselves), so that the tests cannot all skip unnoticed.
#![cfg(any(target_os = "linux", target_os = "fullrust"))]

mod common;

/// Says what a test skipped: on the standard error output itself, which
/// the test harness does not capture.
macro_rules! note {
    ($($arg:tt)*) => {
        crate::common::note(&format!($($arg)*))
    };
}

use std::net::{Ipv4Addr, SocketAddr};
use std::time::{Duration, Instant};

use oscall::event::{self, Interest};
use oscall::fs::{self, OpenOptions};
use oscall::io::linux::{
    Advice, BufRing, CURRENT_POSITION, FallocateMode, Features, FileSlot, MsgHdr, Opcode, RawSqe,
    RegisterOp, RenameFlags, Restriction, Ring, Setup, SockAddr, SpliceFlags, Sqe, SqeFlags, Statx,
    Timespec, WaitInfo,
};
use oscall::io::{self, IoSlice, IoSliceMut, SeekFrom};
use oscall::net::{self, Address, Family, OwnedSocket, Protocol, RecvFlags, SendFlags, Type};
use oscall::raw::linux::syscall;
use oscall::{AsHandle, ErrorKind, OwnedHandle};

const EPERM: i32 = 1;
const ENXIO: i32 = 6;
const ECHILD: i32 = 10;
const ENOMEM: i32 = 12;
const EACCES: i32 = 13;
const EINVAL: i32 = 22;
const ENOSYS: i32 = 38;
const ETIME: i32 = 62;
const EBADFD: i32 = 77;
const ENOBUFS: i32 = 105;
const ECANCELED: i32 = 125;

/// A long wait that is never meant to end by itself.
const LONG: Duration = Duration::from_secs(60);

/// Held for reading by every test, from its first ring to its end, and
/// for writing while a child process is created: a child holds every
/// descriptor of the process until it runs its program, and a pipe whose
/// other end a test has just closed is then not closed yet (no end of
/// stream, no broken pipe). See `docs/internals.md`.
static NO_CHILD_IS_BORN: std::sync::RwLock<()> = std::sync::RwLock::new(());

thread_local! {
    static NO_CHILD: std::cell::RefCell<Option<std::sync::RwLockReadGuard<'static, ()>>> =
        const { std::cell::RefCell::new(None) };
}

/// Keeps child processes from being created until this test, which is
/// this thread, ends.
fn no_child() {
    NO_CHILD.with(|held| {
        let mut held = held.borrow_mut();
        if held.is_none() {
            *held = Some(
                NO_CHILD_IS_BORN
                    .read()
                    .unwrap_or_else(std::sync::PoisonError::into_inner),
            );
        }
    });
}

/// A ring, or `None` with a note when the environment has no io_uring.
fn ring_with(entries: u32, setup: &Setup) -> Option<Ring> {
    no_child();
    match Ring::with_setup(entries, setup) {
        Ok(ring) => Some(ring),
        Err(error) if matches!(error.raw_os_error(), EPERM | ENOMEM | ENOSYS) => {
            let why = match error.raw_os_error() {
                ENOSYS => "the system call is missing (an emulator, an old kernel)",
                EPERM => {
                    "not permitted (a container's system call filter, kernel.io_uring_disabled)"
                }
                _ => "no memory may be locked for the queues (RLIMIT_MEMLOCK)",
            };
            assert!(
                std::env::var_os("OSCALL_REQUIRE_IO_URING").is_none_or(|v| v.is_empty()),
                "io_uring is required here, and there is none: {error}"
            );
            note!("skipped: no io_uring here: {why}: {error}");
            None
        }
        Err(error) => panic!("io_uring_setup: {error}"),
    }
}

fn ring(entries: u32) -> Option<Ring> {
    ring_with(entries, &Setup::new())
}

/// Submits what is queued and takes `count` completions, in the order they
/// came.
fn reap(ring: &mut Ring, count: usize) -> Vec<oscall::io::linux::Cqe> {
    let mut done = Vec::new();
    while done.len() < count {
        match ring.pop() {
            Some(cqe) => done.push(cqe),
            None => {
                ring.wait(1, None).unwrap();
            }
        }
    }
    done
}

/// The completion of `user_data` among `done`.
fn of(done: &[oscall::io::linux::Cqe], user_data: u64) -> oscall::io::linux::Cqe {
    *done
        .iter()
        .find(|cqe| cqe.user_data() == user_data)
        .unwrap_or_else(|| panic!("no completion of {user_data} in {done:?}"))
}

fn v4(port: u16) -> Address {
    SocketAddr::from((Ipv4Addr::LOCALHOST, port)).into()
}

fn tcp() -> OwnedSocket {
    net::socket(Family::Ipv4, Type::Stream, Protocol::Default).unwrap()
}

#[test]
fn setup() {
    let Some(ring) = ring(5) else { return };
    // Sizes are rounded up to powers of two, and the completion queue is
    // twice the submission queue.
    assert_eq!(ring.sq_entries(), 8);
    assert_eq!(ring.cq_entries(), 16);
    assert_eq!(ring.unsubmitted(), 0);
    assert_eq!(ring.ready(), 0);
    assert_eq!(ring.in_flight(), 0);
    assert!(!ring.overflowed());
    assert_eq!(ring.dropped(), 0);
    // Every kernel oscall supports (5.10) has these.
    let features = ring.features();
    assert!(features.contains(Features::SINGLE_MMAP), "{features:?}");
    assert!(features.contains(Features::NODROP), "{features:?}");
    assert!(features.contains(Features::RW_CUR_POS), "{features:?}");
    assert!(format!("{ring:?}").contains("sq_entries: 8"));

    let err = Ring::new(0).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    assert_eq!(err.raw_os_error(), EINVAL);
    // Too many, unless the kernel is asked to make do.
    let err = Ring::new(1 << 20).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    let clamped = Ring::with_setup(1 << 20, &Setup::new().clamp(true)).unwrap();
    assert_eq!(clamped.sq_entries(), 32768);

    let sized = Ring::with_setup(4, &Setup::new().cq_entries(100)).unwrap();
    assert_eq!(sized.sq_entries(), 4);
    assert_eq!(sized.cq_entries(), 128);
    // A completion queue cannot be smaller than the submission queue.
    let err = Ring::with_setup(8, &Setup::new().cq_entries(4)).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);

    // Newer options: there, or refused as unknown.
    for (name, setup) in [
        ("coop_taskrun", Setup::new().coop_taskrun(true)),
        ("single_issuer", Setup::new().single_issuer(true)),
    ] {
        match Ring::with_setup(4, &setup) {
            Ok(mut ring) => {
                ring.push(Sqe::nop().user_data(1)).unwrap();
                assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
            }
            Err(error) if error.raw_os_error() == EINVAL => {
                note!("skipped: this kernel has no {name}");
            }
            Err(error) => panic!("{name}: {error}"),
        }
    }
}

#[test]
fn nop_and_queues() {
    let Some(mut ring) = ring(4) else { return };
    assert!(ring.pop().is_none());
    // Nothing queued: no system call, and nothing taken.
    assert_eq!(ring.submit().unwrap(), 0);

    for user_data in [10, 20, 30] {
        ring.push(Sqe::nop().user_data(user_data)).unwrap();
    }
    assert_eq!(ring.unsubmitted(), 3);
    assert_eq!(ring.submit().unwrap(), 3);
    assert_eq!(ring.unsubmitted(), 0);
    assert_eq!(ring.in_flight(), 3);
    ring.wait(3, None).unwrap();
    assert_eq!(ring.ready(), 3);
    for user_data in [10, 20, 30] {
        let cqe = ring.pop().unwrap();
        assert_eq!(cqe.user_data(), user_data);
        assert_eq!(cqe.result().unwrap(), 0);
        assert_eq!(cqe.raw_result(), 0);
        assert!(!cqe.has_more());
    }
    assert!(ring.pop().is_none());
    assert_eq!(ring.in_flight(), 0);

    // The submission queue is full when it holds its size, whatever was
    // submitted before (the indexes wrap).
    for round in 0..5u64 {
        for i in 0..4 {
            ring.push(Sqe::nop().user_data(round * 4 + i)).unwrap();
        }
        let err = ring.push(Sqe::nop()).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::WouldBlock);
        // `wait` submits too.
        assert_eq!(ring.wait(4, None).unwrap(), 4);
        for i in 0..4 {
            assert_eq!(ring.pop().unwrap().user_data(), round * 4 + i);
        }
    }
    // The widest user data comes back whole, on 32-bit targets too.
    ring.push(Sqe::nop().user_data(u64::MAX - 1)).unwrap();
    assert_eq!(reap(&mut ring, 1)[0].user_data(), u64::MAX - 1);
}

#[test]
fn completion_queue_overflow() {
    // Two submissions at a time, four completions of room.
    let Some(mut ring) = ring(2) else { return };
    assert_eq!(ring.cq_entries(), 4);
    const TOTAL: u64 = 12;
    let mut seen = [false; TOTAL as usize];
    let mut taken = 0;
    let mut take = |ring: &mut Ring, taken: &mut u64| {
        while let Some(cqe) = ring.pop() {
            assert_eq!(cqe.result().unwrap(), 0);
            let slot = &mut seen[cqe.user_data() as usize];
            assert!(!*slot, "{} completed twice", cqe.user_data());
            *slot = true;
            *taken += 1;
        }
    };
    let mut pushed = 0;
    let mut overflowed = false;
    while pushed < TOTAL || ring.unsubmitted() > 0 {
        if pushed < TOTAL && ring.unsubmitted() == 0 {
            ring.push(Sqe::nop().user_data(pushed)).unwrap();
            pushed += 1;
        }
        match ring.submit() {
            Ok(_) => {}
            // Some kernels take nothing more while completions are held
            // back: make room, and have them.
            Err(error) if error.kind() == ErrorKind::ResourceBusy => {
                overflowed = true;
                take(&mut ring, &mut taken);
                ring.wait(0, None).unwrap();
            }
            Err(error) => panic!("submit: {error}"),
        }
        overflowed |= ring.overflowed();
    }
    // Twelve completions cannot be in a queue of four: the kernel holds
    // the others back, and says so.
    assert!(overflowed, "nothing overflowed");
    assert!(ring.ready() <= 4);
    // Nothing is lost: making room and asking brings them all.
    let deadline = Instant::now() + LONG;
    while taken < TOTAL {
        take(&mut ring, &mut taken);
        if taken < TOTAL {
            ring.wait(1, None).unwrap();
        }
        assert!(Instant::now() < deadline);
    }
    assert!(!ring.overflowed());
    assert_eq!(ring.dropped(), 0);
    assert_eq!(ring.in_flight(), 0);
    assert!(ring.pop().is_none());
}

#[test]
fn files() {
    let Some(mut ring) = ring(8) else { return };
    let dir = common::tmp_dir("io_linux_files");
    let path = dir.join("data");
    let c_path = std::ffi::CString::new(path.to_str().unwrap()).unwrap();

    // Open, as `fs::open` would.
    let options = OpenOptions::new().read(true).write(true).create_new(true);
    // SAFETY: the path lives until the completion is taken, below.
    ring.push(unsafe { Sqe::open(&c_path, &options) }.user_data(1))
        .unwrap();
    let opened = reap(&mut ring, 1)[0].result().unwrap();
    // SAFETY: the descriptor was just made by the kernel, for nobody else.
    let file = unsafe { OwnedHandle::from_raw(opened as i32) };
    // Private to the process, as every handle of oscall.
    assert!(!io::is_inheritable(&file).unwrap());
    // A second exclusive creation fails as it does everywhere.
    // SAFETY: as above.
    ring.push(unsafe { Sqe::open(&c_path, &options) }).unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::AlreadyExists);

    // Positional writes, out of order, then to the storage.
    let hello = *b"hello, ";
    let world = *b"world";
    // SAFETY: both buffers live until the completions are taken, below.
    unsafe {
        ring.push(Sqe::write(&file, world.as_ptr(), 5, 7).user_data(2))
            .unwrap();
        ring.push(Sqe::write(&file, hello.as_ptr(), 7, 0).user_data(1))
            .unwrap();
    }
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 1).result().unwrap(), 7);
    assert_eq!(of(&done, 2).result().unwrap(), 5);
    ring.push(Sqe::fsync(&file, false).user_data(3)).unwrap();
    ring.push(Sqe::fsync(&file, true).user_data(4)).unwrap();
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 3).result().unwrap(), 0);
    assert_eq!(of(&done, 4).result().unwrap(), 0);
    assert_eq!(std::fs::read(&path).unwrap(), b"hello, world");

    // A positional read leaves the position of the handle alone.
    let mut buf = [0u8; 32];
    // SAFETY: `buf` lives, unused, until the completion is taken.
    ring.push(unsafe { Sqe::read(&file, buf.as_mut_ptr(), 32, 7) })
        .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 5);
    assert_eq!(&buf[..5], b"world");
    assert_eq!(io::seek(&file, SeekFrom::Current(0)).unwrap(), 0);
    // A read at the position moves it.
    // SAFETY: as above.
    ring.push(unsafe { Sqe::read(&file, buf.as_mut_ptr(), 5, CURRENT_POSITION) })
        .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 5);
    assert_eq!(&buf[..5], b"hello");
    assert_eq!(io::seek(&file, SeekFrom::Current(0)).unwrap(), 5);
    // The end of the file is a read of nothing.
    // SAFETY: as above.
    ring.push(unsafe { Sqe::read(&file, buf.as_mut_ptr(), 32, 100) })
        .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);

    // Vectored, far beyond what 32 bits of offset reach.
    let far = 5 << 32;
    let (a, b) = (*b"abc", *b"defgh");
    let out = [IoSlice::new(&a), IoSlice::new(&b)];
    // SAFETY: the array and the buffers live until the completion is taken.
    ring.push(unsafe { Sqe::writev(&file, out.as_ptr(), 2, far) })
        .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 8);
    assert_eq!(fs::metadata(path.to_str().unwrap()).unwrap().len(), far + 8);
    let (mut x, mut y) = ([0u8; 2], [0u8; 16]);
    let mut into = [IoSliceMut::new(&mut x), IoSliceMut::new(&mut y)];
    // SAFETY: as above, and nothing else uses the buffers meanwhile.
    ring.push(unsafe { Sqe::readv(&file, into.as_mut_ptr(), 2, far) })
        .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 8);
    assert_eq!(&x, b"ab");
    assert_eq!(&y[..6], b"cdefgh");

    // Relative to a directory.
    let dir_handle = fs::open(
        dir.to_str().unwrap(),
        &OpenOptions::new().read(true).directory(true),
    )
    .unwrap();
    // SAFETY: the name is a constant.
    ring.push(unsafe {
        Sqe::openat(
            Some(dir_handle.as_handle()),
            c"data".as_ptr(),
            &OpenOptions::new().read(true),
        )
    })
    .unwrap();
    let second = reap(&mut ring, 1)[0].result().unwrap() as i32;
    // SAFETY: a new descriptor that nothing owns.
    let second = unsafe { OwnedHandle::from_raw(second) };
    let mut start = [0u8; 5];
    assert_eq!(io::read(&second, &mut start).unwrap(), 5);
    assert_eq!(&start, b"hello");
    // And what is not there is not found.
    // SAFETY: the name is a constant.
    ring.push(unsafe {
        Sqe::openat(
            Some(dir_handle.as_handle()),
            c"missing".as_ptr(),
            &OpenOptions::new().read(true),
        )
    })
    .unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);

    // Closing: the number is no handle afterwards.
    let number = second.as_raw();
    ring.push(Sqe::close(second)).unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
    // SAFETY: the number is only asked about; nothing else in this test
    // opens a descriptor meanwhile that the call could harm.
    let gone = unsafe { oscall::BorrowedHandle::borrow_raw(number) };
    assert!(
        io::is_inheritable(gone).is_err() || number != opened as i32,
        "the descriptor is still open"
    );
    assert_eq!(ring.in_flight(), 0);
}

#[test]
fn registered_buffers_and_files() {
    let Some(mut ring) = ring(8) else { return };
    let dir = common::tmp_dir("io_linux_registered");
    let path = dir.join("data");
    std::fs::write(&path, b"0123456789").unwrap();
    let file = fs::open(
        path.to_str().unwrap(),
        &OpenOptions::new().read(true).write(true),
    )
    .unwrap();

    // Files by index: the ring holds them, the handle need not stay.
    let (pipe_read, pipe_write) = io::pipe().unwrap();
    ring.register_files(&[file.as_handle(), pipe_read.as_handle()])
        .unwrap();
    let err = ring.register_files(&[file.as_handle()]).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::ResourceBusy);
    drop(pipe_read);
    io::write(&pipe_write, b"piped").unwrap();
    let mut buf = [0u8; 16];
    // SAFETY: `buf` lives, unused, until the completion is taken. The
    // handle given is replaced by the index.
    ring.push(unsafe { Sqe::read(&file, buf.as_mut_ptr(), 16, CURRENT_POSITION) }.fixed_file(1))
        .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 5);
    assert_eq!(&buf[..5], b"piped");
    // An index nothing is registered at.
    ring.push(Sqe::fsync(&file, false).fixed_file(7)).unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::BadHandle);
    ring.unregister_files().unwrap();
    assert!(ring.unregister_files().is_err());

    // Buffers by index.
    let mut memory = vec![0u8; 8192];
    let mut other = vec![0u8; 4096];
    let registered =
        ring.register_buffers(&[IoSliceMut::new(&mut memory), IoSliceMut::new(&mut other)]);
    match registered {
        Ok(()) => {}
        Err(error) if error.raw_os_error() == ENOMEM => {
            note!("skipped: no memory may be locked for registered buffers: {error}");
            return;
        }
        Err(error) => panic!("register_buffers: {error}"),
    }
    let err = ring
        .register_buffers(&[IoSliceMut::new(&mut [0u8; 16])])
        .unwrap_err();
    assert_eq!(err.kind(), ErrorKind::ResourceBusy);
    // SAFETY: the registered memory lives, and is not used otherwise,
    // until the completions are taken.
    ring.push(unsafe { Sqe::read_fixed(&file, memory.as_mut_ptr().add(100), 10, 0, 0) })
        .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 10);
    assert_eq!(&memory[100..110], b"0123456789");
    other[..4].copy_from_slice(b"WXYZ");
    // SAFETY: as above.
    ring.push(unsafe { Sqe::write_fixed(&file, other.as_ptr(), 4, 3, 1) })
        .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 4);
    assert_eq!(std::fs::read(&path).unwrap(), b"012WXYZ789");
    // Memory that is not within the buffer named is refused.
    // SAFETY: nothing is transferred.
    ring.push(unsafe { Sqe::read_fixed(&file, memory.as_mut_ptr(), 10, 0, 1) })
        .unwrap();
    assert!(reap(&mut ring, 1)[0].result().is_err());
    ring.unregister_buffers().unwrap();
    assert!(ring.unregister_buffers().is_err());
}

#[test]
fn completes_later_and_cancel() {
    let Some(mut ring) = ring(8) else { return };
    let (read, write) = io::pipe().unwrap();

    // A read of an empty pipe is in flight until something is written.
    let mut buf = [0u8; 16];
    // SAFETY: `buf` lives, unused, until the completion is taken: every
    // path below takes it, or fails the test.
    ring.push(unsafe { Sqe::read(&read, buf.as_mut_ptr(), 16, CURRENT_POSITION) }.user_data(1))
        .unwrap();
    assert_eq!(ring.submit().unwrap(), 1);
    assert_eq!(ring.wait(0, None).unwrap(), 0);
    assert_eq!(ring.ready(), 0);
    assert_eq!(ring.in_flight(), 1);
    assert_eq!(io::write(&write, b"later").unwrap(), 5);
    ring.wait(1, None).unwrap();
    let cqe = ring.pop().unwrap();
    assert_eq!(cqe.user_data(), 1);
    assert_eq!(cqe.result().unwrap(), 5);
    assert_eq!(&buf[..5], b"later");
    assert_eq!(ring.in_flight(), 0);

    // Cancelled, it completes all the same, and says so.
    // SAFETY: as above.
    ring.push(unsafe { Sqe::read(&read, buf.as_mut_ptr(), 16, CURRENT_POSITION) }.user_data(2))
        .unwrap();
    ring.submit().unwrap();
    ring.push(Sqe::cancel(2).user_data(3)).unwrap();
    let done = reap(&mut ring, 2);
    let cancelled = of(&done, 2).result().unwrap_err();
    assert_eq!(cancelled.raw_os_error(), ECANCELED);
    assert_eq!(cancelled.kind(), ErrorKind::Canceled);
    match of(&done, 3).result() {
        Ok(0) => {}
        // The operation was running: it was asked to stop, and did.
        Err(error) if error.kind() == ErrorKind::InProgress => {}
        other => panic!("cancel: {other:?}"),
    }
    assert_eq!(ring.in_flight(), 0);

    // Nothing to cancel: not found.
    ring.push(Sqe::cancel(99)).unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);

    // The end of a pipe is a read of nothing.
    drop(write);
    // SAFETY: as above.
    ring.push(unsafe { Sqe::read(&read, buf.as_mut_ptr(), 16, CURRENT_POSITION) })
        .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
    // And writing to one that has no reader is a broken pipe, with no
    // signal that the test would die of... which `SIGPIPE` being ignored
    // in a Rust program guarantees, not io_uring.
    let (read, write) = io::pipe().unwrap();
    drop(read);
    // SAFETY: a constant.
    ring.push(unsafe { Sqe::write(&write, b"x".as_ptr(), 1, CURRENT_POSITION) })
        .unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::BrokenPipe);
}

#[test]
fn dropped_with_an_operation_in_flight() {
    let Some(mut ring) = ring(4) else { return };
    let (read, write) = io::pipe().unwrap();
    // The contract: memory whose completion is never taken is never
    // freed. This buffer is leaked for that reason.
    let buf: &'static mut [u8; 64] = Box::leak(Box::new([0u8; 64]));
    // SAFETY: `buf` lives for ever.
    ring.push(unsafe { Sqe::read(&read, buf.as_mut_ptr(), 64, CURRENT_POSITION) })
        .unwrap();
    ring.submit().unwrap();
    assert_eq!(ring.in_flight(), 1);
    drop(ring);
    // The pipe is as it was: the kernel cancelled the read, or will.
    assert_eq!(io::write(&write, b"still here").unwrap(), 10);
    // Another ring is not disturbed by the end of the first.
    let mut second = Ring::new(4).unwrap();
    second.push(Sqe::nop().user_data(5)).unwrap();
    assert_eq!(reap(&mut second, 1)[0].user_data(), 5);
}

#[test]
fn sockets() {
    let Some(mut ring) = ring(8) else { return };
    let listener = tcp();
    net::bind(&listener, &v4(0)).unwrap();
    net::listen(&listener, 8).unwrap();
    let addr = net::local_addr(&listener).unwrap();

    // Accept and connect, both in flight at once.
    let client = tcp();
    let mut peer = SockAddr::new();
    assert_eq!(peer.address(), None);
    let target = SockAddr::from_address(&addr).unwrap();
    assert_eq!(target.address(), Some(addr));
    // SAFETY: both addresses live, and `peer` is not used, until the
    // completions are taken.
    unsafe {
        ring.push(Sqe::accept(&listener, &raw mut peer).user_data(1))
            .unwrap();
        ring.push(Sqe::connect(&client, &raw const target).user_data(2))
            .unwrap();
    }
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 2).result().unwrap(), 0);
    let accepted = of(&done, 1).result().unwrap();
    // SAFETY: a new socket that nothing owns.
    let server = unsafe { OwnedSocket::from_raw(accepted as i32) };
    // The address the kernel wrote is the client's, and the socket is
    // private to the process.
    assert_eq!(peer.address(), Some(net::local_addr(&client).unwrap()));
    assert_eq!(net::peer_addr(&server).unwrap(), peer.address().unwrap());
    // SAFETY: the socket stays open while the handle is used.
    let as_handle = unsafe { oscall::BorrowedHandle::borrow_raw(server.as_raw()) };
    assert!(!io::is_inheritable(as_handle).unwrap());

    // A receive waits for the send.
    let mut buf = [0u8; 64];
    // SAFETY: `buf` lives, unused, until the completion is taken.
    ring.push(unsafe { Sqe::recv(&server, buf.as_mut_ptr(), 64, RecvFlags::empty()) }.user_data(3))
        .unwrap();
    ring.submit().unwrap();
    assert_eq!(ring.wait(0, None).unwrap(), 0);
    assert_eq!(ring.ready(), 0);
    let message = *b"over the ring";
    // SAFETY: `message` lives until the completion is taken.
    ring.push(unsafe { Sqe::send(&client, message.as_ptr(), 13, SendFlags::empty()) }.user_data(4))
        .unwrap();
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 4).result().unwrap(), 13);
    assert_eq!(of(&done, 3).result().unwrap(), 13);
    assert_eq!(&buf[..13], b"over the ring");

    // Without an address to fill.
    let second = tcp();
    // SAFETY: `target` lives until the completions are taken.
    unsafe {
        ring.push(Sqe::accept(&listener, core::ptr::null_mut()).user_data(5))
            .unwrap();
        ring.push(Sqe::connect(&second, &raw const target).user_data(6))
            .unwrap();
    }
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 6).result().unwrap(), 0);
    // SAFETY: a new socket that nothing owns.
    drop(unsafe { OwnedSocket::from_raw(of(&done, 5).result().unwrap() as i32) });

    // The end of the stream is a receive of nothing.
    if ring.probe().supports(Opcode::Shutdown) {
        ring.push(Sqe::shutdown(&client, net::Shutdown::Write).user_data(7))
            .unwrap();
        assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
    } else {
        note!("skipped: this kernel has no shutdown operation (Linux 5.11)");
        net::shutdown(&client, net::Shutdown::Write).unwrap();
    }
    // SAFETY: as above.
    ring.push(unsafe { Sqe::recv(&server, buf.as_mut_ptr(), 64, RecvFlags::empty()) })
        .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
    // Sending on what was shut down: a broken pipe, and no signal.
    // SAFETY: as above.
    ring.push(unsafe { Sqe::send(&client, message.as_ptr(), 13, SendFlags::empty()) })
        .unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::BrokenPipe);

    // A connection nobody accepts: refused.
    let holder = tcp();
    net::bind(&holder, &v4(0)).unwrap();
    let nobody = SockAddr::from_address(&net::local_addr(&holder).unwrap()).unwrap();
    let third = tcp();
    // SAFETY: `nobody` lives until the completion is taken.
    ring.push(unsafe { Sqe::connect(&third, &raw const nobody) })
        .unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::ConnectionRefused);
    assert_eq!(ring.in_flight(), 0);
}

#[test]
fn timeouts() {
    let Some(mut ring) = ring(8) else { return };
    let short = Timespec::from(Duration::from_millis(60));
    let long = Timespec::from(LONG);
    assert_eq!(long.sec, 60);

    // A timeout expires, and says so.
    let start = Instant::now();
    // SAFETY: the time lives until the completion is taken.
    ring.push(unsafe { Sqe::timeout(&raw const short, 0) }.user_data(1))
        .unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert!(start.elapsed() >= Duration::from_millis(60));
    assert_eq!(err.raw_os_error(), ETIME);
    assert_eq!(err.kind(), ErrorKind::TimedOut);

    // At a time of the monotonic clock.
    let at = oscall::time::Clock::Monotonic.now().unwrap() + Duration::from_millis(60);
    let at_spec = Timespec::from(at);
    // SAFETY: as above.
    ring.push(unsafe { Sqe::timeout_at(&raw const at_spec, 0) })
        .unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.raw_os_error(), ETIME);
    assert!(oscall::time::Clock::Monotonic.now().unwrap() >= at);

    // Or completes with success once enough else has completed.
    // SAFETY: as above.
    ring.push(unsafe { Sqe::timeout(&raw const long, 2) }.user_data(1))
        .unwrap();
    ring.submit().unwrap();
    ring.push(Sqe::nop().user_data(2)).unwrap();
    ring.push(Sqe::nop().user_data(3)).unwrap();
    let done = reap(&mut ring, 3);
    assert_eq!(of(&done, 1).result().unwrap(), 0);

    // Removed, it is cancelled.
    // SAFETY: as above.
    ring.push(unsafe { Sqe::timeout(&raw const long, 0) }.user_data(4))
        .unwrap();
    ring.submit().unwrap();
    ring.push(Sqe::timeout_remove(4).user_data(5)).unwrap();
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 5).result().unwrap(), 0);
    assert_eq!(
        of(&done, 4).result().unwrap_err().kind(),
        ErrorKind::Canceled
    );
    ring.push(Sqe::timeout_remove(4)).unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);

    // A linked timeout bounds the operation before it.
    let (read, _write) = io::pipe().unwrap();
    let mut buf = [0u8; 8];
    let start = Instant::now();
    // SAFETY: `buf` and the time live until the completions are taken.
    unsafe {
        ring.push(
            Sqe::read(&read, buf.as_mut_ptr(), 8, CURRENT_POSITION)
                .flags(SqeFlags::LINK)
                .user_data(6),
        )
        .unwrap();
        ring.push(Sqe::link_timeout(&raw const short).user_data(7))
            .unwrap();
    }
    let done = reap(&mut ring, 2);
    assert!(start.elapsed() >= Duration::from_millis(60));
    let read_error = of(&done, 6).result().unwrap_err();
    assert!(
        matches!(
            read_error.kind(),
            ErrorKind::Canceled | ErrorKind::Interrupted
        ),
        "{read_error:?}"
    );
    assert_eq!(of(&done, 7).result().unwrap_err().raw_os_error(), ETIME);

    // The wait itself can be bounded, where the kernel can.
    if ring.features().contains(Features::EXT_ARG) {
        let start = Instant::now();
        assert_eq!(ring.wait(1, Some(Duration::from_millis(60))).unwrap(), 0);
        assert!(start.elapsed() >= Duration::from_millis(60));
        assert_eq!(ring.ready(), 0);
        // What is submitted with it is counted, and what is there ends it.
        ring.push(Sqe::nop().user_data(8)).unwrap();
        assert_eq!(ring.wait(1, Some(LONG)).unwrap(), 1);
        assert_eq!(ring.pop().unwrap().user_data(), 8);
        // No time at all: a look.
        assert_eq!(ring.wait(1, Some(Duration::ZERO)).unwrap(), 0);
    } else {
        note!("skipped: this kernel's io_uring_enter takes no timeout (Linux 5.11)");
        let err = ring.wait(1, Some(Duration::ZERO)).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
    }
    assert_eq!(ring.in_flight(), 0);
}

#[test]
fn polling() {
    let Some(mut ring) = ring(8) else { return };
    let (read, write) = io::pipe().unwrap();

    // Not ready: in flight, until it is.
    ring.push(Sqe::poll_add(&read, Interest::READABLE).user_data(1))
        .unwrap();
    ring.submit().unwrap();
    assert_eq!(ring.wait(0, None).unwrap(), 0);
    assert_eq!(ring.ready(), 0);
    io::write(&write, b"x").unwrap();
    let cqe = reap(&mut ring, 1)[0];
    assert!(cqe.result().unwrap() > 0);
    assert!(cqe.readiness().is_readable());
    assert!(!cqe.readiness().contains(event::Readiness::WRITABLE));
    // Ready already: at once, and once.
    ring.push(Sqe::poll_add(&write, Interest::WRITABLE).user_data(2))
        .unwrap();
    let cqe = reap(&mut ring, 1)[0];
    assert!(cqe.readiness().contains(event::Readiness::WRITABLE));
    assert_eq!(ring.wait(0, None).unwrap(), 0);
    assert_eq!(ring.ready(), 0);

    // Removed before it has anything to say.
    let (idle, _keep) = io::pipe().unwrap();
    ring.push(Sqe::poll_add(&idle, Interest::READABLE).user_data(3))
        .unwrap();
    ring.submit().unwrap();
    ring.push(Sqe::poll_remove(3).user_data(4)).unwrap();
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 4).result().unwrap(), 0);
    let removed = of(&done, 3);
    assert_eq!(removed.result().unwrap_err().kind(), ErrorKind::Canceled);
    assert!(removed.readiness().is_empty());
    ring.push(Sqe::poll_remove(3)).unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
}

#[test]
fn event_descriptor_and_poll() {
    let Some(mut ring) = ring(8) else { return };
    const O_CLOEXEC: usize = 0o2000000;
    // SAFETY: eventfd2 takes two integers and makes a descriptor.
    let fd = unsafe { syscall!(EVENTFD2, 0, O_CLOEXEC) }.unwrap();
    // SAFETY: the descriptor was just made.
    let eventfd = unsafe { OwnedHandle::from_raw(fd as i32) };
    ring.register_eventfd(&eventfd).unwrap();
    let err = ring.register_eventfd(&eventfd).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::ResourceBusy);

    let ready = |handle: oscall::BorrowedHandle<'_>| {
        let mut entries = [event::unix::poll_entry(&handle, Interest::READABLE)];
        event::poll(&mut entries, Some(Duration::ZERO)).unwrap() == 1
    };
    // Nothing completed: neither the event descriptor nor the ring itself
    // is readable.
    assert!(!ready(eventfd.as_handle()));
    assert!(!ready(ring.as_handle()));
    ring.push(Sqe::nop().user_data(1)).unwrap();
    ring.wait(1, None).unwrap();
    assert!(ready(eventfd.as_handle()));
    assert!(ready(ring.as_handle()));
    // The counter says how many times completions were posted.
    let mut count = [0u8; 8];
    assert_eq!(io::read(&eventfd, &mut count).unwrap(), 8);
    assert_eq!(u64::from_ne_bytes(count), 1);
    assert_eq!(ring.pop().unwrap().user_data(), 1);
    assert!(!ready(ring.as_handle()));

    ring.unregister_eventfd().unwrap();
    assert!(ring.unregister_eventfd().is_err());
    ring.push(Sqe::nop().user_data(2)).unwrap();
    assert_eq!(reap(&mut ring, 1)[0].user_data(), 2);
    assert!(!ready(eventfd.as_handle()));
}

#[test]
fn probe() {
    let Some(ring) = ring(2) else { return };
    let probe = ring.probe();
    // What the oldest kernel oscall supports has: everything this module
    // makes an entry of, but `shutdown`.
    for opcode in [
        Opcode::Nop,
        Opcode::Readv,
        Opcode::Writev,
        Opcode::Fsync,
        Opcode::ReadFixed,
        Opcode::WriteFixed,
        Opcode::PollAdd,
        Opcode::PollRemove,
        Opcode::Timeout,
        Opcode::TimeoutRemove,
        Opcode::Accept,
        Opcode::AsyncCancel,
        Opcode::LinkTimeout,
        Opcode::Connect,
        Opcode::Openat,
        Opcode::Close,
        Opcode::Read,
        Opcode::Write,
        Opcode::Send,
        Opcode::Recv,
        Opcode::Sendmsg,
        Opcode::Recvmsg,
        Opcode::Fallocate,
        Opcode::Statx,
        Opcode::Fadvise,
        Opcode::Madvise,
        Opcode::Splice,
        Opcode::ProvideBuffers,
        Opcode::RemoveBuffers,
        Opcode::Tee,
    ] {
        assert!(probe.supports(opcode), "{opcode:?}");
        assert!(probe.supports_raw(opcode as u8));
    }
    assert!(probe.last_opcode() >= Opcode::Splice as u8);
    assert!(!probe.supports_raw(255));
    assert!(format!("{probe:?}").contains("last_opcode"));
    note!(
        "io_uring here: last opcode {}, features {:?}",
        probe.last_opcode(),
        ring.features()
    );
}

#[test]
fn links_drain_and_raw() {
    let Some(mut ring) = ring(8) else { return };
    let dir = common::tmp_dir("io_linux_links");
    let path = dir.join("data");
    let file = fs::open(
        path.to_str().unwrap(),
        &OpenOptions::new().read(true).write(true).create(true),
    )
    .unwrap();

    // A link runs in order: the read sees what the write before it wrote.
    let data = *b"linked";
    let mut buf = [0u8; 6];
    // SAFETY: both buffers live until the completions are taken.
    unsafe {
        ring.push(
            Sqe::write(&file, data.as_ptr(), 6, 0)
                .flags(SqeFlags::LINK)
                .user_data(1),
        )
        .unwrap();
        ring.push(
            Sqe::fsync(&file, true)
                .flags(SqeFlags::HARD_LINK)
                .user_data(2),
        )
        .unwrap();
        ring.push(Sqe::read(&file, buf.as_mut_ptr(), 6, 0).user_data(3))
            .unwrap();
    }
    let done = reap(&mut ring, 3);
    assert_eq!(of(&done, 1).result().unwrap(), 6);
    assert_eq!(of(&done, 2).result().unwrap(), 0);
    assert_eq!(of(&done, 3).result().unwrap(), 6);
    assert_eq!(&buf, b"linked");

    // A link is broken by a failure: what follows is cancelled.
    let (read, write) = io::pipe().unwrap();
    drop(read);
    // SAFETY: a constant.
    ring.push(
        unsafe { Sqe::write(&write, b"x".as_ptr(), 1, CURRENT_POSITION) }
            .flags(SqeFlags::LINK)
            .user_data(4),
    )
    .unwrap();
    ring.push(Sqe::nop().user_data(5)).unwrap();
    let done = reap(&mut ring, 2);
    assert_eq!(
        of(&done, 4).result().unwrap_err().kind(),
        ErrorKind::BrokenPipe
    );
    assert_eq!(
        of(&done, 5).result().unwrap_err().kind(),
        ErrorKind::Canceled
    );

    // Drained and forced to a worker: they complete all the same.
    ring.push(Sqe::nop().user_data(6)).unwrap();
    ring.push(Sqe::nop().flags(SqeFlags::DRAIN).user_data(7))
        .unwrap();
    ring.push(Sqe::nop().flags(SqeFlags::ASYNC).user_data(8))
        .unwrap();
    let done = reap(&mut ring, 3);
    for user_data in 6..=8 {
        assert_eq!(of(&done, user_data).result().unwrap(), 0);
    }

    // An entry made by hand: the same no-operation, and one the kernel
    // finds wrong (a flag of `fsync` that does not exist).
    let raw = RawSqe {
        user_data: 9,
        fd: -1,
        ..RawSqe::default()
    };
    assert_eq!(*Sqe::nop().user_data(9).as_raw(), raw);
    // SAFETY: neither entry names memory.
    unsafe {
        ring.push(Sqe::from_raw(raw)).unwrap();
        ring.push(Sqe::from_raw(RawSqe {
            op_flags: 1 << 20,
            user_data: 10,
            ..*Sqe::fsync(&file, false).as_raw()
        }))
        .unwrap();
    }
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 9).result().unwrap(), 0);
    let err = of(&done, 10).result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    assert_eq!(ring.in_flight(), 0);

    // An operation no kernel has is refused before it is queued: the ring
    // asked the kernel what there is.
    // SAFETY: the entry names no memory.
    let unknown = unsafe {
        Sqe::from_raw(RawSqe {
            opcode: 255,
            ..RawSqe::default()
        })
    };
    let err = ring.push(unknown).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::Unsupported);
    assert_eq!(ring.unsubmitted(), 0);
    assert_eq!(ring.in_flight(), 0);
}

#[test]
fn moves_between_threads() {
    let Some(mut ring) = ring(8) else { return };
    let (read, write) = io::pipe().unwrap();
    // Leaked: the read is in flight while the ring changes threads, and a
    // failed assertion must not free what the kernel may write to.
    let buf: &'static mut [u8; 8] = Box::leak(Box::new([0u8; 8]));
    let pointer = buf.as_mut_ptr();
    // SAFETY: `buf` lives for ever, and is read only after the completion.
    ring.push(unsafe { Sqe::read(&read, pointer, 8, CURRENT_POSITION) }.user_data(1))
        .unwrap();
    ring.submit().unwrap();
    // Submitted by this thread, reaped by another.
    let reaper = std::thread::spawn(move || {
        let done = reap(&mut ring, 1);
        assert_eq!(done[0].user_data(), 1);
        assert_eq!(done[0].result().unwrap(), 4);
        // And that thread submits in turn.
        ring.push(Sqe::nop().user_data(2)).unwrap();
        assert_eq!(reap(&mut ring, 1)[0].user_data(), 2);
        ring
    });
    io::write(&write, b"sent").unwrap();
    let ring = reaper.join().unwrap();
    assert_eq!(&buf[..4], b"sent");
    assert_eq!(ring.in_flight(), 0);
    // Shared by reference, a ring can be looked at.
    std::thread::scope(|scope| {
        scope.spawn(|| assert_eq!(ring.ready(), 0));
    });
}

// ---------------------------------------------------------------------------
// What came after Linux 5.10
// ---------------------------------------------------------------------------

/// The release of the running kernel, or (0, 0) if it cannot be read.
fn kernel() -> (u32, u32) {
    let release = std::fs::read_to_string("/proc/sys/kernel/osrelease").unwrap_or_default();
    let mut parts = release
        .split(|c: char| !c.is_ascii_digit())
        .map(|part| part.parse().unwrap_or(0));
    (parts.next().unwrap_or(0), parts.next().unwrap_or(0))
}

/// Whether the kernel has the operation, which came with the release
/// `since`. A kernel that should have it and has not is a failure; an
/// older one is a test skipped, and said.
fn has(ring: &Ring, opcode: Opcode, since: (u32, u32)) -> bool {
    if ring.probe().supports(opcode) {
        return true;
    }
    assert!(
        kernel() < since,
        "Linux {:?} has no {opcode:?}, which came with {since:?}",
        kernel()
    );
    note!(
        "skipped: Linux {:?} has no {opcode:?} (Linux {}.{})",
        kernel(),
        since.0,
        since.1
    );
    false
}

/// Whether `error` is how a kernel older than `since` refuses `what`, a
/// way of using something it has: `EINVAL` is all it says. From a kernel
/// that should know, it is a failure.
fn too_old(what: &str, since: (u32, u32), error: &oscall::Error) -> bool {
    let refused = error.raw_os_error() == EINVAL || error.kind() == ErrorKind::Unsupported;
    if !refused {
        return false;
    }
    assert!(
        kernel() < since,
        "Linux {:?} refused {what}, which came with {since:?}: {error}",
        kernel()
    );
    note!(
        "skipped: Linux {:?} has no {what} (Linux {}.{})",
        kernel(),
        since.0,
        since.1
    );
    true
}

/// A ring made with an option that came with `since`, or `None` (said)
/// on an older kernel, and where there is no io_uring at all.
fn ring_since(entries: u32, setup: &Setup, what: &str, since: (u32, u32)) -> Option<Ring> {
    // Is there io_uring at all? That is said, or fails, by `ring`.
    drop(ring(1)?);
    match Ring::with_setup(entries, setup) {
        Ok(ring) => Some(ring),
        Err(error) if too_old(what, since, &error) => None,
        Err(error) => panic!("{what}: {error}"),
    }
}

/// Polls until `done` says so, for as long as a test may take.
fn eventually(mut done: impl FnMut() -> bool) -> bool {
    let deadline = Instant::now() + LONG;
    while !done() {
        if Instant::now() > deadline {
            return false;
        }
        std::thread::sleep(Duration::from_millis(1));
    }
    true
}

fn stream_pair() -> (OwnedSocket, OwnedSocket) {
    net::unix::pair(Type::Stream).unwrap()
}

fn tcp_pair() -> (OwnedSocket, OwnedSocket) {
    let listener = tcp();
    net::bind(&listener, &v4(0)).unwrap();
    net::listen(&listener, 8).unwrap();
    let client = tcp();
    net::connect(&client, &net::local_addr(&listener).unwrap()).unwrap();
    let (server, _) = net::accept(&listener).unwrap();
    (client, server)
}

#[test]
fn setup_options() {
    let Some(_) = ring(1) else { return };

    // An entry the kernel cannot start ends the batch: what follows it
    // stays queued...
    let bad = |user_data| {
        // SAFETY: the entry names no memory.
        unsafe {
            Sqe::from_raw(RawSqe {
                op_flags: 1 << 20,
                user_data,
                ..*Sqe::fsync(io::stdout().unwrap(), false).as_raw()
            })
        }
    };
    let mut plain = Ring::new(8).unwrap();
    plain.push(Sqe::nop().user_data(1)).unwrap();
    plain.push(bad(2)).unwrap();
    plain.push(Sqe::nop().user_data(3)).unwrap();
    assert_eq!(plain.submit().unwrap(), 2);
    assert_eq!(plain.unsubmitted(), 1);
    assert_eq!(plain.in_flight(), 2);
    let done = reap(&mut plain, 3);
    assert_eq!(
        of(&done, 2).result().unwrap_err().kind(),
        ErrorKind::InvalidInput
    );
    assert_eq!(of(&done, 3).result().unwrap(), 0);
    assert_eq!(plain.in_flight(), 0);
    // ... unless the ring was asked to go on.
    let all = Setup::new().submit_all(true);
    if let Some(mut ring) = ring_since(8, &all, "submit_all", (5, 18)) {
        ring.push(Sqe::nop().user_data(1)).unwrap();
        ring.push(bad(2)).unwrap();
        ring.push(Sqe::nop().user_data(3)).unwrap();
        assert_eq!(ring.submit().unwrap(), 3);
        assert_eq!(ring.unsubmitted(), 0);
        let done = reap(&mut ring, 3);
        assert!(of(&done, 2).result().is_err());
        assert_eq!(of(&done, 3).result().unwrap(), 0);
    }

    // A ring that starts disabled takes nothing until it is enabled.
    let mut ring = Ring::with_setup(4, &Setup::new().disabled(true)).unwrap();
    ring.push(Sqe::nop().user_data(1)).unwrap();
    let err = ring.submit().unwrap_err();
    assert_eq!(err.raw_os_error(), EBADFD);
    assert_eq!(ring.unsubmitted(), 1);
    ring.enable().unwrap();
    assert_eq!(ring.enable().unwrap_err().raw_os_error(), EBADFD);
    assert_eq!(reap(&mut ring, 1)[0].user_data(), 1);
    // And one that did not cannot be enabled.
    assert_eq!(plain.enable().unwrap_err().raw_os_error(), EBADFD);

    // Sharing the workers of another ring.
    let attached = Ring::with_setup(4, &Setup::new().attach_wq(plain.as_handle()));
    let mut attached = attached.unwrap();
    attached
        .push(Sqe::nop().flags(SqeFlags::ASYNC).user_data(4))
        .unwrap();
    assert_eq!(reap(&mut attached, 1)[0].result().unwrap(), 0);
    // What is not a ring has no workers to share.
    let (pipe, _write) = io::pipe().unwrap();
    assert!(Ring::with_setup(4, &Setup::new().attach_wq(pipe.as_handle())).is_err());

    // Completions that wait for the thread to ask.
    let deferred = Setup::new().defer_taskrun(true);
    if let Some(mut ring) = ring_since(4, &deferred, "defer_taskrun", (6, 1)) {
        let (read, write) = io::pipe().unwrap();
        let mut buf = [0u8; 8];
        // SAFETY: `buf` lives, unused, until the completion is taken.
        ring.push(unsafe { Sqe::read(&read, buf.as_mut_ptr(), 8, CURRENT_POSITION) })
            .unwrap();
        ring.submit().unwrap();
        io::write(&write, b"deferred").unwrap();
        // The data is there, and the completion is not: nothing posts it
        // until this thread waits.
        std::thread::sleep(Duration::from_millis(50));
        assert_eq!(ring.ready(), 0);
        ring.wait(0, None).unwrap();
        assert_eq!(ring.ready(), 1);
        assert_eq!(ring.pop().unwrap().result().unwrap(), 8);
        assert_eq!(&buf, b"deferred");
        // Such a ring is its thread's: another may not submit to it.
        ring.push(Sqe::nop()).unwrap();
        let ring = std::thread::spawn(move || {
            let err = ring.submit().unwrap_err();
            assert_eq!(err.kind(), ErrorKind::AlreadyExists);
            // Nor register anything with it, a group of buffers included
            // (which is why a `BufRing` dropped elsewhere keeps its
            // memory).
            let err = ring.set_iowq_max_workers(0, 0).unwrap_err();
            assert_eq!(err.kind(), ErrorKind::AlreadyExists);
            let err = BufRing::new(&ring, 0, 2, 16).unwrap_err();
            assert_eq!(err.kind(), ErrorKind::AlreadyExists);
            ring
        })
        .join()
        .unwrap();
        // Dropped here, in the thread it belongs to.
        drop(ring);
    }
}

#[test]
fn submission_thread() {
    let Some(_) = ring(1) else { return };
    // Long enough for this thread to push an entry within it, however
    // slow the machine.
    let idle = Duration::from_millis(500);
    let mut ring = match Ring::with_setup(8, &Setup::new().sqpoll(idle)) {
        Ok(ring) => ring,
        // Before Linux 5.13 it took privilege.
        Err(error) if error.raw_os_error() == EPERM && kernel() < (5, 13) => {
            note!(
                "skipped: Linux {:?} keeps SQPOLL for root: {error}",
                kernel()
            );
            return;
        }
        Err(error) => panic!("sqpoll: {error}"),
    };
    assert!(ring.features().contains(Features::SQPOLL_NONFIXED));

    // The thread of a new ring is asleep, or is not: a 64-bit kernel
    // starts it asleep, and a 32-bit one awake for its first minutes
    // (both measured). `submit` does what it takes either way.
    std::thread::sleep(Duration::from_millis(20));
    note!(
        "the thread of a new ring is {}",
        if ring.needs_wakeup() {
            "asleep"
        } else {
            "awake"
        }
    );
    ring.push(Sqe::nop().user_data(0)).unwrap();
    assert!(ring.submit().unwrap() <= 1);
    assert!(eventually(|| ring.ready() == 1), "the thread did not wake");
    assert_eq!(ring.pop().unwrap().user_data(), 0);
    // Awake, pushing is all it takes: the thread finds the entry, and no
    // system call is made here. (A machine so busy that this test is
    // kept from running for the whole idle time lets the thread go to
    // sleep in between: then it is woken, and this is tried again.)
    let mut without_a_call = false;
    for _ in 0..20 {
        ring.push(Sqe::nop().user_data(1)).unwrap();
        assert!(eventually(|| ring.ready() == 1 || ring.needs_wakeup()));
        without_a_call = ring.ready() == 1;
        if !without_a_call {
            ring.submit().unwrap();
            assert!(eventually(|| ring.ready() == 1), "the thread did not wake");
        }
        assert_eq!(ring.unsubmitted(), 0);
        assert_eq!(ring.in_flight(), 1);
        assert_eq!(ring.pop().unwrap().user_data(), 1);
        assert_eq!(ring.in_flight(), 0);
        if without_a_call {
            break;
        }
    }
    assert!(without_a_call, "the entry was never taken without a call");

    // Left alone, the thread goes to sleep, and says so.
    assert!(eventually(|| ring.needs_wakeup()), "the thread never slept");
    // An entry pushed now waits for `submit`, which wakes the thread and
    // says how many entries it handed over.
    ring.push(Sqe::nop().user_data(2)).unwrap();
    std::thread::sleep(Duration::from_millis(20));
    assert_eq!(ring.ready(), 0);
    assert_eq!(ring.unsubmitted(), 1);
    assert_eq!(ring.submit().unwrap(), 1);
    assert!(eventually(|| ring.ready() == 1), "the thread did not wake");
    assert_eq!(ring.pop().unwrap().user_data(), 2);
    // With nothing queued, `submit` is no call at all.
    assert_eq!(ring.submit().unwrap(), 0);

    // `wait` wakes it too, and waits for the completion as on any ring.
    assert!(eventually(|| ring.needs_wakeup()));
    let (read, write) = io::pipe().unwrap();
    let mut buf = [0u8; 8];
    // SAFETY: `buf` lives, unused, until the completion is taken.
    ring.push(unsafe { Sqe::read(&read, buf.as_mut_ptr(), 8, CURRENT_POSITION) }.user_data(3))
        .unwrap();
    assert_eq!(ring.wait(0, None).unwrap(), 1);
    io::write(&write, b"polled").unwrap();
    let done = reap(&mut ring, 1);
    assert_eq!(done[0].user_data(), 3);
    assert_eq!(done[0].result().unwrap(), 6);
    assert_eq!(&buf[..6], b"polled");

    // More entries than the queue holds, one burst after another: the
    // queue empties by itself, and `wait_for_room` waits for that.
    let mut pushed = 0u64;
    let mut seen = 0u64;
    while pushed < 100 {
        match ring.push(Sqe::nop().user_data(100 + pushed)) {
            Ok(()) => pushed += 1,
            Err(error) => {
                assert_eq!(error.kind(), ErrorKind::WouldBlock);
                ring.submit().unwrap();
                ring.wait_for_room().unwrap();
            }
        }
        while let Some(cqe) = ring.pop() {
            assert_eq!(cqe.user_data(), 100 + seen);
            seen += 1;
        }
    }
    while seen < pushed {
        match ring.pop() {
            Some(cqe) => {
                assert_eq!(cqe.user_data(), 100 + seen);
                seen += 1;
            }
            None => {
                ring.wait(1, None).unwrap();
            }
        }
    }
    assert_eq!(ring.in_flight(), 0);
    assert_eq!(ring.dropped(), 0);

    // Kept on a processor this thread may use, and sharing the thread of
    // the first ring.
    let mut allowed = [0usize; 8192 / usize::BITS as usize];
    oscall::thread::linux::affinity(&mut allowed).unwrap();
    let cpu = allowed
        .iter()
        .enumerate()
        .find(|(_, word)| **word != 0)
        .map(|(index, word)| index as u32 * usize::BITS + word.trailing_zeros())
        .unwrap();
    let pinned = Setup::new()
        .sqpoll(idle)
        .sqpoll_cpu(cpu)
        .attach_wq(ring.as_handle());
    let mut pinned = Ring::with_setup(4, &pinned).unwrap();
    pinned.push(Sqe::nop().user_data(7)).unwrap();
    pinned.submit().unwrap();
    assert!(eventually(|| pinned.ready() == 1));
    assert_eq!(pinned.pop().unwrap().user_data(), 7);
    // A processor without a thread to keep there is refused.
    let err = Ring::with_setup(4, &Setup::new().sqpoll_cpu(cpu)).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);

    // On a ring without such a thread, nothing ever needs waking, and
    // room is made by submitting.
    let mut plain = Ring::new(2).unwrap();
    plain.push(Sqe::nop()).unwrap();
    plain.push(Sqe::nop()).unwrap();
    assert!(!plain.needs_wakeup());
    plain.wait_for_room().unwrap();
    assert_eq!(plain.unsubmitted(), 0);
    assert_eq!(reap(&mut plain, 2).len(), 2);
}

#[test]
fn provided_buffers() {
    let Some(mut ring) = ring(8) else { return };
    const GROUP: u16 = 7;
    const SIZE: usize = 64;
    // Leaked: the kernel is given this memory, and a failed assertion
    // must not free it under an operation.
    let memory: &'static mut [u8] = Box::leak(vec![0u8; 4 * SIZE].into_boxed_slice());
    let base = memory.as_mut_ptr();
    // SAFETY: the memory lives for ever, and is read below only where a
    // completion says a buffer is the program's again.
    ring.push(unsafe { Sqe::provide_buffers(base, SIZE as u32, 4, GROUP, 10) })
        .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);

    let (read, write) = io::pipe().unwrap();
    let select = |len: u32| {
        // SAFETY: no buffer is named, and the group's memory is leaked.
        unsafe {
            Sqe::read(&read, core::ptr::null_mut(), len, CURRENT_POSITION).buffer_select(GROUP)
        }
    };
    // The buffer is picked when there is something to put in it: a read
    // in flight holds none, and the completion says which was used.
    ring.push(select(SIZE as u32).user_data(1)).unwrap();
    ring.submit().unwrap();
    io::write(&write, b"picked").unwrap();
    let cqe = reap(&mut ring, 1)[0];
    assert_eq!(cqe.result().unwrap(), 6);
    let id = cqe.buffer_id().expect("a buffer was picked");
    assert!((10..14).contains(&id), "{id}");
    // SAFETY: the completion was taken: the buffer is the program's.
    let data = unsafe { core::slice::from_raw_parts(base.add((id as usize - 10) * SIZE), 6) };
    assert_eq!(data, b"picked");
    // A completion of anything else names no buffer.
    ring.push(Sqe::nop()).unwrap();
    assert_eq!(reap(&mut ring, 1)[0].buffer_id(), None);

    // The length of the entry bounds the transfer.
    io::write(&write, b"0123456789").unwrap();
    ring.push(select(4)).unwrap();
    let cqe = reap(&mut ring, 1)[0];
    assert_eq!(cqe.result().unwrap(), 4);
    let second = cqe.buffer_id().unwrap();
    assert_ne!(second, id);
    // Two more, and the group is empty: the kernel does not wait for a
    // buffer, it says there is none.
    let mut used = vec![id, second];
    for _ in 0..2 {
        ring.push(select(3)).unwrap();
        let cqe = reap(&mut ring, 1)[0];
        assert_eq!(cqe.result().unwrap(), 3);
        used.push(cqe.buffer_id().unwrap());
    }
    used.sort_unstable();
    assert_eq!(used, [10, 11, 12, 13]);
    io::write(&write, b"more").unwrap();
    ring.push(select(4)).unwrap();
    let cqe = reap(&mut ring, 1)[0];
    assert_eq!(cqe.result().unwrap_err().raw_os_error(), ENOBUFS);
    assert_eq!(cqe.buffer_id(), None);

    // Given again, one buffer; taken back, as many as there are.
    // SAFETY: as above; the buffer 12 is the program's to give.
    ring.push(unsafe { Sqe::provide_buffers(base.add(2 * SIZE), SIZE as u32, 1, GROUP, 12) })
        .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
    ring.push(select(4)).unwrap();
    let cqe = reap(&mut ring, 1)[0];
    assert_eq!(cqe.result().unwrap(), 4);
    assert_eq!(cqe.buffer_id(), Some(12));
    assert_eq!(&memory[2 * SIZE..2 * SIZE + 4], b"more");
    // SAFETY: as above.
    ring.push(unsafe { Sqe::provide_buffers(base, SIZE as u32, 3, GROUP, 10) })
        .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
    ring.push(Sqe::remove_buffers(8, GROUP)).unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 3);
    // A group that never was.
    ring.push(Sqe::remove_buffers(1, GROUP + 1)).unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
    assert_eq!(ring.in_flight(), 0);
}

#[test]
fn buffer_ring() {
    let Some(mut ring) = ring(8) else { return };
    const GROUP: u16 = 3;
    let mut bufs = match BufRing::new(&ring, GROUP, 4, 256) {
        Ok(bufs) => bufs,
        Err(error) if too_old("rings of buffers", (5, 19), &error) => {
            assert_eq!(error.kind(), ErrorKind::Unsupported);
            return;
        }
        Err(error) => panic!("BufRing::new: {error}"),
    };
    assert_eq!(
        (bufs.group(), bufs.count(), bufs.buf_len()),
        (GROUP, 4, 256)
    );
    assert_eq!(bufs.held(), 0);
    assert!(format!("{bufs:?}").contains("count: 4"));
    // Sizes that cannot be, and a number that is taken.
    for (count, len) in [(3, 256), (0, 256), (4, 0)] {
        let err = BufRing::new(&ring, GROUP + 1, count, len).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
    }
    let err = BufRing::new(&ring, GROUP, 2, 16).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::AlreadyExists);

    let (near, far) = stream_pair();
    let select = |user_data| {
        // SAFETY: no buffer is named; `bufs` outlives every completion of
        // these entries, which are all taken below.
        unsafe {
            Sqe::recv(&near, core::ptr::null_mut(), 256, RecvFlags::empty())
                .buffer_select(GROUP)
                .user_data(user_data)
        }
    };
    ring.push(select(1)).unwrap();
    ring.submit().unwrap();
    net::send(&far, b"into a ring", SendFlags::empty()).unwrap();
    let cqe = reap(&mut ring, 1)[0];
    assert_eq!(cqe.result().unwrap(), 11);
    // SAFETY: the completion is of an entry that selected from `bufs`.
    let buf = unsafe { bufs.take(&cqe) }.expect("a buffer was picked");
    assert_eq!(Some(buf.id()), cqe.buffer_id());
    assert_eq!((buf.len(), buf.is_empty()), (11, false));
    assert_eq!(bufs.bytes(&buf), b"into a ring");
    assert_eq!(bufs.held(), 1);
    // The same completion again names a buffer the program holds already.
    // SAFETY: nothing is done with a buffer the kernel has.
    assert!(unsafe { bufs.take(&cqe) }.is_none());
    // And a completion without a buffer names none.
    ring.push(Sqe::nop()).unwrap();
    let nop = reap(&mut ring, 1)[0];
    // SAFETY: as above.
    assert!(unsafe { bufs.take(&nop) }.is_none());

    // Held by the program, the buffers run out: four, and no more.
    let mut held = vec![buf];
    for round in 0..3u8 {
        net::send(&far, &[b'a' + round; 5], SendFlags::empty()).unwrap();
        ring.push(select(2)).unwrap();
        let cqe = reap(&mut ring, 1)[0];
        assert_eq!(cqe.result().unwrap(), 5);
        // SAFETY: as above.
        let buf = unsafe { bufs.take(&cqe) }.unwrap();
        assert_eq!(bufs.bytes(&buf), [b'a' + round; 5]);
        held.push(buf);
    }
    assert_eq!(bufs.held(), 4);
    let mut ids: Vec<u16> = held.iter().map(|buf| buf.id()).collect();
    ids.sort_unstable();
    assert_eq!(ids, [0, 1, 2, 3]);
    net::send(&far, b"no room", SendFlags::empty()).unwrap();
    ring.push(select(3)).unwrap();
    let cqe = reap(&mut ring, 1)[0];
    assert_eq!(cqe.result().unwrap_err().raw_os_error(), ENOBUFS);
    // Given back, a buffer is picked again: no system call was made for
    // that, and what waited in the socket is read into it.
    let last = held.pop().unwrap();
    let last_id = last.id();
    bufs.give_back(last);
    assert_eq!(bufs.held(), 3);
    ring.push(select(4)).unwrap();
    let cqe = reap(&mut ring, 1)[0];
    assert_eq!(cqe.result().unwrap(), 7);
    assert_eq!(cqe.buffer_id(), Some(last_id));
    // SAFETY: as above.
    let buf = unsafe { bufs.take(&cqe) }.unwrap();
    assert_eq!(bufs.bytes(&buf), b"no room");
    bufs.give_back(buf);
    // Many rounds: the ring of buffers wraps, and each is used in turn.
    for buf in held.drain(..) {
        bufs.give_back(buf);
    }
    for round in 0..40u8 {
        net::send(&far, &[round; 9], SendFlags::empty()).unwrap();
        ring.push(select(5)).unwrap();
        let cqe = reap(&mut ring, 1)[0];
        // SAFETY: as above.
        let buf = unsafe { bufs.take(&cqe) }.unwrap();
        assert_eq!(bufs.bytes(&buf), [round; 9]);
        bufs.give_back(buf);
    }
    assert_eq!(bufs.held(), 0);
    assert_eq!(ring.in_flight(), 0);

    // Dropped, the group is gone from the ring: its number is free, and an
    // entry that selects from it finds no buffer.
    drop(bufs);
    net::send(&far, b"x", SendFlags::empty()).unwrap();
    // SAFETY: there is no group, and so no memory, to outlive.
    ring.push(unsafe {
        Sqe::recv(&near, core::ptr::null_mut(), 8, RecvFlags::empty()).buffer_select(GROUP)
    })
    .unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.raw_os_error(), ENOBUFS);
    let again = BufRing::new(&ring, GROUP, 2, 16).unwrap();
    // A group outlives the handle of its ring: it holds one of its own.
    drop(ring);
    drop(again);
}

#[test]
fn multishot_accept() {
    let Some(mut ring) = ring(8) else { return };
    let listener = tcp();
    net::bind(&listener, &v4(0)).unwrap();
    net::listen(&listener, 8).unwrap();
    let addr = net::local_addr(&listener).unwrap();
    ring.push(Sqe::accept_multishot(&listener).user_data(1))
        .unwrap();
    ring.submit().unwrap();

    // One entry, a completion for each connection.
    let mut clients = Vec::new();
    for round in 0..3 {
        let client = tcp();
        net::connect(&client, &addr).unwrap();
        let cqe = reap(&mut ring, 1)[0];
        assert_eq!(cqe.user_data(), 1);
        let accepted = match cqe.result() {
            Ok(fd) => fd,
            Err(error) if round == 0 && too_old("multishot accept", (5, 19), &error) => return,
            Err(error) => panic!("accept: {error}"),
        };
        // SAFETY: a new socket that nothing owns.
        let server = unsafe { OwnedSocket::from_raw(accepted as i32) };
        assert!(cqe.has_more(), "the accept ended by itself");
        assert_eq!(
            net::peer_addr(&server).unwrap(),
            net::local_addr(&client).unwrap()
        );
        // Still in flight, whatever it has completed.
        assert_eq!(ring.in_flight(), 1);
        clients.push((client, server));
    }
    // Cancelled, it has a last completion, which says so.
    ring.push(Sqe::cancel(1).user_data(2)).unwrap();
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 2).result().unwrap(), 0);
    let last = of(&done, 1);
    assert_eq!(last.result().unwrap_err().kind(), ErrorKind::Canceled);
    assert!(!last.has_more());
    assert_eq!(ring.in_flight(), 0);
}

#[test]
fn multishot_receive() {
    let Some(mut ring) = ring(8) else { return };
    const GROUP: u16 = 1;
    let mut bufs = match BufRing::new(&ring, GROUP, 2, 64) {
        Ok(bufs) => bufs,
        Err(error) if too_old("rings of buffers", (5, 19), &error) => return,
        Err(error) => panic!("BufRing::new: {error}"),
    };
    let (near, far) = stream_pair();
    // SAFETY: `bufs` outlives the last completion of each of these
    // entries: all are taken below.
    let receive = |user_data| unsafe {
        Sqe::recv_multishot(&near, GROUP, RecvFlags::empty()).user_data(user_data)
    };
    ring.push(receive(1)).unwrap();
    ring.submit().unwrap();

    // One entry, a completion for each arrival, each in a buffer of its
    // own.
    for round in 0..5u8 {
        net::send(&far, &[b'0' + round; 7], SendFlags::empty()).unwrap();
        let cqe = reap(&mut ring, 1)[0];
        assert_eq!(cqe.user_data(), 1);
        match cqe.result() {
            Ok(count) => assert_eq!(count, 7),
            Err(error) if round == 0 && too_old("multishot receive", (6, 0), &error) => return,
            Err(error) => panic!("receive: {error}"),
        }
        assert!(cqe.has_more(), "the receive ended by itself");
        // SAFETY: the completion is of an entry that selected from `bufs`.
        let buf = unsafe { bufs.take(&cqe) }.unwrap();
        assert_eq!(bufs.bytes(&buf), [b'0' + round; 7]);
        bufs.give_back(buf);
        assert_eq!(ring.in_flight(), 1);
    }

    // With no buffer left the entry ends: a last completion, with no
    // more to come, which is no error of the socket.
    let mut held = Vec::new();
    for _ in 0..2 {
        net::send(&far, b"hold", SendFlags::empty()).unwrap();
        let cqe = reap(&mut ring, 1)[0];
        assert!(cqe.has_more());
        // SAFETY: as above.
        held.push(unsafe { bufs.take(&cqe) }.unwrap());
    }
    net::send(&far, b"late", SendFlags::empty()).unwrap();
    let cqe = reap(&mut ring, 1)[0];
    assert_eq!(cqe.result().unwrap_err().raw_os_error(), ENOBUFS);
    assert!(!cqe.has_more());
    assert_eq!(ring.in_flight(), 0);
    // Pushed again once there are buffers, it goes on where it stopped.
    for buf in held.drain(..) {
        bufs.give_back(buf);
    }
    ring.push(receive(2)).unwrap();
    let cqe = reap(&mut ring, 1)[0];
    assert_eq!((cqe.user_data(), cqe.result().unwrap()), (2, 4));
    assert!(cqe.has_more());
    // SAFETY: as above.
    let buf = unsafe { bufs.take(&cqe) }.unwrap();
    assert_eq!(bufs.bytes(&buf), b"late");
    bufs.give_back(buf);

    // Cancelled by its handle.
    ring.push(Sqe::cancel_fd(&near).user_data(3)).unwrap();
    let done = reap(&mut ring, 2);
    match of(&done, 3).result() {
        Ok(count) => {
            assert_eq!(count, 1);
            let last = of(&done, 2);
            assert_eq!(last.result().unwrap_err().kind(), ErrorKind::Canceled);
            assert!(!last.has_more());
        }
        Err(error) => panic!("cancel_fd: {error}"),
    }
    assert_eq!(ring.in_flight(), 0);

    // The end of the stream ends it too, with a count of nothing.
    ring.push(receive(4)).unwrap();
    ring.submit().unwrap();
    net::send(&far, b"bye", SendFlags::empty()).unwrap();
    drop(far);
    let mut last = None;
    while last.is_none() {
        let cqe = reap(&mut ring, 1)[0];
        // SAFETY: as above.
        if let Some(buf) = unsafe { bufs.take(&cqe) } {
            if !buf.is_empty() {
                assert_eq!(bufs.bytes(&buf), b"bye");
            }
            bufs.give_back(buf);
        }
        if !cqe.has_more() {
            last = Some(cqe);
        }
    }
    assert_eq!(last.unwrap().result().unwrap(), 0);
    assert_eq!(ring.in_flight(), 0);
    assert_eq!(bufs.held(), 0);

    // The same, for what is read and not received.
    let (read, write) = io::pipe().unwrap();
    // SAFETY: as above.
    let entry = unsafe { Sqe::read_multishot(&read, GROUP) }.user_data(5);
    match ring.push(entry) {
        Ok(()) => {
            ring.submit().unwrap();
            for round in 0..3u8 {
                io::write(&write, &[round; 3]).unwrap();
                let cqe = reap(&mut ring, 1)[0];
                assert_eq!(cqe.result().unwrap(), 3);
                assert!(cqe.has_more());
                // SAFETY: as above.
                let buf = unsafe { bufs.take(&cqe) }.unwrap();
                assert_eq!(bufs.bytes(&buf), [round; 3]);
                bufs.give_back(buf);
            }
            ring.push(Sqe::cancel(5).user_data(6)).unwrap();
            let done = reap(&mut ring, 2);
            assert!(!of(&done, 5).has_more());
            assert_eq!(ring.in_flight(), 0);
        }
        Err(error) => {
            assert_eq!(error.kind(), ErrorKind::Unsupported);
            assert!(!has(&ring, Opcode::ReadMultishot, (6, 7)));
        }
    }
}

#[test]
fn multishot_poll_and_timeout() {
    let Some(mut ring) = ring(8) else { return };
    let (read, write) = io::pipe().unwrap();
    ring.push(Sqe::poll_multishot(&read, Interest::READABLE).user_data(1))
        .unwrap();
    ring.submit().unwrap();
    // A completion each time the pipe becomes readable.
    let mut byte = [0u8; 1];
    for _ in 0..3 {
        assert_eq!(ring.wait(0, None).unwrap(), 0);
        assert_eq!(ring.ready(), 0);
        io::write(&write, b"x").unwrap();
        let cqe = reap(&mut ring, 1)[0];
        assert_eq!(cqe.user_data(), 1);
        assert!(cqe.readiness().is_readable());
        assert!(cqe.has_more(), "the poll ended by itself");
        io::read(&read, &mut byte).unwrap();
    }
    assert_eq!(ring.in_flight(), 1);
    ring.push(Sqe::poll_remove(1).user_data(2)).unwrap();
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 2).result().unwrap(), 0);
    let last = of(&done, 1);
    assert_eq!(last.result().unwrap_err().kind(), ErrorKind::Canceled);
    assert!(!last.has_more());
    assert_eq!(ring.in_flight(), 0);

    // A timeout that fires three times.
    let tick = Timespec::from(Duration::from_millis(20));
    let start = Instant::now();
    // SAFETY: the time lives until the completions are taken.
    ring.push(unsafe { Sqe::timeout_multishot(&raw const tick, 3) }.user_data(3))
        .unwrap();
    for round in 0..3 {
        let cqe = reap(&mut ring, 1)[0];
        let error = cqe.result().unwrap_err();
        if round == 0 && too_old("multishot timeouts", (6, 4), &error) {
            return;
        }
        assert_eq!(error.raw_os_error(), ETIME);
        // The last one says it is.
        assert_eq!(cqe.has_more(), round < 2, "round {round}");
    }
    assert!(start.elapsed() >= Duration::from_millis(60));
    assert_eq!(ring.in_flight(), 0);
    // And one that fires until it is removed.
    // SAFETY: as above.
    ring.push(unsafe { Sqe::timeout_multishot(&raw const tick, 0) }.user_data(4))
        .unwrap();
    for _ in 0..4 {
        let cqe = reap(&mut ring, 1)[0];
        assert_eq!(cqe.result().unwrap_err().raw_os_error(), ETIME);
        assert!(cqe.has_more());
    }
    ring.push(Sqe::timeout_remove(4).user_data(5)).unwrap();
    let last = loop {
        let cqe = reap(&mut ring, 1)[0];
        if cqe.user_data() == 4 && !cqe.has_more() {
            break cqe;
        }
    };
    assert_eq!(last.result().unwrap_err().kind(), ErrorKind::Canceled);
    while ring.in_flight() > 0 {
        reap(&mut ring, 1);
    }
}

#[test]
fn messages() {
    let Some(mut ring) = ring(8) else { return };
    let udp = || {
        let socket = net::socket(Family::Ipv4, Type::Datagram, Protocol::Default).unwrap();
        net::bind(&socket, &v4(0)).unwrap();
        socket
    };
    let (sender, receiver) = (udp(), udp());
    let target = SockAddr::from_address(&net::local_addr(&receiver).unwrap()).unwrap();

    // A datagram from two buffers, to an address.
    let (a, b) = (*b"two ", *b"parts");
    let out = [IoSlice::new(&a), IoSlice::new(&b)];
    let send = MsgHdr::new().to(&target).buffers(out.as_ptr(), 2);
    // Into two buffers, with room for the address of the sender.
    let (mut x, mut y) = ([0u8; 3], [0u8; 32]);
    let mut into = [IoSliceMut::new(&mut x), IoSliceMut::new(&mut y)];
    let mut from = SockAddr::new();
    let mut receive = MsgHdr::default()
        .from(&raw mut from)
        .buffers(into.as_mut_ptr(), 2);
    // SAFETY: the headers and all they name live, and what is written to
    // is not used, until the completions are taken.
    unsafe {
        ring.push(Sqe::recvmsg(&receiver, &raw mut receive, RecvFlags::empty()).user_data(1))
            .unwrap();
        ring.submit().unwrap();
        ring.push(Sqe::sendmsg(&sender, &raw const send, SendFlags::empty()).user_data(2))
            .unwrap();
    }
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 2).result().unwrap(), 9);
    assert_eq!(of(&done, 1).result().unwrap(), 9);
    assert_eq!(&x, b"two");
    assert_eq!(&y[..6], b" parts");
    assert_eq!(receive.flags, 0);
    from.set_received_len(receive.name_len);
    assert_eq!(from.address(), Some(net::local_addr(&sender).unwrap()));

    // A datagram longer than the room for it is cut, and the header says
    // so (`MSG_TRUNC`).
    const MSG_TRUNC: i32 = 0x20;
    let mut small = [0u8; 4];
    let mut into = [IoSliceMut::new(&mut small)];
    let mut receive = MsgHdr::new().buffers(into.as_mut_ptr(), 1);
    // SAFETY: as above.
    unsafe {
        ring.push(Sqe::sendmsg(&sender, &raw const send, SendFlags::empty()).user_data(3))
            .unwrap();
        ring.push(Sqe::recvmsg(&receiver, &raw mut receive, RecvFlags::empty()).user_data(4))
            .unwrap();
    }
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 4).result().unwrap(), 4);
    assert_eq!(&small, b"two ");
    assert_eq!(receive.flags & MSG_TRUNC, MSG_TRUNC);

    // On a stream whose reader is gone: a broken pipe, and no signal.
    let (near, far) = stream_pair();
    drop(far);
    let message = MsgHdr::new().buffers(out.as_ptr(), 2);
    // SAFETY: as above.
    ring.push(unsafe { Sqe::sendmsg(&near, &raw const message, SendFlags::empty()) })
        .unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::BrokenPipe);
    assert_eq!(ring.in_flight(), 0);
}

#[test]
fn zero_copy_send() {
    let Some(mut ring) = ring(8) else { return };
    if !has(&ring, Opcode::SendZc, (6, 0)) {
        // SAFETY: nothing is sent: the entry is refused.
        let entry = unsafe { Sqe::send_zc(tcp(), c"".as_ptr().cast(), 0, SendFlags::empty()) };
        assert_eq!(ring.push(entry).unwrap_err().kind(), ErrorKind::Unsupported);
        return;
    }
    let (client, server) = tcp_pair();
    // Leaked: the kernel sends from these pages, until it says otherwise.
    let data: &'static [u8] = Box::leak(vec![0x5au8; 64 * 1024].into_boxed_slice());
    // `IORING_SEND_ZC_REPORT_USAGE` (Linux 6.2): the notification then
    // says whether the kernel copied after all.
    const REPORT_USAGE: u16 = 1 << 3;
    const COPIED: u32 = 1 << 31;
    // SAFETY: `data` lives for ever.
    let plain = unsafe {
        Sqe::send_zc(
            &client,
            data.as_ptr(),
            data.len() as u32,
            SendFlags::empty(),
        )
    };
    let reporting = RawSqe {
        ioprio: REPORT_USAGE,
        user_data: 1,
        ..*plain.as_raw()
    };
    // SAFETY: as above.
    ring.push(unsafe { Sqe::from_raw(reporting) }).unwrap();
    ring.submit().unwrap();

    // The receiver takes it all, so that nothing holds the send back.
    let reader = std::thread::spawn(move || {
        let mut total = 0;
        let mut buf = vec![0u8; 16 * 1024];
        while total < 64 * 1024 {
            let count = net::recv(&server, &mut buf, RecvFlags::empty()).unwrap();
            assert!(count > 0);
            assert!(buf[..count].iter().all(|byte| *byte == 0x5a));
            total += count;
        }
        server
    });
    // Two completions: the result of the send, with more to come, and
    // the notification that the memory is the program's again.
    let first = reap(&mut ring, 1)[0];
    let mut reported = true;
    let first = match first.result() {
        Err(error) if kernel() < (6, 2) && error.raw_os_error() == EINVAL => {
            // The report came later than the operation: without it.
            note!(
                "skipped: Linux {:?} does not report zero-copy usage (Linux 6.2)",
                kernel()
            );
            reported = false;
            assert!(!first.has_more());
            ring.push(plain.user_data(1)).unwrap();
            reap(&mut ring, 1)[0]
        }
        _ => first,
    };
    assert_eq!(first.user_data(), 1);
    assert!(first.result().unwrap() > 0);
    assert!(first.has_more());
    assert!(!first.is_notification());
    // In flight, and its memory in use, until the second.
    assert_eq!(ring.in_flight(), 1);
    let second = reap(&mut ring, 1)[0];
    assert_eq!(second.user_data(), 1);
    assert!(second.is_notification());
    assert!(!second.has_more());
    assert_eq!(ring.in_flight(), 0);
    if reported {
        note!(
            "zero-copy send over loopback: the kernel {} the data",
            if second.raw_result() as u32 & COPIED != 0 {
                "copied"
            } else {
                "did not copy"
            }
        );
    }
    let server = reader.join().unwrap();

    // The same with a header, where the kernel has it.
    if has(&ring, Opcode::SendmsgZc, (6, 1)) {
        let out = [IoSlice::new(&data[..10]), IoSlice::new(&data[..5])];
        let message = MsgHdr::new().buffers(out.as_ptr(), 2);
        // SAFETY: the header, the array and `data` live until the
        // notification is taken.
        ring.push(
            unsafe { Sqe::sendmsg_zc(&client, &raw const message, SendFlags::empty()) }
                .user_data(2),
        )
        .unwrap();
        let done = reap(&mut ring, 2);
        assert_eq!(done[0].result().unwrap(), 15);
        assert!(done[0].has_more() && !done[0].is_notification());
        assert!(done[1].is_notification() && !done[1].has_more());
        let mut buf = [0u8; 32];
        assert_eq!(
            net::recv(&server, &mut buf, RecvFlags::empty()).unwrap(),
            15
        );
    }

    // A send that cannot start: how many completions that has is the
    // kernel's choice, and `has_more` says which it made.
    let unconnected = tcp();
    // SAFETY: as above.
    ring.push(unsafe { Sqe::send_zc(&unconnected, data.as_ptr(), 16, SendFlags::empty()) })
        .unwrap();
    let cqe = reap(&mut ring, 1)[0];
    assert!(cqe.result().is_err());
    note!(
        "a zero-copy send that fails ({}) has {} completion(s)",
        cqe.result().unwrap_err(),
        if cqe.has_more() { 2 } else { 1 }
    );
    if cqe.has_more() {
        let notification = reap(&mut ring, 1)[0];
        assert!(notification.is_notification());
    }
    assert_eq!(ring.in_flight(), 0);
}

#[test]
fn file_operations() {
    let Some(mut ring) = ring(8) else { return };
    let dir = common::tmp_dir("io_linux_file_operations");
    let dir_handle = fs::open(
        dir.to_str().unwrap(),
        &OpenOptions::new().read(true).directory(true),
    )
    .unwrap();
    let at = Some(dir_handle.as_handle());
    std::fs::write(dir.join("file"), b"0123456789").unwrap();

    // What a file is, as `fs::metadata` says it.
    let mut found = Statx::new();
    // SAFETY: the name is a constant, and `found` lives, unused, until
    // the completion is taken.
    ring.push(unsafe { Sqe::statx(at, c"file".as_ptr(), true, &raw mut found) })
        .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
    let expected = fs::metadata(dir.join("file").to_str().unwrap()).unwrap();
    let metadata = found.metadata();
    assert_eq!(metadata.len(), 10);
    assert!(metadata.is_file());
    assert_eq!(metadata.inode(), expected.inode());
    assert_eq!(metadata.modified(), expected.modified());
    // SAFETY: as above.
    ring.push(unsafe { Sqe::statx(at, c"missing".as_ptr(), true, &raw mut found) })
        .unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);

    // Space, and advice.
    let file = fs::open(
        dir.join("file").to_str().unwrap(),
        &OpenOptions::new().read(true).write(true),
    )
    .unwrap();
    ring.push(Sqe::fallocate(&file, FallocateMode::empty(), 0, 8192).user_data(1))
        .unwrap();
    match reap(&mut ring, 1)[0].result() {
        Ok(_) => {
            assert_eq!(fs::handle_metadata(&file).unwrap().len(), 8192);
            // Kept at its length, the file only gains storage.
            ring.push(Sqe::fallocate(&file, FallocateMode::KEEP_SIZE, 0, 1 << 16))
                .unwrap();
            assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
            assert_eq!(fs::handle_metadata(&file).unwrap().len(), 8192);
        }
        // Not every filesystem reserves space.
        Err(error) if error.kind() == ErrorKind::Unsupported => {
            note!("skipped: the filesystem of the tests has no fallocate: {error}");
        }
        Err(error) => panic!("fallocate: {error}"),
    }
    for advice in [
        Advice::Normal,
        Advice::Random,
        Advice::Sequential,
        Advice::WillNeed,
        Advice::DontNeed,
    ] {
        ring.push(Sqe::fadvise(&file, 0, 0, advice)).unwrap();
        assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0, "{advice:?}");
    }
    let (pipe, _write) = io::pipe().unwrap();
    ring.push(Sqe::fadvise(&pipe, 0, 0, Advice::Normal))
        .unwrap();
    assert!(reap(&mut ring, 1)[0].result().is_err());
    // Memory: discarded, private pages read as zeros.
    let len = oscall::mem::page_size();
    let pages = oscall::mem::map_anonymous(len, oscall::mem::Protection::READ_WRITE).unwrap();
    // SAFETY: a mapping of this test's own, of `len` bytes.
    unsafe {
        pages.write_bytes(0xff, len);
        // (Not `WillNeed`: for memory that is no file's, a kernel built
        // without swap answers `EBADF`, as the one of `scripts/vm.sh`.)
        ring.push(Sqe::madvise(pages, len as u32, Advice::Sequential))
            .unwrap();
        assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
        assert_eq!(pages.read(), 0xff);
        ring.push(Sqe::madvise(pages, len as u32, Advice::DontNeed))
            .unwrap();
        assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
        assert_eq!(pages.read(), 0);
        oscall::mem::unmap(pages, len).unwrap();
    }

    // Names: each of these came with a later kernel.
    if has(&ring, Opcode::Renameat, (5, 11)) {
        // SAFETY: the names are constants.
        unsafe {
            ring.push(Sqe::renameat(
                at,
                c"file".as_ptr(),
                at,
                c"renamed".as_ptr(),
                RenameFlags::empty(),
            ))
            .unwrap();
        }
        assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
        assert!(!dir.join("file").exists());
        assert!(dir.join("renamed").exists());
        // Not over another name, when told so.
        std::fs::write(dir.join("other"), b"other").unwrap();
        // SAFETY: as above.
        unsafe {
            ring.push(Sqe::renameat(
                at,
                c"renamed".as_ptr(),
                at,
                c"other".as_ptr(),
                RenameFlags::NO_REPLACE,
            ))
            .unwrap();
        }
        match reap(&mut ring, 1)[0].result() {
            Err(error) if error.kind() == ErrorKind::AlreadyExists => {
                // Exchanged, both names stay.
                // SAFETY: as above.
                unsafe {
                    ring.push(Sqe::renameat(
                        at,
                        c"renamed".as_ptr(),
                        at,
                        c"other".as_ptr(),
                        RenameFlags::EXCHANGE,
                    ))
                    .unwrap();
                }
                assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
                assert_eq!(std::fs::read(dir.join("renamed")).unwrap(), b"other");
            }
            // Not every filesystem takes the flags of `renameat2`.
            Err(error) if error.kind() == ErrorKind::InvalidInput => {
                note!("skipped: the filesystem of the tests takes no rename flags: {error}");
            }
            other => panic!("renameat: {other:?}"),
        }
        // SAFETY: as above.
        unsafe {
            ring.push(Sqe::unlinkat(at, c"other".as_ptr(), false))
                .unwrap();
        }
        assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
        assert!(!dir.join("other").exists());
        // A file is not removed as a directory.
        // SAFETY: as above.
        unsafe {
            ring.push(Sqe::unlinkat(at, c"renamed".as_ptr(), true))
                .unwrap();
        }
        let err = reap(&mut ring, 1)[0].result().unwrap_err();
        assert_eq!(err.kind(), ErrorKind::NotADirectory);
    }
    if has(&ring, Opcode::Mkdirat, (5, 15)) {
        // SAFETY: the names are constants.
        unsafe {
            ring.push(Sqe::mkdirat(at, c"made".as_ptr(), 0o700).user_data(1))
                .unwrap();
            ring.push(Sqe::mkdirat(None, c"/".as_ptr(), 0o700).user_data(2))
                .unwrap();
        }
        let done = reap(&mut ring, 2);
        assert_eq!(of(&done, 1).result().unwrap(), 0);
        assert_eq!(
            of(&done, 2).result().unwrap_err().kind(),
            ErrorKind::AlreadyExists
        );
        let made = fs::metadata(dir.join("made").to_str().unwrap()).unwrap();
        assert!(made.is_dir());
        assert_eq!(made.permissions().mode() & 0o777, 0o700 & !current_umask());

        std::fs::write(dir.join("made/inner"), b"inner").unwrap();
        // SAFETY: as above.
        unsafe {
            ring.push(Sqe::symlinkat(c"made/inner".as_ptr(), at, c"link".as_ptr()).user_data(1))
                .unwrap();
            ring.push(
                Sqe::linkat(at, c"made/inner".as_ptr(), at, c"second".as_ptr(), false).user_data(2),
            )
            .unwrap();
        }
        let done = reap(&mut ring, 2);
        assert_eq!(of(&done, 1).result().unwrap(), 0);
        assert_eq!(of(&done, 2).result().unwrap(), 0);
        assert_eq!(
            std::fs::read_link(dir.join("link")).unwrap().to_str(),
            Some("made/inner")
        );
        assert_eq!(std::fs::read(dir.join("second")).unwrap(), b"inner");
        // A link is what it is, or what it leads to.
        // SAFETY: as above; `found` is used after each completion only.
        unsafe {
            ring.push(Sqe::statx(at, c"link".as_ptr(), false, &raw mut found))
                .unwrap();
        }
        assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
        assert!(found.metadata().is_symlink());
        // SAFETY: as above.
        unsafe {
            ring.push(Sqe::statx(at, c"link".as_ptr(), true, &raw mut found))
                .unwrap();
        }
        assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
        assert!(found.metadata().is_file());
        assert_eq!(found.metadata().links(), 2);
        // A second name for what a link leads to, when it is followed.
        // SAFETY: as above.
        unsafe {
            ring.push(Sqe::linkat(
                at,
                c"link".as_ptr(),
                at,
                c"third".as_ptr(),
                true,
            ))
            .unwrap();
        }
        assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
        assert!(
            !std::fs::symlink_metadata(dir.join("third"))
                .unwrap()
                .is_symlink()
        );
        // A directory that is not empty stays.
        // SAFETY: as above.
        unsafe {
            ring.push(Sqe::unlinkat(at, c"made".as_ptr(), true))
                .unwrap();
        }
        let err = reap(&mut ring, 1)[0].result().unwrap_err();
        assert_eq!(err.kind(), ErrorKind::DirectoryNotEmpty);
    }
    assert_eq!(ring.in_flight(), 0);
}

/// The file creation mask of the process, read without changing it for
/// longer than it takes.
fn current_umask() -> u32 {
    let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default();
    status
        .lines()
        .find_map(|line| line.strip_prefix("Umask:"))
        .and_then(|mask| u32::from_str_radix(mask.trim(), 8).ok())
        .unwrap_or(0o022)
}

#[test]
fn splice_and_tee() {
    let Some(mut ring) = ring(8) else { return };
    let dir = common::tmp_dir("io_linux_splice");
    let (from_read, from_write) = io::pipe().unwrap();
    let (to_read, to_write) = io::pipe().unwrap();
    io::write(&from_write, b"through the kernel").unwrap();

    // Copied to another pipe, the data stays in the first.
    ring.push(Sqe::tee(&from_read, &to_write, 7, SpliceFlags::empty()))
        .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 7);
    let mut buf = [0u8; 32];
    assert_eq!(io::read(&to_read, &mut buf).unwrap(), 7);
    assert_eq!(&buf[..7], b"through");

    // Moved to a file, at an offset, it is gone from the pipe.
    let path = dir.join("out");
    let file = fs::open(
        path.to_str().unwrap(),
        &OpenOptions::new().read(true).write(true).create(true),
    )
    .unwrap();
    ring.push(Sqe::splice(
        &from_read,
        None,
        &file,
        Some(4),
        8,
        SpliceFlags::MOVE,
    ))
    .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 8);
    assert_eq!(std::fs::read(&path).unwrap(), b"\0\0\0\0through ");
    // The handle's own position was not used.
    assert_eq!(io::seek(&file, SeekFrom::Current(0)).unwrap(), 0);
    // From a file at an offset to a pipe; and at the position, which
    // moves.
    ring.push(Sqe::splice(
        &file,
        Some(4),
        &to_write,
        None,
        7,
        SpliceFlags::empty(),
    ))
    .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 7);
    assert_eq!(io::read(&to_read, &mut buf).unwrap(), 7);
    assert_eq!(&buf[..7], b"through");
    ring.push(Sqe::splice(
        &file,
        None,
        &to_write,
        None,
        4,
        SpliceFlags::empty(),
    ))
    .unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 4);
    assert_eq!(io::seek(&file, SeekFrom::Current(0)).unwrap(), 4);
    assert_eq!(io::read(&to_read, &mut buf).unwrap(), 4);
    // What is left in the first pipe is what was not moved.
    assert_eq!(io::read(&from_read, &mut buf).unwrap(), 10);
    assert_eq!(&buf[..10], b"the kernel");
    // An empty pipe makes a splice wait, unless it is told not to.
    ring.push(Sqe::splice(
        &from_read,
        None,
        &to_write,
        None,
        4,
        SpliceFlags::NONBLOCK,
    ))
    .unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::WouldBlock);
    // Neither end a pipe: refused.
    ring.push(Sqe::splice(
        &file,
        Some(0),
        &file,
        Some(100),
        4,
        SpliceFlags::empty(),
    ))
    .unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    assert_eq!(ring.in_flight(), 0);
}

#[test]
fn sockets_made_by_the_ring() {
    let Some(mut ring) = ring(8) else { return };
    if !has(&ring, Opcode::Socket, (5, 19)) {
        let entry = Sqe::socket(Family::Ipv4, Type::Stream, Protocol::Default);
        assert_eq!(ring.push(entry).unwrap_err().kind(), ErrorKind::Unsupported);
        return;
    }
    ring.push(Sqe::socket(Family::Ipv4, Type::Stream, Protocol::Default).user_data(1))
        .unwrap();
    ring.push(Sqe::socket(Family::Unix, Type::Datagram, Protocol::Default).user_data(2))
        .unwrap();
    let done = reap(&mut ring, 2);
    // SAFETY: new sockets that nothing owns.
    let (stream, datagram) = unsafe {
        (
            OwnedSocket::from_raw(of(&done, 1).result().unwrap() as i32),
            OwnedSocket::from_raw(of(&done, 2).result().unwrap() as i32),
        )
    };
    assert_eq!(net::socket_type(&stream).unwrap(), Type::Stream);
    assert_eq!(net::socket_type(&datagram).unwrap(), Type::Datagram);
    // Private to the process, as every socket of oscall, and usable.
    // SAFETY: the socket stays open while the handle is used.
    let as_handle = unsafe { oscall::BorrowedHandle::borrow_raw(stream.as_raw()) };
    assert!(!io::is_inheritable(as_handle).unwrap());
    net::bind(&stream, &v4(0)).unwrap();
    net::listen(&stream, 1).unwrap();
}

#[test]
fn cancelling_many() {
    let Some(mut ring) = ring(16) else { return };
    let (first, _first_write) = io::pipe().unwrap();
    let (second, _second_write) = io::pipe().unwrap();
    // Leaked: reads are in flight on it while assertions may fail.
    let buf: &'static mut [u8; 64] = Box::leak(Box::new([0u8; 64]));
    let pointer = buf.as_mut_ptr();
    let read = |handle: &OwnedHandle, user_data| {
        // SAFETY: the memory lives for ever; the reads all write to it,
        // and nothing reads it.
        unsafe { Sqe::read(handle, pointer, 64, CURRENT_POSITION) }.user_data(user_data)
    };
    let submit = |ring: &mut Ring| {
        ring.push(read(&first, 1)).unwrap();
        ring.push(read(&first, 1)).unwrap();
        ring.push(read(&second, 2)).unwrap();
        ring.submit().unwrap();
        assert_eq!(ring.in_flight(), 3);
    };
    let cancelled = |done: &[oscall::io::linux::Cqe], user_data, count| {
        let of: Vec<_> = done
            .iter()
            .filter(|cqe| cqe.user_data() == user_data)
            .collect();
        assert_eq!(of.len(), count, "{done:?}");
        for cqe in of {
            assert_eq!(cqe.result().unwrap_err().kind(), ErrorKind::Canceled);
        }
    };

    // Every operation of a user data, not the first found.
    submit(&mut ring);
    ring.push(Sqe::cancel_all(1).user_data(9)).unwrap();
    ring.submit().unwrap();
    let answer = reap(&mut ring, 1)[0];
    let mut rest = Vec::new();
    match answer.result() {
        // The answer may come after what it cancelled.
        _ if answer.user_data() != 9 => rest.push(answer),
        Ok(count) => assert_eq!(count, 2),
        Err(error) if too_old("cancelling several operations", (5, 19), &error) => {
            // Nothing was cancelled: end what is in flight, one by one.
            for user_data in [1, 1, 2] {
                ring.push(Sqe::cancel(user_data).user_data(9)).unwrap();
            }
            reap(&mut ring, 6);
            return;
        }
        Err(error) => panic!("cancel_all: {error}"),
    }
    rest.extend(reap(&mut ring, 2));
    if let Some(answer) = rest.iter().find(|cqe| cqe.user_data() == 9) {
        assert_eq!(answer.result().unwrap(), 2);
    }
    cancelled(&rest, 1, 2);
    assert_eq!(ring.in_flight(), 1);

    // Every operation on a handle: on its file, that is, whichever
    // handle of it the operation was started through.
    ring.push(read(&first, 1)).unwrap();
    ring.submit().unwrap();
    let duplicate = io::duplicate(&second).unwrap();
    ring.push(Sqe::cancel_fd(&duplicate).user_data(9)).unwrap();
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 9).result().unwrap(), 1);
    cancelled(&done, 2, 1);
    drop(duplicate);
    // A handle with nothing in flight: none cancelled, which is no
    // error when all are asked for.
    ring.push(Sqe::cancel_fd(&second).user_data(9)).unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
    assert_eq!(ring.in_flight(), 1);

    // Everything.
    ring.push(read(&first, 1)).unwrap();
    ring.push(read(&second, 2)).unwrap();
    ring.submit().unwrap();
    ring.push(Sqe::cancel_any().user_data(9)).unwrap();
    let done = reap(&mut ring, 4);
    assert_eq!(of(&done, 9).result().unwrap(), 3);
    cancelled(&done, 1, 2);
    cancelled(&done, 2, 1);
    assert_eq!(ring.in_flight(), 0);
}

#[test]
fn message_to_another_ring() {
    let Some(mut sender) = ring(4) else { return };
    let mut receiver = Ring::new(4).unwrap();
    if !has(&sender, Opcode::MsgRing, (5, 18)) {
        return;
    }
    // SAFETY: the ring is returned by the thread it moves to, and lives
    // until the end of the test.
    let target = unsafe { oscall::BorrowedHandle::borrow_raw(receiver.as_handle().as_raw()) };
    // A thread that waits on its ring is woken by a completion another
    // ring posts there.
    let waiter = std::thread::spawn(move || {
        let cqe = reap(&mut receiver, 1)[0];
        (receiver, cqe)
    });
    sender
        .push(Sqe::msg_ring(target, 42, u64::MAX - 7).user_data(1))
        .unwrap();
    let sent = reap(&mut sender, 1)[0];
    assert_eq!((sent.user_data(), sent.result().unwrap()), (1, 0));
    let (mut receiver, cqe) = waiter.join().unwrap();
    assert_eq!(cqe.user_data(), u64::MAX - 7);
    assert_eq!(cqe.result().unwrap(), 42);
    assert!(!cqe.has_more());
    assert_eq!(sender.in_flight(), 0);
    // To what is not a ring.
    let (pipe, _write) = io::pipe().unwrap();
    sender.push(Sqe::msg_ring(&pipe, 0, 0)).unwrap();
    assert!(reap(&mut sender, 1)[0].result().is_err());
    // The receiver is none the worse for it.
    receiver.push(Sqe::nop().user_data(3)).unwrap();
    assert_eq!(reap(&mut receiver, 1)[0].user_data(), 3);
}

#[test]
fn futexes() {
    use std::sync::atomic::AtomicU32;
    let Some(mut ring) = ring(8) else { return };
    // Leaked: a wait is in flight on it while assertions may fail.
    let futex: &'static AtomicU32 = Box::leak(Box::new(AtomicU32::new(5)));
    // SAFETY: the futex lives for ever.
    let wait =
        |expected, user_data| unsafe { Sqe::futex_wait(futex, expected) }.user_data(user_data);
    if !has(&ring, Opcode::FutexWait, (6, 7)) {
        assert_eq!(
            ring.push(wait(5, 1)).unwrap_err().kind(),
            ErrorKind::Unsupported
        );
        return;
    }
    // Another value than expected: no wait.
    ring.push(wait(4, 1)).unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::WouldBlock);
    // The value expected: in flight, with no thread blocked, until the
    // address is woken the way `sync` wakes.
    ring.push(wait(5, 2)).unwrap();
    ring.submit().unwrap();
    assert_eq!(ring.wait(0, None).unwrap(), 0);
    assert_eq!(ring.ready(), 0);
    oscall::sync::wake_one(futex);
    let cqe = reap(&mut ring, 1)[0];
    assert_eq!((cqe.user_data(), cqe.result().unwrap()), (2, 0));

    // Woken through the ring: the count of those that were.
    ring.push(wait(5, 3)).unwrap();
    ring.push(wait(5, 4)).unwrap();
    ring.submit().unwrap();
    ring.push(Sqe::futex_wake(futex, 1).user_data(5)).unwrap();
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 5).result().unwrap(), 1);
    assert_eq!(ring.in_flight(), 1);
    ring.push(Sqe::futex_wake(futex, u32::MAX >> 1).user_data(6))
        .unwrap();
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 6).result().unwrap(), 1);
    // Nobody waits: nobody is woken.
    ring.push(Sqe::futex_wake(futex, 1)).unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
    // A thread that waits with `sync` is woken by the ring.
    let sleeper = std::thread::spawn(move || {
        while futex.load(std::sync::atomic::Ordering::SeqCst) == 5 {
            let _ = oscall::sync::wait(futex, 5, None).unwrap();
        }
    });
    futex.store(6, std::sync::atomic::Ordering::SeqCst);
    assert!(eventually(|| {
        ring.push(Sqe::futex_wake(futex, 1)).unwrap();
        reap(&mut ring, 1);
        sleeper.is_finished()
    }));
    sleeper.join().unwrap();
    // A wait can be cancelled.
    ring.push(wait(6, 7)).unwrap();
    ring.submit().unwrap();
    ring.push(Sqe::cancel(7).user_data(8)).unwrap();
    let done = reap(&mut ring, 2);
    assert_eq!(
        of(&done, 7).result().unwrap_err().kind(),
        ErrorKind::Canceled
    );
    assert_eq!(ring.in_flight(), 0);
}

/// A child process that exits with the status 0 as soon as it can: this
/// program, asked for a test that does not exist.
fn child() -> std::process::Child {
    std::process::Command::new(std::env::current_exe().unwrap())
        .args(["--exact", "no test has this name"])
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .unwrap()
}

// The children are collected by the ring, which is what is tested.
#[allow(clippy::zombie_processes)]
#[test]
fn waiting_for_a_child() {
    let Some(mut ring) = ring(8) else { return };
    if !has(&ring, Opcode::Waitid, (6, 7)) {
        let mut info = WaitInfo::new();
        // SAFETY: the entry is refused.
        let entry = unsafe { Sqe::waitid_pid(1, &raw mut info) };
        assert_eq!(ring.push(entry).unwrap_err().kind(), ErrorKind::Unsupported);
        return;
    }
    // The children are created while no other test runs: see
    // `NO_CHILD_IS_BORN`, which this thread holds for reading until here.
    let (first, mut second) = {
        NO_CHILD.with(|held| held.borrow_mut().take());
        let _alone = NO_CHILD_IS_BORN
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        (child(), child())
    };
    no_child();
    let mut info = WaitInfo::new();
    assert_eq!(
        (info.pid(), info.exit_code(), info.signal()),
        (None, None, None)
    );
    // By its identifier: collected by the ring, the child is gone.
    // SAFETY: `info` lives, unused, until the completion is taken.
    ring.push(unsafe { Sqe::waitid_pid(first.id(), &raw mut info) }.user_data(1))
        .unwrap();
    let cqe = reap(&mut ring, 1)[0];
    assert_eq!(cqe.result().unwrap(), 0);
    assert_eq!(info.pid(), Some(first.id()));
    assert_eq!(info.exit_code(), Some(0));
    assert_eq!(info.signal(), None);
    assert!(format!("{info:?}").contains("exit_code: Some(0)"));
    // SAFETY: as above.
    ring.push(unsafe { Sqe::waitid_pid(first.id(), &raw mut info) })
        .unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.raw_os_error(), ECHILD);

    // By a descriptor of the process, and ended by a signal.
    // SAFETY: pidfd_open takes two integers and makes a descriptor.
    let pidfd = unsafe { syscall!(PIDFD_OPEN, second.id() as usize, 0) }.unwrap();
    // SAFETY: the descriptor was just made.
    let pidfd = unsafe { OwnedHandle::from_raw(pidfd as i32) };
    let mut info = WaitInfo::new();
    // SAFETY: as above.
    ring.push(unsafe { Sqe::waitid_pidfd(&pidfd, &raw mut info) }.user_data(2))
        .unwrap();
    ring.submit().unwrap();
    // It may have exited already: either way it ends, and the ring says
    // how.
    let _ = second.kill();
    let cqe = reap(&mut ring, 1)[0];
    assert_eq!(cqe.result().unwrap(), 0);
    assert_eq!(info.pid(), Some(second.id()));
    match (info.exit_code(), info.signal()) {
        (Some(0), None) | (None, Some(9)) => {}
        other => panic!("the child ended with {other:?}"),
    }
    assert_eq!(ring.in_flight(), 0);
}

#[test]
fn wide_entries() {
    let Some(mut plain) = ring(4) else { return };
    // An ordinary ring has neither half.
    let err = plain.push_wide(Sqe::nop(), &[0; 64]).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    plain.push(Sqe::nop().user_data(1)).unwrap();
    plain.wait(1, None).unwrap();
    let (cqe, more) = plain.pop_wide().unwrap();
    assert_eq!((cqe.user_data(), more), (1, [0, 0]));

    // `IORING_NOP_CQE32` (Linux 6.18): a no-operation that answers in
    // the second half of its completion with two members of its entry.
    const NOP_CQE32: u32 = 1 << 5;
    let echo = |user_data: u64| {
        // SAFETY: the entry names no memory: the kernel copies the
        // numbers.
        unsafe {
            Sqe::from_raw(RawSqe {
                op_flags: NOP_CQE32,
                off: user_data * 3,
                addr: !user_data,
                user_data,
                ..*Sqe::nop().as_raw()
            })
        }
    };
    for (sqe128, cqe32) in [(true, true), (true, false), (false, true)] {
        let setup = Setup::new().sqe128(sqe128).cqe32(cqe32);
        let what = format!("wide entries (sqe128 {sqe128}, cqe32 {cqe32})");
        let Some(mut ring) = ring_since(4, &setup, &what, (5, 19)) else {
            return;
        };
        assert_eq!((ring.sq_entries(), ring.cq_entries()), (4, 8));
        // The queues wrap, several times, with entries of either size.
        let mut echoes = cqe32;
        for round in 0..6u64 {
            for i in 0..4 {
                let user_data = round * 4 + i + 1;
                let entry = if echoes {
                    echo(user_data)
                } else {
                    Sqe::nop().user_data(user_data)
                };
                if sqe128 && i % 2 == 0 {
                    ring.push_wide(entry, &[0xa5; 64]).unwrap();
                } else {
                    ring.push(entry).unwrap();
                }
            }
            assert_eq!(
                ring.push(Sqe::nop()).unwrap_err().kind(),
                ErrorKind::WouldBlock
            );
            assert_eq!(ring.wait(4, None).unwrap(), 4);
            for i in 0..4 {
                let user_data = round * 4 + i + 1;
                let (cqe, more) = ring.pop_wide().unwrap();
                assert_eq!(cqe.user_data(), user_data, "{what}");
                match cqe.result() {
                    Ok(_) if echoes => assert_eq!(more, [user_data * 3, !user_data], "{what}"),
                    Ok(_) => assert_eq!(more, [0, 0], "{what}"),
                    Err(error) if echoes && round == 0 && i == 0 => {
                        assert!(too_old(
                            "no-operations that fill a wide completion",
                            (6, 18),
                            &error
                        ));
                        echoes = false;
                    }
                    // The rest of the first round was pushed before the
                    // kernel said it has no such thing.
                    Err(error) if round == 0 => assert_eq!(error.raw_os_error(), EINVAL),
                    Err(error) => panic!("{what}: {error}"),
                }
            }
            assert!(ring.pop().is_none());
        }
        if !cqe32 {
            // Wide answers need a ring of wide completions.
            ring.push(echo(1)).unwrap();
            assert!(reap(&mut ring, 1)[0].result().is_err());
        }
        assert_eq!(ring.in_flight(), 0);
    }

    // A command for a driver: sockets have had two since Linux 6.5,
    // which ask how much there is to read and how much is not sent yet.
    if has(&plain, Opcode::UringCmd, (5, 19)) {
        let (near, far) = tcp_pair();
        net::send(&far, b"12345", SendFlags::empty()).unwrap();
        let mut buf = [0u8; 1];
        // Wait for it to be there.
        assert_eq!(net::recv(&near, &mut buf, RecvFlags::PEEK).unwrap(), 1);
        // SAFETY: the commands name no memory.
        unsafe {
            plain
                .push(Sqe::uring_cmd(&near, 0, [0; 16]).user_data(1))
                .unwrap();
            plain
                .push(Sqe::uring_cmd(&near, 1, [0; 16]).user_data(2))
                .unwrap();
        }
        let done = reap(&mut plain, 2);
        match of(&done, 1).result() {
            Ok(pending) => {
                assert_eq!(pending, 5);
                assert_eq!(of(&done, 2).result().unwrap(), 0);
            }
            // Before, a socket had no commands at all.
            Err(error) => {
                assert!(kernel() < (6, 5), "a command for a socket: {error}");
                note!(
                    "skipped: Linux {:?} has no commands for sockets (Linux 6.5): {error}",
                    kernel()
                );
            }
        }
        // What has no commands says so.
        let (pipe, _write) = io::pipe().unwrap();
        // SAFETY: as above.
        plain
            .push(unsafe { Sqe::uring_cmd(&pipe, 0, [0; 16]) })
            .unwrap();
        assert!(reap(&mut plain, 1)[0].result().is_err());
    }
}

#[test]
fn file_table_updates() {
    let Some(mut ring) = ring(8) else { return };
    let (read, write) = io::pipe().unwrap();
    let (other_read, other_write) = io::pipe().unwrap();
    // Without a table there is nothing to update.
    let err = ring
        .register_files_update(0, &[FileSlot::file(read.as_handle())])
        .unwrap_err();
    assert_eq!(err.raw_os_error(), ENXIO);

    // A table with nothing in it, where the kernel has them; otherwise
    // one with a file to replace.
    let size = match ring.register_files_sparse(4) {
        Ok(()) => 4,
        Err(error) if too_old("sparse file tables", (5, 19), &error) => {
            assert_eq!(error.kind(), ErrorKind::Unsupported);
            let files = [write.as_handle(); 4];
            ring.register_files(&files).unwrap();
            4
        }
        Err(error) => panic!("register_files_sparse: {error}"),
    };
    assert_eq!(
        ring.register_files_sparse(4).unwrap_err().kind(),
        if kernel() < (5, 19) {
            ErrorKind::Unsupported
        } else {
            ErrorKind::ResourceBusy
        }
    );
    let mut buf = [0u8; 8];
    let read_at = |index: u32, buf: &mut [u8; 8]| {
        // SAFETY: `buf` lives, unused, until the completion is taken. The
        // handle given is replaced by the index.
        unsafe { Sqe::read(&write, buf.as_mut_ptr(), 8, CURRENT_POSITION) }.fixed_file(index)
    };
    // Places 1 and 2 filled, the ring holding the files and not the
    // handles.
    let slots = [
        FileSlot::file(read.as_handle()),
        FileSlot::file(other_read.as_handle()),
    ];
    assert!(format!("{slots:?}").contains("FileSlot("));
    assert_eq!(ring.register_files_update(1, &slots).unwrap(), 2);
    drop((read, other_read));
    io::write(&write, b"one").unwrap();
    io::write(&other_write, b"two").unwrap();
    ring.push(read_at(1, &mut buf)).unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 3);
    assert_eq!(&buf[..3], b"one");
    // One place emptied, one kept as it is.
    assert_eq!(format!("{:?}", FileSlot::EMPTY), "FileSlot::EMPTY");
    assert_eq!(format!("{:?}", FileSlot::KEEP), "FileSlot::KEEP");
    let changed = ring.register_files_update(1, &[FileSlot::EMPTY, FileSlot::KEEP]);
    assert_eq!(changed.unwrap(), 2);
    ring.push(read_at(1, &mut buf)).unwrap();
    let err = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(err.kind(), ErrorKind::BadHandle);
    ring.push(read_at(2, &mut buf)).unwrap();
    assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 3);
    assert_eq!(&buf[..3], b"two");
    // Beyond the table.
    let err = ring
        .register_files_update(size, &[FileSlot::EMPTY])
        .unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    ring.unregister_files().unwrap();
    assert_eq!(ring.in_flight(), 0);
}

#[test]
fn workers_and_ring_descriptor() {
    let Some(mut ring) = ring(8) else { return };
    // The limits on the workers of this thread: asked, changed, and put
    // back.
    match ring.set_iowq_max_workers(0, 0) {
        Ok((bounded, unbounded)) => {
            // The second is 0 for a thread that may create any number of
            // processes (root in a container): no limit reads as none.
            assert!(bounded > 0, "{bounded} {unbounded}");
            note!("the workers of a thread: {bounded} bounded, {unbounded} unbounded");
            assert_eq!(
                ring.set_iowq_max_workers(2, 3).unwrap(),
                (bounded, unbounded)
            );
            assert_eq!(ring.set_iowq_max_workers(0, 0).unwrap(), (2, 3));
            assert_eq!(
                ring.set_iowq_max_workers(bounded, unbounded).unwrap(),
                (2, 3)
            );
        }
        Err(error) if too_old("limits on workers", (5, 15), &error) => {
            assert_eq!(error.kind(), ErrorKind::Unsupported);
        }
        Err(error) => panic!("set_iowq_max_workers: {error}"),
    }
    // Where they run: on the processors of this thread, which is where
    // they run already.
    let mut allowed = [0usize; 8192 / usize::BITS as usize];
    oscall::thread::linux::affinity(&mut allowed).unwrap();
    match ring.set_iowq_affinity(&allowed) {
        Ok(()) => {
            // A worker does a blocking operation all the same.
            ring.push(Sqe::nop().flags(SqeFlags::ASYNC).user_data(1))
                .unwrap();
            assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 0);
            ring.clear_iowq_affinity().unwrap();
            ring.clear_iowq_affinity().unwrap();
        }
        Err(error) if too_old("the affinity of workers", (5, 14), &error) => {}
        Err(error) => panic!("set_iowq_affinity: {error}"),
    }

    // The descriptor registered with this thread: the ring works as
    // before, by an index.
    assert_eq!(
        ring.unregister_ring_fd().unwrap_err().kind(),
        ErrorKind::InvalidInput
    );
    match ring.register_ring_fd() {
        Ok(()) => {
            assert_eq!(
                ring.register_ring_fd().unwrap_err().kind(),
                ErrorKind::AlreadyExists
            );
            let (read, write) = io::pipe().unwrap();
            let mut buf = [0u8; 8];
            // SAFETY: `buf` lives, unused, until the completion is taken.
            ring.push(unsafe { Sqe::read(&read, buf.as_mut_ptr(), 8, CURRENT_POSITION) })
                .unwrap();
            assert_eq!(ring.submit().unwrap(), 1);
            assert_eq!(ring.wait(1, Some(Duration::ZERO)).unwrap(), 0);
            io::write(&write, b"by index").unwrap();
            assert_eq!(reap(&mut ring, 1)[0].result().unwrap(), 8);
            assert_eq!(&buf, b"by index");
            // In another thread the index names nothing: the calls fail,
            // and nothing is submitted.
            ring.push(Sqe::nop().user_data(5)).unwrap();
            ring = std::thread::spawn(move || {
                let err = ring.submit().unwrap_err();
                assert!(
                    matches!(err.kind(), ErrorKind::BadHandle | ErrorKind::InvalidInput),
                    "{err:?}"
                );
                assert_eq!(ring.unsubmitted(), 1);
                note!("a ring registered with one thread, entered by another: {err}");
                ring
            })
            .join()
            .unwrap();
            // Back in its thread, it goes on.
            assert_eq!(reap(&mut ring, 1)[0].user_data(), 5);
            ring.unregister_ring_fd().unwrap();
            ring.push(Sqe::nop().user_data(6)).unwrap();
            assert_eq!(reap(&mut ring, 1)[0].user_data(), 6);
        }
        Err(error) if too_old("registered ring descriptors", (5, 18), &error) => {
            assert_eq!(error.kind(), ErrorKind::Unsupported);
        }
        Err(error) => panic!("register_ring_fd: {error}"),
    }
    assert_eq!(ring.in_flight(), 0);
}

#[test]
fn restrictions() {
    let Some(mut open) = ring(4) else { return };
    // Only a ring that has not started can be restricted.
    let allowed = [
        Restriction::op(Opcode::Nop),
        Restriction::op_raw(Opcode::Read as u8),
        Restriction::register(RegisterOp::Eventfd),
        Restriction::register_raw(RegisterOp::UnregisterEventfd as u8),
        Restriction::flags_allowed(SqeFlags::LINK | SqeFlags::FIXED_FILE),
    ];
    assert_eq!(allowed[0], Restriction::op_raw(0));
    let err = open.register_restrictions(&allowed).unwrap_err();
    assert_eq!(err.raw_os_error(), EBADFD);

    let mut ring = Ring::with_setup(8, &Setup::new().disabled(true)).unwrap();
    ring.register_restrictions(&allowed).unwrap();
    // Once.
    let err = ring.register_restrictions(&allowed).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::ResourceBusy);
    ring.enable().unwrap();

    // What is allowed works; the rest completes with a refusal, or fails
    // with one.
    let (read, write) = io::pipe().unwrap();
    io::write(&write, b"allowed").unwrap();
    let mut buf = [0u8; 8];
    ring.push(Sqe::nop().flags(SqeFlags::LINK).user_data(1))
        .unwrap();
    // SAFETY: `buf` lives, unused, until the completion is taken.
    ring.push(unsafe { Sqe::read(&read, buf.as_mut_ptr(), 8, CURRENT_POSITION) }.user_data(2))
        .unwrap();
    let done = reap(&mut ring, 2);
    assert_eq!(of(&done, 1).result().unwrap(), 0);
    assert_eq!(of(&done, 2).result().unwrap(), 7);
    // An operation that is not listed, and a flag that is not.
    ring.push(Sqe::fsync(&read, false).user_data(3)).unwrap();
    let refused = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(refused.raw_os_error(), EACCES);
    assert_eq!(refused.kind(), ErrorKind::PermissionDenied);
    ring.push(Sqe::nop().flags(SqeFlags::ASYNC).user_data(4))
        .unwrap();
    let refused = reap(&mut ring, 1)[0].result().unwrap_err();
    assert_eq!(refused.raw_os_error(), EACCES);
    // Registrations likewise.
    const O_CLOEXEC: usize = 0o2000000;
    // SAFETY: eventfd2 takes two integers and makes a descriptor.
    let fd = unsafe { syscall!(EVENTFD2, 0, O_CLOEXEC) }.unwrap();
    // SAFETY: the descriptor was just made.
    let eventfd = unsafe { OwnedHandle::from_raw(fd as i32) };
    ring.register_eventfd(&eventfd).unwrap();
    ring.unregister_eventfd().unwrap();
    let err = ring.register_files(&[read.as_handle()]).unwrap_err();
    assert_eq!(err.raw_os_error(), EACCES);
    let err = ring.set_iowq_max_workers(0, 0).unwrap_err();
    assert_eq!(err.raw_os_error(), EACCES);
    // What the ring learnt of the kernel when it was made is still
    // there, though it may not ask again.
    assert!(ring.probe().supports(Opcode::Fsync));

    // Flags every entry must have.
    let mut strict = Ring::with_setup(8, &Setup::new().disabled(true)).unwrap();
    strict
        .register_restrictions(&[
            Restriction::op(Opcode::Nop),
            Restriction::flags_required(SqeFlags::ASYNC),
            Restriction::flags_allowed(SqeFlags::ASYNC),
        ])
        .unwrap();
    strict.enable().unwrap();
    strict.push(Sqe::nop().user_data(1)).unwrap();
    let refused = reap(&mut strict, 1)[0].result().unwrap_err();
    assert_eq!(refused.raw_os_error(), EACCES);
    strict
        .push(Sqe::nop().flags(SqeFlags::ASYNC).user_data(2))
        .unwrap();
    assert_eq!(reap(&mut strict, 1)[0].result().unwrap(), 0);

    // The flags `Sqe::flags` does not set are there for this, and only
    // for this.
    let entry = Sqe::nop().flags(SqeFlags::FIXED_FILE | SqeFlags::BUFFER_SELECT | SqeFlags::DRAIN);
    assert_eq!(entry.as_raw().flags, 1 << 1);
    open.push(entry).unwrap();
    assert_eq!(reap(&mut open, 1)[0].result().unwrap(), 0);
}