summaryrefslogtreecommitdiffstats
path: root/sys/kern/vfs_aio.c
blob: 7cd077bb189894a6f3781ca769c6667a25355a83 (plain)
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
/*-
 * Copyright (c) 1997 John S. Dyson.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. John S. Dyson's name may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * DISCLAIMER:  This code isn't warranted to do anything useful.  Anything
 * bad that happens because of using this software isn't the responsibility
 * of the author.  This software is distributed AS-IS.
 */

/*
 * This file contains support for the POSIX 1003.1B AIO/LIO facility.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include "opt_compat.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/malloc.h>
#include <sys/bio.h>
#include <sys/buf.h>
#include <sys/eventhandler.h>
#include <sys/sysproto.h>
#include <sys/filedesc.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/kthread.h>
#include <sys/fcntl.h>
#include <sys/file.h>
#include <sys/limits.h>
#include <sys/lock.h>
#include <sys/mutex.h>
#include <sys/unistd.h>
#include <sys/posix4.h>
#include <sys/proc.h>
#include <sys/resourcevar.h>
#include <sys/signalvar.h>
#include <sys/protosw.h>
#include <sys/sema.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/syscall.h>
#include <sys/sysent.h>
#include <sys/sysctl.h>
#include <sys/sx.h>
#include <sys/taskqueue.h>
#include <sys/vnode.h>
#include <sys/conf.h>
#include <sys/event.h>
#include <sys/mount.h>

#include <machine/atomic.h>

#include <vm/vm.h>
#include <vm/vm_extern.h>
#include <vm/pmap.h>
#include <vm/vm_map.h>
#include <vm/vm_object.h>
#include <vm/uma.h>
#include <sys/aio.h>

#include "opt_vfs_aio.h"

/*
 * Counter for allocating reference ids to new jobs.  Wrapped to 1 on
 * overflow. (XXX will be removed soon.)
 */
static u_long jobrefid;

/*
 * Counter for aio_fsync.
 */
static uint64_t jobseqno;

#define JOBST_NULL		0
#define JOBST_JOBQSOCK		1
#define JOBST_JOBQGLOBAL	2
#define JOBST_JOBRUNNING	3
#define JOBST_JOBFINISHED	4
#define JOBST_JOBQBUF		5
#define JOBST_JOBQSYNC		6

#ifndef MAX_AIO_PER_PROC
#define MAX_AIO_PER_PROC	32
#endif

#ifndef MAX_AIO_QUEUE_PER_PROC
#define MAX_AIO_QUEUE_PER_PROC	256 /* Bigger than AIO_LISTIO_MAX */
#endif

#ifndef MAX_AIO_PROCS
#define MAX_AIO_PROCS		32
#endif

#ifndef MAX_AIO_QUEUE
#define	MAX_AIO_QUEUE		1024 /* Bigger than AIO_LISTIO_MAX */
#endif

#ifndef TARGET_AIO_PROCS
#define TARGET_AIO_PROCS	4
#endif

#ifndef MAX_BUF_AIO
#define MAX_BUF_AIO		16
#endif

#ifndef AIOD_TIMEOUT_DEFAULT
#define	AIOD_TIMEOUT_DEFAULT	(10 * hz)
#endif

#ifndef AIOD_LIFETIME_DEFAULT
#define AIOD_LIFETIME_DEFAULT	(30 * hz)
#endif

FEATURE(aio, "Asynchronous I/O");

static MALLOC_DEFINE(M_LIO, "lio", "listio aio control block list");

static SYSCTL_NODE(_vfs, OID_AUTO, aio, CTLFLAG_RW, 0, "Async IO management");

static int max_aio_procs = MAX_AIO_PROCS;
SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_procs,
	CTLFLAG_RW, &max_aio_procs, 0,
	"Maximum number of kernel threads to use for handling async IO ");

static int num_aio_procs = 0;
SYSCTL_INT(_vfs_aio, OID_AUTO, num_aio_procs,
	CTLFLAG_RD, &num_aio_procs, 0,
	"Number of presently active kernel threads for async IO");

/*
 * The code will adjust the actual number of AIO processes towards this
 * number when it gets a chance.
 */
static int target_aio_procs = TARGET_AIO_PROCS;
SYSCTL_INT(_vfs_aio, OID_AUTO, target_aio_procs, CTLFLAG_RW, &target_aio_procs,
	0, "Preferred number of ready kernel threads for async IO");

static int max_queue_count = MAX_AIO_QUEUE;
SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_queue, CTLFLAG_RW, &max_queue_count, 0,
    "Maximum number of aio requests to queue, globally");

static int num_queue_count = 0;
SYSCTL_INT(_vfs_aio, OID_AUTO, num_queue_count, CTLFLAG_RD, &num_queue_count, 0,
    "Number of queued aio requests");

static int num_buf_aio = 0;
SYSCTL_INT(_vfs_aio, OID_AUTO, num_buf_aio, CTLFLAG_RD, &num_buf_aio, 0,
    "Number of aio requests presently handled by the buf subsystem");

/* Number of async I/O thread in the process of being started */
/* XXX This should be local to aio_aqueue() */
static int num_aio_resv_start = 0;

static int aiod_timeout;
SYSCTL_INT(_vfs_aio, OID_AUTO, aiod_timeout, CTLFLAG_RW, &aiod_timeout, 0,
    "Timeout value for synchronous aio operations");

static int aiod_lifetime;
SYSCTL_INT(_vfs_aio, OID_AUTO, aiod_lifetime, CTLFLAG_RW, &aiod_lifetime, 0,
    "Maximum lifetime for idle aiod");

static int unloadable = 0;
SYSCTL_INT(_vfs_aio, OID_AUTO, unloadable, CTLFLAG_RW, &unloadable, 0,
    "Allow unload of aio (not recommended)");


static int max_aio_per_proc = MAX_AIO_PER_PROC;
SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_per_proc, CTLFLAG_RW, &max_aio_per_proc,
    0, "Maximum active aio requests per process (stored in the process)");

static int max_aio_queue_per_proc = MAX_AIO_QUEUE_PER_PROC;
SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_queue_per_proc, CTLFLAG_RW,
    &max_aio_queue_per_proc, 0,
    "Maximum queued aio requests per process (stored in the process)");

static int max_buf_aio = MAX_BUF_AIO;
SYSCTL_INT(_vfs_aio, OID_AUTO, max_buf_aio, CTLFLAG_RW, &max_buf_aio, 0,
    "Maximum buf aio requests per process (stored in the process)");

typedef struct oaiocb {
	int	aio_fildes;		/* File descriptor */
	off_t	aio_offset;		/* File offset for I/O */
	volatile void *aio_buf;         /* I/O buffer in process space */
	size_t	aio_nbytes;		/* Number of bytes for I/O */
	struct	osigevent aio_sigevent;	/* Signal to deliver */
	int	aio_lio_opcode;		/* LIO opcode */
	int	aio_reqprio;		/* Request priority -- ignored */
	struct	__aiocb_private	_aiocb_private;
} oaiocb_t;

/*
 * Below is a key of locks used to protect each member of struct aiocblist
 * aioliojob and kaioinfo and any backends.
 *
 * * - need not protected
 * a - locked by kaioinfo lock
 * b - locked by backend lock, the backend lock can be null in some cases,
 *     for example, BIO belongs to this type, in this case, proc lock is
 *     reused.
 * c - locked by aio_job_mtx, the lock for the generic file I/O backend.
 */

/*
 * Current, there is only two backends: BIO and generic file I/O.
 * socket I/O is served by generic file I/O, this is not a good idea, since
 * disk file I/O and any other types without O_NONBLOCK flag can block daemon
 * threads, if there is no thread to serve socket I/O, the socket I/O will be
 * delayed too long or starved, we should create some threads dedicated to
 * sockets to do non-blocking I/O, same for pipe and fifo, for these I/O
 * systems we really need non-blocking interface, fiddling O_NONBLOCK in file
 * structure is not safe because there is race between userland and aio
 * daemons.
 */

struct aiocblist {
	TAILQ_ENTRY(aiocblist) list;	/* (b) internal list of for backend */
	TAILQ_ENTRY(aiocblist) plist;	/* (a) list of jobs for each backend */
	TAILQ_ENTRY(aiocblist) allist;  /* (a) list of all jobs in proc */
	int	jobflags;		/* (a) job flags */
	int	jobstate;		/* (b) job state */
	int	inputcharge;		/* (*) input blockes */
	int	outputcharge;		/* (*) output blockes */
	struct	buf *bp;		/* (*) private to BIO backend,
				  	 * buffer pointer
					 */
	struct	proc *userproc;		/* (*) user process */
	struct  ucred *cred;		/* (*) active credential when created */
	struct	file *fd_file;		/* (*) pointer to file structure */
	struct	aioliojob *lio;		/* (*) optional lio job */
	struct	aiocb *uuaiocb;		/* (*) pointer in userspace of aiocb */
	struct	knlist klist;		/* (a) list of knotes */
	struct	aiocb uaiocb;		/* (*) kernel I/O control block */
	ksiginfo_t ksi;			/* (a) realtime signal info */
	struct	task biotask;		/* (*) private to BIO backend */
	uint64_t seqno;			/* (*) job number */
	int	pending;		/* (a) number of pending I/O, aio_fsync only */
};

/* jobflags */
#define AIOCBLIST_DONE		0x01
#define AIOCBLIST_BUFDONE	0x02
#define AIOCBLIST_RUNDOWN	0x04
#define AIOCBLIST_CHECKSYNC	0x08

/*
 * AIO process info
 */
#define AIOP_FREE	0x1			/* proc on free queue */

struct aiothreadlist {
	int aiothreadflags;			/* (c) AIO proc flags */
	TAILQ_ENTRY(aiothreadlist) list;	/* (c) list of processes */
	struct thread *aiothread;		/* (*) the AIO thread */
};

/*
 * data-structure for lio signal management
 */
struct aioliojob {
	int	lioj_flags;			/* (a) listio flags */
	int	lioj_count;			/* (a) listio flags */
	int	lioj_finished_count;		/* (a) listio flags */
	struct	sigevent lioj_signal;		/* (a) signal on all I/O done */
	TAILQ_ENTRY(aioliojob) lioj_list;	/* (a) lio list */
	struct  knlist klist;			/* (a) list of knotes */
	ksiginfo_t lioj_ksi;			/* (a) Realtime signal info */
};

#define	LIOJ_SIGNAL		0x1	/* signal on all done (lio) */
#define	LIOJ_SIGNAL_POSTED	0x2	/* signal has been posted */
#define LIOJ_KEVENT_POSTED	0x4	/* kevent triggered */

/*
 * per process aio data structure
 */
struct kaioinfo {
	struct mtx	kaio_mtx;	/* the lock to protect this struct */
	int	kaio_flags;		/* (a) per process kaio flags */
	int	kaio_maxactive_count;	/* (*) maximum number of AIOs */
	int	kaio_active_count;	/* (c) number of currently used AIOs */
	int	kaio_qallowed_count;	/* (*) maxiumu size of AIO queue */
	int	kaio_count;		/* (a) size of AIO queue */
	int	kaio_ballowed_count;	/* (*) maximum number of buffers */
	int	kaio_buffer_count;	/* (a) number of physio buffers */
	TAILQ_HEAD(,aiocblist) kaio_all;	/* (a) all AIOs in the process */
	TAILQ_HEAD(,aiocblist) kaio_done;	/* (a) done queue for process */
	TAILQ_HEAD(,aioliojob) kaio_liojoblist; /* (a) list of lio jobs */
	TAILQ_HEAD(,aiocblist) kaio_jobqueue;	/* (a) job queue for process */
	TAILQ_HEAD(,aiocblist) kaio_bufqueue;	/* (a) buffer job queue for process */
	TAILQ_HEAD(,aiocblist) kaio_sockqueue;  /* (a) queue for aios waiting on sockets,
						 *  NOT USED YET.
						 */
	TAILQ_HEAD(,aiocblist) kaio_syncqueue;	/* (a) queue for aio_fsync */
	struct	task	kaio_task;	/* (*) task to kick aio threads */
};

#define AIO_LOCK(ki)		mtx_lock(&(ki)->kaio_mtx)
#define AIO_UNLOCK(ki)		mtx_unlock(&(ki)->kaio_mtx)
#define AIO_LOCK_ASSERT(ki, f)	mtx_assert(&(ki)->kaio_mtx, (f))
#define AIO_MTX(ki)		(&(ki)->kaio_mtx)

#define KAIO_RUNDOWN	0x1	/* process is being run down */
#define KAIO_WAKEUP	0x2	/* wakeup process when there is a significant event */

/*
 * Operations used to interact with userland aio control blocks.
 * Different ABIs provide their own operations.
 */
struct aiocb_ops {
	int	(*copyin)(struct aiocb *ujob, struct aiocb *kjob);
	long	(*fetch_status)(struct aiocb *ujob);
	long	(*fetch_error)(struct aiocb *ujob);
	int	(*store_status)(struct aiocb *ujob, long status);
	int	(*store_error)(struct aiocb *ujob, long error);
	int	(*store_kernelinfo)(struct aiocb *ujob, long jobref);
	int	(*store_aiocb)(struct aiocb **ujobp, struct aiocb *ujob);
};

static TAILQ_HEAD(,aiothreadlist) aio_freeproc;		/* (c) Idle daemons */
static struct sema aio_newproc_sem;
static struct mtx aio_job_mtx;
static struct mtx aio_sock_mtx;
static TAILQ_HEAD(,aiocblist) aio_jobs;			/* (c) Async job list */
static struct unrhdr *aiod_unr;

void		aio_init_aioinfo(struct proc *p);
static void	aio_onceonly(void);
static int	aio_free_entry(struct aiocblist *aiocbe);
static void	aio_process(struct aiocblist *aiocbe);
static int	aio_newproc(int *);
int		aio_aqueue(struct thread *td, struct aiocb *job,
			struct aioliojob *lio, int type, struct aiocb_ops *ops);
static void	aio_physwakeup(struct buf *bp);
static void	aio_proc_rundown(void *arg, struct proc *p);
static void	aio_proc_rundown_exec(void *arg, struct proc *p, struct image_params *imgp);
static int	aio_qphysio(struct proc *p, struct aiocblist *iocb);
static void	biohelper(void *, int);
static void	aio_daemon(void *param);
static void	aio_swake_cb(struct socket *, struct sockbuf *);
static int	aio_unload(void);
static void	aio_bio_done_notify(struct proc *userp, struct aiocblist *aiocbe, int type);
#define DONE_BUF	1
#define DONE_QUEUE	2
static int	aio_kick(struct proc *userp);
static void	aio_kick_nowait(struct proc *userp);
static void	aio_kick_helper(void *context, int pending);
static int	filt_aioattach(struct knote *kn);
static void	filt_aiodetach(struct knote *kn);
static int	filt_aio(struct knote *kn, long hint);
static int	filt_lioattach(struct knote *kn);
static void	filt_liodetach(struct knote *kn);
static int	filt_lio(struct knote *kn, long hint);

/*
 * Zones for:
 * 	kaio	Per process async io info
 *	aiop	async io thread data
 *	aiocb	async io jobs
 *	aiol	list io job pointer - internal to aio_suspend XXX
 *	aiolio	list io jobs
 */
static uma_zone_t kaio_zone, aiop_zone, aiocb_zone, aiol_zone, aiolio_zone;

/* kqueue filters for aio */
static struct filterops aio_filtops =
	{ 0, filt_aioattach, filt_aiodetach, filt_aio };
static struct filterops lio_filtops =
	{ 0, filt_lioattach, filt_liodetach, filt_lio };

static eventhandler_tag exit_tag, exec_tag;

TASKQUEUE_DEFINE_THREAD(aiod_bio);

/*
 * Main operations function for use as a kernel module.
 */
static int
aio_modload(struct module *module, int cmd, void *arg)
{
	int error = 0;

	switch (cmd) {
	case MOD_LOAD:
		aio_onceonly();
		break;
	case MOD_UNLOAD:
		error = aio_unload();
		break;
	case MOD_SHUTDOWN:
		break;
	default:
		error = EINVAL;
		break;
	}
	return (error);
}

static moduledata_t aio_mod = {
	"aio",
	&aio_modload,
	NULL
};

SYSCALL_MODULE_HELPER(aio_cancel);
SYSCALL_MODULE_HELPER(aio_error);
SYSCALL_MODULE_HELPER(aio_fsync);
SYSCALL_MODULE_HELPER(aio_read);
SYSCALL_MODULE_HELPER(aio_return);
SYSCALL_MODULE_HELPER(aio_suspend);
SYSCALL_MODULE_HELPER(aio_waitcomplete);
SYSCALL_MODULE_HELPER(aio_write);
SYSCALL_MODULE_HELPER(lio_listio);
SYSCALL_MODULE_HELPER(oaio_read);
SYSCALL_MODULE_HELPER(oaio_write);
SYSCALL_MODULE_HELPER(olio_listio);

DECLARE_MODULE(aio, aio_mod,
	SI_SUB_VFS, SI_ORDER_ANY);
MODULE_VERSION(aio, 1);

/*
 * Startup initialization
 */
static void
aio_onceonly(void)
{

	/* XXX: should probably just use so->callback */
	aio_swake = &aio_swake_cb;
	exit_tag = EVENTHANDLER_REGISTER(process_exit, aio_proc_rundown, NULL,
	    EVENTHANDLER_PRI_ANY);
	exec_tag = EVENTHANDLER_REGISTER(process_exec, aio_proc_rundown_exec, NULL,
	    EVENTHANDLER_PRI_ANY);
	kqueue_add_filteropts(EVFILT_AIO, &aio_filtops);
	kqueue_add_filteropts(EVFILT_LIO, &lio_filtops);
	TAILQ_INIT(&aio_freeproc);
	sema_init(&aio_newproc_sem, 0, "aio_new_proc");
	mtx_init(&aio_job_mtx, "aio_job", NULL, MTX_DEF);
	mtx_init(&aio_sock_mtx, "aio_sock", NULL, MTX_DEF);
	TAILQ_INIT(&aio_jobs);
	aiod_unr = new_unrhdr(1, INT_MAX, NULL);
	kaio_zone = uma_zcreate("AIO", sizeof(struct kaioinfo), NULL, NULL,
	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
	aiop_zone = uma_zcreate("AIOP", sizeof(struct aiothreadlist), NULL,
	    NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
	aiocb_zone = uma_zcreate("AIOCB", sizeof(struct aiocblist), NULL, NULL,
	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
	aiol_zone = uma_zcreate("AIOL", AIO_LISTIO_MAX*sizeof(intptr_t) , NULL,
	    NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
	aiolio_zone = uma_zcreate("AIOLIO", sizeof(struct aioliojob), NULL,
	    NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
	aiod_timeout = AIOD_TIMEOUT_DEFAULT;
	aiod_lifetime = AIOD_LIFETIME_DEFAULT;
	jobrefid = 1;
	async_io_version = _POSIX_VERSION;
	p31b_setcfg(CTL_P1003_1B_AIO_LISTIO_MAX, AIO_LISTIO_MAX);
	p31b_setcfg(CTL_P1003_1B_AIO_MAX, MAX_AIO_QUEUE);
	p31b_setcfg(CTL_P1003_1B_AIO_PRIO_DELTA_MAX, 0);
}

/*
 * Callback for unload of AIO when used as a module.
 */
static int
aio_unload(void)
{
	int error;

	/*
	 * XXX: no unloads by default, it's too dangerous.
	 * perhaps we could do it if locked out callers and then
	 * did an aio_proc_rundown() on each process.
	 *
	 * jhb: aio_proc_rundown() needs to run on curproc though,
	 * so I don't think that would fly.
	 */
	if (!unloadable)
		return (EOPNOTSUPP);

	error = kqueue_del_filteropts(EVFILT_AIO);
	if (error)
		return error;
	error = kqueue_del_filteropts(EVFILT_LIO);
	if (error)
		return error;
	async_io_version = 0;
	aio_swake = NULL;
	taskqueue_free(taskqueue_aiod_bio);
	delete_unrhdr(aiod_unr);
	uma_zdestroy(kaio_zone);
	uma_zdestroy(aiop_zone);
	uma_zdestroy(aiocb_zone);
	uma_zdestroy(aiol_zone);
	uma_zdestroy(aiolio_zone);
	EVENTHANDLER_DEREGISTER(process_exit, exit_tag);
	EVENTHANDLER_DEREGISTER(process_exec, exec_tag);
	mtx_destroy(&aio_job_mtx);
	mtx_destroy(&aio_sock_mtx);
	sema_destroy(&aio_newproc_sem);
	p31b_setcfg(CTL_P1003_1B_AIO_LISTIO_MAX, -1);
	p31b_setcfg(CTL_P1003_1B_AIO_MAX, -1);
	p31b_setcfg(CTL_P1003_1B_AIO_PRIO_DELTA_MAX, -1);
	return (0);
}

/*
 * Init the per-process aioinfo structure.  The aioinfo limits are set
 * per-process for user limit (resource) management.
 */
void
aio_init_aioinfo(struct proc *p)
{
	struct kaioinfo *ki;

	ki = uma_zalloc(kaio_zone, M_WAITOK);
	mtx_init(&ki->kaio_mtx, "aiomtx", NULL, MTX_DEF);
	ki->kaio_flags = 0;
	ki->kaio_maxactive_count = max_aio_per_proc;
	ki->kaio_active_count = 0;
	ki->kaio_qallowed_count = max_aio_queue_per_proc;
	ki->kaio_count = 0;
	ki->kaio_ballowed_count = max_buf_aio;
	ki->kaio_buffer_count = 0;
	TAILQ_INIT(&ki->kaio_all);
	TAILQ_INIT(&ki->kaio_done);
	TAILQ_INIT(&ki->kaio_jobqueue);
	TAILQ_INIT(&ki->kaio_bufqueue);
	TAILQ_INIT(&ki->kaio_liojoblist);
	TAILQ_INIT(&ki->kaio_sockqueue);
	TAILQ_INIT(&ki->kaio_syncqueue);
	TASK_INIT(&ki->kaio_task, 0, aio_kick_helper, p);
	PROC_LOCK(p);
	if (p->p_aioinfo == NULL) {
		p->p_aioinfo = ki;
		PROC_UNLOCK(p);
	} else {
		PROC_UNLOCK(p);
		mtx_destroy(&ki->kaio_mtx);
		uma_zfree(kaio_zone, ki);
	}

	while (num_aio_procs < MIN(target_aio_procs, max_aio_procs))
		aio_newproc(NULL);
}

static int
aio_sendsig(struct proc *p, struct sigevent *sigev, ksiginfo_t *ksi)
{
	int ret = 0;

	PROC_LOCK(p);
	if (!KSI_ONQ(ksi)) {
		ksi->ksi_code = SI_ASYNCIO;
		ksi->ksi_flags |= KSI_EXT | KSI_INS;
		ret = psignal_event(p, sigev, ksi);
	}
	PROC_UNLOCK(p);
	return (ret);
}

/*
 * Free a job entry.  Wait for completion if it is currently active, but don't
 * delay forever.  If we delay, we return a flag that says that we have to
 * restart the queue scan.
 */
static int
aio_free_entry(struct aiocblist *aiocbe)
{
	struct kaioinfo *ki;
	struct aioliojob *lj;
	struct proc *p;

	p = aiocbe->userproc;
	MPASS(curproc == p);
	ki = p->p_aioinfo;
	MPASS(ki != NULL);

	AIO_LOCK_ASSERT(ki, MA_OWNED);
	MPASS(aiocbe->jobstate == JOBST_JOBFINISHED);

	atomic_subtract_int(&num_queue_count, 1);

	ki->kaio_count--;
	MPASS(ki->kaio_count >= 0);

	TAILQ_REMOVE(&ki->kaio_done, aiocbe, plist);
	TAILQ_REMOVE(&ki->kaio_all, aiocbe, allist);

	lj = aiocbe->lio;
	if (lj) {
		lj->lioj_count--;
		lj->lioj_finished_count--;

		if (lj->lioj_count == 0) {
			TAILQ_REMOVE(&ki->kaio_liojoblist, lj, lioj_list);
			/* lio is going away, we need to destroy any knotes */
			knlist_delete(&lj->klist, curthread, 1);
			PROC_LOCK(p);
			sigqueue_take(&lj->lioj_ksi);
			PROC_UNLOCK(p);
			uma_zfree(aiolio_zone, lj);
		}
	}

	/* aiocbe is going away, we need to destroy any knotes */
	knlist_delete(&aiocbe->klist, curthread, 1);
	PROC_LOCK(p);
	sigqueue_take(&aiocbe->ksi);
	PROC_UNLOCK(p);

	MPASS(aiocbe->bp == NULL);
	aiocbe->jobstate = JOBST_NULL;
	AIO_UNLOCK(ki);

	/*
	 * The thread argument here is used to find the owning process
	 * and is also passed to fo_close() which may pass it to various
	 * places such as devsw close() routines.  Because of that, we
	 * need a thread pointer from the process owning the job that is
	 * persistent and won't disappear out from under us or move to
	 * another process.
	 *
	 * Currently, all the callers of this function call it to remove
	 * an aiocblist from the current process' job list either via a
	 * syscall or due to the current process calling exit() or
	 * execve().  Thus, we know that p == curproc.  We also know that
	 * curthread can't exit since we are curthread.
	 *
	 * Therefore, we use curthread as the thread to pass to
	 * knlist_delete().  This does mean that it is possible for the
	 * thread pointer at close time to differ from the thread pointer
	 * at open time, but this is already true of file descriptors in
	 * a multithreaded process.
	 */
	fdrop(aiocbe->fd_file, curthread);
	crfree(aiocbe->cred);
	uma_zfree(aiocb_zone, aiocbe);
	AIO_LOCK(ki);

	return (0);
}

static void
aio_proc_rundown_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
{
   	aio_proc_rundown(arg, p);
}

/*
 * Rundown the jobs for a given process.
 */
static void
aio_proc_rundown(void *arg, struct proc *p)
{
	struct kaioinfo *ki;
	struct aioliojob *lj;
	struct aiocblist *cbe, *cbn;
	struct file *fp;
	struct socket *so;
	int remove;

	KASSERT(curthread->td_proc == p,
	    ("%s: called on non-curproc", __func__));
	ki = p->p_aioinfo;
	if (ki == NULL)
		return;

	AIO_LOCK(ki);
	ki->kaio_flags |= KAIO_RUNDOWN;

restart:

	/*
	 * Try to cancel all pending requests. This code simulates
	 * aio_cancel on all pending I/O requests.
	 */
	TAILQ_FOREACH_SAFE(cbe, &ki->kaio_jobqueue, plist, cbn) {
		remove = 0;
		mtx_lock(&aio_job_mtx);
		if (cbe->jobstate == JOBST_JOBQGLOBAL) {
			TAILQ_REMOVE(&aio_jobs, cbe, list);
			remove = 1;
		} else if (cbe->jobstate == JOBST_JOBQSOCK) {
			fp = cbe->fd_file;
			MPASS(fp->f_type == DTYPE_SOCKET);
			so = fp->f_data;
			TAILQ_REMOVE(&so->so_aiojobq, cbe, list);
			remove = 1;
		} else if (cbe->jobstate == JOBST_JOBQSYNC) {
			TAILQ_REMOVE(&ki->kaio_syncqueue, cbe, list);
			remove = 1;
		}
		mtx_unlock(&aio_job_mtx);

		if (remove) {
			cbe->jobstate = JOBST_JOBFINISHED;
			cbe->uaiocb._aiocb_private.status = -1;
			cbe->uaiocb._aiocb_private.error = ECANCELED;
			TAILQ_REMOVE(&ki->kaio_jobqueue, cbe, plist);
			aio_bio_done_notify(p, cbe, DONE_QUEUE);
		}
	}

	/* Wait for all running I/O to be finished */
	if (TAILQ_FIRST(&ki->kaio_bufqueue) ||
	    TAILQ_FIRST(&ki->kaio_jobqueue)) {
		ki->kaio_flags |= KAIO_WAKEUP;
		msleep(&p->p_aioinfo, AIO_MTX(ki), PRIBIO, "aioprn", hz);
		goto restart;
	}

	/* Free all completed I/O requests. */
	while ((cbe = TAILQ_FIRST(&ki->kaio_done)) != NULL)
		aio_free_entry(cbe);

	while ((lj = TAILQ_FIRST(&ki->kaio_liojoblist)) != NULL) {
		if (lj->lioj_count == 0) {
			TAILQ_REMOVE(&ki->kaio_liojoblist, lj, lioj_list);
			knlist_delete(&lj->klist, curthread, 1);
			PROC_LOCK(p);
			sigqueue_take(&lj->lioj_ksi);
			PROC_UNLOCK(p);
			uma_zfree(aiolio_zone, lj);
		} else {
			panic("LIO job not cleaned up: C:%d, FC:%d\n",
			    lj->lioj_count, lj->lioj_finished_count);
		}
	}
	AIO_UNLOCK(ki);
	taskqueue_drain(taskqueue_aiod_bio, &ki->kaio_task);
	mtx_destroy(&ki->kaio_mtx);
	uma_zfree(kaio_zone, ki);
	p->p_aioinfo = NULL;
}

/*
 * Select a job to run (called by an AIO daemon).
 */
static struct aiocblist *
aio_selectjob(struct aiothreadlist *aiop)
{
	struct aiocblist *aiocbe;
	struct kaioinfo *ki;
	struct proc *userp;

	mtx_assert(&aio_job_mtx, MA_OWNED);
	TAILQ_FOREACH(aiocbe, &aio_jobs, list) {
		userp = aiocbe->userproc;
		ki = userp->p_aioinfo;

		if (ki->kaio_active_count < ki->kaio_maxactive_count) {
			TAILQ_REMOVE(&aio_jobs, aiocbe, list);
			/* Account for currently active jobs. */
			ki->kaio_active_count++;
			aiocbe->jobstate = JOBST_JOBRUNNING;
			break;
		}
	}
	return (aiocbe);
}

/*
 *  Move all data to a permanent storage device, this code
 *  simulates fsync syscall.
 */
static int
aio_fsync_vnode(struct thread *td, struct vnode *vp)
{
	struct mount *mp;
	int vfslocked;
	int error;

	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
	if ((error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
		goto drop;
	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
	if (vp->v_object != NULL) {
		VM_OBJECT_LOCK(vp->v_object);
		vm_object_page_clean(vp->v_object, 0, 0, 0);
		VM_OBJECT_UNLOCK(vp->v_object);
	}
	error = VOP_FSYNC(vp, MNT_WAIT, td);

	VOP_UNLOCK(vp, 0);
	vn_finished_write(mp);
drop:
	VFS_UNLOCK_GIANT(vfslocked);
	return (error);
}

/*
 * The AIO processing activity.  This is the code that does the I/O request for
 * the non-physio version of the operations.  The normal vn operations are used,
 * and this code should work in all instances for every type of file, including
 * pipes, sockets, fifos, and regular files.
 *
 * XXX I don't think it works well for socket, pipe, and fifo.
 */
static void
aio_process(struct aiocblist *aiocbe)
{
	struct ucred *td_savedcred;
	struct thread *td;
	struct aiocb *cb;
	struct file *fp;
	struct socket *so;
	struct uio auio;
	struct iovec aiov;
	int cnt;
	int error;
	int oublock_st, oublock_end;
	int inblock_st, inblock_end;

	td = curthread;
	td_savedcred = td->td_ucred;
	td->td_ucred = aiocbe->cred;
	cb = &aiocbe->uaiocb;
	fp = aiocbe->fd_file;

	if (cb->aio_lio_opcode == LIO_SYNC) {
		error = 0;
		cnt = 0;
		if (fp->f_vnode != NULL)
			error = aio_fsync_vnode(td, fp->f_vnode);
		cb->_aiocb_private.error = error;
		cb->_aiocb_private.status = 0;
		td->td_ucred = td_savedcred;
		return;
	}

	aiov.iov_base = (void *)(uintptr_t)cb->aio_buf;
	aiov.iov_len = cb->aio_nbytes;

	auio.uio_iov = &aiov;
	auio.uio_iovcnt = 1;
	auio.uio_offset = cb->aio_offset;
	auio.uio_resid = cb->aio_nbytes;
	cnt = cb->aio_nbytes;
	auio.uio_segflg = UIO_USERSPACE;
	auio.uio_td = td;

	inblock_st = td->td_ru.ru_inblock;
	oublock_st = td->td_ru.ru_oublock;
	/*
	 * aio_aqueue() acquires a reference to the file that is
	 * released in aio_free_entry().
	 */
	if (cb->aio_lio_opcode == LIO_READ) {
		auio.uio_rw = UIO_READ;
		if (auio.uio_resid == 0)
			error = 0;
		else
			error = fo_read(fp, &auio, fp->f_cred, FOF_OFFSET, td);
	} else {
		if (fp->f_type == DTYPE_VNODE)
			bwillwrite();
		auio.uio_rw = UIO_WRITE;
		error = fo_write(fp, &auio, fp->f_cred, FOF_OFFSET, td);
	}
	inblock_end = td->td_ru.ru_inblock;
	oublock_end = td->td_ru.ru_oublock;

	aiocbe->inputcharge = inblock_end - inblock_st;
	aiocbe->outputcharge = oublock_end - oublock_st;

	if ((error) && (auio.uio_resid != cnt)) {
		if (error == ERESTART || error == EINTR || error == EWOULDBLOCK)
			error = 0;
		if ((error == EPIPE) && (cb->aio_lio_opcode == LIO_WRITE)) {
			int sigpipe = 1;
			if (fp->f_type == DTYPE_SOCKET) {
				so = fp->f_data;
				if (so->so_options & SO_NOSIGPIPE)
					sigpipe = 0;
			}
			if (sigpipe) {
				PROC_LOCK(aiocbe->userproc);
				psignal(aiocbe->userproc, SIGPIPE);
				PROC_UNLOCK(aiocbe->userproc);
			}
		}
	}

	cnt -= auio.uio_resid;
	cb->_aiocb_private.error = error;
	cb->_aiocb_private.status = cnt;
	td->td_ucred = td_savedcred;
}

static void
aio_bio_done_notify(struct proc *userp, struct aiocblist *aiocbe, int type)
{
	struct aioliojob *lj;
	struct kaioinfo *ki;
	struct aiocblist *scb, *scbn;
	int lj_done;

	ki = userp->p_aioinfo;
	AIO_LOCK_ASSERT(ki, MA_OWNED);
	lj = aiocbe->lio;
	lj_done = 0;
	if (lj) {
		lj->lioj_finished_count++;
		if (lj->lioj_count == lj->lioj_finished_count)
			lj_done = 1;
	}
	if (type == DONE_QUEUE) {
		aiocbe->jobflags |= AIOCBLIST_DONE;
	} else {
		aiocbe->jobflags |= AIOCBLIST_BUFDONE;
	}
	TAILQ_INSERT_TAIL(&ki->kaio_done, aiocbe, plist);
	aiocbe->jobstate = JOBST_JOBFINISHED;

	if (ki->kaio_flags & KAIO_RUNDOWN)
		goto notification_done;

	if (aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_SIGNAL ||
	    aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_THREAD_ID)
		aio_sendsig(userp, &aiocbe->uaiocb.aio_sigevent, &aiocbe->ksi);

	KNOTE_LOCKED(&aiocbe->klist, 1);

	if (lj_done) {
		if (lj->lioj_signal.sigev_notify == SIGEV_KEVENT) {
			lj->lioj_flags |= LIOJ_KEVENT_POSTED;
			KNOTE_LOCKED(&lj->klist, 1);
		}
		if ((lj->lioj_flags & (LIOJ_SIGNAL|LIOJ_SIGNAL_POSTED))
		    == LIOJ_SIGNAL
		    && (lj->lioj_signal.sigev_notify == SIGEV_SIGNAL ||
		        lj->lioj_signal.sigev_notify == SIGEV_THREAD_ID)) {
			aio_sendsig(userp, &lj->lioj_signal, &lj->lioj_ksi);
			lj->lioj_flags |= LIOJ_SIGNAL_POSTED;
		}
	}

notification_done:
	if (aiocbe->jobflags & AIOCBLIST_CHECKSYNC) {
		TAILQ_FOREACH_SAFE(scb, &ki->kaio_syncqueue, list, scbn) {
			if (aiocbe->fd_file == scb->fd_file &&
			    aiocbe->seqno < scb->seqno) {
				if (--scb->pending == 0) {
					mtx_lock(&aio_job_mtx);
					scb->jobstate = JOBST_JOBQGLOBAL;
					TAILQ_REMOVE(&ki->kaio_syncqueue, scb, list);
					TAILQ_INSERT_TAIL(&aio_jobs, scb, list);
					aio_kick_nowait(userp);
					mtx_unlock(&aio_job_mtx);
				}
			}
		}
	}
	if (ki->kaio_flags & KAIO_WAKEUP) {
		ki->kaio_flags &= ~KAIO_WAKEUP;
		wakeup(&userp->p_aioinfo);
	}
}

/*
 * The AIO daemon, most of the actual work is done in aio_process,
 * but the setup (and address space mgmt) is done in this routine.
 */
static void
aio_daemon(void *_id)
{
	struct aiocblist *aiocbe;
	struct aiothreadlist *aiop;
	struct kaioinfo *ki;
	struct proc *curcp, *mycp, *userp;
	struct vmspace *myvm, *tmpvm;
	struct thread *td = curthread;
	int id = (intptr_t)_id;

	/*
	 * Local copies of curproc (cp) and vmspace (myvm)
	 */
	mycp = td->td_proc;
	myvm = mycp->p_vmspace;

	KASSERT(mycp->p_textvp == NULL, ("kthread has a textvp"));

	/*
	 * Allocate and ready the aio control info.  There is one aiop structure
	 * per daemon.
	 */
	aiop = uma_zalloc(aiop_zone, M_WAITOK);
	aiop->aiothread = td;
	aiop->aiothreadflags = 0;

	/* The daemon resides in its own pgrp. */
	setsid(td, NULL);

	/*
	 * Wakeup parent process.  (Parent sleeps to keep from blasting away
	 * and creating too many daemons.)
	 */
	sema_post(&aio_newproc_sem);

	mtx_lock(&aio_job_mtx);
	for (;;) {
		/*
		 * curcp is the current daemon process context.
		 * userp is the current user process context.
		 */
		curcp = mycp;

		/*
		 * Take daemon off of free queue
		 */
		if (aiop->aiothreadflags & AIOP_FREE) {
			TAILQ_REMOVE(&aio_freeproc, aiop, list);
			aiop->aiothreadflags &= ~AIOP_FREE;
		}

		/*
		 * Check for jobs.
		 */
		while ((aiocbe = aio_selectjob(aiop)) != NULL) {
			mtx_unlock(&aio_job_mtx);
			userp = aiocbe->userproc;

			/*
			 * Connect to process address space for user program.
			 */
			if (userp != curcp) {
				/*
				 * Save the current address space that we are
				 * connected to.
				 */
				tmpvm = mycp->p_vmspace;

				/*
				 * Point to the new user address space, and
				 * refer to it.
				 */
				mycp->p_vmspace = userp->p_vmspace;
				atomic_add_int(&mycp->p_vmspace->vm_refcnt, 1);

				/* Activate the new mapping. */
				pmap_activate(FIRST_THREAD_IN_PROC(mycp));

				/*
				 * If the old address space wasn't the daemons
				 * own address space, then we need to remove the
				 * daemon's reference from the other process
				 * that it was acting on behalf of.
				 */
				if (tmpvm != myvm) {
					vmspace_free(tmpvm);
				}
				curcp = userp;
			}

			ki = userp->p_aioinfo;

			/* Do the I/O function. */
			aio_process(aiocbe);

			mtx_lock(&aio_job_mtx);
			/* Decrement the active job count. */
			ki->kaio_active_count--;
			mtx_unlock(&aio_job_mtx);

			AIO_LOCK(ki);
			TAILQ_REMOVE(&ki->kaio_jobqueue, aiocbe, plist);
			aio_bio_done_notify(userp, aiocbe, DONE_QUEUE);
			AIO_UNLOCK(ki);

			mtx_lock(&aio_job_mtx);
		}

		/*
		 * Disconnect from user address space.
		 */
		if (curcp != mycp) {

			mtx_unlock(&aio_job_mtx);

			/* Get the user address space to disconnect from. */
			tmpvm = mycp->p_vmspace;

			/* Get original address space for daemon. */
			mycp->p_vmspace = myvm;

			/* Activate the daemon's address space. */
			pmap_activate(FIRST_THREAD_IN_PROC(mycp));
#ifdef DIAGNOSTIC
			if (tmpvm == myvm) {
				printf("AIOD: vmspace problem -- %d\n",
				    mycp->p_pid);
			}
#endif
			/* Remove our vmspace reference. */
			vmspace_free(tmpvm);

			curcp = mycp;

			mtx_lock(&aio_job_mtx);
			/*
			 * We have to restart to avoid race, we only sleep if
			 * no job can be selected, that should be
			 * curcp == mycp.
			 */
			continue;
		}

		mtx_assert(&aio_job_mtx, MA_OWNED);

		TAILQ_INSERT_HEAD(&aio_freeproc, aiop, list);
		aiop->aiothreadflags |= AIOP_FREE;

		/*
		 * If daemon is inactive for a long time, allow it to exit,
		 * thereby freeing resources.
		 */
		if (msleep(aiop->aiothread, &aio_job_mtx, PRIBIO, "aiordy",
		    aiod_lifetime)) {
			if (TAILQ_EMPTY(&aio_jobs)) {
				if ((aiop->aiothreadflags & AIOP_FREE) &&
				    (num_aio_procs > target_aio_procs)) {
					TAILQ_REMOVE(&aio_freeproc, aiop, list);
					num_aio_procs--;
					mtx_unlock(&aio_job_mtx);
					uma_zfree(aiop_zone, aiop);
					free_unr(aiod_unr, id);
#ifdef DIAGNOSTIC
					if (mycp->p_vmspace->vm_refcnt <= 1) {
						printf("AIOD: bad vm refcnt for"
						    " exiting daemon: %d\n",
						    mycp->p_vmspace->vm_refcnt);
					}
#endif
					kproc_exit(0);
				}
			}
		}
	}
	mtx_unlock(&aio_job_mtx);
	panic("shouldn't be here\n");
}

/*
 * Create a new AIO daemon. This is mostly a kernel-thread fork routine. The
 * AIO daemon modifies its environment itself.
 */
static int
aio_newproc(int *start)
{
	int error;
	struct proc *p;
	int id;

	id = alloc_unr(aiod_unr);
	error = kproc_create(aio_daemon, (void *)(intptr_t)id, &p,
		RFNOWAIT, 0, "aiod%d", id);
	if (error == 0) {
		/*
		 * Wait until daemon is started.
		 */
		sema_wait(&aio_newproc_sem);
		mtx_lock(&aio_job_mtx);
		num_aio_procs++;
		if (start != NULL)
			(*start)--;
		mtx_unlock(&aio_job_mtx);
	} else {
		free_unr(aiod_unr, id);
	}
	return (error);
}

/*
 * Try the high-performance, low-overhead physio method for eligible
 * VCHR devices.  This method doesn't use an aio helper thread, and
 * thus has very low overhead.
 *
 * Assumes that the caller, aio_aqueue(), has incremented the file
 * structure's reference count, preventing its deallocation for the
 * duration of this call.
 */
static int
aio_qphysio(struct proc *p, struct aiocblist *aiocbe)
{
	struct aiocb *cb;
	struct file *fp;
	struct buf *bp;
	struct vnode *vp;
	struct kaioinfo *ki;
	struct aioliojob *lj;
	int error;

	cb = &aiocbe->uaiocb;
	fp = aiocbe->fd_file;

	if (fp->f_type != DTYPE_VNODE)
		return (-1);

	vp = fp->f_vnode;

	/*
	 * If its not a disk, we don't want to return a positive error.
	 * It causes the aio code to not fall through to try the thread
	 * way when you're talking to a regular file.
	 */
	if (!vn_isdisk(vp, &error)) {
		if (error == ENOTBLK)
			return (-1);
		else
			return (error);
	}

	if (vp->v_bufobj.bo_bsize == 0)
		return (-1);

 	if (cb->aio_nbytes % vp->v_bufobj.bo_bsize)
		return (-1);

	if (cb->aio_nbytes > vp->v_rdev->si_iosize_max)
		return (-1);

	if (cb->aio_nbytes >
	    MAXPHYS - (((vm_offset_t) cb->aio_buf) & PAGE_MASK))
		return (-1);

	ki = p->p_aioinfo;
	if (ki->kaio_buffer_count >= ki->kaio_ballowed_count)
		return (-1);

	/* Create and build a buffer header for a transfer. */
	bp = (struct buf *)getpbuf(NULL);
	BUF_KERNPROC(bp);

	AIO_LOCK(ki);
	ki->kaio_count++;
	ki->kaio_buffer_count++;
	lj = aiocbe->lio;
	if (lj)
		lj->lioj_count++;
	AIO_UNLOCK(ki);

	/*
	 * Get a copy of the kva from the physical buffer.
	 */
	error = 0;

	bp->b_bcount = cb->aio_nbytes;
	bp->b_bufsize = cb->aio_nbytes;
	bp->b_iodone = aio_physwakeup;
	bp->b_saveaddr = bp->b_data;
	bp->b_data = (void *)(uintptr_t)cb->aio_buf;
	bp->b_offset = cb->aio_offset;
	bp->b_iooffset = cb->aio_offset;
	bp->b_blkno = btodb(cb->aio_offset);
	bp->b_iocmd = cb->aio_lio_opcode == LIO_WRITE ? BIO_WRITE : BIO_READ;

	/*
	 * Bring buffer into kernel space.
	 */
	if (vmapbuf(bp) < 0) {
		error = EFAULT;
		goto doerror;
	}

	AIO_LOCK(ki);
	aiocbe->bp = bp;
	bp->b_caller1 = (void *)aiocbe;
	TAILQ_INSERT_TAIL(&ki->kaio_bufqueue, aiocbe, plist);
	TAILQ_INSERT_TAIL(&ki->kaio_all, aiocbe, allist);
	aiocbe->jobstate = JOBST_JOBQBUF;
	cb->_aiocb_private.status = cb->aio_nbytes;
	AIO_UNLOCK(ki);

	atomic_add_int(&num_queue_count, 1);
	atomic_add_int(&num_buf_aio, 1);

	bp->b_error = 0;

	TASK_INIT(&aiocbe->biotask, 0, biohelper, aiocbe);

	/* Perform transfer. */
	dev_strategy(vp->v_rdev, bp);
	return (0);

doerror:
	AIO_LOCK(ki);
	ki->kaio_count--;
	ki->kaio_buffer_count--;
	if (lj)
		lj->lioj_count--;
	aiocbe->bp = NULL;
	AIO_UNLOCK(ki);
	relpbuf(bp, NULL);
	return (error);
}

/*
 * Wake up aio requests that may be serviceable now.
 */
static void
aio_swake_cb(struct socket *so, struct sockbuf *sb)
{
	struct aiocblist *cb, *cbn;
	int opcode;

	if (sb == &so->so_snd)
		opcode = LIO_WRITE;
	else
		opcode = LIO_READ;

	SOCKBUF_LOCK(sb);
	sb->sb_flags &= ~SB_AIO;
	mtx_lock(&aio_job_mtx);
	TAILQ_FOREACH_SAFE(cb, &so->so_aiojobq, list, cbn) {
		if (opcode == cb->uaiocb.aio_lio_opcode) {
			if (cb->jobstate != JOBST_JOBQSOCK)
				panic("invalid queue value");
			/* XXX
			 * We don't have actual sockets backend yet,
			 * so we simply move the requests to the generic
			 * file I/O backend.
			 */
			TAILQ_REMOVE(&so->so_aiojobq, cb, list);
			TAILQ_INSERT_TAIL(&aio_jobs, cb, list);
			aio_kick_nowait(cb->userproc);
		}
	}
	mtx_unlock(&aio_job_mtx);
	SOCKBUF_UNLOCK(sb);
}

static int
convert_old_sigevent(struct osigevent *osig, struct sigevent *nsig)
{

	/*
	 * Only SIGEV_NONE, SIGEV_SIGNAL, and SIGEV_KEVENT are
	 * supported by AIO with the old sigevent structure.
	 */
	nsig->sigev_notify = osig->sigev_notify;
	switch (nsig->sigev_notify) {
	case SIGEV_NONE:
		break;
	case SIGEV_SIGNAL:
		nsig->sigev_signo = osig->__sigev_u.__sigev_signo;
		break;
	case SIGEV_KEVENT:
		nsig->sigev_notify_kqueue =
		    osig->__sigev_u.__sigev_notify_kqueue;
		nsig->sigev_value.sival_ptr = osig->sigev_value.sival_ptr;
		break;
	default:
		return (EINVAL);
	}
	return (0);
}

static int
aiocb_copyin_old_sigevent(struct aiocb *ujob, struct aiocb *kjob)
{
	struct oaiocb *ojob;
	int error;

	bzero(kjob, sizeof(struct aiocb));
	error = copyin(ujob, kjob, sizeof(struct oaiocb));
	if (error)
		return (error);
	ojob = (struct oaiocb *)kjob;
	return (convert_old_sigevent(&ojob->aio_sigevent, &kjob->aio_sigevent));
}

static int
aiocb_copyin(struct aiocb *ujob, struct aiocb *kjob)
{

	return (copyin(ujob, kjob, sizeof(struct aiocb)));
}

static long
aiocb_fetch_status(struct aiocb *ujob)
{

	return (fuword(&ujob->_aiocb_private.status));
}

static long
aiocb_fetch_error(struct aiocb *ujob)
{

	return (fuword(&ujob->_aiocb_private.error));
}

static int
aiocb_store_status(struct aiocb *ujob, long status)
{

	return (suword(&ujob->_aiocb_private.status, status));
}

static int
aiocb_store_error(struct aiocb *ujob, long error)
{

	return (suword(&ujob->_aiocb_private.error, error));
}

static int
aiocb_store_kernelinfo(struct aiocb *ujob, long jobref)
{

	return (suword(&ujob->_aiocb_private.kernelinfo, jobref));
}

static int
aiocb_store_aiocb(struct aiocb **ujobp, struct aiocb *ujob)
{

	return (suword(ujobp, (long)ujob));
}

static struct aiocb_ops aiocb_ops = {
	.copyin = aiocb_copyin,
	.fetch_status = aiocb_fetch_status,
	.fetch_error = aiocb_fetch_error,
	.store_status = aiocb_store_status,
	.store_error = aiocb_store_error,
	.store_kernelinfo = aiocb_store_kernelinfo,
	.store_aiocb = aiocb_store_aiocb,
};

static struct aiocb_ops aiocb_ops_osigevent = {
	.copyin = aiocb_copyin_old_sigevent,
	.fetch_status = aiocb_fetch_status,
	.fetch_error = aiocb_fetch_error,
	.store_status = aiocb_store_status,
	.store_error = aiocb_store_error,
	.store_kernelinfo = aiocb_store_kernelinfo,
	.store_aiocb = aiocb_store_aiocb,
};

/*
 * Queue a new AIO request.  Choosing either the threaded or direct physio VCHR
 * technique is done in this code.
 */
int
aio_aqueue(struct thread *td, struct aiocb *job, struct aioliojob *lj,
	int type, struct aiocb_ops *ops)
{
	struct proc *p = td->td_proc;
	struct file *fp;
	struct socket *so;
	struct aiocblist *aiocbe, *cb;
	struct kaioinfo *ki;
	struct kevent kev;
	struct sockbuf *sb;
	int opcode;
	int error;
	int fd, kqfd;
	int jid;

	if (p->p_aioinfo == NULL)
		aio_init_aioinfo(p);

	ki = p->p_aioinfo;

	ops->store_status(job, -1);
	ops->store_error(job, 0);
	ops->store_kernelinfo(job, -1);

	if (num_queue_count >= max_queue_count ||
	    ki->kaio_count >= ki->kaio_qallowed_count) {
		ops->store_error(job, EAGAIN);
		return (EAGAIN);
	}

	aiocbe = uma_zalloc(aiocb_zone, M_WAITOK | M_ZERO);
	aiocbe->inputcharge = 0;
	aiocbe->outputcharge = 0;
	knlist_init(&aiocbe->klist, AIO_MTX(ki), NULL, NULL, NULL);

	error = ops->copyin(job, &aiocbe->uaiocb);
	if (error) {
		ops->store_error(job, error);
		uma_zfree(aiocb_zone, aiocbe);
		return (error);
	}

	if (aiocbe->uaiocb.aio_sigevent.sigev_notify != SIGEV_KEVENT &&
	    aiocbe->uaiocb.aio_sigevent.sigev_notify != SIGEV_SIGNAL &&
	    aiocbe->uaiocb.aio_sigevent.sigev_notify != SIGEV_THREAD_ID &&
	    aiocbe->uaiocb.aio_sigevent.sigev_notify != SIGEV_NONE) {
		ops->store_error(job, EINVAL);
		uma_zfree(aiocb_zone, aiocbe);
		return (EINVAL);
	}

	if ((aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_SIGNAL ||
	     aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_THREAD_ID) &&
		!_SIG_VALID(aiocbe->uaiocb.aio_sigevent.sigev_signo)) {
		uma_zfree(aiocb_zone, aiocbe);
		return (EINVAL);
	}

	ksiginfo_init(&aiocbe->ksi);

	/* Save userspace address of the job info. */
	aiocbe->uuaiocb = job;

	/* Get the opcode. */
	if (type != LIO_NOP)
		aiocbe->uaiocb.aio_lio_opcode = type;
	opcode = aiocbe->uaiocb.aio_lio_opcode;

	/* Fetch the file object for the specified file descriptor. */
	fd = aiocbe->uaiocb.aio_fildes;
	switch (opcode) {
	case LIO_WRITE:
		error = fget_write(td, fd, &fp);
		break;
	case LIO_READ:
		error = fget_read(td, fd, &fp);
		break;
	default:
		error = fget(td, fd, &fp);
	}
	if (error) {
		uma_zfree(aiocb_zone, aiocbe);
		ops->store_error(job, error);
		return (error);
	}

	if (opcode == LIO_SYNC && fp->f_vnode == NULL) {
		error = EINVAL;
		goto aqueue_fail;
	}

	if (opcode != LIO_SYNC && aiocbe->uaiocb.aio_offset == -1LL) {
		error = EINVAL;
		goto aqueue_fail;
	}

	aiocbe->fd_file = fp;

	mtx_lock(&aio_job_mtx);
	jid = jobrefid++;
	aiocbe->seqno = jobseqno++;
	mtx_unlock(&aio_job_mtx);
	error = ops->store_kernelinfo(job, jid);
	if (error) {
		error = EINVAL;
		goto aqueue_fail;
	}
	aiocbe->uaiocb._aiocb_private.kernelinfo = (void *)(intptr_t)jid;

	if (opcode == LIO_NOP) {
		fdrop(fp, td);
		uma_zfree(aiocb_zone, aiocbe);
		return (0);
	}
	if ((opcode != LIO_READ) && (opcode != LIO_WRITE) &&
	    (opcode != LIO_SYNC)) {
		error = EINVAL;
		goto aqueue_fail;
	}

	if (aiocbe->uaiocb.aio_sigevent.sigev_notify != SIGEV_KEVENT)
		goto no_kqueue;
	kqfd = aiocbe->uaiocb.aio_sigevent.sigev_notify_kqueue;
	kev.ident = (uintptr_t)aiocbe->uuaiocb;
	kev.filter = EVFILT_AIO;
	kev.flags = EV_ADD | EV_ENABLE | EV_FLAG1;
	kev.data = (intptr_t)aiocbe;
	kev.udata = aiocbe->uaiocb.aio_sigevent.sigev_value.sival_ptr;
	error = kqfd_register(kqfd, &kev, td, 1);
aqueue_fail:
	if (error) {
		fdrop(fp, td);
		uma_zfree(aiocb_zone, aiocbe);
		ops->store_error(job, error);
		goto done;
	}
no_kqueue:

	ops->store_error(job, EINPROGRESS);
	aiocbe->uaiocb._aiocb_private.error = EINPROGRESS;
	aiocbe->userproc = p;
	aiocbe->cred = crhold(td->td_ucred);
	aiocbe->jobflags = 0;
	aiocbe->lio = lj;

	if (opcode == LIO_SYNC)
		goto queueit;

	if (fp->f_type == DTYPE_SOCKET) {
		/*
		 * Alternate queueing for socket ops: Reach down into the
		 * descriptor to get the socket data.  Then check to see if the
		 * socket is ready to be read or written (based on the requested
		 * operation).
		 *
		 * If it is not ready for io, then queue the aiocbe on the
		 * socket, and set the flags so we get a call when sbnotify()
		 * happens.
		 *
		 * Note if opcode is neither LIO_WRITE nor LIO_READ we lock
		 * and unlock the snd sockbuf for no reason.
		 */
		so = fp->f_data;
		sb = (opcode == LIO_READ) ? &so->so_rcv : &so->so_snd;
		SOCKBUF_LOCK(sb);
		if (((opcode == LIO_READ) && (!soreadable(so))) || ((opcode ==
		    LIO_WRITE) && (!sowriteable(so)))) {
			sb->sb_flags |= SB_AIO;

			mtx_lock(&aio_job_mtx);
			TAILQ_INSERT_TAIL(&so->so_aiojobq, aiocbe, list);
			mtx_unlock(&aio_job_mtx);

			AIO_LOCK(ki);
			TAILQ_INSERT_TAIL(&ki->kaio_all, aiocbe, allist);
			TAILQ_INSERT_TAIL(&ki->kaio_jobqueue, aiocbe, plist);
			aiocbe->jobstate = JOBST_JOBQSOCK;
			ki->kaio_count++;
			if (lj)
				lj->lioj_count++;
			AIO_UNLOCK(ki);
			SOCKBUF_UNLOCK(sb);
			atomic_add_int(&num_queue_count, 1);
			error = 0;
			goto done;
		}
		SOCKBUF_UNLOCK(sb);
	}

	if ((error = aio_qphysio(p, aiocbe)) == 0)
		goto done;
#if 0
	if (error > 0) {
		aiocbe->uaiocb._aiocb_private.error = error;
		ops->store_error(job, error);
		goto done;
	}
#endif
queueit:
	/* No buffer for daemon I/O. */
	aiocbe->bp = NULL;
	atomic_add_int(&num_queue_count, 1);

	AIO_LOCK(ki);
	ki->kaio_count++;
	if (lj)
		lj->lioj_count++;
	TAILQ_INSERT_TAIL(&ki->kaio_jobqueue, aiocbe, plist);
	TAILQ_INSERT_TAIL(&ki->kaio_all, aiocbe, allist);
	if (opcode == LIO_SYNC) {
		TAILQ_FOREACH(cb, &ki->kaio_jobqueue, plist) {
			if (cb->fd_file == aiocbe->fd_file &&
			    cb->uaiocb.aio_lio_opcode != LIO_SYNC &&
			    cb->seqno < aiocbe->seqno) {
				cb->jobflags |= AIOCBLIST_CHECKSYNC;
				aiocbe->pending++;
			}
		}
		TAILQ_FOREACH(cb, &ki->kaio_bufqueue, plist) {
			if (cb->fd_file == aiocbe->fd_file &&
			    cb->uaiocb.aio_lio_opcode != LIO_SYNC &&
			    cb->seqno < aiocbe->seqno) {
				cb->jobflags |= AIOCBLIST_CHECKSYNC;
				aiocbe->pending++;
			}
		}
		if (aiocbe->pending != 0) {
			TAILQ_INSERT_TAIL(&ki->kaio_syncqueue, aiocbe, list);
			aiocbe->jobstate = JOBST_JOBQSYNC;
			AIO_UNLOCK(ki);
			goto done;
		}
	}
	mtx_lock(&aio_job_mtx);
	TAILQ_INSERT_TAIL(&aio_jobs, aiocbe, list);
	aiocbe->jobstate = JOBST_JOBQGLOBAL;
	aio_kick_nowait(p);
	mtx_unlock(&aio_job_mtx);
	AIO_UNLOCK(ki);
	error = 0;
done:
	return (error);
}

static void
aio_kick_nowait(struct proc *userp)
{
	struct kaioinfo *ki = userp->p_aioinfo;
	struct aiothreadlist *aiop;

	mtx_assert(&aio_job_mtx, MA_OWNED);
	if ((aiop = TAILQ_FIRST(&aio_freeproc)) != NULL) {
		TAILQ_REMOVE(&aio_freeproc, aiop, list);
		aiop->aiothreadflags &= ~AIOP_FREE;
		wakeup(aiop->aiothread);
	} else if (((num_aio_resv_start + num_aio_procs) < max_aio_procs) &&
	    ((ki->kaio_active_count + num_aio_resv_start) <
	    ki->kaio_maxactive_count)) {
		taskqueue_enqueue(taskqueue_aiod_bio, &ki->kaio_task);
	}
}

static int
aio_kick(struct proc *userp)
{
	struct kaioinfo *ki = userp->p_aioinfo;
	struct aiothreadlist *aiop;
	int error, ret = 0;

	mtx_assert(&aio_job_mtx, MA_OWNED);
retryproc:
	if ((aiop = TAILQ_FIRST(&aio_freeproc)) != NULL) {
		TAILQ_REMOVE(&aio_freeproc, aiop, list);
		aiop->aiothreadflags &= ~AIOP_FREE;
		wakeup(aiop->aiothread);
	} else if (((num_aio_resv_start + num_aio_procs) < max_aio_procs) &&
	    ((ki->kaio_active_count + num_aio_resv_start) <
	    ki->kaio_maxactive_count)) {
		num_aio_resv_start++;
		mtx_unlock(&aio_job_mtx);
		error = aio_newproc(&num_aio_resv_start);
		mtx_lock(&aio_job_mtx);
		if (error) {
			num_aio_resv_start--;
			goto retryproc;
		}
	} else {
		ret = -1;
	}
	return (ret);
}

static void
aio_kick_helper(void *context, int pending)
{
	struct proc *userp = context;

	mtx_lock(&aio_job_mtx);
	while (--pending >= 0) {
		if (aio_kick(userp))
			break;
	}
	mtx_unlock(&aio_job_mtx);
}

/*
 * Support the aio_return system call, as a side-effect, kernel resources are
 * released.
 */
static int
kern_aio_return(struct thread *td, struct aiocb *uaiocb, struct aiocb_ops *ops)
{
	struct proc *p = td->td_proc;
	struct aiocblist *cb;
	struct kaioinfo *ki;
	int status, error;

	ki = p->p_aioinfo;
	if (ki == NULL)
		return (EINVAL);
	AIO_LOCK(ki);
	TAILQ_FOREACH(cb, &ki->kaio_done, plist) {
		if (cb->uuaiocb == uaiocb)
			break;
	}
	if (cb != NULL) {
		MPASS(cb->jobstate == JOBST_JOBFINISHED);
		status = cb->uaiocb._aiocb_private.status;
		error = cb->uaiocb._aiocb_private.error;
		td->td_retval[0] = status;
		if (cb->uaiocb.aio_lio_opcode == LIO_WRITE) {
			td->td_ru.ru_oublock += cb->outputcharge;
			cb->outputcharge = 0;
		} else if (cb->uaiocb.aio_lio_opcode == LIO_READ) {
			td->td_ru.ru_inblock += cb->inputcharge;
			cb->inputcharge = 0;
		}
		aio_free_entry(cb);
		AIO_UNLOCK(ki);
		ops->store_error(uaiocb, error);
		ops->store_status(uaiocb, status);
	} else {
		error = EINVAL;
		AIO_UNLOCK(ki);
	}
	return (error);
}

int
aio_return(struct thread *td, struct aio_return_args *uap)
{

	return (kern_aio_return(td, uap->aiocbp, &aiocb_ops));
}

/*
 * Allow a process to wakeup when any of the I/O requests are completed.
 */
static int
kern_aio_suspend(struct thread *td, int njoblist, struct aiocb **ujoblist,
    struct timespec *ts)
{
	struct proc *p = td->td_proc;
	struct timeval atv;
	struct kaioinfo *ki;
	struct aiocblist *cb, *cbfirst;
	int error, i, timo;

	timo = 0;
	if (ts) {
		if (ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
			return (EINVAL);

		TIMESPEC_TO_TIMEVAL(&atv, ts);
		if (itimerfix(&atv))
			return (EINVAL);
		timo = tvtohz(&atv);
	}

	ki = p->p_aioinfo;
	if (ki == NULL)
		return (EAGAIN);

	if (njoblist == 0)
		return (0);

	AIO_LOCK(ki);
	for (;;) {
		cbfirst = NULL;
		error = 0;
		TAILQ_FOREACH(cb, &ki->kaio_all, allist) {
			for (i = 0; i < njoblist; i++) {
				if (cb->uuaiocb == ujoblist[i]) {
					if (cbfirst == NULL)
						cbfirst = cb;
					if (cb->jobstate == JOBST_JOBFINISHED)
						goto RETURN;
				}
			}
		}
		/* All tasks were finished. */
		if (cbfirst == NULL)
			break;

		ki->kaio_flags |= KAIO_WAKEUP;
		error = msleep(&p->p_aioinfo, AIO_MTX(ki), PRIBIO | PCATCH,
		    "aiospn", timo);
		if (error == ERESTART)
			error = EINTR;
		if (error)
			break;
	}
RETURN:
	AIO_UNLOCK(ki);
	return (error);
}

int
aio_suspend(struct thread *td, struct aio_suspend_args *uap)
{
	struct timespec ts, *tsp;
	struct aiocb **ujoblist;
	int error;

	if (uap->nent < 0 || uap->nent > AIO_LISTIO_MAX)
		return (EINVAL);

	if (uap->timeout) {
		/* Get timespec struct. */
		if ((error = copyin(uap->timeout, &ts, sizeof(ts))) != 0)
			return (error);
		tsp = &ts;
	} else
		tsp = NULL;

	ujoblist = uma_zalloc(aiol_zone, M_WAITOK);
	error = copyin(uap->aiocbp, ujoblist, uap->nent * sizeof(ujoblist[0]));
	if (error == 0)
		error = kern_aio_suspend(td, uap->nent, ujoblist, tsp);
	uma_zfree(aiol_zone, ujoblist);
	return (error);
}

/*
 * aio_cancel cancels any non-physio aio operations not currently in
 * progress.
 */
int
aio_cancel(struct thread *td, struct aio_cancel_args *uap)
{
	struct proc *p = td->td_proc;
	struct kaioinfo *ki;
	struct aiocblist *cbe, *cbn;
	struct file *fp;
	struct socket *so;
	int error;
	int remove;
	int cancelled = 0;
	int notcancelled = 0;
	struct vnode *vp;

	/* Lookup file object. */
	error = fget(td, uap->fd, &fp);
	if (error)
		return (error);

	ki = p->p_aioinfo;
	if (ki == NULL)
		goto done;

	if (fp->f_type == DTYPE_VNODE) {
		vp = fp->f_vnode;
		if (vn_isdisk(vp, &error)) {
			fdrop(fp, td);
			td->td_retval[0] = AIO_NOTCANCELED;
			return (0);
		}
	}

	AIO_LOCK(ki);
	TAILQ_FOREACH_SAFE(cbe, &ki->kaio_jobqueue, plist, cbn) {
		if ((uap->fd == cbe->uaiocb.aio_fildes) &&
		    ((uap->aiocbp == NULL) ||
		     (uap->aiocbp == cbe->uuaiocb))) {
			remove = 0;

			mtx_lock(&aio_job_mtx);
			if (cbe->jobstate == JOBST_JOBQGLOBAL) {
				TAILQ_REMOVE(&aio_jobs, cbe, list);
				remove = 1;
			} else if (cbe->jobstate == JOBST_JOBQSOCK) {
				MPASS(fp->f_type == DTYPE_SOCKET);
				so = fp->f_data;
				TAILQ_REMOVE(&so->so_aiojobq, cbe, list);
				remove = 1;
			} else if (cbe->jobstate == JOBST_JOBQSYNC) {
				TAILQ_REMOVE(&ki->kaio_syncqueue, cbe, list);
				remove = 1;
			}
			mtx_unlock(&aio_job_mtx);

			if (remove) {
				TAILQ_REMOVE(&ki->kaio_jobqueue, cbe, plist);
				cbe->uaiocb._aiocb_private.status = -1;
				cbe->uaiocb._aiocb_private.error = ECANCELED;
				aio_bio_done_notify(p, cbe, DONE_QUEUE);
				cancelled++;
			} else {
				notcancelled++;
			}
			if (uap->aiocbp != NULL)
				break;
		}
	}
	AIO_UNLOCK(ki);

done:
	fdrop(fp, td);

	if (uap->aiocbp != NULL) {
		if (cancelled) {
			td->td_retval[0] = AIO_CANCELED;
			return (0);
		}
	}

	if (notcancelled) {
		td->td_retval[0] = AIO_NOTCANCELED;
		return (0);
	}

	if (cancelled) {
		td->td_retval[0] = AIO_CANCELED;
		return (0);
	}

	td->td_retval[0] = AIO_ALLDONE;

	return (0);
}

/*
 * aio_error is implemented in the kernel level for compatibility purposes
 * only.  For a user mode async implementation, it would be best to do it in
 * a userland subroutine.
 */
static int
kern_aio_error(struct thread *td, struct aiocb *aiocbp, struct aiocb_ops *ops)
{
	struct proc *p = td->td_proc;
	struct aiocblist *cb;
	struct kaioinfo *ki;
	int status;

	ki = p->p_aioinfo;
	if (ki == NULL) {
		td->td_retval[0] = EINVAL;
		return (0);
	}

	AIO_LOCK(ki);
	TAILQ_FOREACH(cb, &ki->kaio_all, allist) {
		if (cb->uuaiocb == aiocbp) {
			if (cb->jobstate == JOBST_JOBFINISHED)
				td->td_retval[0] =
					cb->uaiocb._aiocb_private.error;
			else
				td->td_retval[0] = EINPROGRESS;
			AIO_UNLOCK(ki);
			return (0);
		}
	}
	AIO_UNLOCK(ki);

	/*
	 * Hack for failure of aio_aqueue.
	 */
	status = ops->fetch_status(aiocbp);
	if (status == -1) {
		td->td_retval[0] = ops->fetch_error(aiocbp);
		return (0);
	}

	td->td_retval[0] = EINVAL;
	return (0);
}

int
aio_error(struct thread *td, struct aio_error_args *uap)
{

	return (kern_aio_error(td, uap->aiocbp, &aiocb_ops));
}

/* syscall - asynchronous read from a file (REALTIME) */
int
oaio_read(struct thread *td, struct oaio_read_args *uap)
{

	return (aio_aqueue(td, (struct aiocb *)uap->aiocbp, NULL, LIO_READ,
	    &aiocb_ops_osigevent));
}

int
aio_read(struct thread *td, struct aio_read_args *uap)
{

	return (aio_aqueue(td, uap->aiocbp, NULL, LIO_READ, &aiocb_ops));
}

/* syscall - asynchronous write to a file (REALTIME) */
int
oaio_write(struct thread *td, struct oaio_write_args *uap)
{

	return (aio_aqueue(td, (struct aiocb *)uap->aiocbp, NULL, LIO_WRITE,
	    &aiocb_ops_osigevent));
}

int
aio_write(struct thread *td, struct aio_write_args *uap)
{

	return (aio_aqueue(td, uap->aiocbp, NULL, LIO_WRITE, &aiocb_ops));
}

static int
kern_lio_listio(struct thread *td, int mode, struct aiocb * const *uacb_list,
    struct aiocb **acb_list, int nent, struct sigevent *sig,
    struct aiocb_ops *ops)
{
	struct proc *p = td->td_proc;
	struct aiocb *iocb;
	struct kaioinfo *ki;
	struct aioliojob *lj;
	struct kevent kev;
	int error;
	int nerror;
	int i;

	if ((mode != LIO_NOWAIT) && (mode != LIO_WAIT))
		return (EINVAL);

	if (nent < 0 || nent > AIO_LISTIO_MAX)
		return (EINVAL);

	if (p->p_aioinfo == NULL)
		aio_init_aioinfo(p);

	ki = p->p_aioinfo;

	lj = uma_zalloc(aiolio_zone, M_WAITOK);
	lj->lioj_flags = 0;
	lj->lioj_count = 0;
	lj->lioj_finished_count = 0;
	knlist_init(&lj->klist, AIO_MTX(ki), NULL, NULL, NULL);
	ksiginfo_init(&lj->lioj_ksi);

	/*
	 * Setup signal.
	 */
	if (sig && (mode == LIO_NOWAIT)) {
		bcopy(sig, &lj->lioj_signal, sizeof(lj->lioj_signal));
		if (lj->lioj_signal.sigev_notify == SIGEV_KEVENT) {
			/* Assume only new style KEVENT */
			kev.filter = EVFILT_LIO;
			kev.flags = EV_ADD | EV_ENABLE | EV_FLAG1;
			kev.ident = (uintptr_t)uacb_list; /* something unique */
			kev.data = (intptr_t)lj;
			/* pass user defined sigval data */
			kev.udata = lj->lioj_signal.sigev_value.sival_ptr;
			error = kqfd_register(
			    lj->lioj_signal.sigev_notify_kqueue, &kev, td, 1);
			if (error) {
				uma_zfree(aiolio_zone, lj);
				return (error);
			}
		} else if (lj->lioj_signal.sigev_notify == SIGEV_NONE) {
			;
		} else if (lj->lioj_signal.sigev_notify == SIGEV_SIGNAL ||
			   lj->lioj_signal.sigev_notify == SIGEV_THREAD_ID) {
				if (!_SIG_VALID(lj->lioj_signal.sigev_signo)) {
					uma_zfree(aiolio_zone, lj);
					return EINVAL;
				}
				lj->lioj_flags |= LIOJ_SIGNAL;
		} else {
			uma_zfree(aiolio_zone, lj);
			return EINVAL;
		}
	}

	AIO_LOCK(ki);
	TAILQ_INSERT_TAIL(&ki->kaio_liojoblist, lj, lioj_list);
	/*
	 * Add extra aiocb count to avoid the lio to be freed
	 * by other threads doing aio_waitcomplete or aio_return,
	 * and prevent event from being sent until we have queued
	 * all tasks.
	 */
	lj->lioj_count = 1;
	AIO_UNLOCK(ki);

	/*
	 * Get pointers to the list of I/O requests.
	 */
	nerror = 0;
	for (i = 0; i < nent; i++) {
		iocb = acb_list[i];
		if (iocb != NULL) {
			error = aio_aqueue(td, iocb, lj, LIO_NOP, ops);
			if (error != 0)
				nerror++;
		}
	}

	error = 0;
	AIO_LOCK(ki);
	if (mode == LIO_WAIT) {
		while (lj->lioj_count - 1 != lj->lioj_finished_count) {
			ki->kaio_flags |= KAIO_WAKEUP;
			error = msleep(&p->p_aioinfo, AIO_MTX(ki),
			    PRIBIO | PCATCH, "aiospn", 0);
			if (error == ERESTART)
				error = EINTR;
			if (error)
				break;
		}
	} else {
		if (lj->lioj_count - 1 == lj->lioj_finished_count) {
			if (lj->lioj_signal.sigev_notify == SIGEV_KEVENT) {
				lj->lioj_flags |= LIOJ_KEVENT_POSTED;
				KNOTE_LOCKED(&lj->klist, 1);
			}
			if ((lj->lioj_flags & (LIOJ_SIGNAL|LIOJ_SIGNAL_POSTED))
			    == LIOJ_SIGNAL
			    && (lj->lioj_signal.sigev_notify == SIGEV_SIGNAL ||
			    lj->lioj_signal.sigev_notify == SIGEV_THREAD_ID)) {
				aio_sendsig(p, &lj->lioj_signal,
					    &lj->lioj_ksi);
				lj->lioj_flags |= LIOJ_SIGNAL_POSTED;
			}
		}
	}
	lj->lioj_count--;
	if (lj->lioj_count == 0) {
		TAILQ_REMOVE(&ki->kaio_liojoblist, lj, lioj_list);
		knlist_delete(&lj->klist, curthread, 1);
		PROC_LOCK(p);
		sigqueue_take(&lj->lioj_ksi);
		PROC_UNLOCK(p);
		AIO_UNLOCK(ki);
		uma_zfree(aiolio_zone, lj);
	} else
		AIO_UNLOCK(ki);

	if (nerror)
		return (EIO);
	return (error);
}

/* syscall - list directed I/O (REALTIME) */
int
olio_listio(struct thread *td, struct olio_listio_args *uap)
{
	struct aiocb **acb_list;
	struct sigevent *sigp, sig;
	struct osigevent osig;
	int error, nent;

	if ((uap->mode != LIO_NOWAIT) && (uap->mode != LIO_WAIT))
		return (EINVAL);

	nent = uap->nent;
	if (nent < 0 || nent > AIO_LISTIO_MAX)
		return (EINVAL);

	if (uap->sig && (uap->mode == LIO_NOWAIT)) {
		error = copyin(uap->sig, &osig, sizeof(osig));
		if (error)
			return (error);
		error = convert_old_sigevent(&osig, &sig);
		if (error)
			return (error);
		sigp = &sig;
	} else
		sigp = NULL;

	acb_list = malloc(sizeof(struct aiocb *) * nent, M_LIO, M_WAITOK);
	error = copyin(uap->acb_list, acb_list, nent * sizeof(acb_list[0]));
	if (error == 0)
		error = kern_lio_listio(td, uap->mode,
		    (struct aiocb * const *)uap->acb_list, acb_list, nent, sigp,
		    &aiocb_ops_osigevent);
	free(acb_list, M_LIO);
	return (error);
}

/* syscall - list directed I/O (REALTIME) */
int
lio_listio(struct thread *td, struct lio_listio_args *uap)
{
	struct aiocb **acb_list;
	struct sigevent *sigp, sig;
	int error, nent;

	if ((uap->mode != LIO_NOWAIT) && (uap->mode != LIO_WAIT))
		return (EINVAL);

	nent = uap->nent;
	if (nent < 0 || nent > AIO_LISTIO_MAX)
		return (EINVAL);

	if (uap->sig && (uap->mode == LIO_NOWAIT)) {
		error = copyin(uap->sig, &sig, sizeof(sig));
		if (error)
			return (error);
		sigp = &sig;
	} else
		sigp = NULL;

	acb_list = malloc(sizeof(struct aiocb *) * nent, M_LIO, M_WAITOK);
	error = copyin(uap->acb_list, acb_list, nent * sizeof(acb_list[0]));
	if (error == 0)
		error = kern_lio_listio(td, uap->mode, uap->acb_list, acb_list,
		    nent, sigp, &aiocb_ops);
	free(acb_list, M_LIO);
	return (error);
}

/*
 * Called from interrupt thread for physio, we should return as fast
 * as possible, so we schedule a biohelper task.
 */
static void
aio_physwakeup(struct buf *bp)
{
	struct aiocblist *aiocbe;

	aiocbe = (struct aiocblist *)bp->b_caller1;
	taskqueue_enqueue(taskqueue_aiod_bio, &aiocbe->biotask);
}

/*
 * Task routine to perform heavy tasks, process wakeup, and signals.
 */
static void
biohelper(void *context, int pending)
{
	struct aiocblist *aiocbe = context;
	struct buf *bp;
	struct proc *userp;
	struct kaioinfo *ki;
	int nblks;

	bp = aiocbe->bp;
	userp = aiocbe->userproc;
	ki = userp->p_aioinfo;
	AIO_LOCK(ki);
	aiocbe->uaiocb._aiocb_private.status -= bp->b_resid;
	aiocbe->uaiocb._aiocb_private.error = 0;
	if (bp->b_ioflags & BIO_ERROR)
		aiocbe->uaiocb._aiocb_private.error = bp->b_error;
	nblks = btodb(aiocbe->uaiocb.aio_nbytes);
	if (aiocbe->uaiocb.aio_lio_opcode == LIO_WRITE)
		aiocbe->outputcharge += nblks;
	else
		aiocbe->inputcharge += nblks;
	aiocbe->bp = NULL;
	TAILQ_REMOVE(&userp->p_aioinfo->kaio_bufqueue, aiocbe, plist);
	ki->kaio_buffer_count--;
	aio_bio_done_notify(userp, aiocbe, DONE_BUF);
	AIO_UNLOCK(ki);

	/* Release mapping into kernel space. */
	vunmapbuf(bp);
	relpbuf(bp, NULL);
	atomic_subtract_int(&num_buf_aio, 1);
}

/* syscall - wait for the next completion of an aio request */
static int
kern_aio_waitcomplete(struct thread *td, struct aiocb **aiocbp,
    struct timespec *ts, struct aiocb_ops *ops)
{
	struct proc *p = td->td_proc;
	struct timeval atv;
	struct kaioinfo *ki;
	struct aiocblist *cb;
	struct aiocb *uuaiocb;
	int error, status, timo;

	ops->store_aiocb(aiocbp, NULL);

	timo = 0;
	if (ts) {
		if ((ts->tv_nsec < 0) || (ts->tv_nsec >= 1000000000))
			return (EINVAL);

		TIMESPEC_TO_TIMEVAL(&atv, ts);
		if (itimerfix(&atv))
			return (EINVAL);
		timo = tvtohz(&atv);
	}

	if (p->p_aioinfo == NULL)
		aio_init_aioinfo(p);
	ki = p->p_aioinfo;

	error = 0;
	cb = NULL;
	AIO_LOCK(ki);
	while ((cb = TAILQ_FIRST(&ki->kaio_done)) == NULL) {
		ki->kaio_flags |= KAIO_WAKEUP;
		error = msleep(&p->p_aioinfo, AIO_MTX(ki), PRIBIO | PCATCH,
		    "aiowc", timo);
		if (timo && error == ERESTART)
			error = EINTR;
		if (error)
			break;
	}

	if (cb != NULL) {
		MPASS(cb->jobstate == JOBST_JOBFINISHED);
		uuaiocb = cb->uuaiocb;
		status = cb->uaiocb._aiocb_private.status;
		error = cb->uaiocb._aiocb_private.error;
		td->td_retval[0] = status;
		if (cb->uaiocb.aio_lio_opcode == LIO_WRITE) {
			td->td_ru.ru_oublock += cb->outputcharge;
			cb->outputcharge = 0;
		} else if (cb->uaiocb.aio_lio_opcode == LIO_READ) {
			td->td_ru.ru_inblock += cb->inputcharge;
			cb->inputcharge = 0;
		}
		aio_free_entry(cb);
		AIO_UNLOCK(ki);
		ops->store_aiocb(aiocbp, uuaiocb);
		ops->store_error(uuaiocb, error);
		ops->store_status(uuaiocb, status);
	} else
		AIO_UNLOCK(ki);

	return (error);
}

int
aio_waitcomplete(struct thread *td, struct aio_waitcomplete_args *uap)
{
	struct timespec ts, *tsp;
	int error;

	if (uap->timeout) {
		/* Get timespec struct. */
		error = copyin(uap->timeout, &ts, sizeof(ts));
		if (error)
			return (error);
		tsp = &ts;
	} else
		tsp = NULL;

	return (kern_aio_waitcomplete(td, uap->aiocbp, tsp, &aiocb_ops));
}

static int
kern_aio_fsync(struct thread *td, int op, struct aiocb *aiocbp,
    struct aiocb_ops *ops)
{
	struct proc *p = td->td_proc;
	struct kaioinfo *ki;

	if (op != O_SYNC) /* XXX lack of O_DSYNC */
		return (EINVAL);
	ki = p->p_aioinfo;
	if (ki == NULL)
		aio_init_aioinfo(p);
	return (aio_aqueue(td, aiocbp, NULL, LIO_SYNC, ops));
}

int
aio_fsync(struct thread *td, struct aio_fsync_args *uap)
{

	return (kern_aio_fsync(td, uap->op, uap->aiocbp, &aiocb_ops));
}

/* kqueue attach function */
static int
filt_aioattach(struct knote *kn)
{
	struct aiocblist *aiocbe = (struct aiocblist *)kn->kn_sdata;

	/*
	 * The aiocbe pointer must be validated before using it, so
	 * registration is restricted to the kernel; the user cannot
	 * set EV_FLAG1.
	 */
	if ((kn->kn_flags & EV_FLAG1) == 0)
		return (EPERM);
	kn->kn_ptr.p_aio = aiocbe;
	kn->kn_flags &= ~EV_FLAG1;

	knlist_add(&aiocbe->klist, kn, 0);

	return (0);
}

/* kqueue detach function */
static void
filt_aiodetach(struct knote *kn)
{
	struct aiocblist *aiocbe = kn->kn_ptr.p_aio;

	if (!knlist_empty(&aiocbe->klist))
		knlist_remove(&aiocbe->klist, kn, 0);
}

/* kqueue filter function */
/*ARGSUSED*/
static int
filt_aio(struct knote *kn, long hint)
{
	struct aiocblist *aiocbe = kn->kn_ptr.p_aio;

	kn->kn_data = aiocbe->uaiocb._aiocb_private.error;
	if (aiocbe->jobstate != JOBST_JOBFINISHED)
		return (0);
	kn->kn_flags |= EV_EOF;
	return (1);
}

/* kqueue attach function */
static int
filt_lioattach(struct knote *kn)
{
	struct aioliojob * lj = (struct aioliojob *)kn->kn_sdata;

	/*
	 * The aioliojob pointer must be validated before using it, so
	 * registration is restricted to the kernel; the user cannot
	 * set EV_FLAG1.
	 */
	if ((kn->kn_flags & EV_FLAG1) == 0)
		return (EPERM);
	kn->kn_ptr.p_lio = lj;
	kn->kn_flags &= ~EV_FLAG1;

	knlist_add(&lj->klist, kn, 0);

	return (0);
}

/* kqueue detach function */
static void
filt_liodetach(struct knote *kn)
{
	struct aioliojob * lj = kn->kn_ptr.p_lio;

	if (!knlist_empty(&lj->klist))
		knlist_remove(&lj->klist, kn, 0);
}

/* kqueue filter function */
/*ARGSUSED*/
static int
filt_lio(struct knote *kn, long hint)
{
	struct aioliojob * lj = kn->kn_ptr.p_lio;

	return (lj->lioj_flags & LIOJ_KEVENT_POSTED);
}

#ifdef COMPAT_IA32
#include <sys/mount.h>
#include <sys/socket.h>
#include <compat/freebsd32/freebsd32.h>
#include <compat/freebsd32/freebsd32_proto.h>
#include <compat/freebsd32/freebsd32_signal.h>
#include <compat/freebsd32/freebsd32_syscall.h>
#include <compat/freebsd32/freebsd32_util.h>

struct __aiocb_private32 {
	int32_t	status;
	int32_t	error;
	uint32_t kernelinfo;
};

typedef struct oaiocb32 {
	int	aio_fildes;		/* File descriptor */
	uint64_t aio_offset __packed;	/* File offset for I/O */
	uint32_t aio_buf;		/* I/O buffer in process space */
	uint32_t aio_nbytes;		/* Number of bytes for I/O */
	struct	osigevent32 aio_sigevent; /* Signal to deliver */
	int	aio_lio_opcode;		/* LIO opcode */
	int	aio_reqprio;		/* Request priority -- ignored */
	struct	__aiocb_private32 _aiocb_private;
} oaiocb32_t;

typedef struct aiocb32 {
	int32_t	aio_fildes;		/* File descriptor */
	uint64_t aio_offset __packed;	/* File offset for I/O */
	uint32_t aio_buf;		/* I/O buffer in process space */
	uint32_t aio_nbytes;		/* Number of bytes for I/O */
	int	__spare__[2];
	uint32_t __spare2__;
	int	aio_lio_opcode;		/* LIO opcode */
	int	aio_reqprio;		/* Request priority -- ignored */
	struct __aiocb_private32 _aiocb_private;
	struct sigevent32 aio_sigevent;	/* Signal to deliver */
} aiocb32_t;

static int
convert_old_sigevent32(struct osigevent32 *osig, struct sigevent *nsig)
{

	/*
	 * Only SIGEV_NONE, SIGEV_SIGNAL, and SIGEV_KEVENT are
	 * supported by AIO with the old sigevent structure.
	 */
	CP(*osig, *nsig, sigev_notify);
	switch (nsig->sigev_notify) {
	case SIGEV_NONE:
		break;
	case SIGEV_SIGNAL:
		nsig->sigev_signo = osig->__sigev_u.__sigev_signo;
		break;
	case SIGEV_KEVENT:
		nsig->sigev_notify_kqueue =
		    osig->__sigev_u.__sigev_notify_kqueue;
		PTRIN_CP(*osig, *nsig, sigev_value.sival_ptr);
		break;
	default:
		return (EINVAL);
	}
	return (0);
}

static int
aiocb32_copyin_old_sigevent(struct aiocb *ujob, struct aiocb *kjob)
{
	struct oaiocb32 job32;
	int error;

	bzero(kjob, sizeof(struct aiocb));
	error = copyin(ujob, &job32, sizeof(job32));
	if (error)
		return (error);

	CP(job32, *kjob, aio_fildes);
	CP(job32, *kjob, aio_offset);
	PTRIN_CP(job32, *kjob, aio_buf);
	CP(job32, *kjob, aio_nbytes);
	CP(job32, *kjob, aio_lio_opcode);
	CP(job32, *kjob, aio_reqprio);
	CP(job32, *kjob, _aiocb_private.status);
	CP(job32, *kjob, _aiocb_private.error);
	PTRIN_CP(job32, *kjob, _aiocb_private.kernelinfo);
	return (convert_old_sigevent32(&job32.aio_sigevent,
	    &kjob->aio_sigevent));
}

static int
convert_sigevent32(struct sigevent32 *sig32, struct sigevent *sig)
{

	CP(*sig32, *sig, sigev_notify);
	switch (sig->sigev_notify) {
	case SIGEV_NONE:
		break;
	case SIGEV_THREAD_ID:
		CP(*sig32, *sig, sigev_notify_thread_id);
		/* FALLTHROUGH */
	case SIGEV_SIGNAL:
		CP(*sig32, *sig, sigev_signo);
		break;
	case SIGEV_KEVENT:
		CP(*sig32, *sig, sigev_notify_kqueue);
		PTRIN_CP(*sig32, *sig, sigev_value.sival_ptr);
		break;
	default:
		return (EINVAL);
	}
	return (0);
}

static int
aiocb32_copyin(struct aiocb *ujob, struct aiocb *kjob)
{
	struct aiocb32 job32;
	int error;

	error = copyin(ujob, &job32, sizeof(job32));
	if (error)
		return (error);
	CP(job32, *kjob, aio_fildes);
	CP(job32, *kjob, aio_offset);
	PTRIN_CP(job32, *kjob, aio_buf);
	CP(job32, *kjob, aio_nbytes);
	CP(job32, *kjob, aio_lio_opcode);
	CP(job32, *kjob, aio_reqprio);
	CP(job32, *kjob, _aiocb_private.status);
	CP(job32, *kjob, _aiocb_private.error);
	PTRIN_CP(job32, *kjob, _aiocb_private.kernelinfo);
	return (convert_sigevent32(&job32.aio_sigevent, &kjob->aio_sigevent));
}

static long
aiocb32_fetch_status(struct aiocb *ujob)
{
	struct aiocb32 *ujob32;

	ujob32 = (struct aiocb32 *)ujob;
	return (fuword32(&ujob32->_aiocb_private.status));
}

static long
aiocb32_fetch_error(struct aiocb *ujob)
{
	struct aiocb32 *ujob32;

	ujob32 = (struct aiocb32 *)ujob;
	return (fuword32(&ujob32->_aiocb_private.error));
}

static int
aiocb32_store_status(struct aiocb *ujob, long status)
{
	struct aiocb32 *ujob32;

	ujob32 = (struct aiocb32 *)ujob;
	return (suword32(&ujob32->_aiocb_private.status, status));
}

static int
aiocb32_store_error(struct aiocb *ujob, long error)
{
	struct aiocb32 *ujob32;

	ujob32 = (struct aiocb32 *)ujob;
	return (suword32(&ujob32->_aiocb_private.error, error));
}

static int
aiocb32_store_kernelinfo(struct aiocb *ujob, long jobref)
{
	struct aiocb32 *ujob32;

	ujob32 = (struct aiocb32 *)ujob;
	return (suword32(&ujob32->_aiocb_private.kernelinfo, jobref));
}

static int
aiocb32_store_aiocb(struct aiocb **ujobp, struct aiocb *ujob)
{

	return (suword32(ujobp, (long)ujob));
}

static struct aiocb_ops aiocb32_ops = {
	.copyin = aiocb32_copyin,
	.fetch_status = aiocb32_fetch_status,
	.fetch_error = aiocb32_fetch_error,
	.store_status = aiocb32_store_status,
	.store_error = aiocb32_store_error,
	.store_kernelinfo = aiocb32_store_kernelinfo,
	.store_aiocb = aiocb32_store_aiocb,
};

static struct aiocb_ops aiocb32_ops_osigevent = {
	.copyin = aiocb32_copyin_old_sigevent,
	.fetch_status = aiocb32_fetch_status,
	.fetch_error = aiocb32_fetch_error,
	.store_status = aiocb32_store_status,
	.store_error = aiocb32_store_error,
	.store_kernelinfo = aiocb32_store_kernelinfo,
	.store_aiocb = aiocb32_store_aiocb,
};

int
freebsd32_aio_return(struct thread *td, struct freebsd32_aio_return_args *uap)
{

	return (kern_aio_return(td, (struct aiocb *)uap->aiocbp, &aiocb32_ops));
}

int
freebsd32_aio_suspend(struct thread *td, struct freebsd32_aio_suspend_args *uap)
{
	struct timespec32 ts32;
	struct timespec ts, *tsp;
	struct aiocb **ujoblist;
	uint32_t *ujoblist32;
	int error, i;

	if (uap->nent < 0 || uap->nent > AIO_LISTIO_MAX)
		return (EINVAL);

	if (uap->timeout) {
		/* Get timespec struct. */
		if ((error = copyin(uap->timeout, &ts32, sizeof(ts32))) != 0)
			return (error);
		CP(ts32, ts, tv_sec);
		CP(ts32, ts, tv_nsec);
		tsp = &ts;
	} else
		tsp = NULL;

	ujoblist = uma_zalloc(aiol_zone, M_WAITOK);
	ujoblist32 = (uint32_t *)ujoblist;
	error = copyin(uap->aiocbp, ujoblist32, uap->nent *
	    sizeof(ujoblist32[0]));
	if (error == 0) {
		for (i = uap->nent; i > 0; i--)
			ujoblist[i] = PTRIN(ujoblist32[i]);

		error = kern_aio_suspend(td, uap->nent, ujoblist, tsp);
	}
	uma_zfree(aiol_zone, ujoblist);
	return (error);
}

int
freebsd32_aio_cancel(struct thread *td, struct freebsd32_aio_cancel_args *uap)
{

	return (aio_cancel(td, (struct aio_cancel_args *)uap));
}

int
freebsd32_aio_error(struct thread *td, struct freebsd32_aio_error_args *uap)
{

	return (kern_aio_error(td, (struct aiocb *)uap->aiocbp, &aiocb32_ops));
}

int
freebsd32_oaio_read(struct thread *td, struct freebsd32_oaio_read_args *uap)
{

	return (aio_aqueue(td, (struct aiocb *)uap->aiocbp, NULL, LIO_READ,
	    &aiocb32_ops_osigevent));
}

int
freebsd32_aio_read(struct thread *td, struct freebsd32_aio_read_args *uap)
{

	return (aio_aqueue(td, (struct aiocb *)uap->aiocbp, NULL, LIO_READ,
	    &aiocb32_ops));
}

int
freebsd32_oaio_write(struct thread *td, struct freebsd32_oaio_write_args *uap)
{

	return (aio_aqueue(td, (struct aiocb *)uap->aiocbp, NULL, LIO_WRITE,
	    &aiocb32_ops_osigevent));
}

int
freebsd32_aio_write(struct thread *td, struct freebsd32_aio_write_args *uap)
{

	return (aio_aqueue(td, (struct aiocb *)uap->aiocbp, NULL, LIO_WRITE,
	    &aiocb32_ops));
}

int
freebsd32_aio_waitcomplete(struct thread *td,
    struct freebsd32_aio_waitcomplete_args *uap)
{
	struct timespec32 ts32;
	struct timespec ts, *tsp;
	int error;

	if (uap->timeout) {
		/* Get timespec struct. */
		error = copyin(uap->timeout, &ts32, sizeof(ts32));
		if (error)
			return (error);
		CP(ts32, ts, tv_sec);
		CP(ts32, ts, tv_nsec);
		tsp = &ts;
	} else
		tsp = NULL;

	return (kern_aio_waitcomplete(td, (struct aiocb **)uap->aiocbp, tsp,
	    &aiocb32_ops));
}

int
freebsd32_aio_fsync(struct thread *td, struct freebsd32_aio_fsync_args *uap)
{

	return (kern_aio_fsync(td, uap->op, (struct aiocb *)uap->aiocbp,
	    &aiocb32_ops));
}

int
freebsd32_olio_listio(struct thread *td, struct freebsd32_olio_listio_args *uap)
{
	struct aiocb **acb_list;
	struct sigevent *sigp, sig;
	struct osigevent32 osig;
	uint32_t *acb_list32;
	int error, i, nent;

	if ((uap->mode != LIO_NOWAIT) && (uap->mode != LIO_WAIT))
		return (EINVAL);

	nent = uap->nent;
	if (nent < 0 || nent > AIO_LISTIO_MAX)
		return (EINVAL);

	if (uap->sig && (uap->mode == LIO_NOWAIT)) {
		error = copyin(uap->sig, &osig, sizeof(osig));
		if (error)
			return (error);
		error = convert_old_sigevent32(&osig, &sig);
		if (error)
			return (error);
		sigp = &sig;
	} else
		sigp = NULL;

	acb_list32 = malloc(sizeof(uint32_t) * nent, M_LIO, M_WAITOK);
	error = copyin(uap->acb_list, acb_list32, nent * sizeof(uint32_t));
	if (error) {
		free(acb_list32, M_LIO);
		return (error);
	}
	acb_list = malloc(sizeof(struct aiocb *) * nent, M_LIO, M_WAITOK);
	for (i = 0; i < nent; i++)
		acb_list[i] = PTRIN(acb_list32[i]);
	free(acb_list32, M_LIO);

	error = kern_lio_listio(td, uap->mode,
	    (struct aiocb * const *)uap->acb_list, acb_list, nent, sigp,
	    &aiocb32_ops_osigevent);
	free(acb_list, M_LIO);
	return (error);
}

int
freebsd32_lio_listio(struct thread *td, struct freebsd32_lio_listio_args *uap)
{
	struct aiocb **acb_list;
	struct sigevent *sigp, sig;
	struct sigevent32 sig32;
	uint32_t *acb_list32;
	int error, i, nent;

	if ((uap->mode != LIO_NOWAIT) && (uap->mode != LIO_WAIT))
		return (EINVAL);

	nent = uap->nent;
	if (nent < 0 || nent > AIO_LISTIO_MAX)
		return (EINVAL);

	if (uap->sig && (uap->mode == LIO_NOWAIT)) {
		error = copyin(uap->sig, &sig32, sizeof(sig32));
		if (error)
			return (error);
		error = convert_sigevent32(&sig32, &sig);
		if (error)
			return (error);
		sigp = &sig;
	} else
		sigp = NULL;

	acb_list32 = malloc(sizeof(uint32_t) * nent, M_LIO, M_WAITOK);
	error = copyin(uap->acb_list, acb_list32, nent * sizeof(uint32_t));
	if (error) {
		free(acb_list32, M_LIO);
		return (error);
	}
	acb_list = malloc(sizeof(struct aiocb *) * nent, M_LIO, M_WAITOK);
	for (i = 0; i < nent; i++)
		acb_list[i] = PTRIN(acb_list32[i]);
	free(acb_list32, M_LIO);

	error = kern_lio_listio(td, uap->mode,
	    (struct aiocb * const *)uap->acb_list, acb_list, nent, sigp,
	    &aiocb32_ops);
	free(acb_list, M_LIO);
	return (error);
}

SYSCALL32_MODULE_HELPER(freebsd32_aio_return);
SYSCALL32_MODULE_HELPER(freebsd32_aio_suspend);
SYSCALL32_MODULE_HELPER(freebsd32_aio_cancel);
SYSCALL32_MODULE_HELPER(freebsd32_aio_error);
SYSCALL32_MODULE_HELPER(freebsd32_aio_fsync);
SYSCALL32_MODULE_HELPER(freebsd32_aio_read);
SYSCALL32_MODULE_HELPER(freebsd32_aio_write);
SYSCALL32_MODULE_HELPER(freebsd32_aio_waitcomplete);
SYSCALL32_MODULE_HELPER(freebsd32_lio_listio);
SYSCALL32_MODULE_HELPER(freebsd32_oaio_read);
SYSCALL32_MODULE_HELPER(freebsd32_oaio_write);
SYSCALL32_MODULE_HELPER(freebsd32_olio_listio);
#endif
OpenPOWER on IntegriCloud