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
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
//! What Linux alone has: io_uring, the kernel's interface for I/O that
//! completes later.
//!
//! A [`Ring`] is two queues the program shares with the kernel. The program
//! writes *submission entries* ([`Sqe`]: one operation each, with a number
//! of the caller's choosing, the *user data*) to the first, tells the
//! kernel ([`Ring::submit`]), and later reads *completion entries*
//! ([`Cqe`]: the user data and the result) from the second
//! ([`Ring::pop`]), waiting for them if it wants to ([`Ring::wait`]). The
//! operation runs in the kernel meanwhile, whatever the handle is: unlike
//! [`event`](crate::event), which says when a socket *could* be read, this
//! reads it, and it works on files too.
//!
//! ```no_run
//! use oscall::io::linux::{Ring, Sqe};
//!
//! # fn main() -> oscall::Result<()> {
//! let file = oscall::fs::open("data", &oscall::fs::OpenOptions::new().read(true))?;
//! let mut ring = Ring::new(8)?;
//! let mut buf = [0u8; 4096];
//! // SAFETY: `buf` lives, and is not used, until the completion is taken.
//! let read = unsafe { Sqe::read(&file, buf.as_mut_ptr(), buf.len() as u32, 0) };
//! ring.push(read.user_data(7))?;
//! ring.wait(1, None)?;
//! let completion = ring.pop().expect("one completion was waited for");
//! assert_eq!(completion.user_data(), 7);
//! let count = completion.result()? as usize;
//! let _data = &buf[..count];
//! # Ok(())
//! # }
//! ```
//!
//! This module is thin: an entry is the kernel's `struct io_uring_sqe`, the
//! queues are the kernel's, and nothing is allocated or remembered about an
//! operation. What it adds is the setup (the three mappings, with
//! [`mem`](crate::mem)'s own `mmap`), the queue protocol with its memory
//! ordering, typed constructors for the common operations, and errors as
//! [`Error`]s.
//!
//! # Memory: where `unsafe` is
//!
//! The kernel reads and writes the memory an entry names *after* the call
//! that submitted it has returned, until the operation completes: nothing
//! in the types can hold a buffer for that long. So the constructors that
//! take a pointer are `unsafe`, and the contract is theirs:
//!
//! > Memory named by an entry that is pushed must stay valid, and for
//! > memory the kernel writes must not be used otherwise, **until the
//! > completion of that entry has been taken from the ring**.
//!
//! Three consequences that are easy to miss:
//!
//! - **Dropping the ring is not the end of its operations.** Closing the
//!   descriptor makes the kernel cancel them, in its own time: one that is
//!   running goes on writing to its buffer for a moment. Before freeing
//!   buffers, cancel what is in flight ([`Sqe::cancel`]) and take every
//!   completion ([`Ring::in_flight`] counts what is left); a buffer whose
//!   completion was never taken must not be freed at all.
//! - **Leaving a function is not either**, be it by `?` or by a panic:
//!   a buffer on the stack needs the completion to be taken on every path.
//! - **A cancelled operation still completes**, with
//!   [`Canceled`](crate::ErrorKind::Canceled) or with its result if the
//!   request came too late; its buffer is in use until that completion.
//!
//! The constructors that name no memory ([`Sqe::nop`], [`Sqe::fsync`],
//! [`Sqe::poll_add`], [`Sqe::cancel`], [`Sqe::close`]...) are safe, and so
//! are pushing, submitting and reaping. An entry that completes
//! [several times](self#multishot) is in flight until its last completion,
//! and a [zero-copy send](self#zero-copy-sends) until its notification.
//!
//! Handles are named by number and looked up by the kernel when the entry
//! is *submitted*; from then on the operation holds the file itself, and
//! closing the handle does not stop it. Close a handle after the entries
//! that name it are submitted, not between [`Ring::push`] and
//! [`Ring::submit`]: such an entry fails with
//! [`BadHandle`](crate::ErrorKind::BadHandle), or acts on whatever was
//! given the number since.
//!
//! # The two queues can be full
//!
//! - The submission queue holds what was pushed and not yet submitted:
//!   [`Ring::push`] fails with [`WouldBlock`](crate::ErrorKind::WouldBlock)
//!   when it is full, and [`Ring::submit`] empties it.
//! - The completion queue is twice that size unless
//!   [`Setup::cq_entries`] says otherwise, and the kernel does not stop
//!   taking submissions when it is full. Completions that find no room are
//!   kept by the kernel in a list of its own ([`Features::NODROP`], which
//!   every kernel oscall supports has) and [`Ring::overflowed`] says so;
//!   they are moved to the queue, as room is made, by the next
//!   [`Ring::wait`]. While some are held back, the kernel may refuse new
//!   submissions with [`ResourceBusy`](crate::ErrorKind::ResourceBusy).
//!   Nothing is lost unless the kernel cannot even allocate the list entry,
//!   which [`Ring::dropped`] counts.
//!
//! # Threads
//!
//! Every method that touches a queue takes `&mut self`: a ring is used by
//! one thread at a time, and can be sent to another. What a ring shares
//! with other threads is the kernel side, which is the kernel's concern.
//! To submit from several threads, give each its own ring, or guard one
//! with a lock.
//!
//! A ring whose descriptor is [registered](Ring::register_ring_fd) with a
//! thread is that thread's until the registration ends, and a ring made
//! for [one thread](Setup::single_issuer) is that thread's for good.
//!
//! # A thread of the kernel that submits
//!
//! With [`Setup::sqpoll`] the kernel gives the ring a thread that reads
//! the submission queue by itself: [`Ring::push`] is then all it takes to
//! start an operation, with no system call, for as long as the thread is
//! awake. It sleeps when it has found nothing for the idle time it was
//! given, and says so in the queue ([`Ring::needs_wakeup`]);
//! [`Ring::submit`] looks, and makes the system call that wakes it only
//! then. (Whether the thread of a new ring starts asleep is the kernel's
//! business, and differs: always `submit` after the first `push` too.) So the pattern does not change (push, submit, wait), and what
//! changes is what the calls cost. What does change:
//!
//! - an entry may be taken as soon as it is pushed: "until it is
//!   submitted" in a contract below means "until it is pushed" here, and a
//!   handle must stay open until the completion, not until `submit`;
//! - [`Ring::submit`] cannot say how many entries the kernel took, and
//!   says how many it had not taken yet;
//! - a full queue empties by itself: [`Ring::wait_for_room`] waits for
//!   that;
//! - the thread is the kernel's, runs with the credentials of the thread
//!   that made the ring, and spins for the idle time after each burst.
//!
//! # Multishot
//!
//! Some entries complete more than once: [`Sqe::accept_multishot`],
//! [`Sqe::recv_multishot`], [`Sqe::read_multishot`],
//! [`Sqe::poll_multishot`], [`Sqe::timeout_multishot`], and a
//! [zero-copy send](self#zero-copy-sends). Each of their completions has
//! the user data of the entry, and [`Cqe::has_more`] says whether another
//! will come (`IORING_CQE_F_MORE`):
//!
//! - while it is true, the entry is in flight and so is its memory;
//! - **the completion without it is the last**, whatever its result: the
//!   kernel has dropped the entry, which must be pushed again to go on.
//!   That happens on an error, and also for reasons that are none: the
//!   completion queue was full, the group of buffers was empty (`ENOBUFS`),
//!   a stream ended (a count of 0). A program must look at the flag of
//!   every completion, not at the result alone;
//! - a multishot entry is ended by cancelling it ([`Sqe::cancel`] with its
//!   user data, [`Sqe::cancel_fd`], [`Sqe::poll_remove`],
//!   [`Sqe::timeout_remove`]): its last completion is then
//!   [`Canceled`](crate::ErrorKind::Canceled). Completions that were
//!   posted before the cancelling are still in the queue, before it.
//!
//! [`Ring::in_flight`] counts an entry until its last completion.
//!
//! # Buffers the kernel picks
//!
//! A receive that is given its buffer when it is submitted holds that
//! buffer for as long as nothing comes. The other way is to give the
//! kernel a *group* of buffers, and have each operation pick one when it
//! has data to put there ([`Sqe::buffer_select`]); it is the only way for
//! [`Sqe::recv_multishot`] and [`Sqe::read_multishot`]. The completion
//! names the buffer that was picked ([`Cqe::buffer_id`]), which is from
//! then on the program's, until it gives it back. A group has a number,
//! of the program's choosing, and there are two kinds:
//!
//! - a [`BufRing`] (Linux 5.19) owns the memory and shares a ring of
//!   buffers with the kernel: giving a buffer back is a write to that
//!   ring. It keeps track of which buffers the program holds, so that
//!   reading one ([`BufRing::bytes`]) and giving it back
//!   ([`BufRing::give_back`]) are safe;
//! - [`Sqe::provide_buffers`] (every kernel oscall supports) gives the
//!   kernel memory of the caller's with an entry, and gives a buffer back
//!   with another. Nothing is tracked: all of it is the caller's promise.
//!
//! Two things are promised by `unsafe` either way. The entry that selects
//! says the memory of the group outlives it: the kernel may hold a buffer
//! it picked for as long as the operation runs. And whoever turns a
//! completion into a buffer ([`BufRing::take`]) says the completion is of
//! that group: the number in it is all there is to go by.
//!
//! # Zero-copy sends
//!
//! [`Sqe::send_zc`] and [`Sqe::sendmsg_zc`] send from the program's pages
//! instead of copying them into the socket's buffer. The memory is then in
//! use until the network stack is done with it, which is later than the
//! send: such an entry has **two completions**. The first has the result
//! of the send and [`Cqe::has_more`]; the second, which
//! [`Cqe::is_notification`] tells apart, comes when the memory is the
//! program's again, and that may be long after (an acknowledgement from
//! the peer, for TCP). A send that fails has the two as well, once the
//! kernel has started on it (a socket that is not connected, on Linux
//! 6.18), and one, without `has_more`, when the entry itself is refused:
//! the flag is what tells, never the result.
//!
//! The kernel copies all the same when it cannot do otherwise (a loopback
//! connection, a device without the feature), and the two completions come
//! regardless. It pays for large sends on real devices only: each one
//! pins pages and posts a second completion.
//!
//! # What is not here
//!
//! - *Direct descriptors*: operations that put the file they make
//!   (accept, open, socket) straight into the table of registered files.
//!   [`Sqe::from_raw`] makes them (`file_index`).
//! - *Bundles* and *incremental* buffer rings (`IORING_RECVSEND_BUNDLE`,
//!   `IOU_PBUF_RING_INC`), where a completion covers several buffers or
//!   part of one: a [`BufRing`] hands out whole buffers, one a completion.
//! - `recvmsg` as a multishot, whose buffers start with a header of the
//!   kernel's.
//! - Polling the device for completions (`IORING_SETUP_IOPOLL`), rings
//!   on memory the program supplies (`IORING_SETUP_NO_MMAP`) or without
//!   the array of indexes (`IORING_SETUP_NO_SQARRAY`), resizing, and
//!   NAPI.
//!
//! # Where there is no io_uring
//!
//! [`Ring::new`] reports what the kernel says, and there are three ways for
//! it to say no:
//!
//! - [`Unsupported`](crate::ErrorKind::Unsupported) (`ENOSYS`): the kernel
//!   was built without it, or the program runs under an emulator that does
//!   not pass it on (qemu-user);
//! - [`PermissionDenied`](crate::ErrorKind::PermissionDenied) (`EPERM`):
//!   the system call filter of a container refuses it, as Docker's default
//!   one does, or the administrator turned it off
//!   (`kernel.io_uring_disabled`);
//! - [`OutOfMemory`](crate::ErrorKind::OutOfMemory) (`ENOMEM`): the locked
//!   memory limit of the user leaves no room for the queues, on kernels
//!   that charge them to it.
//!
//! A program must be ready for all three and have another way: this is why
//! oscall has no portable interface made of it (see `docs/plan.md`).
//!
//! # What an older kernel lacks
//!
//! The operations came with different kernels; the oldest one oscall
//! supports (5.10) has those of reading, writing, sockets, timeouts,
//! polling, cancelling, opening, `statx`, `fallocate`, the advice calls,
//! `splice`, `tee` and provided buffers, and each constructor that needs a
//! newer one says which. A program finds out in one of four ways, by what
//! is missing:
//!
//! - *an operation*: the ring asks the kernel which it has when it is
//!   made ([`Ring::probe`]), and [`Ring::push`] refuses an entry of one it
//!   lacks with [`Unsupported`](crate::ErrorKind::Unsupported), before
//!   anything is queued;
//! - *a registration* ([`BufRing::new`], [`Ring::register_ring_fd`]...):
//!   the call fails with `Unsupported`. (The kernel says `EINVAL` to a
//!   registration it does not know as to one it finds wrong; the two are
//!   told apart by an operation of the same release being there or not.)
//! - *a way of using an operation it has* (the multishot forms, cancelling
//!   by handle): the entry completes with
//!   [`InvalidInput`](crate::ErrorKind::InvalidInput), which is all the
//!   kernel says;
//! - *an option of the ring* ([`Setup`]): [`Ring::with_setup`] fails with
//!   `InvalidInput`.

use core::ffi::{CStr, c_void};
use core::fmt;
use core::marker::PhantomData;
use core::ptr::{self, NonNull};
use core::sync::atomic::{AtomicU16, AtomicU32, Ordering, fence};
use core::time::Duration;

use crate::event::{Interest, Readiness};
use crate::fs::{Metadata, OpenOptions};
use crate::io::{IoSlice, IoSliceMut};
use crate::macros::flags;
use crate::net::{
    Address, AsSocket, Family, Protocol, RawAddr, RecvFlags, SendFlags, Shutdown, Type,
};
use crate::sys::uring as sys;
use crate::{AsHandle, BorrowedHandle, Error, ErrorKind, OwnedHandle, Result};

// ---------------------------------------------------------------------------
// Entries
// ---------------------------------------------------------------------------

/// A submission entry as the kernel lays it out: `struct io_uring_sqe`, 64
/// bytes, with the first member of each of its unions.
///
/// It is public for [`Sqe::from_raw`], which makes an entry of any
/// operation the kernel has, whether or not this module knows it. The
/// meaning of each field depends on the operation: see `io_uring_enter(2)`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[repr(C)]
pub struct RawSqe {
    /// The operation: an `IORING_OP_*` value (see [`Opcode`]).
    pub opcode: u8,
    /// `IOSQE_*` flags.
    pub flags: u8,
    /// The I/O priority of the request, or flags of the operation.
    pub ioprio: u16,
    /// The descriptor to work on, or an index among the registered files.
    pub fd: i32,
    /// An offset in the file; `addr2` for some operations.
    pub off: u64,
    /// A pointer to a buffer or to an array of buffers.
    pub addr: u64,
    /// The length of the buffer, or the number of buffers.
    pub len: u32,
    /// The flags of the operation (`rw_flags`, `msg_flags`,
    /// `timeout_flags`, `poll32_events`...).
    pub op_flags: u32,
    /// What the completion carries back.
    pub user_data: u64,
    /// An index among the registered buffers, or a group of buffers.
    pub buf_index: u16,
    /// The personality to run the request with.
    pub personality: u16,
    /// `splice_fd_in`, `file_index`, `addr_len`... by operation.
    pub file_index: u32,
    /// A third address, by operation.
    pub addr3: u64,
    /// Must be zero.
    pub pad: u64,
}

/// A completion entry: `struct io_uring_cqe`, the user data of the
/// submission and its result.
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct Cqe {
    user_data: u64,
    res: i32,
    flags: u32,
}

/// `struct __kernel_timespec`: a time for [`Sqe::timeout`], in seconds and
/// nanoseconds, both 64 bits wide on every architecture.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[repr(C)]
pub struct Timespec {
    /// Seconds.
    pub sec: i64,
    /// Nanoseconds, below a thousand million.
    pub nsec: i64,
}

const _: () = {
    assert!(size_of::<RawSqe>() == 64);
    assert!(core::mem::offset_of!(RawSqe, user_data) == 32);
    assert!(core::mem::offset_of!(RawSqe, addr3) == 48);
    assert!(size_of::<Cqe>() == 16);
    assert!(size_of::<Timespec>() == 16);
    assert!(size_of::<SockAddr>() >= RawAddr::CAPACITY + 4);
};

impl From<Duration> for Timespec {
    /// Seconds beyond what the kernel counts saturate.
    fn from(duration: Duration) -> Self {
        Self {
            sec: i64::try_from(duration.as_secs()).unwrap_or(i64::MAX),
            nsec: duration.subsec_nanos().into(),
        }
    }
}

/// A socket address in the system's layout, with its length: what
/// [`Sqe::connect`] reads and [`Sqe::accept`] fills.
#[repr(transparent)]
pub struct SockAddr(RawAddr);

impl SockAddr {
    /// Room for an address the kernel will write ([`Sqe::accept`]).
    pub fn new() -> Self {
        let mut raw = RawAddr::new();
        // The kernel is told how much room there is, and writes back how
        // much it used.
        raw.set_len(RawAddr::CAPACITY);
        Self(raw)
    }

    /// The address `addr`, for [`Sqe::connect`].
    ///
    /// Fails with [`InvalidInput`](ErrorKind::InvalidInput) for the unnamed
    /// Unix address, which names nothing to connect to.
    pub fn from_address(addr: &Address) -> Result<Self> {
        RawAddr::encode(addr).map(Self)
    }

    /// Says how long the address is that the kernel wrote here for a
    /// [received message](Sqe::recvmsg): the
    /// [`name_len`](MsgHdr::name_len) of its header, where the kernel
    /// left it. (An [accept](Sqe::accept) writes the length here itself.)
    pub fn set_received_len(&mut self, len: u32) {
        self.0.set_len((len as usize).min(RawAddr::CAPACITY));
    }

    /// The address held: the one given, or the one the kernel wrote once an
    /// [accept](Sqe::accept) has completed. `None` if there is none yet, or
    /// if it is of a family oscall has no type for.
    pub fn address(&self) -> Option<Address> {
        self.0.decode()
    }
}

impl Default for SockAddr {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for SockAddr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("SockAddr").field(&self.address()).finish()
    }
}

/// `struct msghdr`, as the kernel reads it from a program: what
/// [`Sqe::sendmsg`] and [`Sqe::recvmsg`] point to. The members are
/// pointers and `size_t` lengths, so the layout is the target's own.
///
/// An array of [`IoSlice`] or [`IoSliceMut`] is an array of `struct iovec`:
/// that is what `iov` points to.
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct MsgHdr {
    /// The address to send to, or where to write the sender's: a
    /// [`SockAddr`], or null.
    pub name: *mut c_void,
    /// The length of the address, or the room there is for one.
    pub name_len: u32,
    /// An array of buffers (`struct iovec`).
    pub iov: *mut c_void,
    /// How many buffers there are.
    pub iov_len: usize,
    /// Control messages (`cmsg(3)`), or null.
    pub control: *mut c_void,
    /// The length of the control messages, or the room there is for them.
    pub control_len: usize,
    /// The flags of a message received (`MSG_TRUNC`...): written by the
    /// kernel, ignored when sending.
    pub flags: i32,
}

impl MsgHdr {
    /// A header that names nothing.
    #[inline]
    pub const fn new() -> Self {
        Self {
            name: ptr::null_mut(),
            name_len: 0,
            iov: ptr::null_mut(),
            iov_len: 0,
            control: ptr::null_mut(),
            control_len: 0,
            flags: 0,
        }
    }

    /// Names `addr` as the address to send to. The header keeps a pointer
    /// to it.
    #[inline]
    pub fn to(mut self, addr: &SockAddr) -> Self {
        self.name = ptr::from_ref(addr).cast_mut().cast();
        self.name_len = addr.0.len();
        self
    }

    /// Names `addr`, a [`SockAddr::new`], as the room for the address of
    /// the sender. Once the message is received,
    /// [`SockAddr::set_received_len`] with [`name_len`](Self::name_len)
    /// makes it readable.
    #[inline]
    pub const fn from(mut self, addr: *mut SockAddr) -> Self {
        self.name = addr.cast();
        self.name_len = RawAddr::CAPACITY as u32;
        self
    }

    /// Names `count` buffers at `bufs`: an array of [`IoSlice`] or of
    /// [`IoSliceMut`].
    #[inline]
    pub const fn buffers<T>(mut self, bufs: *const T, count: usize) -> Self {
        self.iov = bufs.cast_mut().cast();
        self.iov_len = count;
        self
    }
}

impl Default for MsgHdr {
    fn default() -> Self {
        Self::new()
    }
}

/// `struct statx`: where [`Sqe::statx`] has the kernel write what it knows
/// of a file.
#[repr(transparent)]
pub struct Statx(crate::sys::fs::Statx);

impl Statx {
    /// Room for the kernel's answer.
    #[inline]
    pub fn new() -> Self {
        Self(crate::sys::fs::Statx::default())
    }

    /// What the kernel wrote, as [`fs::metadata`](crate::fs::metadata)
    /// returns it. Meaningless before the completion of the entry has been
    /// taken, and if it failed.
    pub fn metadata(&self) -> Metadata {
        crate::sys::fs::statx_metadata(&self.0)
    }
}

impl Default for Statx {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for Statx {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Statx").finish_non_exhaustive()
    }
}

/// `siginfo_t`: where [`Sqe::waitid_pid`] and [`Sqe::waitid_pidfd`] have
/// the kernel write how a child ended. 128 bytes.
#[derive(Clone, Copy)]
#[repr(C, align(8))]
pub struct WaitInfo([i32; 32]);

/// `CLD_EXITED`, `CLD_KILLED` and `CLD_DUMPED`: the `si_code` of a child
/// that ended.
const CLD_EXITED: i32 = 1;
const CLD_KILLED: i32 = 2;
const CLD_DUMPED: i32 = 3;

impl WaitInfo {
    /// Three `int`s (`si_signo`, `si_errno`, `si_code`), then a union that
    /// is aligned like a pointer: this is the index of its first `int`,
    /// `si_pid`; `si_uid` and `si_status` follow.
    const FIELDS: usize = if cfg!(target_pointer_width = "64") {
        4
    } else {
        3
    };

    /// Room for the kernel's answer.
    #[inline]
    pub const fn new() -> Self {
        Self([0; 32])
    }

    /// The identifier of the child that ended, or `None` if nothing was
    /// written: the completion has not come, or it failed.
    #[inline]
    pub fn pid(&self) -> Option<u32> {
        match self.0[Self::FIELDS] {
            0 => None,
            pid => Some(pid as u32),
        }
    }

    /// The exit code of a child that exited.
    #[inline]
    pub fn exit_code(&self) -> Option<i32> {
        (self.pid().is_some() && self.0[2] == CLD_EXITED).then(|| self.0[Self::FIELDS + 2])
    }

    /// The signal that ended a child that did not exit by itself.
    #[inline]
    pub fn signal(&self) -> Option<i32> {
        (self.pid().is_some() && matches!(self.0[2], CLD_KILLED | CLD_DUMPED))
            .then(|| self.0[Self::FIELDS + 2])
    }
}

impl Default for WaitInfo {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for WaitInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WaitInfo")
            .field("pid", &self.pid())
            .field("exit_code", &self.exit_code())
            .field("signal", &self.signal())
            .finish()
    }
}

const _: () = {
    assert!(size_of::<MsgHdr>() == 7 * size_of::<usize>());
    assert!(size_of::<Statx>() == 256);
    assert!(size_of::<WaitInfo>() == 128);
    assert!(size_of::<Restriction>() == 16);
    assert!(size_of::<FileSlot<'_>>() == 4);
};

/// What a program says of how it will use a range of a file
/// ([`Sqe::fadvise`]) or of memory ([`Sqe::madvise`]): the values the two
/// calls share (`POSIX_FADV_*`, `MADV_*`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u8)]
pub enum Advice {
    /// Nothing in particular: the default.
    Normal = 0,
    /// In no order: reading ahead is of no use.
    Random = 1,
    /// From start to end: read ahead more.
    Sequential = 2,
    /// Soon: start reading it in.
    WillNeed = 3,
    /// Not any more. For a file, what the system holds of the range may be
    /// let go. For memory this is `MADV_DONTNEED`, which *discards* the
    /// contents of private anonymous pages: they read as zeros afterwards.
    DontNeed = 4,
}

flags! {
    /// How [`Sqe::fallocate`] changes a file. The values are the kernel's
    /// (`FALLOC_FL_*`); none is the plain reservation
    /// [`fs::allocate`](crate::fs::allocate) makes.
    pub struct FallocateMode: u32 {
        /// Do not change the length of the file.
        const KEEP_SIZE = 0x01;
        /// Free the range, which then reads as zeros: with
        /// [`KEEP_SIZE`](Self::KEEP_SIZE), always.
        const PUNCH_HOLE = 0x02;
        /// Remove the range, the rest of the file moving down.
        const COLLAPSE_RANGE = 0x08;
        /// Make the range read as zeros.
        const ZERO_RANGE = 0x10;
        /// Insert a hole, the rest of the file moving up.
        const INSERT_RANGE = 0x20;
    }
}

flags! {
    /// How [`Sqe::renameat`] renames. The values are the kernel's
    /// (`RENAME_*`).
    pub struct RenameFlags: u32 {
        /// Fail with [`AlreadyExists`](ErrorKind::AlreadyExists) rather
        /// than replace.
        const NO_REPLACE = 1 << 0;
        /// Exchange the two names, both of which must exist.
        const EXCHANGE = 1 << 1;
    }
}

flags! {
    /// How [`Sqe::splice`] and [`Sqe::tee`] move data. The values are the
    /// kernel's (`SPLICE_F_*`).
    pub struct SpliceFlags: u32 {
        /// Move pages instead of copying them, where that can be done.
        const MOVE = 1 << 0;
        /// Do not wait for a pipe.
        const NONBLOCK = 1 << 1;
        /// More is coming: a hint for a socket.
        const MORE = 1 << 2;
    }
}

/// A place in the table of [registered files](Ring::register_files), as
/// [`Ring::register_files_update`] is told to fill it.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct FileSlot<'a>(i32, PhantomData<BorrowedHandle<'a>>);

impl<'a> FileSlot<'a> {
    /// Nothing: what was there is released.
    pub const EMPTY: Self = Self(-1, PhantomData);
    /// What is there stays (`IORING_REGISTER_FILES_SKIP`).
    pub const KEEP: Self = Self(-2, PhantomData);

    /// The file of `handle`.
    #[inline]
    pub const fn file(handle: BorrowedHandle<'a>) -> Self {
        Self(handle.as_raw(), PhantomData)
    }
}

impl fmt::Debug for FileSlot<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            -1 => f.write_str("FileSlot::EMPTY"),
            -2 => f.write_str("FileSlot::KEEP"),
            fd => f.debug_tuple("FileSlot").field(&fd).finish(),
        }
    }
}

/// The registrations a [restricted](Ring::register_restrictions) ring may
/// be left: the kernel's `IORING_REGISTER_*` values.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u8)]
pub enum RegisterOp {
    /// [`Ring::register_buffers`].
    Buffers = 0,
    /// [`Ring::unregister_buffers`].
    UnregisterBuffers = 1,
    /// [`Ring::register_files`].
    Files = 2,
    /// [`Ring::unregister_files`].
    UnregisterFiles = 3,
    /// [`Ring::register_eventfd`].
    Eventfd = 4,
    /// [`Ring::unregister_eventfd`].
    UnregisterEventfd = 5,
    /// [`Ring::register_files_update`].
    FilesUpdate = 6,
    /// Asking which operations there are, which a [`Ring`] does once, when
    /// it is made.
    Probe = 8,
    /// [`Ring::register_restrictions`].
    Restrictions = 11,
    /// [`Ring::enable`].
    EnableRings = 12,
    /// [`Ring::register_files_sparse`].
    Files2 = 13,
    /// [`Ring::set_iowq_affinity`].
    IowqAff = 17,
    /// [`Ring::clear_iowq_affinity`].
    UnregisterIowqAff = 18,
    /// [`Ring::set_iowq_max_workers`].
    IowqMaxWorkers = 19,
    /// [`Ring::register_ring_fd`].
    RingFds = 20,
    /// [`Ring::unregister_ring_fd`].
    UnregisterRingFds = 21,
    /// [`BufRing::new`].
    PbufRing = 22,
    /// Dropping a [`BufRing`].
    UnregisterPbufRing = 23,
}

/// One thing a ring is allowed once it is
/// [restricted](Ring::register_restrictions): `struct
/// io_uring_restriction`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct Restriction {
    opcode: u16,
    value: u8,
    resv: u8,
    resv2: [u32; 3],
}

impl Restriction {
    const fn new(opcode: u16, value: u8) -> Self {
        Self {
            opcode,
            value,
            resv: 0,
            resv2: [0; 3],
        }
    }

    /// Allows the operation `opcode` in entries.
    #[inline]
    pub const fn op(opcode: Opcode) -> Self {
        Self::op_raw(opcode as u8)
    }

    /// Allows the operation of this number (`IORING_OP_*`) in entries.
    #[inline]
    pub const fn op_raw(opcode: u8) -> Self {
        Self::new(sys::IORING_RESTRICTION_SQE_OP, opcode)
    }

    /// Allows the registration `op`.
    #[inline]
    pub const fn register(op: RegisterOp) -> Self {
        Self::register_raw(op as u8)
    }

    /// Allows the registration of this number (`IORING_REGISTER_*`).
    #[inline]
    pub const fn register_raw(op: u8) -> Self {
        Self::new(sys::IORING_RESTRICTION_REGISTER_OP, op)
    }

    /// Allows entries to have these flags, and no other.
    #[inline]
    pub const fn flags_allowed(flags: SqeFlags) -> Self {
        Self::new(sys::IORING_RESTRICTION_SQE_FLAGS_ALLOWED, flags.bits())
    }

    /// Makes every entry have these flags.
    #[inline]
    pub const fn flags_required(flags: SqeFlags) -> Self {
        Self::new(sys::IORING_RESTRICTION_SQE_FLAGS_REQUIRED, flags.bits())
    }
}

/// The operations this module names: the kernel's `IORING_OP_*` values,
/// for [`Probe::supports`] and [`RawSqe::opcode`].
///
/// The kernel has more, and gains some with every release:
/// [`Probe::supports_raw`] and [`Sqe::from_raw`] take any number.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u8)]
pub enum Opcode {
    /// Nothing: [`Sqe::nop`].
    Nop = 0,
    /// [`Sqe::readv`].
    Readv = 1,
    /// [`Sqe::writev`].
    Writev = 2,
    /// [`Sqe::fsync`].
    Fsync = 3,
    /// [`Sqe::read_fixed`].
    ReadFixed = 4,
    /// [`Sqe::write_fixed`].
    WriteFixed = 5,
    /// [`Sqe::poll_add`], [`Sqe::poll_multishot`].
    PollAdd = 6,
    /// [`Sqe::poll_remove`].
    PollRemove = 7,
    /// [`Sqe::sendmsg`].
    Sendmsg = 9,
    /// [`Sqe::recvmsg`].
    Recvmsg = 10,
    /// [`Sqe::timeout`], [`Sqe::timeout_multishot`].
    Timeout = 11,
    /// [`Sqe::timeout_remove`].
    TimeoutRemove = 12,
    /// [`Sqe::accept`], [`Sqe::accept_multishot`].
    Accept = 13,
    /// [`Sqe::cancel`] and its kin.
    AsyncCancel = 14,
    /// [`Sqe::link_timeout`].
    LinkTimeout = 15,
    /// [`Sqe::connect`].
    Connect = 16,
    /// [`Sqe::fallocate`].
    Fallocate = 17,
    /// [`Sqe::openat`].
    Openat = 18,
    /// [`Sqe::close`].
    Close = 19,
    /// [`Sqe::statx`].
    Statx = 21,
    /// [`Sqe::read`].
    Read = 22,
    /// [`Sqe::write`].
    Write = 23,
    /// [`Sqe::fadvise`].
    Fadvise = 24,
    /// [`Sqe::madvise`].
    Madvise = 25,
    /// [`Sqe::send`].
    Send = 26,
    /// [`Sqe::recv`], [`Sqe::recv_multishot`].
    Recv = 27,
    /// `openat2`.
    Openat2 = 28,
    /// [`Sqe::splice`].
    Splice = 30,
    /// [`Sqe::provide_buffers`].
    ProvideBuffers = 31,
    /// [`Sqe::remove_buffers`].
    RemoveBuffers = 32,
    /// [`Sqe::tee`].
    Tee = 33,
    /// [`Sqe::shutdown`] (Linux 5.11).
    Shutdown = 34,
    /// [`Sqe::renameat`] (Linux 5.11).
    Renameat = 35,
    /// [`Sqe::unlinkat`] (Linux 5.11).
    Unlinkat = 36,
    /// [`Sqe::mkdirat`] (Linux 5.15).
    Mkdirat = 37,
    /// [`Sqe::symlinkat`] (Linux 5.15).
    Symlinkat = 38,
    /// [`Sqe::linkat`] (Linux 5.15).
    Linkat = 39,
    /// [`Sqe::msg_ring`] (Linux 5.18).
    MsgRing = 40,
    /// [`Sqe::socket`] (Linux 5.19).
    Socket = 45,
    /// [`Sqe::uring_cmd`] (Linux 5.19).
    UringCmd = 46,
    /// [`Sqe::send_zc`] (Linux 6.0).
    SendZc = 47,
    /// [`Sqe::sendmsg_zc`] (Linux 6.1).
    SendmsgZc = 48,
    /// [`Sqe::read_multishot`] (Linux 6.7).
    ReadMultishot = 49,
    /// [`Sqe::waitid_pid`], [`Sqe::waitid_pidfd`] (Linux 6.7).
    Waitid = 50,
    /// [`Sqe::futex_wait`] (Linux 6.7).
    FutexWait = 51,
    /// [`Sqe::futex_wake`] (Linux 6.7).
    FutexWake = 52,
}

flags! {
    /// How the kernel treats an entry among the others: [`Sqe::flags`].
    /// The values are the kernel's (`IOSQE_*`).
    pub struct SqeFlags: u8 {
        /// The entry names a registered file. [`Sqe::fixed_file`] sets
        /// it, and [`Sqe::flags`] does not: it is here for
        /// [`Restriction::flags_allowed`] and
        /// [`Restriction::flags_required`].
        const FIXED_FILE = 1 << 0;
        /// The entries pushed before this one complete before it starts.
        const DRAIN = 1 << 1;
        /// The next entry starts when this one has succeeded, and is
        /// cancelled if it fails (a short read or write is a failure
        /// here): a *link*, which goes on for as long as entries have the
        /// flag.
        const LINK = 1 << 2;
        /// As [`LINK`](Self::LINK), but the next entry starts whatever
        /// happened to this one.
        const HARD_LINK = 1 << 3;
        /// Do not try the operation at once: hand it to a worker thread
        /// of the kernel straight away.
        const ASYNC = 1 << 4;
        /// The kernel picks the buffer from a group.
        /// [`Sqe::buffer_select`] sets it, and [`Sqe::flags`] does not: it
        /// is here for the restrictions, as
        /// [`FIXED_FILE`](Self::FIXED_FILE) is.
        const BUFFER_SELECT = 1 << 5;
        /// No completion if the operation succeeds (Linux 5.17:
        /// [`Features::CQE_SKIP`]; `InvalidInput` in the completion
        /// before). [`Ring::in_flight`] then counts the entry for ever.
        const CQE_SKIP_SUCCESS = 1 << 6;
    }
}

flags! {
    /// What the running kernel's io_uring can do: [`Ring::features`]. The
    /// values are the kernel's (`IORING_FEAT_*`); a kernel may set bits
    /// that have no name here.
    pub struct Features: u32 {
        /// The two queues are one mapping (Linux 5.4).
        const SINGLE_MMAP = 1 << 0;
        /// Completions that find the queue full are kept, not dropped
        /// (Linux 5.5).
        const NODROP = 1 << 1;
        /// What an entry points to, other than buffers to transfer, need
        /// not outlive [`Ring::submit`] (Linux 5.5).
        const SUBMIT_STABLE = 1 << 2;
        /// An offset of `u64::MAX` means the position of the handle
        /// (Linux 5.6).
        const RW_CUR_POS = 1 << 3;
        /// Operations on sockets and pipes wait for readiness in the
        /// kernel, with no worker thread (Linux 5.7).
        const FAST_POLL = 1 << 5;
        /// [`Ring::wait`] takes a timeout (Linux 5.11).
        const EXT_ARG = 1 << 8;
        /// A ring whose queue a kernel thread polls ([`Setup::sqpoll`])
        /// takes handles that are not registered (Linux 5.11).
        const SQPOLL_NONFIXED = 1 << 7;
        /// The workers are threads of the process (Linux 5.12).
        const NATIVE_WORKERS = 1 << 9;
        /// Registered files and buffers can be tagged and updated (Linux
        /// 5.13).
        const RSRC_TAGS = 1 << 10;
        /// [`SqeFlags::CQE_SKIP_SUCCESS`] (Linux 5.17).
        const CQE_SKIP = 1 << 11;
    }
}

/// An offset that means "at the position of the handle, and move it", as
/// [`read`](crate::io::read()) does. See [`Sqe::read`].
pub const CURRENT_POSITION: u64 = u64::MAX;

/// A submission entry: one operation for the kernel to do, and the number
/// that will name its completion.
///
/// A constructor makes the entry of an operation; [`user_data`] and
/// [`flags`] then say how it is named and how it runs. An entry does
/// nothing until it is [pushed](Ring::push) and
/// [submitted](Ring::submit). It is plain data, and copying one makes
/// another request for the same operation, bound by the same
/// [contract](self#memory-where-unsafe-is).
///
/// [`user_data`]: Self::user_data
/// [`flags`]: Self::flags
#[derive(Clone, Copy, Debug)]
#[repr(transparent)]
pub struct Sqe(RawSqe);

/// The number of a handle, as an entry names it.
fn fd(handle: impl AsHandle) -> i32 {
    handle.as_handle().as_raw()
}

/// The number of a socket, which is a handle here.
fn socket_fd(socket: impl AsSocket) -> i32 {
    socket.as_socket().as_raw()
}

impl Sqe {
    const fn op(opcode: Opcode, fd: i32) -> RawSqe {
        RawSqe {
            opcode: opcode as u8,
            flags: 0,
            ioprio: 0,
            fd,
            off: 0,
            addr: 0,
            len: 0,
            op_flags: 0,
            user_data: 0,
            buf_index: 0,
            personality: 0,
            file_index: 0,
            addr3: 0,
            pad: 0,
        }
    }

    /// An entry made field by field: the way to any operation the kernel
    /// has.
    ///
    /// # Safety
    ///
    /// As the operation requires: whatever memory the entry names must be
    /// valid as the kernel uses it, until the completion of the entry has
    /// been taken from the ring it was pushed to. See the
    /// [module documentation](self#memory-where-unsafe-is).
    #[inline]
    pub const unsafe fn from_raw(raw: RawSqe) -> Self {
        Self(raw)
    }

    /// The entry, as the kernel will read it.
    #[inline]
    pub const fn as_raw(&self) -> &RawSqe {
        &self.0
    }

    /// Sets the number the completion of this entry will carry: any value,
    /// which the kernel only copies. It is 0 otherwise.
    #[inline]
    pub const fn user_data(mut self, user_data: u64) -> Self {
        self.0.user_data = user_data;
        self
    }

    /// Adds `flags` to the entry, apart from
    /// [`FIXED_FILE`](SqeFlags::FIXED_FILE) and
    /// [`BUFFER_SELECT`](SqeFlags::BUFFER_SELECT), which
    /// [`fixed_file`](Self::fixed_file) and
    /// [`buffer_select`](Self::buffer_select) set with what they need.
    #[inline]
    pub const fn flags(mut self, flags: SqeFlags) -> Self {
        self.0.flags |= flags.bits() & !(sys::IOSQE_FIXED_FILE | sys::IOSQE_BUFFER_SELECT);
        self
    }

    /// Makes the entry work on a [registered file](Ring::register_files)
    /// instead of the handle it was made with: `index` is its place in the
    /// slice that was registered.
    #[inline]
    pub const fn fixed_file(mut self, index: u32) -> Self {
        self.0.fd = index as i32;
        self.0.flags |= sys::IOSQE_FIXED_FILE;
        self
    }

    /// Does nothing, and completes with 0.
    #[inline]
    pub const fn nop() -> Self {
        Self(Self::op(Opcode::Nop, -1))
    }

    /// Reads up to `len` bytes from `handle` into `buf`, at `offset` bytes
    /// from the start of the file: the completion has the count, 0 at the
    /// end. `offset` is [`CURRENT_POSITION`] to read at the position of
    /// the handle and move it, which is the only way for a handle that has
    /// none (a pipe, a socket, a terminal).
    ///
    /// # Safety
    ///
    /// `buf` must be valid for writes of `len` bytes, and not used
    /// otherwise, until the completion of the entry has been taken: see
    /// the [module documentation](self#memory-where-unsafe-is).
    #[inline]
    pub unsafe fn read(handle: impl AsHandle, buf: *mut u8, len: u32, offset: u64) -> Self {
        let mut raw = Self::op(Opcode::Read, fd(handle));
        raw.addr = buf.addr() as u64;
        raw.len = len;
        raw.off = offset;
        Self(raw)
    }

    /// Writes `len` bytes from `buf` to `handle`, at `offset` (see
    /// [`read`](Self::read)): the completion has the count, which may be
    /// less.
    ///
    /// # Safety
    ///
    /// `buf` must be valid for reads of `len` bytes, and not written to,
    /// until the completion of the entry has been taken.
    #[inline]
    pub unsafe fn write(handle: impl AsHandle, buf: *const u8, len: u32, offset: u64) -> Self {
        let mut raw = Self::op(Opcode::Write, fd(handle));
        raw.addr = buf.addr() as u64;
        raw.len = len;
        raw.off = offset;
        Self(raw)
    }

    /// [`read`](Self::read) into `count` buffers, filling each before the
    /// next (`preadv2`).
    ///
    /// # Safety
    ///
    /// `bufs` must point to `count` buffers. The array and the buffers
    /// must be valid, and the buffers not used otherwise, until the
    /// completion of the entry has been taken. (The kernel has copied the
    /// array itself once the entry is submitted, where it says
    /// [`Features::SUBMIT_STABLE`].)
    #[inline]
    pub unsafe fn readv(
        handle: impl AsHandle,
        bufs: *const IoSliceMut<'_>,
        count: u32,
        offset: u64,
    ) -> Self {
        let mut raw = Self::op(Opcode::Readv, fd(handle));
        raw.addr = bufs.addr() as u64;
        raw.len = count;
        raw.off = offset;
        Self(raw)
    }

    /// [`write`](Self::write) from `count` buffers, in order (`pwritev2`).
    ///
    /// # Safety
    ///
    /// As [`readv`](Self::readv); the buffers are read.
    #[inline]
    pub unsafe fn writev(
        handle: impl AsHandle,
        bufs: *const IoSlice<'_>,
        count: u32,
        offset: u64,
    ) -> Self {
        let mut raw = Self::op(Opcode::Writev, fd(handle));
        raw.addr = bufs.addr() as u64;
        raw.len = count;
        raw.off = offset;
        Self(raw)
    }

    /// [`read`](Self::read) into memory that is part of a
    /// [registered buffer](Ring::register_buffers), the one at `index` in
    /// the slice that was registered: the kernel has the memory mapped
    /// already.
    ///
    /// # Safety
    ///
    /// As [`read`](Self::read). The range must lie within the registered
    /// buffer, or the operation fails.
    #[inline]
    pub unsafe fn read_fixed(
        handle: impl AsHandle,
        buf: *mut u8,
        len: u32,
        offset: u64,
        index: u16,
    ) -> Self {
        let mut raw = Self::op(Opcode::ReadFixed, fd(handle));
        raw.addr = buf.addr() as u64;
        raw.len = len;
        raw.off = offset;
        raw.buf_index = index;
        Self(raw)
    }

    /// [`write`](Self::write) from memory that is part of a
    /// [registered buffer](Ring::register_buffers).
    ///
    /// # Safety
    ///
    /// As [`write`](Self::write). The range must lie within the registered
    /// buffer, or the operation fails.
    #[inline]
    pub unsafe fn write_fixed(
        handle: impl AsHandle,
        buf: *const u8,
        len: u32,
        offset: u64,
        index: u16,
    ) -> Self {
        let mut raw = Self::op(Opcode::WriteFixed, fd(handle));
        raw.addr = buf.addr() as u64;
        raw.len = len;
        raw.off = offset;
        raw.buf_index = index;
        Self(raw)
    }

    /// Writes what the system holds of the file to its storage: all of it,
    /// or with `data_only` what is needed to read the data back
    /// (`fdatasync`).
    #[inline]
    pub fn fsync(handle: impl AsHandle, data_only: bool) -> Self {
        let mut raw = Self::op(Opcode::Fsync, fd(handle));
        if data_only {
            raw.op_flags = sys::IORING_FSYNC_DATASYNC;
        }
        Self(raw)
    }

    /// Accepts a connection on the listening `socket`. The completion has
    /// the number of the new socket, which is close-on-exec and blocking,
    /// and which nothing owns until it is given an owner:
    /// `OwnedSocket::from_raw(completion.result()? as i32)`.
    ///
    /// `addr` is where the kernel writes the address of the peer, or null.
    /// Give each accept a [`SockAddr::new`] of its own: the kernel reads
    /// from it how much room there is, and leaves there how much it used.
    ///
    /// # Safety
    ///
    /// `addr` must be null or point to a [`SockAddr::new`] that is valid,
    /// and not used otherwise, until the completion of the entry has been
    /// taken.
    #[inline]
    pub unsafe fn accept(socket: impl AsSocket, addr: *mut SockAddr) -> Self {
        let mut raw = Self::op(Opcode::Accept, socket_fd(socket));
        if !addr.is_null() {
            raw.addr = addr.addr() as u64;
            // `addr2`: where the length is.
            raw.off = (addr.addr() + RawAddr::LEN_OFFSET) as u64;
        }
        raw.op_flags = crate::sys::net::SOCK_CLOEXEC as u32;
        Self(raw)
    }

    /// Connects `socket` to `addr`. The completion has 0, or the error.
    ///
    /// # Safety
    ///
    /// `addr` must point to a [`SockAddr`] that is valid until the entry
    /// has been submitted (until its completion has been taken, on a
    /// kernel without [`Features::SUBMIT_STABLE`]).
    #[inline]
    pub unsafe fn connect(socket: impl AsSocket, addr: *const SockAddr) -> Self {
        let mut raw = Self::op(Opcode::Connect, socket_fd(socket));
        raw.addr = addr.addr() as u64;
        // SAFETY: the caller's contract: `addr` points to a `SockAddr`.
        raw.off = u64::from(unsafe { (*addr).0.len() });
        Self(raw)
    }

    /// Sends `len` bytes from `buf` on `socket`, as
    /// [`net::send`](crate::net::send) does: the completion has the count.
    /// No `SIGPIPE` is raised.
    ///
    /// # Safety
    ///
    /// As [`write`](Self::write).
    #[inline]
    pub unsafe fn send(socket: impl AsSocket, buf: *const u8, len: u32, flags: SendFlags) -> Self {
        let mut raw = Self::op(Opcode::Send, socket_fd(socket));
        raw.addr = buf.addr() as u64;
        raw.len = len;
        raw.op_flags = crate::sys::net::send_flags(flags) as u32;
        Self(raw)
    }

    /// Receives up to `len` bytes from `socket` into `buf`, as
    /// [`net::recv`](crate::net::recv) does: the completion has the count,
    /// 0 when the peer has closed a stream.
    ///
    /// # Safety
    ///
    /// As [`read`](Self::read).
    #[inline]
    pub unsafe fn recv(socket: impl AsSocket, buf: *mut u8, len: u32, flags: RecvFlags) -> Self {
        let mut raw = Self::op(Opcode::Recv, socket_fd(socket));
        raw.addr = buf.addr() as u64;
        raw.len = len;
        raw.op_flags = crate::sys::net::recv_flags(flags) as u32;
        Self(raw)
    }

    /// Shuts down one or both directions of `socket`, as
    /// [`net::shutdown`](crate::net::shutdown) does (Linux 5.11).
    #[inline]
    pub fn shutdown(socket: impl AsSocket, how: Shutdown) -> Self {
        let mut raw = Self::op(Opcode::Shutdown, socket_fd(socket));
        raw.len = match how {
            Shutdown::Read => 0,
            Shutdown::Write => 1,
            Shutdown::Both => 2,
        };
        Self(raw)
    }

    /// Completes when the time `*time` has passed, counted from the
    /// submission on the monotonic clock, with an error whose
    /// [`raw_os_error`](crate::Error::raw_os_error) is `ETIME` (its kind
    /// is [`TimedOut`](ErrorKind::TimedOut)): that is the timeout doing
    /// its job. With `count` other than 0 it completes earlier, with 0,
    /// once that many other completions have been posted.
    ///
    /// # Safety
    ///
    /// `time` must point to a [`Timespec`] that is valid until the entry
    /// has been submitted.
    #[inline]
    pub unsafe fn timeout(time: *const Timespec, count: u32) -> Self {
        let mut raw = Self::op(Opcode::Timeout, -1);
        raw.addr = time.addr() as u64;
        raw.len = 1;
        raw.off = u64::from(count);
        Self(raw)
    }

    /// As [`timeout`](Self::timeout), for a time of the monotonic clock
    /// ([`Clock::Monotonic`](crate::time::Clock::Monotonic)) instead of a
    /// delay.
    ///
    /// # Safety
    ///
    /// As [`timeout`](Self::timeout).
    #[inline]
    pub unsafe fn timeout_at(time: *const Timespec, count: u32) -> Self {
        // SAFETY: the caller's contract.
        let mut sqe = unsafe { Self::timeout(time, count) };
        sqe.0.op_flags = sys::IORING_TIMEOUT_ABS;
        sqe
    }

    /// Removes the [timeout](Self::timeout) whose user data is
    /// `user_data`: that one completes with
    /// [`Canceled`](ErrorKind::Canceled), this one with 0, or with
    /// [`NotFound`](ErrorKind::NotFound) if there is no such timeout (any
    /// more).
    #[inline]
    pub const fn timeout_remove(user_data: u64) -> Self {
        let mut raw = Self::op(Opcode::TimeoutRemove, -1);
        raw.addr = user_data;
        Self(raw)
    }

    /// Bounds the entry pushed just before this one, which must have
    /// [`SqeFlags::LINK`]: if that operation has not completed after
    /// `*time`, it is cancelled. This entry then completes with `ETIME`,
    /// and with [`Canceled`](ErrorKind::Canceled) if the operation
    /// completed in time.
    ///
    /// # Safety
    ///
    /// As [`timeout`](Self::timeout).
    #[inline]
    pub unsafe fn link_timeout(time: *const Timespec) -> Self {
        let mut raw = Self::op(Opcode::LinkTimeout, -1);
        raw.addr = time.addr() as u64;
        raw.len = 1;
        Self(raw)
    }

    /// Asks for the operation whose user data is `user_data` to be
    /// cancelled. This entry completes with 0 if it was, with
    /// [`NotFound`](ErrorKind::NotFound) if there is no such operation (it
    /// completed already), and with an error whose kind is
    /// [`InProgress`](ErrorKind::InProgress) (`EALREADY`) if it is running
    /// and may or may not stop.
    ///
    /// The operation itself always completes, with
    /// [`Canceled`](ErrorKind::Canceled) if it was stopped: its memory is
    /// in use until then.
    #[inline]
    pub const fn cancel(user_data: u64) -> Self {
        let mut raw = Self::op(Opcode::AsyncCancel, -1);
        raw.addr = user_data;
        Self(raw)
    }

    /// Completes once, when `handle` is ready for `interest`: the
    /// completion says what is true of it ([`Cqe::readiness`]). It is
    /// [`event::poll`](crate::event::poll) for one handle, without the
    /// wait.
    #[inline]
    pub fn poll_add(handle: impl AsHandle, interest: Interest) -> Self {
        let handle = handle.as_handle();
        let mut raw = Self::op(Opcode::PollAdd, handle.as_raw());
        let events = crate::sys::event::PollFd::new(handle.as_raw(), interest).events();
        // `poll32_events`, which is `poll_events` on a little-endian
        // target, the only kind oscall has.
        raw.op_flags = u32::from(events as u16);
        Self(raw)
    }

    /// Removes the [poll](Self::poll_add) whose user data is `user_data`,
    /// which completes with [`Canceled`](ErrorKind::Canceled); this entry
    /// completes with 0, or with [`NotFound`](ErrorKind::NotFound).
    #[inline]
    pub const fn poll_remove(user_data: u64) -> Self {
        let mut raw = Self::op(Opcode::PollRemove, -1);
        raw.addr = user_data;
        Self(raw)
    }

    /// Closes `handle`, which the entry now owns: an entry that is never
    /// submitted leaves it open for good.
    #[inline]
    pub fn close(handle: OwnedHandle) -> Self {
        Self(Self::op(Opcode::Close, handle.into_raw()))
    }

    /// Opens `path` as [`fs::open`](crate::fs::open) does, or relative to
    /// the directory `dir` as [`fs::open_at`](crate::fs::open_at) does
    /// (though nothing keeps the path under that directory here). The
    /// completion has the number of the new handle, which is close-on-exec
    /// and which nothing owns until it is given an owner:
    /// `OwnedHandle::from_raw(completion.result()? as i32)`.
    ///
    /// # Safety
    ///
    /// `path` must point to a NUL-terminated string that is valid until
    /// the entry has been submitted.
    #[inline]
    pub unsafe fn openat(
        dir: Option<BorrowedHandle<'_>>,
        path: *const core::ffi::c_char,
        options: &OpenOptions,
    ) -> Self {
        let dir = dir.map_or(crate::sys::fs::AT_FDCWD, BorrowedHandle::as_raw);
        let mut raw = Self::op(Opcode::Openat, dir);
        raw.addr = path.addr() as u64;
        raw.len = options.mode;
        raw.op_flags = crate::sys::fs::open_flags(options) as u32;
        Self(raw)
    }

    /// [`openat`](Self::openat) for a path that is a C string.
    ///
    /// # Safety
    ///
    /// As [`openat`](Self::openat): the string must live until the entry
    /// has been submitted, which is longer than this call.
    #[inline]
    pub unsafe fn open(path: &CStr, options: &OpenOptions) -> Self {
        // SAFETY: the caller's contract.
        unsafe { Self::openat(None, path.as_ptr(), options) }
    }

    // -- More of files ----------------------------------------------------

    /// Asks what `path` is, as [`fs::metadata`](crate::fs::metadata) does
    /// (or, when `follow` is false, as
    /// [`fs::symlink_metadata`](crate::fs::symlink_metadata)), relative to
    /// `dir` if there is one. The kernel writes to `out`, which
    /// [`Statx::metadata`] reads once the entry has completed with 0.
    ///
    /// # Safety
    ///
    /// `path` must point to a NUL-terminated string, and `out` to a
    /// [`Statx`] that is not used otherwise, both valid until the
    /// completion of the entry has been taken.
    #[inline]
    pub unsafe fn statx(
        dir: Option<BorrowedHandle<'_>>,
        path: *const core::ffi::c_char,
        follow: bool,
        out: *mut Statx,
    ) -> Self {
        let dir = dir.map_or(crate::sys::fs::AT_FDCWD, BorrowedHandle::as_raw);
        let mut raw = Self::op(Opcode::Statx, dir);
        raw.addr = path.addr() as u64;
        raw.off = out.addr() as u64;
        raw.len = crate::sys::fs::STATX_MASK;
        if !follow {
            raw.op_flags = crate::sys::fs::AT_SYMLINK_NOFOLLOW as u32;
        }
        Self(raw)
    }

    /// Reserves, frees or shifts `len` bytes of the file at `offset`, as
    /// `mode` says (`fallocate`); with no mode, reserves storage and
    /// extends the file to hold the range.
    #[inline]
    pub fn fallocate(handle: impl AsHandle, mode: FallocateMode, offset: u64, len: u64) -> Self {
        let mut raw = Self::op(Opcode::Fallocate, fd(handle));
        raw.off = offset;
        raw.addr = len;
        raw.len = mode.bits();
        Self(raw)
    }

    /// Tells the kernel how `len` bytes of the file at `offset` will be
    /// used (`posix_fadvise`); a length of 0 means up to the end.
    #[inline]
    pub fn fadvise(handle: impl AsHandle, offset: u64, len: u32, advice: Advice) -> Self {
        let mut raw = Self::op(Opcode::Fadvise, fd(handle));
        raw.off = offset;
        raw.len = len;
        raw.op_flags = advice as u32;
        Self(raw)
    }

    /// Tells the kernel how `len` bytes of memory at `addr` will be used
    /// (`madvise`).
    ///
    /// # Safety
    ///
    /// The range must be memory of the caller's that the advice may be
    /// applied to: [`Advice::DontNeed`] discards what private anonymous
    /// pages hold.
    #[inline]
    pub unsafe fn madvise(addr: *mut u8, len: u32, advice: Advice) -> Self {
        let mut raw = Self::op(Opcode::Madvise, -1);
        raw.addr = addr.addr() as u64;
        raw.len = len;
        raw.op_flags = advice as u32;
        Self(raw)
    }

    /// Renames `old_path` to `new_path`, each relative to its directory if
    /// it is given one, as [`fs::rename`](crate::fs::rename) does
    /// (`renameat2`; Linux 5.11).
    ///
    /// # Safety
    ///
    /// Both paths must point to NUL-terminated strings that are valid
    /// until the entry has been submitted.
    #[inline]
    pub unsafe fn renameat(
        old_dir: Option<BorrowedHandle<'_>>,
        old_path: *const core::ffi::c_char,
        new_dir: Option<BorrowedHandle<'_>>,
        new_path: *const core::ffi::c_char,
        flags: RenameFlags,
    ) -> Self {
        let at = |dir: Option<BorrowedHandle<'_>>| {
            dir.map_or(crate::sys::fs::AT_FDCWD, BorrowedHandle::as_raw)
        };
        let mut raw = Self::op(Opcode::Renameat, at(old_dir));
        raw.addr = old_path.addr() as u64;
        raw.len = at(new_dir) as u32;
        raw.off = new_path.addr() as u64;
        raw.op_flags = flags.bits();
        Self(raw)
    }

    /// Removes the file `path`, or with `directory` the empty directory
    /// `path`, relative to `dir` if there is one (`unlinkat`; Linux 5.11).
    ///
    /// # Safety
    ///
    /// `path` must point to a NUL-terminated string that is valid until
    /// the entry has been submitted.
    #[inline]
    pub unsafe fn unlinkat(
        dir: Option<BorrowedHandle<'_>>,
        path: *const core::ffi::c_char,
        directory: bool,
    ) -> Self {
        let dir = dir.map_or(crate::sys::fs::AT_FDCWD, BorrowedHandle::as_raw);
        let mut raw = Self::op(Opcode::Unlinkat, dir);
        raw.addr = path.addr() as u64;
        if directory {
            raw.op_flags = crate::sys::fs::AT_REMOVEDIR as u32;
        }
        Self(raw)
    }

    /// Creates the directory `path` with the permissions `mode` (less the
    /// file creation mask), relative to `dir` if there is one (`mkdirat`;
    /// Linux 5.15).
    ///
    /// # Safety
    ///
    /// As [`unlinkat`](Self::unlinkat).
    #[inline]
    pub unsafe fn mkdirat(
        dir: Option<BorrowedHandle<'_>>,
        path: *const core::ffi::c_char,
        mode: u32,
    ) -> Self {
        let dir = dir.map_or(crate::sys::fs::AT_FDCWD, BorrowedHandle::as_raw);
        let mut raw = Self::op(Opcode::Mkdirat, dir);
        raw.addr = path.addr() as u64;
        raw.len = mode;
        Self(raw)
    }

    /// Creates the symbolic link `link_path`, relative to `dir` if there
    /// is one, that points to `target` (`symlinkat`; Linux 5.15).
    ///
    /// # Safety
    ///
    /// Both must point to NUL-terminated strings that are valid until the
    /// entry has been submitted.
    #[inline]
    pub unsafe fn symlinkat(
        target: *const core::ffi::c_char,
        dir: Option<BorrowedHandle<'_>>,
        link_path: *const core::ffi::c_char,
    ) -> Self {
        let dir = dir.map_or(crate::sys::fs::AT_FDCWD, BorrowedHandle::as_raw);
        let mut raw = Self::op(Opcode::Symlinkat, dir);
        raw.addr = target.addr() as u64;
        raw.off = link_path.addr() as u64;
        Self(raw)
    }

    /// Gives the file `old_path` the second name `new_path`, each relative
    /// to its directory if it is given one (`linkat`; Linux 5.15). With
    /// `follow`, a symbolic link at `old_path` is followed, instead of
    /// being given the name itself.
    ///
    /// # Safety
    ///
    /// As [`renameat`](Self::renameat).
    #[inline]
    pub unsafe fn linkat(
        old_dir: Option<BorrowedHandle<'_>>,
        old_path: *const core::ffi::c_char,
        new_dir: Option<BorrowedHandle<'_>>,
        new_path: *const core::ffi::c_char,
        follow: bool,
    ) -> Self {
        /// `AT_SYMLINK_FOLLOW`.
        const FOLLOW: u32 = 0x400;
        let at = |dir: Option<BorrowedHandle<'_>>| {
            dir.map_or(crate::sys::fs::AT_FDCWD, BorrowedHandle::as_raw)
        };
        let mut raw = Self::op(Opcode::Linkat, at(old_dir));
        raw.addr = old_path.addr() as u64;
        raw.len = at(new_dir) as u32;
        raw.off = new_path.addr() as u64;
        if follow {
            raw.op_flags = FOLLOW;
        }
        Self(raw)
    }

    /// Moves up to `len` bytes from `from` to `to`, one of which must be a
    /// pipe, without their passing through the program (`splice`). An
    /// offset is `None` for a pipe, and for a file to use and move the
    /// position of its handle. The completion has the count.
    ///
    /// [`fixed_file`](Self::fixed_file) on this entry is about `to`.
    #[inline]
    pub fn splice(
        from: impl AsHandle,
        from_offset: Option<u64>,
        to: impl AsHandle,
        to_offset: Option<u64>,
        len: u32,
        flags: SpliceFlags,
    ) -> Self {
        let mut raw = Self::op(Opcode::Splice, fd(to));
        // `splice_fd_in` and `splice_off_in`.
        raw.file_index = fd(from) as u32;
        raw.addr = from_offset.unwrap_or(u64::MAX);
        raw.off = to_offset.unwrap_or(u64::MAX);
        raw.len = len;
        raw.op_flags = flags.bits();
        Self(raw)
    }

    /// Copies up to `len` bytes from the pipe `from` to the pipe `to`,
    /// leaving them in `from` (`tee`). The completion has the count.
    #[inline]
    pub fn tee(from: impl AsHandle, to: impl AsHandle, len: u32, flags: SpliceFlags) -> Self {
        let mut raw = Self::op(Opcode::Tee, fd(to));
        raw.file_index = fd(from) as u32;
        raw.len = len;
        raw.op_flags = flags.bits();
        Self(raw)
    }

    // -- More of sockets --------------------------------------------------

    /// Creates a socket, as [`net::socket`](crate::net::socket) does
    /// (Linux 5.19). The completion has its number, which is close-on-exec
    /// and which nothing owns until it is given an owner:
    /// `OwnedSocket::from_raw(completion.result()? as i32)`.
    #[inline]
    pub fn socket(family: Family, ty: Type, protocol: Protocol) -> Self {
        let mut raw = Self::op(Opcode::Socket, crate::sys::net::family(family));
        raw.off = (crate::sys::net::socket_kind(ty) | crate::sys::net::SOCK_CLOEXEC) as u64;
        raw.len = protocol.number() as u32;
        Self(raw)
    }

    /// Sends the message `*msg` describes on `socket` (`sendmsg`): the
    /// completion has the count. No `SIGPIPE` is raised.
    ///
    /// # Safety
    ///
    /// `msg` must point to a [`MsgHdr`]. It and everything it names must
    /// be valid, and the buffers not written to, until the completion of
    /// the entry has been taken.
    #[inline]
    pub unsafe fn sendmsg(socket: impl AsSocket, msg: *const MsgHdr, flags: SendFlags) -> Self {
        let mut raw = Self::op(Opcode::Sendmsg, socket_fd(socket));
        raw.addr = msg.addr() as u64;
        raw.len = 1;
        raw.op_flags = crate::sys::net::send_flags(flags) as u32;
        Self(raw)
    }

    /// Receives a message on `socket` into what `*msg` describes
    /// (`recvmsg`): the completion has the count, and the kernel writes
    /// to the header the lengths it used and the flags of the message.
    ///
    /// # Safety
    ///
    /// `msg` must point to a [`MsgHdr`]. It and everything it names must
    /// be valid, and not used otherwise, until the completion of the entry
    /// has been taken.
    #[inline]
    pub unsafe fn recvmsg(socket: impl AsSocket, msg: *mut MsgHdr, flags: RecvFlags) -> Self {
        let mut raw = Self::op(Opcode::Recvmsg, socket_fd(socket));
        raw.addr = msg.addr() as u64;
        raw.len = 1;
        raw.op_flags = crate::sys::net::recv_flags(flags) as u32;
        Self(raw)
    }

    /// [`send`](Self::send) without a copy: the kernel sends from the
    /// program's pages (Linux 6.0). See
    /// [the module documentation](self#zero-copy-sends) for the two
    /// completions this has.
    ///
    /// # Safety
    ///
    /// `buf` must be valid for reads of `len` bytes, and not written to,
    /// until the *notification* of the entry has been taken: the
    /// completion that has not [`Cqe::has_more`].
    #[inline]
    pub unsafe fn send_zc(
        socket: impl AsSocket,
        buf: *const u8,
        len: u32,
        flags: SendFlags,
    ) -> Self {
        let mut raw = Self::op(Opcode::SendZc, socket_fd(socket));
        raw.addr = buf.addr() as u64;
        raw.len = len;
        raw.op_flags = crate::sys::net::send_flags(flags) as u32;
        Self(raw)
    }

    /// [`sendmsg`](Self::sendmsg) without a copy (Linux 6.1): see
    /// [`send_zc`](Self::send_zc).
    ///
    /// # Safety
    ///
    /// As [`sendmsg`](Self::sendmsg), until the *notification* of the
    /// entry has been taken.
    #[inline]
    pub unsafe fn sendmsg_zc(socket: impl AsSocket, msg: *const MsgHdr, flags: SendFlags) -> Self {
        let mut raw = Self::op(Opcode::SendmsgZc, socket_fd(socket));
        raw.addr = msg.addr() as u64;
        raw.len = 1;
        raw.op_flags = crate::sys::net::send_flags(flags) as u32;
        Self(raw)
    }

    // -- Multishot --------------------------------------------------------

    /// Accepts every connection that comes on the listening `socket`, one
    /// completion each, until it fails or is cancelled (Linux 5.19;
    /// `InvalidInput` in the completion before): a
    /// [multishot](self#multishot) entry. Each completion has the number
    /// of a new socket, as [`accept`](Self::accept) describes; the address
    /// of the peer is asked of the socket
    /// ([`net::peer_addr`](crate::net::peer_addr)).
    #[inline]
    pub fn accept_multishot(socket: impl AsSocket) -> Self {
        let mut raw = Self::op(Opcode::Accept, socket_fd(socket));
        raw.op_flags = crate::sys::net::SOCK_CLOEXEC as u32;
        raw.ioprio = sys::IORING_ACCEPT_MULTISHOT;
        Self(raw)
    }

    /// Receives from `socket` again and again, each time into a buffer
    /// the kernel picks from the group `group`, until it fails, the stream
    /// ends, the group is empty (an error whose
    /// [`raw_os_error`](Error::raw_os_error) is `ENOBUFS`) or it is
    /// cancelled (Linux 6.0; `InvalidInput` in the completion before): a
    /// [multishot](self#multishot) entry. Each completion has a count and
    /// names its buffer ([`Cqe::buffer_id`], [`BufRing::take`]).
    /// [`RecvFlags::WAIT_ALL`] is refused.
    ///
    /// # Safety
    ///
    /// As [`buffer_select`](Self::buffer_select).
    #[inline]
    pub unsafe fn recv_multishot(socket: impl AsSocket, group: u16, flags: RecvFlags) -> Self {
        let mut raw = Self::op(Opcode::Recv, socket_fd(socket));
        raw.op_flags = crate::sys::net::recv_flags(flags) as u32;
        raw.ioprio = sys::IORING_RECV_MULTISHOT;
        // SAFETY: the caller's contract.
        unsafe { Self(raw).buffer_select(group) }
    }

    /// Reads from `handle` again and again, as
    /// [`recv_multishot`](Self::recv_multishot) receives (Linux 6.7). The
    /// handle must be one that can be polled (a pipe, a socket, a
    /// terminal): a file is refused.
    ///
    /// # Safety
    ///
    /// As [`buffer_select`](Self::buffer_select).
    #[inline]
    pub unsafe fn read_multishot(handle: impl AsHandle, group: u16) -> Self {
        let mut raw = Self::op(Opcode::ReadMultishot, fd(handle));
        raw.off = CURRENT_POSITION;
        // SAFETY: the caller's contract.
        unsafe { Self(raw).buffer_select(group) }
    }

    /// As [`poll_add`](Self::poll_add), again and again: a completion each
    /// time `handle` becomes ready for `interest`, until it fails or is
    /// removed ([`poll_remove`](Self::poll_remove), or any cancelling):
    /// a [multishot](self#multishot) entry (Linux 5.13). It reports
    /// changes, like an edge-triggered poller: a handle that stays
    /// readable is not reported twice.
    #[inline]
    pub fn poll_multishot(handle: impl AsHandle, interest: Interest) -> Self {
        let mut sqe = Self::poll_add(handle, interest);
        sqe.0.len = sys::IORING_POLL_ADD_MULTI;
        sqe
    }

    /// A [timeout](Self::timeout) that fires every `*time`, `repeats`
    /// times, or with 0 until it is removed
    /// ([`timeout_remove`](Self::timeout_remove)): a
    /// [multishot](self#multishot) entry (Linux 6.4; `InvalidInput` in
    /// the completion before). Each completion has the error `ETIME`.
    ///
    /// # Safety
    ///
    /// As [`timeout`](Self::timeout).
    #[inline]
    pub unsafe fn timeout_multishot(time: *const Timespec, repeats: u32) -> Self {
        // SAFETY: the caller's contract.
        let mut sqe = unsafe { Self::timeout(time, repeats) };
        sqe.0.op_flags = sys::IORING_TIMEOUT_MULTISHOT;
        sqe
    }

    // -- Buffers the kernel picks -----------------------------------------

    /// Makes the kernel pick the buffer of this entry from the group
    /// `group` when it has something to put there, instead of the one the
    /// entry was made with (make it with a null pointer; its length is
    /// then the most to transfer). For
    /// [`read`](Self::read), [`recv`](Self::recv) and
    /// [`recvmsg`](Self::recvmsg). See
    /// [the module documentation](self#buffers-the-kernel-picks).
    ///
    /// The completion names the buffer ([`Cqe::buffer_id`]); with none
    /// left in the group it is an error whose
    /// [`raw_os_error`](Error::raw_os_error) is `ENOBUFS`.
    ///
    /// # Safety
    ///
    /// The memory of the group, whoever gave it (a [`BufRing`], which
    /// must then not be dropped, or [`provide_buffers`]), must stay valid
    /// until the last completion of this entry has been taken.
    ///
    /// [`provide_buffers`]: Self::provide_buffers
    #[inline]
    pub const unsafe fn buffer_select(mut self, group: u16) -> Self {
        self.0.flags |= sys::IOSQE_BUFFER_SELECT;
        self.0.buf_index = group;
        self
    }

    /// Gives the kernel `count` buffers of `len` bytes each, one after the
    /// other from `addr`, for the group `group`: they are numbered from
    /// `first_id`, and entries with
    /// [`buffer_select`](Self::buffer_select) pick from them. A buffer
    /// that was picked is the program's again, and is provided again to be
    /// used again. The completion has 0. This is the older of the two ways
    /// to do it: see [`BufRing`].
    ///
    /// # Safety
    ///
    /// The memory must be valid for writes, and each buffer not used
    /// otherwise from the moment the entry is submitted until the
    /// completion that names it has been taken, or until it has been
    /// [removed](Self::remove_buffers) and nothing that selects from the
    /// group is in flight.
    #[inline]
    pub unsafe fn provide_buffers(
        addr: *mut u8,
        len: u32,
        count: u16,
        group: u16,
        first_id: u16,
    ) -> Self {
        let mut raw = Self::op(Opcode::ProvideBuffers, i32::from(count));
        raw.addr = addr.addr() as u64;
        raw.len = len;
        raw.off = u64::from(first_id);
        raw.buf_index = group;
        Self(raw)
    }

    /// Takes back up to `count` of the buffers
    /// [provided](Self::provide_buffers) to the group `group` that were
    /// not picked: the completion says how many, or
    /// [`NotFound`](ErrorKind::NotFound) if there is no such group.
    #[inline]
    pub const fn remove_buffers(count: u16, group: u16) -> Self {
        let mut raw = Self::op(Opcode::RemoveBuffers, count as i32);
        raw.buf_index = group;
        Self(raw)
    }

    // -- Cancelling, rings, futexes, children -------------------------------

    /// As [`cancel`](Self::cancel), for every operation whose user data is
    /// `user_data` and not the first found (Linux 5.19): the completion
    /// has how many were cancelled.
    #[inline]
    pub const fn cancel_all(user_data: u64) -> Self {
        let mut sqe = Self::cancel(user_data);
        sqe.0.op_flags = sys::IORING_ASYNC_CANCEL_ALL;
        sqe
    }

    /// Asks for every operation in flight on `handle` to be cancelled
    /// (Linux 5.19; `InvalidInput` in the completion before): the
    /// completion has how many were, 0 included. It is the file that is
    /// matched, not the number: an operation started through a duplicate
    /// of the handle is cancelled too.
    #[inline]
    pub fn cancel_fd(handle: impl AsHandle) -> Self {
        let mut raw = Self::op(Opcode::AsyncCancel, fd(handle));
        raw.op_flags = sys::IORING_ASYNC_CANCEL_FD | sys::IORING_ASYNC_CANCEL_ALL;
        Self(raw)
    }

    /// Asks for every operation in flight on the ring to be cancelled
    /// (Linux 5.19): the completion has how many were.
    #[inline]
    pub const fn cancel_any() -> Self {
        let mut raw = Self::op(Opcode::AsyncCancel, -1);
        raw.op_flags = sys::IORING_ASYNC_CANCEL_ANY | sys::IORING_ASYNC_CANCEL_ALL;
        Self(raw)
    }

    /// Posts a completion to another ring, `target` (the [`Ring`] itself,
    /// or its handle): it has `user_data` and the result `result`, as if
    /// an entry of that ring had completed (Linux 5.18). This is how one
    /// thread wakes another that waits on its ring. This entry completes
    /// with 0, in its own ring.
    ///
    /// The completion counts as one in the target's
    /// [`in_flight`](Ring::in_flight), which no entry there balances: a
    /// ring that is sent messages cannot use that count.
    #[inline]
    pub fn msg_ring(target: impl AsHandle, result: u32, user_data: u64) -> Self {
        let mut raw = Self::op(Opcode::MsgRing, fd(target));
        // `addr` is the command: 0, `IORING_MSG_DATA`.
        raw.len = result;
        raw.off = user_data;
        Self(raw)
    }

    /// Waits on the 32-bit futex at `addr`, as
    /// [`sync::wait`](crate::sync::wait) does, without a thread blocked in
    /// it (Linux 6.7). If the value there is not `expected` the completion
    /// is [`WouldBlock`](ErrorKind::WouldBlock); otherwise it comes, with
    /// 0, when the address is woken: by [`futex_wake`](Self::futex_wake),
    /// or by [`sync::wake_one`](crate::sync::wake_one) and
    /// [`sync::wake_all`](crate::sync::wake_all).
    ///
    /// # Safety
    ///
    /// `addr` must be valid for reads until the completion of the entry
    /// has been taken: the kernel reads the value when it starts the
    /// operation, which for an entry that is linked or handed to a worker
    /// is later than its submission.
    #[inline]
    pub unsafe fn futex_wait(addr: *const AtomicU32, expected: u32) -> Self {
        let mut raw = Self::op(Opcode::FutexWait, sys::FUTEX2_U32_PRIVATE);
        raw.addr = addr.addr() as u64;
        raw.off = u64::from(expected);
        raw.addr3 = sys::FUTEX_BITSET_MATCH_ANY;
        Self(raw)
    }

    /// Wakes up to `count` waiters of the futex at `addr` (Linux 6.7): the
    /// completion has how many were woken. The address is a name here, and
    /// is not read.
    #[inline]
    pub fn futex_wake(addr: *const AtomicU32, count: u32) -> Self {
        let mut raw = Self::op(Opcode::FutexWake, sys::FUTEX2_U32_PRIVATE);
        raw.addr = addr.addr() as u64;
        raw.off = u64::from(count);
        raw.addr3 = sys::FUTEX_BITSET_MATCH_ANY;
        Self(raw)
    }

    /// Waits for the child process `pid` to end, and collects it
    /// (`waitid` with `P_PID` and `WEXITED`; Linux 6.7): the completion
    /// has 0, and `*info` says how it ended. The child is then gone:
    /// nothing else can wait for it.
    ///
    /// # Safety
    ///
    /// `info` must point to a [`WaitInfo`] that is valid, and not used
    /// otherwise, until the completion of the entry has been taken.
    #[inline]
    pub unsafe fn waitid_pid(pid: u32, info: *mut WaitInfo) -> Self {
        const P_PID: u32 = 1;
        // SAFETY: the caller's contract.
        unsafe { Self::waitid(P_PID, pid as i32, info) }
    }

    /// [`waitid_pid`](Self::waitid_pid) for the child a process descriptor
    /// names (`P_PIDFD`).
    ///
    /// # Safety
    ///
    /// As [`waitid_pid`](Self::waitid_pid).
    #[inline]
    pub unsafe fn waitid_pidfd(pidfd: impl AsHandle, info: *mut WaitInfo) -> Self {
        const P_PIDFD: u32 = 3;
        // SAFETY: the caller's contract.
        unsafe { Self::waitid(P_PIDFD, fd(pidfd), info) }
    }

    /// # Safety
    ///
    /// As `waitid_pid`.
    unsafe fn waitid(which: u32, id: i32, info: *mut WaitInfo) -> Self {
        const WEXITED: u32 = 4;
        let mut raw = Self::op(Opcode::Waitid, id);
        raw.len = which;
        raw.off = info.addr() as u64;
        // The options.
        raw.file_index = WEXITED;
        Self(raw)
    }

    /// A command for the driver of `handle`, as `ioctl` is but without the
    /// wait (`IORING_OP_URING_CMD`, Linux 5.19): `cmd_op` says which, and
    /// `cmd` is the 16 bytes an entry has room for. A driver that wants
    /// more (80 bytes) needs a ring made with [`Setup::sqe128`] and
    /// [`Ring::push_wide`], which carries the other 64. What the
    /// completion has is the driver's business.
    ///
    /// Sockets have had commands since Linux 6.5: 0 for the bytes there
    /// are to read (`SOCKET_URING_OP_SIOCINQ`) and 1 for those not yet
    /// sent (`SOCKET_URING_OP_SIOCOUTQ`), both with `cmd` zeroed.
    ///
    /// # Safety
    ///
    /// As the command requires: memory it names must be valid as the
    /// driver uses it, until the completion of the entry has been taken.
    #[inline]
    pub unsafe fn uring_cmd(handle: impl AsHandle, cmd_op: u32, cmd: [u8; 16]) -> Self {
        let mut raw = Self::op(Opcode::UringCmd, fd(handle));
        raw.off = u64::from(cmd_op);
        let (low, high) = cmd.split_at(8);
        // The command starts where `addr3` is, as bytes: neither half can
        // fail to be eight bytes long.
        raw.addr3 = u64::from_ne_bytes(low.try_into().unwrap_or([0; 8]));
        raw.pad = u64::from_ne_bytes(high.try_into().unwrap_or([0; 8]));
        Self(raw)
    }
}

impl Cqe {
    /// The user data of the entry this is the completion of.
    #[inline]
    pub const fn user_data(&self) -> u64 {
        self.user_data
    }

    /// The result of the operation: what its system call would have
    /// returned (a count of bytes, a new descriptor, 0), or its error.
    #[inline]
    pub fn result(&self) -> Result<u32> {
        if self.res < 0 {
            Err(Error::from_raw_os_error(self.res.wrapping_neg()))
        } else {
            Ok(self.res as u32)
        }
    }

    /// The result as the kernel wrote it: negative for an error, whose
    /// number it then is the opposite of.
    #[inline]
    pub const fn raw_result(&self) -> i32 {
        self.res
    }

    /// The kernel's flags of the completion (`IORING_CQE_F_*`).
    #[inline]
    pub const fn flags(&self) -> u32 {
        self.flags
    }

    /// Whether the entry will have more completions after this one
    /// (`IORING_CQE_F_MORE`): it is then still in flight, and its memory
    /// in use. See [the module documentation](self#multishot).
    #[inline]
    pub const fn has_more(&self) -> bool {
        self.flags & sys::IORING_CQE_F_MORE != 0
    }

    /// The number of the buffer the kernel picked for the operation, if
    /// it picked one ([`Sqe::buffer_select`]): the data is there, and the
    /// buffer is the program's again.
    #[inline]
    pub const fn buffer_id(&self) -> Option<u16> {
        if self.flags & sys::IORING_CQE_F_BUFFER != 0 {
            Some((self.flags >> sys::IORING_CQE_BUFFER_SHIFT) as u16)
        } else {
            None
        }
    }

    /// Whether this is the notification of a
    /// [zero-copy send](self#zero-copy-sends): the kernel is done with the
    /// memory that was sent. Its result means nothing.
    #[inline]
    pub const fn is_notification(&self) -> bool {
        self.flags & sys::IORING_CQE_F_NOTIF != 0
    }

    /// For the completion of a receive: whether the socket had more to
    /// read when it completed (Linux 5.19; never set before).
    #[inline]
    pub const fn socket_nonempty(&self) -> bool {
        self.flags & sys::IORING_CQE_F_SOCK_NONEMPTY != 0
    }

    /// For the completion of a [poll](Sqe::poll_add): what is true of the
    /// handle. Empty if the operation failed.
    #[inline]
    pub fn readiness(&self) -> Readiness {
        if self.res < 0 {
            return Readiness::empty();
        }
        crate::sys::event::PollFd::answered(self.res as i16).readiness()
    }
}

impl fmt::Debug for Cqe {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Cqe")
            .field("user_data", &self.user_data)
            .field("result", &self.result())
            .field("flags", &self.flags)
            .finish()
    }
}

// ---------------------------------------------------------------------------
// The ring
// ---------------------------------------------------------------------------

/// How a [`Ring`] is to be made: [`Ring::with_setup`].
///
/// An option the running kernel does not know makes
/// [`Ring::with_setup`] fail with
/// [`InvalidInput`](ErrorKind::InvalidInput): there is no ring yet to ask
/// what the kernel has.
#[derive(Clone, Copy, Debug, Default)]
#[non_exhaustive]
pub struct Setup {
    cq_entries: u32,
    flags: u32,
    sq_thread_idle: u32,
    sq_thread_cpu: u32,
    wq_fd: u32,
}

impl Setup {
    /// What [`Ring::new`] does.
    #[inline]
    pub const fn new() -> Self {
        Self {
            cq_entries: 0,
            flags: 0,
            sq_thread_idle: 0,
            sq_thread_cpu: 0,
            wq_fd: 0,
        }
    }

    /// Asks for a completion queue of `entries`, rounded up to a power of
    /// two, instead of twice the submission queue. It cannot be smaller
    /// than the submission queue.
    #[inline]
    pub const fn cq_entries(mut self, entries: u32) -> Self {
        self.cq_entries = entries;
        self.flags |= sys::IORING_SETUP_CQSIZE;
        self
    }

    /// Makes the kernel reduce sizes that are over its limits (32768
    /// submissions, 65536 completions) instead of failing.
    #[inline]
    pub const fn clamp(mut self, clamp: bool) -> Self {
        self.flags = set(self.flags, sys::IORING_SETUP_CLAMP, clamp);
        self
    }

    /// Tells the kernel not to interrupt the thread to post completions,
    /// which are then posted when the thread next enters the kernel
    /// (Linux 5.19: `IORING_SETUP_COOP_TASKRUN`). Fewer interruptions, for
    /// a program that waits with [`Ring::wait`] anyway.
    #[inline]
    pub const fn coop_taskrun(mut self, enabled: bool) -> Self {
        self.flags = set(self.flags, sys::IORING_SETUP_COOP_TASKRUN, enabled);
        self
    }

    /// Promises that one thread only will submit to the ring, the one
    /// that creates it, which the kernel enforces and takes advantage of
    /// (Linux 6.0: `IORING_SETUP_SINGLE_ISSUER`). A submission from
    /// another thread then fails with
    /// [`AlreadyExists`](ErrorKind::AlreadyExists). For a ring that
    /// starts [disabled](Self::disabled), the thread is the one that
    /// [enables](Ring::enable) it.
    #[inline]
    pub const fn single_issuer(mut self, enabled: bool) -> Self {
        self.flags = set(self.flags, sys::IORING_SETUP_SINGLE_ISSUER, enabled);
        self
    }

    /// Makes the kernel do the work that ends in a completion only when
    /// the thread asks for completions ([`Ring::wait`], with a count of 0
    /// too), never by interrupting it or at another system call (Linux
    /// 6.1: `IORING_SETUP_DEFER_TASKRUN`). This sets
    /// [`single_issuer`](Self::single_issuer) as well, which the kernel
    /// wants with it.
    ///
    /// On such a ring [`Ring::ready`] sees nothing new until the thread
    /// has waited, and only the thread that submits may wait
    /// ([`AlreadyExists`](ErrorKind::AlreadyExists) for another).
    #[inline]
    pub const fn defer_taskrun(mut self, enabled: bool) -> Self {
        self.flags = set(self.flags, sys::IORING_SETUP_DEFER_TASKRUN, enabled);
        if enabled {
            self.flags |= sys::IORING_SETUP_SINGLE_ISSUER;
        }
        self
    }

    /// Makes [`Ring::submit`] go on with the entries that follow one the
    /// kernel could not start, instead of ending the batch there (Linux
    /// 5.18: `IORING_SETUP_SUBMIT_ALL`).
    #[inline]
    pub const fn submit_all(mut self, enabled: bool) -> Self {
        self.flags = set(self.flags, sys::IORING_SETUP_SUBMIT_ALL, enabled);
        self
    }

    /// Gives the ring a thread of the kernel that takes the entries from
    /// the submission queue by itself, without a system call
    /// (`IORING_SETUP_SQPOLL`). The thread goes to sleep when it has seen
    /// nothing for `idle` (rounded to milliseconds, and at least one), and
    /// [`Ring::submit`] wakes it. See
    /// [the module documentation](self#a-thread-of-the-kernel-that-submits).
    ///
    /// An older kernel keeps it for the privileged
    /// ([`PermissionDenied`](ErrorKind::PermissionDenied); by the
    /// kernel's manual, `CAP_SYS_ADMIN` up to Linux 5.10, `CAP_SYS_NICE`
    /// in 5.11 and 5.12, and nothing since), and up to 5.10 entries must
    /// name registered files ([`Features::SQPOLL_NONFIXED`]).
    #[inline]
    pub const fn sqpoll(mut self, idle: Duration) -> Self {
        self.flags |= sys::IORING_SETUP_SQPOLL;
        let millis = idle.as_millis();
        self.sq_thread_idle = if millis == 0 {
            1
        } else if millis > u32::MAX as u128 {
            u32::MAX
        } else {
            millis as u32
        };
        self
    }

    /// Keeps the thread of [`sqpoll`](Self::sqpoll) on the processor
    /// `cpu` (`IORING_SETUP_SQ_AFF`). Without `sqpoll` the ring is
    /// refused.
    #[inline]
    pub const fn sqpoll_cpu(mut self, cpu: u32) -> Self {
        self.flags |= sys::IORING_SETUP_SQ_AFF;
        self.sq_thread_cpu = cpu;
        self
    }

    /// Makes the new ring share the kernel threads of `ring`, another
    /// ring of the process: its workers, and with
    /// [`sqpoll`](Self::sqpoll) on both, the thread that polls
    /// (`IORING_SETUP_ATTACH_WQ`). What is kept is the number of the
    /// handle, which must still be that ring's when the new one is made.
    #[inline]
    pub const fn attach_wq(mut self, ring: BorrowedHandle<'_>) -> Self {
        self.flags |= sys::IORING_SETUP_ATTACH_WQ;
        self.wq_fd = ring.as_raw() as u32;
        self
    }

    /// Makes the ring start disabled (`IORING_SETUP_R_DISABLED`): nothing
    /// can be submitted ([`Ring::submit`] fails with an error whose
    /// [`raw_os_error`](Error::raw_os_error) is `EBADFD`) until
    /// [`Ring::enable`]. That is when a ring can be
    /// [restricted](Ring::register_restrictions).
    #[inline]
    pub const fn disabled(mut self, disabled: bool) -> Self {
        self.flags = set(self.flags, sys::IORING_SETUP_R_DISABLED, disabled);
        self
    }

    /// Asks for submission entries of 128 bytes instead of 64 (Linux
    /// 5.19: `IORING_SETUP_SQE128`), which some
    /// [commands](Sqe::uring_cmd) need: [`Ring::push_wide`] fills the
    /// other half, and [`Ring::push`] zeroes it.
    #[inline]
    pub const fn sqe128(mut self, enabled: bool) -> Self {
        self.flags = set(self.flags, sys::IORING_SETUP_SQE128, enabled);
        self
    }

    /// Asks for completion entries of 32 bytes instead of 16 (Linux 5.19:
    /// `IORING_SETUP_CQE32`): [`Ring::pop_wide`] returns the other half,
    /// in which some [commands](Sqe::uring_cmd) answer.
    #[inline]
    pub const fn cqe32(mut self, enabled: bool) -> Self {
        self.flags = set(self.flags, sys::IORING_SETUP_CQE32, enabled);
        self
    }
}

const fn set(flags: u32, flag: u32, on: bool) -> u32 {
    if on { flags | flag } else { flags & !flag }
}

/// A mapping of memory the ring shares with the kernel, or of a group of
/// buffers.
struct Map {
    ptr: NonNull<u8>,
    len: usize,
}

impl Map {
    fn new(fd: BorrowedHandle<'_>, offset: u64, len: usize) -> Result<Self> {
        Self::of(crate::sys::mem::map_shared(fd, offset, len)?, len)
    }

    /// Memory of the program's own, zeroed.
    fn anonymous(len: usize) -> Result<Self> {
        let options = crate::mem::MapOptions::new();
        Self::of(crate::sys::mem::map_anonymous(len, &options)?, len)
    }

    fn of(ptr: *mut u8, len: usize) -> Result<Self> {
        match NonNull::new(ptr) {
            Some(ptr) => Ok(Self { ptr, len }),
            None => Err(ErrorKind::Other.into()),
        }
    }

    /// A pointer to the `T` at `offset`, if there is room for `count` of
    /// them there and it is aligned.
    fn at<T>(&self, offset: usize, count: usize) -> Result<NonNull<T>> {
        let size = size_of::<T>().checked_mul(count);
        let end = size.and_then(|size| offset.checked_add(size));
        match end {
            Some(end) if end <= self.len && offset.is_multiple_of(align_of::<T>()) => {
                // SAFETY: the offset is within the mapping.
                Ok(unsafe { self.ptr.add(offset) }.cast())
            }
            // The kernel described a ring that does not fit its mapping.
            _ => Err(ErrorKind::Other.into()),
        }
    }
}

impl Drop for Map {
    fn drop(&mut self) {
        // SAFETY: the mapping was made by `new`, and whoever had pointers
        // into it is being dropped with it.
        let _ = unsafe { crate::sys::mem::unmap(self.ptr.as_ptr(), self.len) };
    }
}

/// An io_uring: a submission queue and a completion queue shared with the
/// kernel. See the [module documentation](self).
///
/// Dropping it closes the descriptor and unmaps the queues. The kernel
/// then cancels what is in flight in its own time: see
/// [the contract](self#memory-where-unsafe-is) about the memory of those
/// operations. (A [`BufRing`] made for the ring, and a
/// [registration](Self::register_ring_fd) of its descriptor with a thread,
/// each keep the kernel's side of it alive until they end.)
pub struct Ring {
    // The submission queue. `sq_head` is the kernel's to write, `sq_tail`
    // the program's.
    sq_head: NonNull<AtomicU32>,
    sq_tail: NonNull<AtomicU32>,
    sq_flags: NonNull<AtomicU32>,
    sq_mask: u32,
    sq_entries: u32,
    /// 1 if the entries are 128 bytes, each then taking two places.
    sqe_shift: u32,
    sqes: NonNull<RawSqe>,
    // The completion queue. `cq_head` is the program's to write, `cq_tail`
    // the kernel's.
    cq_head: NonNull<AtomicU32>,
    cq_tail: NonNull<AtomicU32>,
    cq_overflow: NonNull<AtomicU32>,
    cq_mask: u32,
    cq_entries: u32,
    /// 1 if the entries are 32 bytes.
    cqe_shift: u32,
    cqes: NonNull<Cqe>,
    features: Features,
    probe: Probe,
    /// Whether a thread of the kernel reads the submission queue.
    sqpoll: bool,
    /// The index the descriptor is registered at, for the thread that
    /// registered it.
    ring_index: Option<u32>,
    /// Entries pushed, and final completions taken.
    pushed: u64,
    completed: u64,
    // Dropped in this order: the descriptor, then what it mapped.
    fd: OwnedHandle,
    _sq_map: Map,
    _cq_map: Option<Map>,
    _sqes_map: Map,
}

// SAFETY: the pointers are into mappings the ring owns, which are shared
// with the kernel and with nothing else in the process; a ring is used
// through `&mut self`, by whichever thread has it.
unsafe impl Send for Ring {}
// SAFETY: what `&self` gives is loads of atomics, the descriptor, and
// registrations, which the kernel serialises.
unsafe impl Sync for Ring {}

/// What the kernel supports of io_uring: [`Ring::probe`].
#[derive(Clone)]
pub struct Probe {
    last: u8,
    supported: [u32; 8],
}

impl Probe {
    /// Whether the kernel has the operation.
    #[inline]
    pub fn supports(&self, opcode: Opcode) -> bool {
        self.supports_raw(opcode as u8)
    }

    /// Whether the kernel has the operation of this number
    /// (`IORING_OP_*`).
    #[inline]
    pub fn supports_raw(&self, opcode: u8) -> bool {
        self.supported[usize::from(opcode / 32)] & (1 << (opcode % 32)) != 0
    }

    /// The highest operation number the kernel knows.
    #[inline]
    pub fn last_opcode(&self) -> u8 {
        self.last
    }
}

impl fmt::Debug for Probe {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Probe")
            .field("last_opcode", &self.last)
            .finish_non_exhaustive()
    }
}

impl Ring {
    /// Creates a ring whose submission queue holds `entries` entries,
    /// rounded up to a power of two (at most 32768), and whose completion
    /// queue holds twice as many.
    ///
    /// `io_uring_setup`, `mmap` for the queues, and one
    /// `io_uring_register` that asks which operations the kernel has
    /// ([`probe`](Self::probe)). The descriptor is close-on-exec. See the
    /// [module documentation](self#where-there-is-no-io_uring) for the
    /// errors that mean there is no io_uring to use:
    /// [`Unsupported`](ErrorKind::Unsupported),
    /// [`PermissionDenied`](ErrorKind::PermissionDenied) and
    /// [`OutOfMemory`](ErrorKind::OutOfMemory). No entries, or too many,
    /// fail with [`InvalidInput`](ErrorKind::InvalidInput).
    pub fn new(entries: u32) -> Result<Self> {
        Self::with_setup(entries, &Setup::new())
    }

    /// [`new`](Self::new), with options. An option the kernel does not
    /// know fails with [`InvalidInput`](ErrorKind::InvalidInput).
    pub fn with_setup(entries: u32, setup: &Setup) -> Result<Self> {
        let mut params = sys::Params {
            flags: setup.flags,
            cq_entries: setup.cq_entries,
            sq_thread_cpu: setup.sq_thread_cpu,
            sq_thread_idle: setup.sq_thread_idle,
            wq_fd: setup.wq_fd,
            ..sys::Params::default()
        };
        let fd = sys::setup(entries, &mut params)?;
        let sqe_shift = u32::from(setup.flags & sys::IORING_SETUP_SQE128 != 0);
        let cqe_shift = u32::from(setup.flags & sys::IORING_SETUP_CQE32 != 0);
        let sq = &params.sq_off;
        let cq = &params.cq_off;
        let (sq_entries, cq_entries) = (params.sq_entries as usize, params.cq_entries as usize);
        // How many 64-byte and 16-byte places the entries take.
        let (sqe_places, cqe_places) = (sq_entries << sqe_shift, cq_entries << cqe_shift);
        let (Some(sq_len), Some(cq_len), Some(sqes_len)) = (
            sq_entries
                .checked_mul(size_of::<u32>())
                .and_then(|len| len.checked_add(sq.array as usize)),
            cqe_places
                .checked_mul(size_of::<Cqe>())
                .and_then(|len| len.checked_add(cq.cqes as usize)),
            sqe_places.checked_mul(size_of::<RawSqe>()),
        ) else {
            return Err(ErrorKind::Other.into());
        };
        if !params.sq_entries.is_power_of_two() || !params.cq_entries.is_power_of_two() {
            return Err(ErrorKind::Other.into());
        }
        let handle = fd.as_handle();
        let (sq_map, cq_map) = if params.features & sys::IORING_FEAT_SINGLE_MMAP != 0 {
            let len = sq_len.max(cq_len);
            (Map::new(handle, sys::IORING_OFF_SQ_RING, len)?, None)
        } else {
            (
                Map::new(handle, sys::IORING_OFF_SQ_RING, sq_len)?,
                Some(Map::new(handle, sys::IORING_OFF_CQ_RING, cq_len)?),
            )
        };
        let sqes_map = Map::new(handle, sys::IORING_OFF_SQES, sqes_len)?;
        let cq_ring = cq_map.as_ref().unwrap_or(&sq_map);

        // The kernel submits `sqes[array[i]]`: make the indirection the
        // identity, once and for all.
        let array = sq_map.at::<u32>(sq.array as usize, sq_entries)?;
        for index in 0..params.sq_entries {
            // SAFETY: `at` checked that the array has that many entries;
            // the kernel reads no further than the tail, which is still
            // where it started.
            unsafe { array.add(index as usize).write(index) };
        }
        let mut ring = Self {
            sq_head: sq_map.at(sq.head as usize, 1)?,
            sq_tail: sq_map.at(sq.tail as usize, 1)?,
            sq_flags: sq_map.at(sq.flags as usize, 1)?,
            sq_mask: params.sq_entries - 1,
            sq_entries: params.sq_entries,
            sqe_shift,
            sqes: sqes_map.at(0, sqe_places)?,
            cq_head: cq_ring.at(cq.head as usize, 1)?,
            cq_tail: cq_ring.at(cq.tail as usize, 1)?,
            cq_overflow: cq_ring.at(cq.overflow as usize, 1)?,
            cq_mask: params.cq_entries - 1,
            cq_entries: params.cq_entries,
            cqe_shift,
            cqes: cq_ring.at(cq.cqes as usize, cqe_places)?,
            features: Features(params.features),
            probe: Probe {
                last: 0,
                supported: [0; 8],
            },
            sqpoll: setup.flags & sys::IORING_SETUP_SQPOLL != 0,
            ring_index: None,
            pushed: 0,
            completed: 0,
            fd,
            _sq_map: sq_map,
            _cq_map: cq_map,
            _sqes_map: sqes_map,
        };
        ring.probe = ring.ask_probe()?;
        Ok(ring)
    }

    /// What the kernel's io_uring can do.
    #[inline]
    pub fn features(&self) -> Features {
        self.features
    }

    /// How many entries the submission queue holds.
    #[inline]
    pub fn sq_entries(&self) -> u32 {
        self.sq_entries
    }

    /// How many entries the completion queue holds.
    #[inline]
    pub fn cq_entries(&self) -> u32 {
        self.cq_entries
    }

    #[inline]
    fn atomic(&self, pointer: NonNull<AtomicU32>) -> &AtomicU32 {
        // SAFETY: the pointer is to a counter in a mapping that lives as
        // long as `self`, which the kernel and the program only access as
        // an atomic.
        unsafe { pointer.as_ref() }
    }

    /// How many entries are pushed and not yet taken by the kernel.
    #[inline]
    pub fn unsubmitted(&self) -> u32 {
        // The kernel moves the head as it takes entries: during
        // `io_uring_enter`, or at any time if it has a thread for that.
        let head = self.atomic(self.sq_head).load(Ordering::Acquire);
        let tail = self.atomic(self.sq_tail).load(Ordering::Relaxed);
        tail.wrapping_sub(head)
    }

    /// Adds an entry to the submission queue. Nothing happens to it until
    /// [`submit`](Self::submit) or [`wait`](Self::wait), unless the ring
    /// has a [thread that submits](self#a-thread-of-the-kernel-that-submits),
    /// which may take it at once.
    ///
    /// Fails with [`WouldBlock`](ErrorKind::WouldBlock) when the queue is
    /// full: submit, and push again. Fails with
    /// [`Unsupported`](ErrorKind::Unsupported), and queues nothing, when
    /// the running kernel does not have the operation of the entry
    /// ([`probe`](Self::probe)).
    ///
    /// This is safe because what an entry may point to was promised when
    /// the entry was made.
    pub fn push(&mut self, sqe: Sqe) -> Result<()> {
        self.push_entry(sqe, None)
    }

    /// [`push`](Self::push) on a ring of 128-byte entries
    /// ([`Setup::sqe128`]): `more` is the second half of the entry, which
    /// for a [command](Sqe::uring_cmd) is the rest of its 80 bytes. Fails
    /// with [`InvalidInput`](ErrorKind::InvalidInput) on a ring of
    /// ordinary entries.
    pub fn push_wide(&mut self, sqe: Sqe, more: &[u8; 64]) -> Result<()> {
        if self.sqe_shift == 0 {
            return Err(ErrorKind::InvalidInput.into());
        }
        self.push_entry(sqe, Some(more))
    }

    fn push_entry(&mut self, sqe: Sqe, more: Option<&[u8; 64]>) -> Result<()> {
        if !self.probe.supports_raw(sqe.0.opcode) {
            return Err(ErrorKind::Unsupported.into());
        }
        let head = self.atomic(self.sq_head).load(Ordering::Acquire);
        let tail = self.atomic(self.sq_tail).load(Ordering::Relaxed);
        if tail.wrapping_sub(head) >= self.sq_entries {
            return Err(ErrorKind::WouldBlock.into());
        }
        let place = ((tail & self.sq_mask) as usize) << self.sqe_shift;
        // SAFETY: the index is within the array (which has two places an
        // entry when they are 128 bytes), and the kernel does not read the
        // slot before the tail says it is there: the queue has room, so
        // the slot is beyond what was published.
        unsafe {
            let slot = self.sqes.add(place);
            slot.write(sqe.0);
            if self.sqe_shift != 0 {
                let rest = slot.add(1).cast::<[u8; 64]>();
                rest.write(more.copied().unwrap_or([0; 64]));
            }
        }
        // Published with `Release`: the kernel's load of the tail sees the
        // entry written above.
        self.atomic(self.sq_tail)
            .store(tail.wrapping_add(1), Ordering::Release);
        self.pushed += 1;
        Ok(())
    }

    /// Whether the thread that reads the submission queue
    /// ([`Setup::sqpoll`]) has gone to sleep and must be woken, which
    /// [`submit`](Self::submit) and [`wait`](Self::wait) do. Always false
    /// on a ring without one.
    #[inline]
    pub fn needs_wakeup(&self) -> bool {
        // The thread sets the flag and then looks at the tail once more;
        // the program wrote the tail and now looks at the flag. One of
        // the two must see the other's write, which takes a full barrier
        // between this side's store and its load.
        fence(Ordering::SeqCst);
        self.atomic(self.sq_flags).load(Ordering::Relaxed) & sys::IORING_SQ_NEED_WAKEUP != 0
    }

    fn enter(&mut self, want: u32, mut flags: u32, arg: *const sys::GeteventsArg) -> Result<usize> {
        let to_submit = self.unsubmitted();
        if self.sqpoll && self.needs_wakeup() {
            flags |= sys::IORING_ENTER_SQ_WAKEUP;
        }
        let fd = match self.ring_index {
            Some(index) => {
                flags |= sys::IORING_ENTER_REGISTERED_RING;
                index as i32
            }
            None => self.fd.as_raw(),
        };
        // SAFETY: `arg` is null or what the flags say, from `wait`; what
        // the entries name is their makers' promise.
        unsafe { sys::enter(fd, to_submit, want, flags, arg) }
    }

    /// Hands the entries of the submission queue to the kernel, and
    /// returns how many it took. The operations start; the call does not
    /// wait for any.
    ///
    /// The kernel may take fewer than there are: an entry it cannot even
    /// start ends the batch (and gets a completion saying why), the others
    /// stay queued for the next call. With nothing queued this is no
    /// system call.
    ///
    /// On a ring with a [thread that submits](self#a-thread-of-the-kernel-that-submits)
    /// this is a system call only when the thread sleeps and there is
    /// something for it, and what is returned is how many entries the
    /// thread had not taken yet.
    ///
    /// Fails with [`ResourceBusy`](ErrorKind::ResourceBusy) while
    /// completions are [held back](self#the-two-queues-can-be-full) for
    /// want of room, on the kernels that insist: take completions, and
    /// call [`wait`](Self::wait). `io_uring_enter`.
    pub fn submit(&mut self) -> Result<usize> {
        let pending = self.unsubmitted();
        if pending == 0 || (self.sqpoll && !self.needs_wakeup()) {
            return Ok(pending as usize);
        }
        self.enter(0, 0, ptr::null())
    }

    /// Waits until the submission queue has room, on a ring with a
    /// [thread that submits](self#a-thread-of-the-kernel-that-submits):
    /// what to do when [`push`](Self::push) says
    /// [`WouldBlock`](ErrorKind::WouldBlock) there
    /// (`IORING_ENTER_SQ_WAIT`). On any other ring room is made by
    /// submitting, and this is [`submit`](Self::submit).
    pub fn wait_for_room(&mut self) -> Result<()> {
        if !self.sqpoll {
            return self.submit().map(drop);
        }
        self.enter(0, sys::IORING_ENTER_SQ_WAIT, ptr::null())
            .map(drop)
    }

    /// Submits as [`submit`](Self::submit) does, then waits until `want`
    /// completions are in the queue (those that were there count), or
    /// until `timeout` has passed. Returns how many entries were
    /// submitted; [`ready`](Self::ready) and [`pop`](Self::pop) tell what
    /// came.
    ///
    /// With `want` 0 it does not wait, but still moves into the queue the
    /// completions the kernel [held back](self#the-two-queues-can-be-full).
    ///
    /// The timeout is counted on the monotonic clock. It needs
    /// [`Features::EXT_ARG`] (Linux 5.11): without it, a `timeout` that is
    /// not `None` fails with [`Unsupported`](ErrorKind::Unsupported), and
    /// a [`Sqe::timeout`] entry is the way.
    ///
    /// A signal handler that runs in the thread ends the wait with
    /// [`Interrupted`](ErrorKind::Interrupted), unless entries were
    /// submitted, whose count is then returned.
    pub fn wait(&mut self, want: u32, timeout: Option<Duration>) -> Result<usize> {
        let Some(timeout) = timeout else {
            return self.enter(want, sys::IORING_ENTER_GETEVENTS, ptr::null());
        };
        if !self.features.contains(Features::EXT_ARG) {
            return Err(ErrorKind::Unsupported.into());
        }
        let time = Timespec::from(timeout);
        let arg = sys::GeteventsArg {
            sigmask: 0,
            sigmask_sz: 0,
            min_wait_usec: 0,
            ts: (&raw const time).addr() as u64,
        };
        let flags = sys::IORING_ENTER_GETEVENTS | sys::IORING_ENTER_EXT_ARG;
        match self.enter(want, flags, &raw const arg) {
            // The time passed, and nothing was submitted (the kernel
            // returns the count rather than this when something was).
            Err(error) if error.raw_os_error() == crate::sys::errno::ETIME => Ok(0),
            result => result,
        }
    }

    /// How many completions are in the queue, to [`pop`](Self::pop).
    #[inline]
    pub fn ready(&self) -> u32 {
        let tail = self.atomic(self.cq_tail).load(Ordering::Acquire);
        let head = self.atomic(self.cq_head).load(Ordering::Relaxed);
        tail.wrapping_sub(head)
    }

    /// Takes the oldest completion from the queue, if there is one. No
    /// system call.
    pub fn pop(&mut self) -> Option<Cqe> {
        self.pop_wide().map(|(cqe, _)| cqe)
    }

    /// [`pop`](Self::pop), with the second half of a 32-byte completion
    /// ([`Setup::cqe32`]): two numbers whose meaning is the operation's.
    /// They are zeros on a ring of ordinary completions.
    pub fn pop_wide(&mut self) -> Option<(Cqe, [u64; 2])> {
        let head = self.atomic(self.cq_head).load(Ordering::Relaxed);
        // `Acquire`: the entry the kernel wrote before it moved the tail
        // is seen.
        let tail = self.atomic(self.cq_tail).load(Ordering::Acquire);
        if head == tail {
            return None;
        }
        let place = ((head & self.cq_mask) as usize) << self.cqe_shift;
        // SAFETY: the index is within the array (which has two places an
        // entry when they are 32 bytes), and the kernel wrote the entry
        // before publishing it; it does not write it again before the
        // head has moved past it.
        let (cqe, more) = unsafe {
            let slot = self.cqes.add(place);
            let more = if self.cqe_shift != 0 {
                slot.add(1).cast::<[u64; 2]>().read()
            } else {
                [0; 2]
            };
            (slot.read(), more)
        };
        // `Release`: the kernel may reuse the slot once it sees this.
        self.atomic(self.cq_head)
            .store(head.wrapping_add(1), Ordering::Release);
        if !cqe.has_more() {
            self.completed += 1;
        }
        Some((cqe, more))
    }

    /// How many entries the kernel has taken whose last completion has not
    /// been [popped](Self::pop): the operations that may still use the
    /// memory they were given.
    ///
    /// It counts on every entry having one final completion and on every
    /// completion being of an entry, which is so for everything this
    /// module makes but an entry with [`SqeFlags::CQE_SKIP_SUCCESS`] and a
    /// [message from another ring](Sqe::msg_ring) (and an entry made
    /// [raw](Sqe::from_raw) may ask for none).
    #[inline]
    pub fn in_flight(&self) -> u64 {
        self.pushed
            .wrapping_sub(u64::from(self.unsubmitted()))
            .wrapping_sub(self.completed)
    }

    /// Whether the kernel holds completions back because the queue was
    /// full: [`pop`](Self::pop) to make room, and [`wait`](Self::wait) to
    /// have them.
    #[inline]
    pub fn overflowed(&self) -> bool {
        self.atomic(self.sq_flags).load(Ordering::Relaxed) & sys::IORING_SQ_CQ_OVERFLOW != 0
    }

    /// How many completions were lost for good, the kernel having had
    /// neither room in the queue nor memory to keep them.
    #[inline]
    pub fn dropped(&self) -> u32 {
        self.atomic(self.cq_overflow).load(Ordering::Relaxed)
    }

    /// # Safety
    ///
    /// As `sys::register`.
    unsafe fn register(&self, opcode: u32, arg: *const c_void, count: usize) -> Result<usize> {
        let count = u32::try_from(count).map_err(|_| Error::from(ErrorKind::InvalidInput))?;
        // SAFETY: the caller's contract.
        unsafe { sys::register(self.fd.as_raw(), opcode, arg, count) }
    }

    /// What to say of a registration the kernel refused: it answers
    /// `EINVAL` to one it does not know, as to one it finds wrong. When
    /// the kernel also lacks `witness`, an operation that came with the
    /// same release, the first is meant.
    fn or_unsupported(&self, error: Error, witness: Opcode) -> Error {
        if error.raw_os_error() == crate::sys::errno::EINVAL && !self.probe.supports(witness) {
            ErrorKind::Unsupported.into()
        } else {
            error
        }
    }

    fn ask_probe(&self) -> Result<Probe> {
        // SAFETY: plain data, which the call wants zeroed.
        let mut probe: sys::Probe = unsafe { core::mem::zeroed() };
        // SAFETY: the structure has room for the operations announced.
        unsafe {
            self.register(
                sys::IORING_REGISTER_PROBE,
                (&raw mut probe).cast(),
                sys::PROBE_OPS,
            )
        }?;
        let mut supported = [0; 8];
        for op in &probe.ops[..usize::from(probe.ops_len)] {
            if op.flags & sys::IO_URING_OP_SUPPORTED != 0 {
                supported[usize::from(op.op / 32)] |= 1 << (op.op % 32);
            }
        }
        Ok(Probe {
            last: probe.last_op,
            supported,
        })
    }

    /// Which operations the kernel has, as it said when the ring was made
    /// (`io_uring_register` with `IORING_REGISTER_PROBE`): no system
    /// call. It is what makes [`push`](Self::push) refuse an entry the
    /// kernel would not know.
    ///
    /// An operation may be there and a way of using it not: the
    /// [multishot](self#multishot) forms came after their operations, and
    /// a kernel that does not know one says
    /// [`InvalidInput`](ErrorKind::InvalidInput) in the completion.
    #[inline]
    pub fn probe(&self) -> &Probe {
        &self.probe
    }

    /// Lets a ring that started [disabled](Setup::disabled) work
    /// (`IORING_REGISTER_ENABLE_RINGS`). Fails with an error whose
    /// [`raw_os_error`](Error::raw_os_error) is `EBADFD` on a ring that
    /// works already.
    pub fn enable(&self) -> Result<()> {
        // SAFETY: the operation takes no argument.
        unsafe { self.register(sys::IORING_REGISTER_ENABLE_RINGS, ptr::null(), 0) }.map(drop)
    }

    /// Restricts what the ring will do once it is
    /// [enabled](Self::enable), for good: only the operations, the
    /// registrations and the flags `allowed` lists
    /// (`IORING_REGISTER_RESTRICTIONS`). An entry that asks for anything
    /// else completes with
    /// [`PermissionDenied`](ErrorKind::PermissionDenied) (`EACCES`), and a
    /// registration fails with it. This is for a ring that is then handed
    /// to code that is trusted less.
    ///
    /// The ring must have started [disabled](Setup::disabled) and not be
    /// enabled yet (`EBADFD` otherwise), and can be restricted once
    /// ([`ResourceBusy`](ErrorKind::ResourceBusy)).
    pub fn register_restrictions(&self, allowed: &[Restriction]) -> Result<()> {
        // SAFETY: a `Restriction` is a `struct io_uring_restriction`, and
        // the slice has `len` of them.
        unsafe {
            self.register(
                sys::IORING_REGISTER_RESTRICTIONS,
                allowed.as_ptr().cast(),
                allowed.len(),
            )
        }
        .map(drop)
    }

    /// Registers buffers for [`Sqe::read_fixed`] and
    /// [`Sqe::write_fixed`], which name them by their index in `bufs`: the
    /// kernel maps and pins their memory once, instead of at each
    /// operation.
    ///
    /// The memory stays pinned until
    /// [`unregister_buffers`](Self::unregister_buffers) or the end of the
    /// ring, whatever the program does with it: registering is safe, and
    /// it is the entries that use a buffer that promise it is still
    /// theirs to use. A ring has one set of buffers:
    /// [`ResourceBusy`](ErrorKind::ResourceBusy) if it has one already.
    /// The memory counts against the locked memory limit of the user on
    /// some kernels ([`OutOfMemory`](ErrorKind::OutOfMemory)).
    pub fn register_buffers(&self, bufs: &[IoSliceMut<'_>]) -> Result<()> {
        // SAFETY: an `IoSliceMut` is a `struct iovec`, and the slice has
        // `len` of them.
        unsafe {
            self.register(
                sys::IORING_REGISTER_BUFFERS,
                bufs.as_ptr().cast(),
                bufs.len(),
            )
        }
        .map(drop)
    }

    /// Releases the registered buffers. Fails with
    /// [`InvalidInput`](ErrorKind::InvalidInput) (`ENXIO` on some kernels)
    /// if there are none.
    pub fn unregister_buffers(&self) -> Result<()> {
        // SAFETY: the operation takes no argument.
        unsafe { self.register(sys::IORING_UNREGISTER_BUFFERS, ptr::null(), 0) }.map(drop)
    }

    /// Registers files for entries to name by index
    /// ([`Sqe::fixed_file`]), which spares the kernel a look-up at each
    /// operation.
    ///
    /// The ring keeps the files open, not the handles: a handle can be
    /// closed afterwards, and its file lives until
    /// [`unregister_files`](Self::unregister_files) or the end of the
    /// ring. A ring has one set of files:
    /// [`ResourceBusy`](ErrorKind::ResourceBusy) if it has one already.
    pub fn register_files(&self, files: &[BorrowedHandle<'_>]) -> Result<()> {
        // SAFETY: a `BorrowedHandle` is a descriptor, an `i32`, and the
        // slice has `len` of them.
        unsafe {
            self.register(
                sys::IORING_REGISTER_FILES,
                files.as_ptr().cast(),
                files.len(),
            )
        }
        .map(drop)
    }

    /// Registers a table of `count` places with no file in any, to be
    /// filled by [`register_files_update`](Self::register_files_update)
    /// (Linux 5.19: `IORING_REGISTER_FILES2` with
    /// `IORING_RSRC_REGISTER_SPARSE`;
    /// [`Unsupported`](ErrorKind::Unsupported) before). It is the ring's
    /// one set of files, as [`register_files`](Self::register_files)
    /// makes.
    pub fn register_files_sparse(&self, count: u32) -> Result<()> {
        let table = sys::RsrcRegister {
            nr: count,
            flags: sys::IORING_RSRC_REGISTER_SPARSE,
            resv2: 0,
            data: 0,
            tags: 0,
        };
        // SAFETY: the operation reads one structure, whose size is the
        // count it is given.
        unsafe {
            self.register(
                sys::IORING_REGISTER_FILES2,
                (&raw const table).cast(),
                size_of::<sys::RsrcRegister>(),
            )
        }
        .map(drop)
        .map_err(|error| self.or_unsupported(error, Opcode::Socket))
    }

    /// Changes the places of the table of registered files from `offset`
    /// on, one for each of `files`: a file, nothing, or what was there
    /// (`IORING_REGISTER_FILES_UPDATE`). Returns how many places were
    /// done, which is fewer than asked if one failed after others
    /// succeeded.
    ///
    /// Fails with [`InvalidInput`](ErrorKind::InvalidInput) for places
    /// beyond the table, and with an error whose
    /// [`raw_os_error`](Error::raw_os_error) is `ENXIO` if no table is
    /// registered.
    pub fn register_files_update(&self, offset: u32, files: &[FileSlot<'_>]) -> Result<usize> {
        let update = sys::RsrcUpdate {
            offset,
            resv: 0,
            data: files.as_ptr().addr() as u64,
        };
        // SAFETY: the structure names `len` descriptors, which is what a
        // `FileSlot` is.
        unsafe {
            self.register(
                sys::IORING_REGISTER_FILES_UPDATE,
                (&raw const update).cast(),
                files.len(),
            )
        }
    }

    /// Releases the registered files.
    pub fn unregister_files(&self) -> Result<()> {
        // SAFETY: the operation takes no argument.
        unsafe { self.register(sys::IORING_UNREGISTER_FILES, ptr::null(), 0) }.map(drop)
    }

    /// Makes the kernel add one to the counter of `eventfd`, an event
    /// descriptor (`eventfd(2)`), each time it posts completions: the
    /// descriptor is then readable, which is how a ring is waited for by
    /// an [`event::Poller`](crate::event::Poller) or by `poll`.
    ///
    /// The ring keeps the event file, not the handle. A ring has one:
    /// [`ResourceBusy`](ErrorKind::ResourceBusy) if it has one already.
    pub fn register_eventfd(&self, eventfd: impl AsHandle) -> Result<()> {
        let fd = eventfd.as_handle().as_raw();
        // SAFETY: the operation reads one descriptor.
        unsafe { self.register(sys::IORING_REGISTER_EVENTFD, (&raw const fd).cast(), 1) }.map(drop)
    }

    /// Stops telling the registered event descriptor.
    pub fn unregister_eventfd(&self) -> Result<()> {
        // SAFETY: the operation takes no argument.
        unsafe { self.register(sys::IORING_UNREGISTER_EVENTFD, ptr::null(), 0) }.map(drop)
    }

    /// Keeps the worker threads the kernel runs blocking operations on,
    /// for the calling thread's use of io_uring, to the processors of
    /// `mask`: one bit a processor, in the layout of
    /// [`thread::linux::affinity`](crate::thread::linux::affinity)
    /// (`IORING_REGISTER_IOWQ_AFF`, Linux 5.14). The workers belong to
    /// the thread that submits, not to the ring.
    ///
    /// Fails with [`Unsupported`](ErrorKind::Unsupported) on a kernel
    /// older than 5.13; Linux 5.13 itself, which has no such
    /// registration either, says
    /// [`InvalidInput`](ErrorKind::InvalidInput). A mask with no
    /// processor in it is accepted (Linux 6.18), and means nothing.
    pub fn set_iowq_affinity(&self, mask: &[usize]) -> Result<()> {
        // SAFETY: the kernel reads the bytes of `mask`, whose count is
        // given.
        unsafe {
            self.register(
                sys::IORING_REGISTER_IOWQ_AFF,
                mask.as_ptr().cast(),
                size_of_val(mask),
            )
        }
        .map(drop)
        .map_err(|error| self.iowq_unsupported(error))
    }

    /// Lets the workers run on any processor again
    /// (`IORING_UNREGISTER_IOWQ_AFF`).
    pub fn clear_iowq_affinity(&self) -> Result<()> {
        // SAFETY: the operation takes no argument.
        unsafe { self.register(sys::IORING_UNREGISTER_IOWQ_AFF, ptr::null(), 0) }
            .map(drop)
            .map_err(|error| self.iowq_unsupported(error))
    }

    /// `EINVAL` from a kernel that tells by its features that it is older
    /// than the registrations about workers.
    fn iowq_unsupported(&self, error: Error) -> Error {
        if error.raw_os_error() == crate::sys::errno::EINVAL
            && !self.features.contains(Features::RSRC_TAGS)
        {
            ErrorKind::Unsupported.into()
        } else {
            error
        }
    }

    /// Sets how many worker threads the kernel may run for the calling
    /// thread's use of io_uring: `bounded` for operations that end by
    /// themselves (on files), `unbounded` for those that may wait for
    /// ever (on sockets and pipes); 0 leaves a limit as it is. Returns
    /// the two limits as they were, so that two zeros only ask
    /// (`IORING_REGISTER_IOWQ_MAX_WORKERS`, Linux 5.15;
    /// [`Unsupported`](ErrorKind::Unsupported) before).
    ///
    /// The second limit starts as the number of processes the user may
    /// have (`RLIMIT_NPROC`), and reads as 0 when that is unlimited, as
    /// it is for root in a container.
    pub fn set_iowq_max_workers(&self, bounded: u32, unbounded: u32) -> Result<(u32, u32)> {
        let mut limits = [bounded, unbounded];
        // SAFETY: the operation reads and writes two numbers.
        unsafe {
            self.register(
                sys::IORING_REGISTER_IOWQ_MAX_WORKERS,
                (&raw mut limits).cast(),
                2,
            )
        }
        .map_err(|error| self.or_unsupported(error, Opcode::Mkdirat))?;
        Ok((limits[0], limits[1]))
    }

    /// Registers the descriptor of the ring with the calling thread, so
    /// that [`submit`](Self::submit) and [`wait`](Self::wait) name it by
    /// an index and spare the kernel the look-up and the reference count
    /// of a descriptor, which costs in a process with several threads
    /// (`IORING_REGISTER_RING_FDS`, Linux 5.18;
    /// [`Unsupported`](ErrorKind::Unsupported) before).
    ///
    /// **The registration is the thread's, not the ring's.** From then on
    /// the ring is to be used by this thread only, until
    /// [`unregister_ring_fd`](Self::unregister_ring_fd): in another
    /// thread the index names nothing (`submit` and `wait` then fail with
    /// [`BadHandle`](ErrorKind::BadHandle) or
    /// [`InvalidInput`](ErrorKind::InvalidInput)), or names the ring that
    /// thread registered, which would then be entered in place of this
    /// one. Unregister before sending the ring elsewhere, and before
    /// dropping it: dropping does not unregister (it may happen in
    /// another thread), and the kernel keeps a registered ring alive
    /// until the thread that registered it ends.
    ///
    /// Fails with [`AlreadyExists`](ErrorKind::AlreadyExists) if the ring
    /// is registered already, and with
    /// [`ResourceBusy`](ErrorKind::ResourceBusy) when the thread has
    /// registered as many rings as the kernel lets it (16).
    pub fn register_ring_fd(&mut self) -> Result<()> {
        if self.ring_index.is_some() {
            return Err(ErrorKind::AlreadyExists.into());
        }
        let mut update = sys::RsrcUpdate {
            // Any index that is free.
            offset: u32::MAX,
            resv: 0,
            data: self.fd.as_raw() as u64,
        };
        // SAFETY: the operation reads one structure, and writes the index
        // it chose to it.
        unsafe { self.register(sys::IORING_REGISTER_RING_FDS, (&raw mut update).cast(), 1) }
            .map_err(|error| self.or_unsupported(error, Opcode::MsgRing))?;
        self.ring_index = Some(update.offset);
        Ok(())
    }

    /// Ends the [registration](Self::register_ring_fd) of the descriptor
    /// with the calling thread, which must be the one that registered it.
    /// Fails with [`InvalidInput`](ErrorKind::InvalidInput) if the ring is
    /// not registered.
    pub fn unregister_ring_fd(&mut self) -> Result<()> {
        let Some(index) = self.ring_index else {
            return Err(ErrorKind::InvalidInput.into());
        };
        let update = sys::RsrcUpdate {
            offset: index,
            resv: 0,
            data: 0,
        };
        // SAFETY: the operation reads one structure.
        unsafe {
            self.register(
                sys::IORING_UNREGISTER_RING_FDS,
                (&raw const update).cast(),
                1,
            )
        }?;
        self.ring_index = None;
        Ok(())
    }
}

impl AsHandle for Ring {
    /// The descriptor of the ring: readable, for `poll`, when there are
    /// completions.
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        self.fd.as_handle()
    }
}

impl fmt::Debug for Ring {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Ring")
            .field("fd", &self.fd)
            .field("sq_entries", &self.sq_entries)
            .field("cq_entries", &self.cq_entries)
            .field("features", &self.features)
            .finish_non_exhaustive()
    }
}

// ---------------------------------------------------------------------------
// A ring of buffers
// ---------------------------------------------------------------------------

/// A buffer the kernel picked from a [`BufRing`] and filled:
/// [`BufRing::take`] makes it, [`BufRing::bytes`] reads it and
/// [`BufRing::give_back`] ends it.
#[derive(Debug)]
pub struct Buf {
    id: u16,
    len: u32,
}

impl Buf {
    /// The number of the buffer in its group.
    #[inline]
    pub const fn id(&self) -> u16 {
        self.id
    }

    /// How many bytes the kernel put there.
    #[inline]
    pub const fn len(&self) -> usize {
        self.len as usize
    }

    /// Whether the kernel put nothing there.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }
}

/// A group of buffers the kernel picks from, which owns their memory: a
/// *ring of buffers* shared with the kernel
/// (`IORING_REGISTER_PBUF_RING`, Linux 5.19). See
/// [the module documentation](self#buffers-the-kernel-picks).
///
/// Every buffer is the kernel's to pick from the start. An entry made
/// with [`Sqe::buffer_select`] (or [`Sqe::recv_multishot`]) for
/// [`group`](Self::group) picks one when it has data; its completion says
/// which, [`take`](Self::take) makes the buffer the program's,
/// [`bytes`](Self::bytes) reads it, and [`give_back`](Self::give_back)
/// makes it the kernel's again, with no system call.
///
/// Dropping it takes the group from the ring and frees the memory. The
/// entries that select from the group are what must not outlive it: that
/// is the promise of [`Sqe::buffer_select`]. (If the kernel refuses to
/// forget the group, as it does to a thread that is not the one a ring of
/// [one thread](Setup::single_issuer) belongs to, the memory is kept
/// mapped for the life of the process rather than freed under it.)
pub struct BufRing {
    /// A handle of the ring's own, to take the group back with.
    fd: OwnedHandle,
    group: u16,
    count: u16,
    buf_len: u32,
    /// The next place of the ring to write.
    tail: u16,
    /// How many buffers the program holds.
    held: u16,
    /// The ring the kernel reads: `count` entries, the tail among them.
    entries: NonNull<sys::Buf>,
    /// A byte a buffer: 1 while the program holds it.
    state: NonNull<u8>,
    /// `count` buffers of `buf_len` bytes.
    bufs: NonNull<u8>,
    map: core::mem::ManuallyDrop<Map>,
}

// SAFETY: the pointers are into a mapping the group owns, shared with the
// kernel alone; it is changed through `&mut self`.
unsafe impl Send for BufRing {}
// SAFETY: what `&self` gives is reads of buffers the program holds, which
// the kernel does not write.
unsafe impl Sync for BufRing {}

impl BufRing {
    /// Makes the group `group` of `ring`: `count` buffers of `buf_len`
    /// bytes each, all of them the kernel's to pick. `count` must be a
    /// power of two, at most 32768.
    ///
    /// One anonymous mapping holds the ring and the buffers; the
    /// registration is `io_uring_register` with
    /// `IORING_REGISTER_PBUF_RING`. Fails with
    /// [`Unsupported`](ErrorKind::Unsupported) on a kernel older than
    /// 5.19, with [`InvalidInput`](ErrorKind::InvalidInput) for sizes
    /// that cannot be, and with
    /// [`AlreadyExists`](ErrorKind::AlreadyExists) if the ring has a
    /// group of that number.
    pub fn new(ring: &Ring, group: u16, count: u16, buf_len: u32) -> Result<Self> {
        if !count.is_power_of_two() || count > 1 << 15 || buf_len == 0 {
            return Err(ErrorKind::InvalidInput.into());
        }
        let page = crate::sys::mem::page_size();
        let entries = usize::from(count);
        // The ring must start a page, and the buffers start one too.
        let ring_len = (entries * size_of::<sys::Buf>() + entries).next_multiple_of(page);
        let len = entries
            .checked_mul(buf_len as usize)
            .and_then(|bufs| bufs.checked_add(ring_len))
            .filter(|len| *len <= isize::MAX as usize)
            .ok_or(ErrorKind::InvalidInput)?;
        let fd = crate::sys::io::duplicate(ring.as_handle())?;
        let map = Map::anonymous(len)?;
        let ring_entries: NonNull<sys::Buf> = map.at(0, entries)?;
        let state = map.at(entries * size_of::<sys::Buf>(), entries)?;
        let bufs = map.at(ring_len, len - ring_len)?;
        let registration = sys::BufReg {
            ring_addr: ring_entries.addr().get() as u64,
            ring_entries: u32::from(count),
            bgid: group,
            flags: 0,
            resv: [0; 3],
        };
        // SAFETY: the operation reads one structure; the ring it names is
        // the mapping, which lives until the group is taken back. (If it
        // fails the kernel knows nothing of the memory, which goes.)
        unsafe {
            ring.register(
                sys::IORING_REGISTER_PBUF_RING,
                (&raw const registration).cast(),
                1,
            )
        }
        .map_err(|error| ring.or_unsupported(error, Opcode::Socket))?;
        let mut this = Self {
            fd,
            group,
            count,
            buf_len,
            tail: 0,
            held: 0,
            entries: ring_entries,
            state,
            bufs,
            map: core::mem::ManuallyDrop::new(map),
        };
        for id in 0..count {
            this.add(id);
        }
        Ok(this)
    }

    /// The number of the group, for [`Sqe::buffer_select`].
    #[inline]
    pub fn group(&self) -> u16 {
        self.group
    }

    /// How many buffers the group has.
    #[inline]
    pub fn count(&self) -> u16 {
        self.count
    }

    /// The size of each buffer.
    #[inline]
    pub fn buf_len(&self) -> u32 {
        self.buf_len
    }

    /// How many buffers the program holds: taken, and not given back.
    /// When it is all of them the kernel has none to pick.
    #[inline]
    pub fn held(&self) -> u16 {
        self.held
    }

    fn ring_tail(&self) -> &AtomicU16 {
        // SAFETY: the tail is two bytes of the first entry of the ring,
        // aligned for it, which the program and the kernel only access as
        // an atomic.
        unsafe {
            self.entries
                .cast::<u8>()
                .add(sys::BUF_RING_TAIL)
                .cast::<AtomicU16>()
                .as_ref()
        }
    }

    /// Makes the buffer `id`, which the kernel does not have, the next it
    /// will pick.
    fn add(&mut self, id: u16) {
        let place = usize::from(self.tail & (self.count - 1));
        let addr = self.bufs.addr().get() + usize::from(id) * self.buf_len as usize;
        // SAFETY: the place is within the ring. The kernel reads the
        // places between its head and the tail: a buffer is there once at
        // most, so they are fewer than the ring has, and this one is not
        // among them. The members are written one by one because the last
        // two bytes of the first entry are the tail.
        unsafe {
            let entry = self.entries.add(place).as_ptr();
            (&raw mut (*entry).addr).write(addr as u64);
            (&raw mut (*entry).len).write(self.buf_len);
            (&raw mut (*entry).bid).write(id);
        }
        self.tail = self.tail.wrapping_add(1);
        // `Release`: the kernel's load of the tail sees the entry.
        self.ring_tail().store(self.tail, Ordering::Release);
    }

    fn state(&self, id: u16) -> Option<NonNull<u8>> {
        // SAFETY: there is a byte for each buffer.
        (id < self.count).then(|| unsafe { self.state.add(usize::from(id)) })
    }

    /// Makes the buffer a completion names the program's. `None` if the
    /// completion names none (it failed, or the stream ended), or one
    /// the program holds already.
    ///
    /// # Safety
    ///
    /// `cqe` must be a completion of an entry that selected from this
    /// group, on the ring the group was made for, and must be given here
    /// once: the kernel is taken at its word that the buffer is not its
    /// own any more.
    pub unsafe fn take(&mut self, cqe: &Cqe) -> Option<Buf> {
        let id = cqe.buffer_id()?;
        let state = self.state(id)?;
        // SAFETY: a byte of the mapping, which only this type reads and
        // writes.
        unsafe {
            if state.read() != 0 {
                return None;
            }
            state.write(1);
        }
        self.held += 1;
        Some(Buf {
            id,
            len: (cqe.raw_result().max(0) as u32).min(self.buf_len),
        })
    }

    /// What the kernel put in a buffer. Empty for a buffer that is not
    /// one this group has given out.
    pub fn bytes(&self, buf: &Buf) -> &[u8] {
        match self.state(buf.id) {
            // SAFETY: the program holds the buffer, so the kernel does
            // not write it, and it is within the mapping; it is not given
            // back while `self` is borrowed.
            Some(state) if unsafe { state.read() } != 0 => unsafe {
                let start = self.bufs.add(usize::from(buf.id) * self.buf_len as usize);
                core::slice::from_raw_parts(start.as_ptr(), buf.len.min(self.buf_len) as usize)
            },
            _ => &[],
        }
    }

    /// Makes a buffer the kernel's to pick again, after the others it
    /// has: a write to shared memory, and no system call.
    pub fn give_back(&mut self, buf: Buf) {
        let Some(state) = self.state(buf.id) else {
            return;
        };
        // SAFETY: as in `take`.
        unsafe {
            if state.read() == 0 {
                // Not one the program holds: of another group.
                return;
            }
            state.write(0);
        }
        self.held -= 1;
        self.add(buf.id);
    }
}

impl Drop for BufRing {
    fn drop(&mut self) {
        let registration = sys::BufReg {
            ring_addr: 0,
            ring_entries: 0,
            bgid: self.group,
            flags: 0,
            resv: [0; 3],
        };
        // SAFETY: the operation reads one structure.
        let gone = unsafe {
            sys::register(
                self.fd.as_raw(),
                sys::IORING_UNREGISTER_PBUF_RING,
                (&raw const registration).cast(),
                1,
            )
        };
        match gone {
            Ok(_) => {}
            // The ring has no such group: it never knew the memory, or
            // forgot it.
            Err(error) if error.raw_os_error() == crate::sys::errno::ENOENT => {}
            // The kernel still has the group, and may write to its
            // buffers: the memory stays.
            Err(_) => return,
        }
        // SAFETY: dropped once, here; the kernel has no group that names
        // the memory, and the entries that picked from it are over by the
        // promise of `Sqe::buffer_select`.
        unsafe { core::mem::ManuallyDrop::drop(&mut self.map) };
    }
}

impl fmt::Debug for BufRing {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BufRing")
            .field("group", &self.group)
            .field("count", &self.count)
            .field("buf_len", &self.buf_len)
            .field("held", &self.held)
            .finish_non_exhaustive()
    }
}