Loading...
   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
/*
 * Copyright (c) 2000-2024 Apple Inc. All rights reserved.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. The rights granted to you under the License
 * may not be used to create, or enable the creation or redistribution of,
 * unlawful or unlicensed copies of an Apple operating system, or to
 * circumvent, violate, or enable the circumvention or violation of, any
 * terms of an Apple operating system software license agreement.
 *
 * Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
 */
/* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
/*
 * Copyright (c) 1982, 1986, 1989, 1993
 *	The Regents of the University of California.  All rights reserved.
 * (c) UNIX System Laboratories, Inc.
 * All or some portions of this file are derived from material licensed
 * to the University of California by American Telephone and Telegraph
 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
 * the permission of UNIX System Laboratories, Inc.
 *
 * 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. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)sys_generic.c	8.9 (Berkeley) 2/14/95
 */
/*
 * NOTICE: This file was modified by SPARTA, Inc. in 2006 to introduce
 * support for mandatory and extensible security protections.  This notice
 * is included in support of clause 2.2 (b) of the Apple Public License,
 * Version 2.0.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/filedesc.h>
#include <sys/ioctl.h>
#include <sys/file_internal.h>
#include <sys/proc_internal.h>
#include <sys/socketvar.h>
#include <sys/uio_internal.h>
#include <sys/kernel.h>
#include <sys/guarded.h>
#include <sys/stat.h>
#include <sys/malloc.h>
#include <sys/sysproto.h>

#include <sys/mount_internal.h>
#include <sys/protosw.h>
#include <sys/ev.h>
#include <sys/user.h>
#include <sys/kdebug.h>
#include <sys/poll.h>
#include <sys/event.h>
#include <sys/eventvar.h>
#include <sys/proc.h>
#include <sys/kauth.h>

#include <machine/smp.h>
#include <mach/mach_types.h>
#include <kern/kern_types.h>
#include <kern/assert.h>
#include <kern/kalloc.h>
#include <kern/thread.h>
#include <kern/clock.h>
#include <kern/ledger.h>
#include <kern/monotonic.h>
#include <kern/task.h>
#include <kern/telemetry.h>
#include <kern/waitq.h>
#include <kern/mpsc_queue.h>
#include <kern/debug.h>

#include <sys/mbuf.h>
#include <sys/domain.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/errno.h>
#include <sys/syscall.h>
#include <sys/pipe.h>

#include <security/audit/audit.h>

#include <net/if.h>
#include <net/route.h>

#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/in_pcb.h>
#include <netinet/ip_var.h>
#include <netinet/ip6.h>
#include <netinet/tcp.h>
#include <netinet/tcp_fsm.h>
#include <netinet/tcp_seq.h>
#include <netinet/tcp_timer.h>
#include <netinet/tcp_var.h>
#include <netinet/tcpip.h>
/* for wait queue based select */
#include <kern/waitq.h>
#include <sys/vnode_internal.h>
/* for remote time api*/
#include <kern/remote_time.h>
#include <os/log.h>
#include <sys/log_data.h>

#include <machine/monotonic.h>

#if CONFIG_MACF
#include <security/mac_framework.h>
#endif

#ifdef CONFIG_KDP_INTERACTIVE_DEBUGGING
#include <mach_debug/mach_debug_types.h>
#endif

/* for entitlement check */
#include <IOKit/IOBSD.h>

/* XXX should be in a header file somewhere */
extern kern_return_t IOBSDGetPlatformUUID(__darwin_uuid_t uuid, mach_timespec_t timeoutp);

int do_uiowrite(struct proc *p, struct fileproc *fp, uio_t uio, int flags, user_ssize_t *retval);
__private_extern__ int  dofileread(vfs_context_t ctx, struct fileproc *fp,
    user_addr_t bufp, user_size_t nbyte,
    off_t offset, int flags, user_ssize_t *retval);
__private_extern__ int  dofilewrite(vfs_context_t ctx, struct fileproc *fp,
    user_addr_t bufp, user_size_t nbyte,
    off_t offset, int flags, user_ssize_t *retval);
static int preparefileread(struct proc *p, struct fileproc **fp_ret, int fd, int check_for_vnode);

/* needed by guarded_writev, etc. */
int write_internal(struct proc *p, int fd, user_addr_t buf, user_size_t nbyte,
    off_t offset, int flags, guardid_t *puguard, user_ssize_t *retval);
int writev_uio(struct proc *p, int fd, user_addr_t user_iovp, int iovcnt, off_t offset, int flags,
    guardid_t *puguard, user_ssize_t *retval);

#define f_flag fp_glob->fg_flag
#define f_type fp_glob->fg_ops->fo_type
#define f_cred fp_glob->fg_cred
#define f_ops fp_glob->fg_ops

/*
 * Validate if the file can be used for random access (pread, pwrite, etc).
 *
 * Conditions:
 *		proc_fdlock is held
 *
 * Returns:    0                       Success
 *             ESPIPE
 *             ENXIO
 */
static int
valid_for_random_access(struct fileproc *fp, bool check_for_pwrite)
{
	if (__improbable(fp->f_type != DTYPE_VNODE)) {
		return ESPIPE;
	}

	vnode_t vp = (struct vnode *)fp_get_data(fp);
	if (__improbable(vnode_isfifo(vp))) {
		return ESPIPE;
	}

	if (__improbable(vp->v_flag & VISTTY)) {
		return ENXIO;
	}

	if (check_for_pwrite && vnode_isappendonly(vp)) {
		return EPERM;
	}

	return 0;
}

/*
 * Returns:	0			Success
 *		EBADF
 *		ESPIPE
 *		ENXIO
 *	fp_lookup:EBADF
 *  valid_for_random_access:ESPIPE
 *  valid_for_random_access:ENXIO
 */
static int
preparefileread(struct proc *p, struct fileproc **fp_ret, int fd, int check_for_pread)
{
	int     error;
	struct fileproc *fp;

	AUDIT_ARG(fd, fd);

	proc_fdlock_spin(p);

	error = fp_lookup(p, fd, &fp, 1);

	if (error) {
		proc_fdunlock(p);
		return error;
	}
	if ((fp->f_flag & FREAD) == 0) {
		error = EBADF;
		goto out;
	}
	if (check_for_pread) {
		if ((error = valid_for_random_access(fp, false))) {
			goto out;
		}
	}

	*fp_ret = fp;

	proc_fdunlock(p);
	return 0;

out:
	fp_drop(p, fd, fp, 1);
	proc_fdunlock(p);
	return error;
}

static int
fp_readv(vfs_context_t ctx, struct fileproc *fp, uio_t uio, int flags,
    user_ssize_t *retval)
{
	int error;
	user_ssize_t count;

	if ((error = uio_calculateresid_user(uio))) {
		*retval = 0;
		return error;
	}

	count = uio_resid(uio);
	error = fo_read(fp, uio, flags, ctx);

	switch (error) {
	case ERESTART:
	case EINTR:
	case EWOULDBLOCK:
		if (uio_resid(uio) != count) {
			error = 0;
		}
		break;

	default:
		break;
	}

	*retval = count - uio_resid(uio);
	return error;
}

/*
 * Returns:	0			Success
 *		EINVAL
 *	fo_read:???
 */
__private_extern__ int
dofileread(vfs_context_t ctx, struct fileproc *fp,
    user_addr_t bufp, user_size_t nbyte, off_t offset, int flags,
    user_ssize_t *retval)
{
	UIO_STACKBUF(uio_buf, 1);
	uio_t uio;
	int spacetype;

	if (nbyte > INT_MAX) {
		*retval = 0;
		return EINVAL;
	}

	spacetype = vfs_context_is64bit(ctx) ? UIO_USERSPACE64 : UIO_USERSPACE32;
	uio = uio_createwithbuffer(1, offset, spacetype, UIO_READ, &uio_buf[0],
	    sizeof(uio_buf));

	if (uio_addiov(uio, bufp, nbyte) != 0) {
		*retval = 0;
		return EINVAL;
	}

	return fp_readv(ctx, fp, uio, flags, retval);
}

static int
readv_internal(struct proc *p, int fd, uio_t uio, int flags,
    user_ssize_t *retval)
{
	struct fileproc *fp = NULL;
	struct vfs_context context;
	int error;

	if ((error = preparefileread(p, &fp, fd, flags & FOF_OFFSET))) {
		*retval = 0;
		return error;
	}

	context = *(vfs_context_current());
	context.vc_ucred = fp->fp_glob->fg_cred;

	error = fp_readv(&context, fp, uio, flags, retval);

	fp_drop(p, fd, fp, 0);
	return error;
}

static int
read_internal(struct proc *p, int fd, user_addr_t buf, user_size_t nbyte,
    off_t offset, int flags, user_ssize_t *retval)
{
	UIO_STACKBUF(uio_buf, 1);
	uio_t uio;
	int spacetype = IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32;

	if (nbyte > INT_MAX) {
		*retval = 0;
		return EINVAL;
	}

	uio = uio_createwithbuffer(1, offset, spacetype, UIO_READ,
	    &uio_buf[0], sizeof(uio_buf));

	if (uio_addiov(uio, buf, nbyte) != 0) {
		*retval = 0;
		return EINVAL;
	}

	return readv_internal(p, fd, uio, flags, retval);
}

int
read_nocancel(struct proc *p, struct read_nocancel_args *uap, user_ssize_t *retval)
{
	return read_internal(p, uap->fd, uap->cbuf, uap->nbyte, (off_t)-1, 0,
	           retval);
}

/*
 * Read system call.
 *
 * Returns:	0			Success
 *	preparefileread:EBADF
 *	preparefileread:ESPIPE
 *	preparefileread:ENXIO
 *	preparefileread:EBADF
 *	dofileread:???
 */
int
read(struct proc *p, struct read_args *uap, user_ssize_t *retval)
{
	__pthread_testcancel(1);
	return read_nocancel(p, (struct read_nocancel_args *)uap, retval);
}

int
pread_nocancel(struct proc *p, struct pread_nocancel_args *uap, user_ssize_t *retval)
{
	KERNEL_DEBUG_CONSTANT((BSDDBG_CODE(DBG_BSD_SC_EXTENDED_INFO, SYS_pread) | DBG_FUNC_NONE),
	    uap->fd, uap->nbyte, (unsigned int)((uap->offset >> 32)), (unsigned int)(uap->offset), 0);

	return read_internal(p, uap->fd, uap->buf, uap->nbyte, uap->offset,
	           FOF_OFFSET, retval);
}

/*
 * Pread system call
 *
 * Returns:	0			Success
 *	preparefileread:EBADF
 *	preparefileread:ESPIPE
 *	preparefileread:ENXIO
 *	preparefileread:EBADF
 *	dofileread:???
 */
int
pread(struct proc *p, struct pread_args *uap, user_ssize_t *retval)
{
	__pthread_testcancel(1);
	return pread_nocancel(p, (struct pread_nocancel_args *)uap, retval);
}

/*
 * Vector read.
 *
 * Returns:    0                       Success
 *             EINVAL
 *             ENOMEM
 *     preparefileread:EBADF
 *     preparefileread:ESPIPE
 *     preparefileread:ENXIO
 *     preparefileread:EBADF
 *     copyin:EFAULT
 *     rd_uio:???
 */
static int
readv_uio(struct proc *p, int fd,
    user_addr_t user_iovp, int iovcnt, off_t offset, int flags,
    user_ssize_t *retval)
{
	uio_t uio = NULL;
	int error;
	struct user_iovec *iovp;

	if (iovcnt <= 0 || iovcnt > UIO_MAXIOV) {
		error = EINVAL;
		goto out;
	}

	uio = uio_create(iovcnt, offset,
	    (IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32),
	    UIO_READ);

	iovp = uio_iovsaddr_user(uio);
	if (iovp == NULL) {
		error = ENOMEM;
		goto out;
	}

	error = copyin_user_iovec_array(user_iovp,
	    IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32,
	    iovcnt, iovp, iovcnt);

	if (error) {
		goto out;
	}

	error = readv_internal(p, fd, uio, flags, retval);

out:
	if (uio != NULL) {
		uio_free(uio);
	}

	return error;
}

int
readv_nocancel(struct proc *p, struct readv_nocancel_args *uap, user_ssize_t *retval)
{
	return readv_uio(p, uap->fd, uap->iovp, uap->iovcnt, 0, 0, retval);
}

/*
 * Scatter read system call.
 */
int
readv(struct proc *p, struct readv_args *uap, user_ssize_t *retval)
{
	__pthread_testcancel(1);
	return readv_nocancel(p, (struct readv_nocancel_args *)uap, retval);
}

int
sys_preadv_nocancel(struct proc *p, struct preadv_nocancel_args *uap, user_ssize_t *retval)
{
	return readv_uio(p, uap->fd, uap->iovp, uap->iovcnt, uap->offset,
	           FOF_OFFSET, retval);
}

/*
 * Preadv system call
 */
int
sys_preadv(struct proc *p, struct preadv_args *uap, user_ssize_t *retval)
{
	__pthread_testcancel(1);
	return sys_preadv_nocancel(p, (struct preadv_nocancel_args *)uap, retval);
}

/*
 * Returns:	0			Success
 *		EBADF
 *		ESPIPE
 *		ENXIO
 *	fp_lookup:EBADF
 *	fp_guard_exception:???
 *  valid_for_random_access:ESPIPE
 *  valid_for_random_access:ENXIO
 */
static int
preparefilewrite(struct proc *p, struct fileproc **fp_ret, int fd, int check_for_pwrite,
    guardid_t *puguard)
{
	int error;
	struct fileproc *fp;

	AUDIT_ARG(fd, fd);

	proc_fdlock_spin(p);

	if (puguard) {
		error = fp_lookup_guarded(p, fd, *puguard, &fp, 1);
		if (error) {
			proc_fdunlock(p);
			return error;
		}

		if ((fp->f_flag & FWRITE) == 0) {
			error = EBADF;
			goto out;
		}
	} else {
		error = fp_lookup(p, fd, &fp, 1);
		if (error) {
			proc_fdunlock(p);
			return error;
		}

		/* Allow EBADF first. */
		if ((fp->f_flag & FWRITE) == 0) {
			error = EBADF;
			goto out;
		}

		if (fp_isguarded(fp, GUARD_WRITE)) {
			error = fp_guard_exception(p, fd, fp, kGUARD_EXC_WRITE);
			goto out;
		}
	}

	if (check_for_pwrite) {
		if ((error = valid_for_random_access(fp, true))) {
			goto out;
		}
	}

	*fp_ret = fp;

	proc_fdunlock(p);
	return 0;

out:
	fp_drop(p, fd, fp, 1);
	proc_fdunlock(p);
	return error;
}

static int
fp_writev(vfs_context_t ctx, struct fileproc *fp, uio_t uio, int flags,
    user_ssize_t *retval)
{
	int error;
	user_ssize_t count;

	if ((error = uio_calculateresid_user(uio))) {
		*retval = 0;
		return error;
	}

	count = uio_resid(uio);
	error = fo_write(fp, uio, flags, ctx);

	switch (error) {
	case ERESTART:
	case EINTR:
	case EWOULDBLOCK:
		if (uio_resid(uio) != count) {
			error = 0;
		}
		break;

	case EPIPE:
		if (fp->f_type != DTYPE_SOCKET &&
		    (fp->fp_glob->fg_lflags & FG_NOSIGPIPE) == 0) {
			/* XXX Raise the signal on the thread? */
			psignal(vfs_context_proc(ctx), SIGPIPE);
		}
		break;

	default:
		break;
	}

	if ((*retval = count - uio_resid(uio))) {
		os_atomic_or(&fp->fp_glob->fg_flag, FWASWRITTEN, relaxed);
	}

	return error;
}

/*
 * Returns:	0			Success
 *		EINVAL
 *	<fo_write>:EPIPE
 *	<fo_write>:???			[indirect through struct fileops]
 */
__private_extern__ int
dofilewrite(vfs_context_t ctx, struct fileproc *fp,
    user_addr_t bufp, user_size_t nbyte, off_t offset, int flags,
    user_ssize_t *retval)
{
	UIO_STACKBUF(uio_buf, 1);
	uio_t uio;
	int spacetype;

	if (nbyte > INT_MAX) {
		*retval = 0;
		return EINVAL;
	}

	spacetype = vfs_context_is64bit(ctx) ? UIO_USERSPACE64 : UIO_USERSPACE32;
	uio = uio_createwithbuffer(1, offset, spacetype, UIO_WRITE, &uio_buf[0],
	    sizeof(uio_buf));

	if (uio_addiov(uio, bufp, nbyte) != 0) {
		*retval = 0;
		return EINVAL;
	}

	return fp_writev(ctx, fp, uio, flags, retval);
}

static int
writev_internal(struct proc *p, int fd, uio_t uio, int flags,
    guardid_t *puguard, user_ssize_t *retval)
{
	struct fileproc *fp = NULL;
	struct vfs_context context;
	int error;

	if ((error = preparefilewrite(p, &fp, fd, flags & FOF_OFFSET, puguard))) {
		*retval = 0;
		return error;
	}

	context = *(vfs_context_current());
	context.vc_ucred = fp->fp_glob->fg_cred;

	error = fp_writev(&context, fp, uio, flags, retval);

	fp_drop(p, fd, fp, 0);
	return error;
}

int
write_internal(struct proc *p, int fd, user_addr_t buf, user_size_t nbyte,
    off_t offset, int flags, guardid_t *puguard, user_ssize_t *retval)
{
	UIO_STACKBUF(uio_buf, 1);
	uio_t uio;
	int spacetype = IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32;

	if (nbyte > INT_MAX) {
		*retval = 0;
		return EINVAL;
	}

	uio = uio_createwithbuffer(1, offset, spacetype, UIO_WRITE,
	    &uio_buf[0], sizeof(uio_buf));

	if (uio_addiov(uio, buf, nbyte) != 0) {
		*retval = 0;
		return EINVAL;
	}

	return writev_internal(p, fd, uio, flags, puguard, retval);
}

int
write_nocancel(struct proc *p, struct write_nocancel_args *uap, user_ssize_t *retval)
{
	return write_internal(p, uap->fd, uap->cbuf, uap->nbyte, (off_t)-1, 0,
	           NULL, retval);
}

/*
 * Write system call
 *
 * Returns:	0			Success
 *		EBADF
 *	fp_lookup:EBADF
 *	dofilewrite:???
 */
int
write(struct proc *p, struct write_args *uap, user_ssize_t *retval)
{
	__pthread_testcancel(1);
	return write_nocancel(p, (struct write_nocancel_args *)uap, retval);
}

int
pwrite_nocancel(struct proc *p, struct pwrite_nocancel_args *uap, user_ssize_t *retval)
{
	KERNEL_DEBUG_CONSTANT((BSDDBG_CODE(DBG_BSD_SC_EXTENDED_INFO, SYS_pwrite) | DBG_FUNC_NONE),
	    uap->fd, uap->nbyte, (unsigned int)((uap->offset >> 32)), (unsigned int)(uap->offset), 0);

	/* XXX: Should be < 0 instead? (See man page + pwritev) */
	if (uap->offset == (off_t)-1) {
		return EINVAL;
	}

	return write_internal(p, uap->fd, uap->buf, uap->nbyte, uap->offset,
	           FOF_OFFSET, NULL, retval);
}

/*
 * pwrite system call
 *
 * Returns:	0			Success
 *		EBADF
 *		ESPIPE
 *		ENXIO
 *		EINVAL
 *	fp_lookup:EBADF
 *	dofilewrite:???
 */
int
pwrite(struct proc *p, struct pwrite_args *uap, user_ssize_t *retval)
{
	__pthread_testcancel(1);
	return pwrite_nocancel(p, (struct pwrite_nocancel_args *)uap, retval);
}

int
writev_uio(struct proc *p, int fd,
    user_addr_t user_iovp, int iovcnt, off_t offset, int flags,
    guardid_t *puguard, user_ssize_t *retval)
{
	uio_t uio = NULL;
	int error;
	struct user_iovec *iovp;

	if (iovcnt <= 0 || iovcnt > UIO_MAXIOV || offset < 0) {
		error = EINVAL;
		goto out;
	}

	uio = uio_create(iovcnt, offset,
	    (IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32),
	    UIO_WRITE);

	iovp = uio_iovsaddr_user(uio);
	if (iovp == NULL) {
		error = ENOMEM;
		goto out;
	}

	error = copyin_user_iovec_array(user_iovp,
	    IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32,
	    iovcnt, iovp, iovcnt);

	if (error) {
		goto out;
	}

	error = writev_internal(p, fd, uio, flags, puguard, retval);

out:
	if (uio != NULL) {
		uio_free(uio);
	}

	return error;
}

int
writev_nocancel(struct proc *p, struct writev_nocancel_args *uap, user_ssize_t *retval)
{
	return writev_uio(p, uap->fd, uap->iovp, uap->iovcnt, 0, 0, NULL, retval);
}

/*
 * Gather write system call
 */
int
writev(struct proc *p, struct writev_args *uap, user_ssize_t *retval)
{
	__pthread_testcancel(1);
	return writev_nocancel(p, (struct writev_nocancel_args *)uap, retval);
}

int
sys_pwritev_nocancel(struct proc *p, struct pwritev_nocancel_args *uap, user_ssize_t *retval)
{
	return writev_uio(p, uap->fd, uap->iovp, uap->iovcnt, uap->offset,
	           FOF_OFFSET, NULL, retval);
}

/*
 * Pwritev system call
 */
int
sys_pwritev(struct proc *p, struct pwritev_args *uap, user_ssize_t *retval)
{
	__pthread_testcancel(1);
	return sys_pwritev_nocancel(p, (struct pwritev_nocancel_args *)uap, retval);
}

/*
 * Ioctl system call
 *
 * Returns:	0			Success
 *		EBADF
 *		ENOTTY
 *		ENOMEM
 *		ESRCH
 *	copyin:EFAULT
 *	copyoutEFAULT
 *	fp_lookup:EBADF			Bad file descriptor
 *	fo_ioctl:???
 */
int
ioctl(struct proc *p, struct ioctl_args *uap, __unused int32_t *retval)
{
	struct fileproc *fp = NULL;
	int error = 0;
	u_int size = 0;
	caddr_t datap = NULL, memp = NULL;
	boolean_t is64bit = FALSE;
	int tmp = 0;
#define STK_PARAMS      128
	char stkbuf[STK_PARAMS] = {};
	int fd = uap->fd;
	u_long com = uap->com;
	struct vfs_context context = *vfs_context_current();

	AUDIT_ARG(fd, uap->fd);
	AUDIT_ARG(addr, uap->data);

	is64bit = proc_is64bit(p);
#if CONFIG_AUDIT
	if (is64bit) {
		AUDIT_ARG(value64, com);
	} else {
		AUDIT_ARG(cmd, CAST_DOWN_EXPLICIT(int, com));
	}
#endif /* CONFIG_AUDIT */

	/*
	 * Interpret high order word to find amount of data to be
	 * copied to/from the user's address space.
	 */
	size = IOCPARM_LEN(com);
	if (size > IOCPARM_MAX) {
		return ENOTTY;
	}
	if (size > sizeof(stkbuf)) {
		memp = (caddr_t)kalloc_data(size, Z_WAITOK);
		if (memp == 0) {
			return ENOMEM;
		}
		datap = memp;
	} else {
		datap = &stkbuf[0];
	}
	if (com & IOC_IN) {
		if (size) {
			error = copyin(uap->data, datap, size);
			if (error) {
				goto out_nofp;
			}
		} else {
			/* XXX - IOC_IN and no size?  we should proably return an error here!! */
			if (is64bit) {
				*(user_addr_t *)datap = uap->data;
			} else {
				*(uint32_t *)datap = (uint32_t)uap->data;
			}
		}
	} else if ((com & IOC_OUT) && size) {
		/*
		 * Zero the buffer so the user always
		 * gets back something deterministic.
		 */
		bzero(datap, size);
	} else if (com & IOC_VOID) {
		/* XXX - this is odd since IOC_VOID means no parameters */
		if (is64bit) {
			*(user_addr_t *)datap = uap->data;
		} else {
			*(uint32_t *)datap = (uint32_t)uap->data;
		}
	}

	proc_fdlock(p);
	error = fp_lookup(p, fd, &fp, 1);
	if (error) {
		proc_fdunlock(p);
		goto out_nofp;
	}

	AUDIT_ARG(file, p, fp);

	if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
		error = EBADF;
		goto out;
	}

	context.vc_ucred = fp->fp_glob->fg_cred;

#if CONFIG_MACF
	error = mac_file_check_ioctl(context.vc_ucred, fp->fp_glob, com);
	if (error) {
		goto out;
	}
#endif

	switch (com) {
	case FIONCLEX:
		fp->fp_flags &= ~FP_CLOEXEC;
		break;

	case FIOCLEX:
		fp->fp_flags |= FP_CLOEXEC;
		break;

	case FIONBIO:
		// FIXME (rdar://54898652)
		//
		// this code is broken if fnctl(F_SETFL), ioctl() are
		// called concurrently for the same fileglob.
		if ((tmp = *(int *)datap)) {
			os_atomic_or(&fp->f_flag, FNONBLOCK, relaxed);
		} else {
			os_atomic_andnot(&fp->f_flag, FNONBLOCK, relaxed);
		}
		error = fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, &context);
		break;

	case FIOASYNC:
		// FIXME (rdar://54898652)
		//
		// this code is broken if fnctl(F_SETFL), ioctl() are
		// called concurrently for the same fileglob.
		if ((tmp = *(int *)datap)) {
			os_atomic_or(&fp->f_flag, FASYNC, relaxed);
		} else {
			os_atomic_andnot(&fp->f_flag, FASYNC, relaxed);
		}
		error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, &context);
		break;

	case FIOSETOWN:
		tmp = *(int *)datap;
		if (fp->f_type == DTYPE_SOCKET) {
			((struct socket *)fp_get_data(fp))->so_pgid = tmp;
			break;
		}
		if (fp->f_type == DTYPE_PIPE) {
			error = fo_ioctl(fp, TIOCSPGRP, (caddr_t)&tmp, &context);
			break;
		}
		if (tmp <= 0) {
			tmp = -tmp;
		} else {
			struct proc *p1 = proc_find(tmp);
			if (p1 == 0) {
				error = ESRCH;
				break;
			}
			tmp = p1->p_pgrpid;
			proc_rele(p1);
		}
		error = fo_ioctl(fp, TIOCSPGRP, (caddr_t)&tmp, &context);
		break;

	case FIOGETOWN:
		if (fp->f_type == DTYPE_SOCKET) {
			*(int *)datap = ((struct socket *)fp_get_data(fp))->so_pgid;
			break;
		}
		error = fo_ioctl(fp, TIOCGPGRP, datap, &context);
		*(int *)datap = -*(int *)datap;
		break;

	default:
		error = fo_ioctl(fp, com, datap, &context);
		/*
		 * Copy any data to user, size was
		 * already set and checked above.
		 */
		if (error == 0 && (com & IOC_OUT) && size) {
			error = copyout(datap, uap->data, (u_int)size);
		}
		break;
	}
out:
	fp_drop(p, fd, fp, 1);
	proc_fdunlock(p);

out_nofp:
	if (memp) {
		kfree_data(memp, size);
	}
	return error;
}

int     selwait;
#define SEL_FIRSTPASS 1
#define SEL_SECONDPASS 2
static int selprocess(struct proc *p, int error, int sel_pass);
static int selscan(struct proc *p, struct _select * sel, struct _select_data * seldata,
    int nfd, int32_t *retval, int sel_pass, struct select_set *selset);
static int selcount(struct proc *p, u_int32_t *ibits, int nfd, int *count);
static int seldrop_locked(struct proc *p, u_int32_t *ibits, int nfd, int lim, int *need_wakeup);
static int seldrop(struct proc *p, u_int32_t *ibits, int nfd, int lim);
static int select_internal(struct proc *p, struct select_nocancel_args *uap, uint64_t timeout, int32_t *retval);

/*
 * This is used for the special device nodes that do not implement
 * a proper kevent filter (see filt_specattach).
 *
 * In order to enable kevents on those, the spec_filtops will pretend
 * to call select, and try to sniff the selrecord(), if it observes one,
 * the knote is attached, which pairs with selwakeup() or selthreadclear().
 *
 * The last issue remaining, is that we need to serialize filt_specdetach()
 * with this, but it really can't know the "selinfo" or any locking domain.
 * To make up for this, We protect knote list operations with a global lock,
 * which give us a safe shared locking domain.
 *
 * Note: It is a little distasteful, but we really have very few of those.
 *       The big problem here is that sharing a lock domain without
 *       any kind of shared knowledge is a little complicated.
 *
 *       1. filters can really implement their own kqueue integration
 *          to side step this,
 *
 *       2. There's an opportunity to pick a private lock in selspec_attach()
 *          because both the selinfo and the knote are locked at that time.
 *          The cleanup story is however a little complicated.
 */
static LCK_GRP_DECLARE(selspec_grp, "spec_filtops");
static LCK_SPIN_DECLARE(selspec_lock, &selspec_grp);

/*
 * The "primitive" lock is held.
 * The knote lock is held.
 */
void
selspec_attach(struct knote *kn, struct selinfo *si)
{
	struct selinfo *cur = knote_kn_hook_get_raw(kn);

	if (cur == NULL) {
		si->si_flags |= SI_SELSPEC;
		lck_spin_lock(&selspec_lock);
		knote_kn_hook_set_raw(kn, (void *) si);
		KNOTE_ATTACH(&si->si_note, kn);
		lck_spin_unlock(&selspec_lock);
	} else {
		/*
		 * selspec_attach() can be called from e.g. filt_spectouch()
		 * which might be called before any event was dequeued.
		 *
		 * It is hence not impossible for the knote already be hooked.
		 *
		 * Note that selwakeup_internal() could possibly
		 * already have cleared this pointer. This is a race
		 * that filt_specprocess will debounce.
		 */
		assert(si->si_flags & SI_SELSPEC);
		assert(cur == si);
	}
}

/*
 * The "primitive" lock is _not_ held.
 *
 * knote "lock" is held
 */
void
selspec_detach(struct knote *kn)
{
	lck_spin_lock(&selspec_lock);

	if (!KNOTE_IS_AUTODETACHED(kn)) {
		struct selinfo *sip = knote_kn_hook_get_raw(kn);
		if (sip) {
			KNOTE_DETACH(&sip->si_note, kn);
		}
	}

	knote_kn_hook_set_raw(kn, NULL);

	lck_spin_unlock(&selspec_lock);
}

/*
 * Select system call.
 *
 * Returns:	0			Success
 *		EINVAL			Invalid argument
 *		EAGAIN			Nonconformant error if allocation fails
 */
int
select(struct proc *p, struct select_args *uap, int32_t *retval)
{
	__pthread_testcancel(1);
	return select_nocancel(p, (struct select_nocancel_args *)uap, retval);
}

int
select_nocancel(struct proc *p, struct select_nocancel_args *uap, int32_t *retval)
{
	uint64_t timeout = 0;

	if (uap->tv) {
		int err;
		struct timeval atv;
		if (IS_64BIT_PROCESS(p)) {
			struct user64_timeval atv64;
			err = copyin(uap->tv, (caddr_t)&atv64, sizeof(atv64));
			/* Loses resolution - assume timeout < 68 years */
			atv.tv_sec = (__darwin_time_t)atv64.tv_sec;
			atv.tv_usec = atv64.tv_usec;
		} else {
			struct user32_timeval atv32;
			err = copyin(uap->tv, (caddr_t)&atv32, sizeof(atv32));
			atv.tv_sec = atv32.tv_sec;
			atv.tv_usec = atv32.tv_usec;
		}
		if (err) {
			return err;
		}

		if (itimerfix(&atv)) {
			err = EINVAL;
			return err;
		}

		clock_absolutetime_interval_to_deadline(tvtoabstime(&atv), &timeout);
	}

	return select_internal(p, uap, timeout, retval);
}

int
pselect(struct proc *p, struct pselect_args *uap, int32_t *retval)
{
	__pthread_testcancel(1);
	return pselect_nocancel(p, (struct pselect_nocancel_args *)uap, retval);
}

int
pselect_nocancel(struct proc *p, struct pselect_nocancel_args *uap, int32_t *retval)
{
	int err;
	struct uthread *ut;
	uint64_t timeout = 0;

	if (uap->ts) {
		struct timespec ts;

		if (IS_64BIT_PROCESS(p)) {
			struct user64_timespec ts64;
			err = copyin(uap->ts, (caddr_t)&ts64, sizeof(ts64));
			ts.tv_sec = (__darwin_time_t)ts64.tv_sec;
			ts.tv_nsec = (long)ts64.tv_nsec;
		} else {
			struct user32_timespec ts32;
			err = copyin(uap->ts, (caddr_t)&ts32, sizeof(ts32));
			ts.tv_sec = ts32.tv_sec;
			ts.tv_nsec = ts32.tv_nsec;
		}
		if (err) {
			return err;
		}

		if (!timespec_is_valid(&ts)) {
			return EINVAL;
		}
		clock_absolutetime_interval_to_deadline(tstoabstime(&ts), &timeout);
	}

	ut = current_uthread();

	if (uap->mask != USER_ADDR_NULL) {
		/* save current mask, then copyin and set new mask */
		sigset_t newset;
		err = copyin(uap->mask, &newset, sizeof(sigset_t));
		if (err) {
			return err;
		}
		ut->uu_oldmask = ut->uu_sigmask;
		ut->uu_flag |= UT_SAS_OLDMASK;
		ut->uu_sigmask = (newset & ~sigcantmask);
	}

	err = select_internal(p, (struct select_nocancel_args *)uap, timeout, retval);

	if (err != EINTR && ut->uu_flag & UT_SAS_OLDMASK) {
		/*
		 * Restore old mask (direct return case). NOTE: EINTR can also be returned
		 * if the thread is cancelled. In that case, we don't reset the signal
		 * mask to its original value (which usually happens in the signal
		 * delivery path). This behavior is permitted by POSIX.
		 */
		ut->uu_sigmask = ut->uu_oldmask;
		ut->uu_oldmask = 0;
		ut->uu_flag &= ~UT_SAS_OLDMASK;
	}

	return err;
}

void
select_cleanup_uthread(struct _select *sel)
{
	kfree_data(sel->ibits, 2 * sel->nbytes);
	sel->ibits = sel->obits = NULL;
	sel->nbytes = 0;
}

static int
select_grow_uthread_cache(struct _select *sel, uint32_t nbytes)
{
	uint32_t *buf;

	buf = kalloc_data(2 * nbytes, Z_WAITOK | Z_ZERO);
	if (buf) {
		select_cleanup_uthread(sel);
		sel->ibits = buf;
		sel->obits = buf + nbytes / sizeof(uint32_t);
		sel->nbytes = nbytes;
		return true;
	}
	return false;
}

static void
select_bzero_uthread_cache(struct _select *sel)
{
	bzero(sel->ibits, sel->nbytes * 2);
}

/*
 * Generic implementation of {,p}select. Care: we type-pun uap across the two
 * syscalls, which differ slightly. The first 4 arguments (nfds and the fd sets)
 * are identical. The 5th (timeout) argument points to different types, so we
 * unpack in the syscall-specific code, but the generic code still does a null
 * check on this argument to determine if a timeout was specified.
 */
static int
select_internal(struct proc *p, struct select_nocancel_args *uap, uint64_t timeout, int32_t *retval)
{
	struct uthread *uth = current_uthread();
	struct _select *sel = &uth->uu_select;
	struct _select_data *seldata = &uth->uu_save.uus_select_data;
	int error = 0;
	u_int ni, nw;

	*retval = 0;

	seldata->abstime = timeout;
	seldata->args = uap;
	seldata->retval = retval;
	seldata->count = 0;

	if (uap->nd < 0) {
		return EINVAL;
	}

	if (uap->nd > p->p_fd.fd_nfiles) {
		uap->nd = p->p_fd.fd_nfiles; /* forgiving; slightly wrong */
	}
	nw = howmany(uap->nd, NFDBITS);
	ni = nw * sizeof(fd_mask);

	/*
	 * if the previously allocated space for the bits is smaller than
	 * what is requested or no space has yet been allocated for this
	 * thread, allocate enough space now.
	 *
	 * Note: If this process fails, select() will return EAGAIN; this
	 * is the same thing pool() returns in a no-memory situation, but
	 * it is not a POSIX compliant error code for select().
	 */
	if (sel->nbytes >= (3 * ni)) {
		select_bzero_uthread_cache(sel);
	} else if (!select_grow_uthread_cache(sel, 3 * ni)) {
		return EAGAIN;
	}

	/*
	 * get the bits from the user address space
	 */
#define getbits(name, x) \
	(uap->name ? copyin(uap->name, &sel->ibits[(x) * nw], ni) : 0)

	if ((error = getbits(in, 0))) {
		return error;
	}
	if ((error = getbits(ou, 1))) {
		return error;
	}
	if ((error = getbits(ex, 2))) {
		return error;
	}
#undef  getbits

	if ((error = selcount(p, sel->ibits, uap->nd, &seldata->count))) {
		return error;
	}

	if (uth->uu_selset == NULL) {
		uth->uu_selset = select_set_alloc();
	}
	return selprocess(p, 0, SEL_FIRSTPASS);
}

static int
selcontinue(int error)
{
	return selprocess(current_proc(), error, SEL_SECONDPASS);
}


/*
 * selprocess
 *
 * Parameters:	error			The error code from our caller
 *		sel_pass		The pass we are on
 */
int
selprocess(struct proc *p, int error, int sel_pass)
{
	struct uthread *uth = current_uthread();
	struct _select *sel = &uth->uu_select;
	struct _select_data *seldata = &uth->uu_save.uus_select_data;
	struct select_nocancel_args *uap = seldata->args;
	int *retval = seldata->retval;

	int unwind = 1;
	int prepost = 0;
	int somewakeup = 0;
	int doretry = 0;
	wait_result_t wait_result;

	if ((error != 0) && (sel_pass == SEL_FIRSTPASS)) {
		unwind = 0;
	}
	if (seldata->count == 0) {
		unwind = 0;
	}
retry:
	if (error != 0) {
		goto done;
	}

	OSBitOrAtomic(P_SELECT, &p->p_flag);

	/* skip scans if the select is just for timeouts */
	if (seldata->count) {
		error = selscan(p, sel, seldata, uap->nd, retval, sel_pass,
		    uth->uu_selset);
		if (error || *retval) {
			goto done;
		}
		if (prepost || somewakeup) {
			/*
			 * if the select of log, then we can wakeup and
			 * discover some one else already read the data;
			 * go to select again if time permits
			 */
			prepost = 0;
			somewakeup = 0;
			doretry = 1;
		}
	}

	if (uap->tv) {
		uint64_t        now;

		clock_get_uptime(&now);
		if (now >= seldata->abstime) {
			goto done;
		}
	}

	if (doretry) {
		/* cleanup obits and try again */
		doretry = 0;
		sel_pass = SEL_FIRSTPASS;
		goto retry;
	}

	/*
	 * To effect a poll, the timeout argument should be
	 * non-nil, pointing to a zero-valued timeval structure.
	 */
	if (uap->tv && seldata->abstime == 0) {
		goto done;
	}

	/* No spurious wakeups due to colls,no need to check for them */
	if ((sel_pass == SEL_SECONDPASS) || ((p->p_flag & P_SELECT) == 0)) {
		sel_pass = SEL_FIRSTPASS;
		goto retry;
	}

	OSBitAndAtomic(~((uint32_t)P_SELECT), &p->p_flag);

	/* if the select is just for timeout skip check */
	if (seldata->count && (sel_pass == SEL_SECONDPASS)) {
		panic("selprocess: 2nd pass assertwaiting");
	}

	wait_result = waitq_assert_wait64_leeway(uth->uu_selset,
	    NO_EVENT64, THREAD_ABORTSAFE,
	    TIMEOUT_URGENCY_USER_NORMAL,
	    seldata->abstime,
	    TIMEOUT_NO_LEEWAY);
	if (wait_result != THREAD_AWAKENED) {
		/* there are no preposted events */
		error = tsleep1(NULL, PSOCK | PCATCH,
		    "select", 0, selcontinue);
	} else {
		prepost = 1;
		error = 0;
	}

	if (error == 0) {
		sel_pass = SEL_SECONDPASS;
		if (!prepost) {
			somewakeup = 1;
		}
		goto retry;
	}
done:
	if (unwind) {
		seldrop(p, sel->ibits, uap->nd, seldata->count);
		select_set_reset(uth->uu_selset);
	}
	OSBitAndAtomic(~((uint32_t)P_SELECT), &p->p_flag);
	/* select is not restarted after signals... */
	if (error == ERESTART) {
		error = EINTR;
	}
	if (error == EWOULDBLOCK) {
		error = 0;
	}

	if (error == 0) {
		uint32_t nw = howmany(uap->nd, NFDBITS);
		uint32_t ni = nw * sizeof(fd_mask);

#define putbits(name, x) \
	(uap->name ? copyout(&sel->obits[(x) * nw], uap->name, ni) : 0)
		int e0 = putbits(in, 0);
		int e1 = putbits(ou, 1);
		int e2 = putbits(ex, 2);

		error = e0 ?: e1 ?: e2;
#undef putbits
	}

	if (error != EINTR && sel_pass == SEL_SECONDPASS && uth->uu_flag & UT_SAS_OLDMASK) {
		/* restore signal mask - continuation case */
		uth->uu_sigmask = uth->uu_oldmask;
		uth->uu_oldmask = 0;
		uth->uu_flag &= ~UT_SAS_OLDMASK;
	}

	return error;
}


/**
 * remove the fileproc's underlying waitq from the supplied waitq set;
 * clear FP_INSELECT when appropriate
 *
 * Parameters:
 *		fp	File proc that is potentially currently in select
 *		selset	Waitq set to which the fileproc may belong
 *			(usually this is the thread's private waitq set)
 * Conditions:
 *		proc_fdlock is held
 */
static void
selunlinkfp(struct fileproc *fp, struct select_set *selset)
{
	if (fp->fp_flags & FP_INSELECT) {
		if (fp->fp_guard_attrs) {
			if (fp->fp_guard->fpg_wset == selset) {
				fp->fp_guard->fpg_wset = NULL;
				fp->fp_flags &= ~FP_INSELECT;
			}
		} else {
			if (fp->fp_wset == selset) {
				fp->fp_wset = NULL;
				fp->fp_flags &= ~FP_INSELECT;
			}
		}
	}
}

/**
 * connect a fileproc to the given selset, potentially bridging to a waitq
 * pointed to indirectly by wq_data
 *
 * Parameters:
 *		fp	File proc potentially currently in select
 *		selset	Waitq set to which the fileproc should now belong
 *			(usually this is the thread's private waitq set)
 *
 * Conditions:
 *		proc_fdlock is held
 */
static void
sellinkfp(struct fileproc *fp, struct select_set *selset, waitq_link_t *linkp)
{
	if ((fp->fp_flags & FP_INSELECT) == 0) {
		if (fp->fp_guard_attrs) {
			fp->fp_guard->fpg_wset = selset;
		} else {
			fp->fp_wset = selset;
		}
		fp->fp_flags |= FP_INSELECT;
	} else {
		fp->fp_flags |= FP_SELCONFLICT;
		if (linkp->wqlh == NULL) {
			*linkp = waitq_link_alloc(WQT_SELECT_SET);
		}
		select_set_link(&select_conflict_queue, selset, linkp);
	}
}


/*
 * selscan
 *
 * Parameters:	p			Process performing the select
 *		sel			The per-thread select context structure
 *		nfd			The number of file descriptors to scan
 *		retval			The per thread system call return area
 *		sel_pass		Which pass this is; allowed values are
 *						SEL_FIRSTPASS and SEL_SECONDPASS
 *		selset			The per thread wait queue set
 *
 * Returns:	0			Success
 *		EIO			Invalid p->p_fd field XXX Obsolete?
 *		EBADF			One of the files in the bit vector is
 *						invalid.
 */
static int
selscan(struct proc *p, struct _select *sel, struct _select_data * seldata,
    int nfd, int32_t *retval, int sel_pass, struct select_set *selset)
{
	int msk, i, j, fd;
	u_int32_t bits;
	struct fileproc *fp;
	int n = 0;              /* count of bits */
	int nc = 0;             /* bit vector offset (nc'th bit) */
	static int flag[3] = { FREAD, FWRITE, 0 };
	u_int32_t *iptr, *optr;
	u_int nw;
	u_int32_t *ibits, *obits;
	int count;
	struct vfs_context context = {
		.vc_thread = current_thread(),
	};
	waitq_link_t link = WQL_NULL;
	void *s_data;

	ibits = sel->ibits;
	obits = sel->obits;

	nw = howmany(nfd, NFDBITS);

	count = seldata->count;

	nc = 0;
	if (!count) {
		*retval = 0;
		return 0;
	}

	if (sel_pass == SEL_FIRSTPASS) {
		/*
		 * Make sure the waitq-set is all clean:
		 *
		 * select loops until it finds at least one event, however it
		 * doesn't mean that the event that woke up select is still
		 * fired by the time the second pass runs, and then
		 * select_internal will loop back to a first pass.
		 */
		select_set_reset(selset);
		s_data = &link;
	} else {
		s_data = NULL;
	}

	proc_fdlock(p);
	for (msk = 0; msk < 3; msk++) {
		iptr = (u_int32_t *)&ibits[msk * nw];
		optr = (u_int32_t *)&obits[msk * nw];

		for (i = 0; i < nfd; i += NFDBITS) {
			bits = iptr[i / NFDBITS];

			while ((j = ffs(bits)) && (fd = i + --j) < nfd) {
				bits &= ~(1U << j);

				fp = fp_get_noref_locked(p, fd);
				if (fp == NULL) {
					/*
					 * If we abort because of a bad
					 * fd, let the caller unwind...
					 */
					proc_fdunlock(p);
					return EBADF;
				}
				if (sel_pass == SEL_SECONDPASS) {
					selunlinkfp(fp, selset);
				} else if (link.wqlh == NULL) {
					link = waitq_link_alloc(WQT_SELECT_SET);
				}

				context.vc_ucred = fp->f_cred;

				/* The select; set the bit, if true */
				if (fo_select(fp, flag[msk], s_data, &context)) {
					optr[fd / NFDBITS] |= (1U << (fd % NFDBITS));
					n++;
				}
				if (sel_pass == SEL_FIRSTPASS) {
					/*
					 * Hook up the thread's waitq set either to
					 * the fileproc structure, or to the global
					 * conflict queue: but only on the first
					 * select pass.
					 */
					sellinkfp(fp, selset, &link);
				}
				nc++;
			}
		}
	}
	proc_fdunlock(p);

	if (link.wqlh) {
		waitq_link_free(WQT_SELECT_SET, link);
	}

	*retval = n;
	return 0;
}

static int poll_callback(struct kevent_qos_s *, kevent_ctx_t);

int
poll(struct proc *p, struct poll_args *uap, int32_t *retval)
{
	__pthread_testcancel(1);
	return poll_nocancel(p, (struct poll_nocancel_args *)uap, retval);
}


int
poll_nocancel(struct proc *p, struct poll_nocancel_args *uap, int32_t *retval)
{
	struct pollfd *fds = NULL;
	struct kqueue *kq = NULL;
	int error = 0;
	u_int nfds = uap->nfds;
	u_int rfds = 0;
	rlim_t nofile = proc_limitgetcur(p, RLIMIT_NOFILE);
	size_t ni = nfds * sizeof(struct pollfd);

	/*
	 * This is kinda bogus.  We have fd limits, but that is not
	 * really related to the size of the pollfd array.  Make sure
	 * we let the process use at least FD_SETSIZE entries and at
	 * least enough for the current limits.  We want to be reasonably
	 * safe, but not overly restrictive.
	 */
	if (nfds > OPEN_MAX ||
	    (nfds > nofile && (proc_suser(p) || nfds > FD_SETSIZE))) {
		return EINVAL;
	}

	kq = kqueue_alloc(p);
	if (kq == NULL) {
		return EAGAIN;
	}

	if (nfds) {
		fds = (struct pollfd *)kalloc_data(ni, Z_WAITOK);
		if (NULL == fds) {
			error = EAGAIN;
			goto out;
		}

		error = copyin(uap->fds, fds, nfds * sizeof(struct pollfd));
		if (error) {
			goto out;
		}
	}

	/* JMM - all this P_SELECT stuff is bogus */
	OSBitOrAtomic(P_SELECT, &p->p_flag);
	for (u_int i = 0; i < nfds; i++) {
		short events = fds[i].events;
		__assert_only int rc;

		/* per spec, ignore fd values below zero */
		if (fds[i].fd < 0) {
			fds[i].revents = 0;
			continue;
		}

		/* convert the poll event into a kqueue kevent */
		struct kevent_qos_s kev = {
			.ident = fds[i].fd,
			.flags = EV_ADD | EV_ONESHOT | EV_POLL,
			.udata = i, /* Index into pollfd array */
		};

		/* Handle input events */
		if (events & (POLLIN | POLLRDNORM | POLLPRI | POLLRDBAND | POLLHUP)) {
			kev.filter = EVFILT_READ;
			if (events & (POLLPRI | POLLRDBAND)) {
				kev.flags |= EV_OOBAND;
			}
			rc = kevent_register(kq, &kev, NULL);
			assert((rc & FILTER_REGISTER_WAIT) == 0);
		}

		/* Handle output events */
		if ((kev.flags & EV_ERROR) == 0 &&
		    (events & (POLLOUT | POLLWRNORM | POLLWRBAND))) {
			kev.filter = EVFILT_WRITE;
			rc = kevent_register(kq, &kev, NULL);
			assert((rc & FILTER_REGISTER_WAIT) == 0);
		}

		/* Handle BSD extension vnode events */
		if ((kev.flags & EV_ERROR) == 0 &&
		    (events & (POLLEXTEND | POLLATTRIB | POLLNLINK | POLLWRITE))) {
			kev.filter = EVFILT_VNODE;
			kev.fflags = 0;
			if (events & POLLEXTEND) {
				kev.fflags |= NOTE_EXTEND;
			}
			if (events & POLLATTRIB) {
				kev.fflags |= NOTE_ATTRIB;
			}
			if (events & POLLNLINK) {
				kev.fflags |= NOTE_LINK;
			}
			if (events & POLLWRITE) {
				kev.fflags |= NOTE_WRITE;
			}
			rc = kevent_register(kq, &kev, NULL);
			assert((rc & FILTER_REGISTER_WAIT) == 0);
		}

		if (kev.flags & EV_ERROR) {
			fds[i].revents = POLLNVAL;
			rfds++;
		} else {
			fds[i].revents = 0;
		}
	}

	/*
	 * Did we have any trouble registering?
	 * If user space passed 0 FDs, then respect any timeout value passed.
	 * This is an extremely inefficient sleep. If user space passed one or
	 * more FDs, and we had trouble registering _all_ of them, then bail
	 * out. If a subset of the provided FDs failed to register, then we
	 * will still call the kqueue_scan function.
	 */
	if (nfds && (rfds == nfds)) {
		goto done;
	}

	/* scan for, and possibly wait for, the kevents to trigger */
	kevent_ctx_t kectx = kevent_get_context(current_thread());
	*kectx = (struct kevent_ctx_s){
		.kec_process_noutputs = rfds,
		.kec_process_flags    = KEVENT_FLAG_POLL,
		.kec_deadline         = 0, /* wait forever */
		.kec_poll_fds         = fds,
	};

	/*
	 * If any events have trouble registering, an event has fired and we
	 * shouldn't wait for events in kqueue_scan.
	 */
	if (rfds) {
		kectx->kec_process_flags |= KEVENT_FLAG_IMMEDIATE;
	} else if (uap->timeout != -1) {
		clock_interval_to_deadline(uap->timeout, NSEC_PER_MSEC,
		    &kectx->kec_deadline);
	}

	error = kqueue_scan(kq, kectx->kec_process_flags, kectx, poll_callback);
	rfds = kectx->kec_process_noutputs;

done:
	OSBitAndAtomic(~((uint32_t)P_SELECT), &p->p_flag);
	/* poll is not restarted after signals... */
	if (error == ERESTART) {
		error = EINTR;
	}
	if (error == 0) {
		error = copyout(fds, uap->fds, nfds * sizeof(struct pollfd));
		*retval = rfds;
	}

out:
	kfree_data(fds, ni);

	kqueue_dealloc(kq);
	return error;
}

static int
poll_callback(struct kevent_qos_s *kevp, kevent_ctx_t kectx)
{
	assert(kectx->kec_process_flags & KEVENT_FLAG_POLL);
	struct pollfd *fds = &kectx->kec_poll_fds[kevp->udata];

	short prev_revents = fds->revents;
	short mask = 0;

	/* convert the results back into revents */
	if (kevp->flags & EV_EOF) {
		fds->revents |= POLLHUP;
	}
	if (kevp->flags & EV_ERROR) {
		fds->revents |= POLLERR;
	}

	switch (kevp->filter) {
	case EVFILT_READ:
		if (fds->revents & POLLHUP) {
			mask = (POLLIN | POLLRDNORM | POLLPRI | POLLRDBAND);
		} else {
			mask = (POLLIN | POLLRDNORM);
			if (kevp->flags & EV_OOBAND) {
				mask |= (POLLPRI | POLLRDBAND);
			}
		}
		fds->revents |= (fds->events & mask);
		break;

	case EVFILT_WRITE:
		if (!(fds->revents & POLLHUP)) {
			fds->revents |= (fds->events & (POLLOUT | POLLWRNORM | POLLWRBAND));
		}
		break;

	case EVFILT_VNODE:
		if (kevp->fflags & NOTE_EXTEND) {
			fds->revents |= (fds->events & POLLEXTEND);
		}
		if (kevp->fflags & NOTE_ATTRIB) {
			fds->revents |= (fds->events & POLLATTRIB);
		}
		if (kevp->fflags & NOTE_LINK) {
			fds->revents |= (fds->events & POLLNLINK);
		}
		if (kevp->fflags & NOTE_WRITE) {
			fds->revents |= (fds->events & POLLWRITE);
		}
		break;
	}

	if (fds->revents != 0 && prev_revents == 0) {
		kectx->kec_process_noutputs++;
	}

	return 0;
}

int
seltrue(__unused dev_t dev, __unused int flag, __unused struct proc *p)
{
	return 1;
}

/*
 * selcount
 *
 * Count the number of bits set in the input bit vector, and establish an
 * outstanding fp->fp_iocount for each of the descriptors which will be in
 * use in the select operation.
 *
 * Parameters:	p			The process doing the select
 *		ibits			The input bit vector
 *		nfd			The number of fd's in the vector
 *		countp			Pointer to where to store the bit count
 *
 * Returns:	0			Success
 *		EIO			Bad per process open file table
 *		EBADF			One of the bits in the input bit vector
 *						references an invalid fd
 *
 * Implicit:	*countp (modified)	Count of fd's
 *
 * Notes:	This function is the first pass under the proc_fdlock() that
 *		permits us to recognize invalid descriptors in the bit vector;
 *		the may, however, not remain valid through the drop and
 *		later reacquisition of the proc_fdlock().
 */
static int
selcount(struct proc *p, u_int32_t *ibits, int nfd, int *countp)
{
	int msk, i, j, fd;
	u_int32_t bits;
	struct fileproc *fp;
	int n = 0;
	u_int32_t *iptr;
	u_int nw;
	int error = 0;
	int need_wakeup = 0;

	nw = howmany(nfd, NFDBITS);

	proc_fdlock(p);
	for (msk = 0; msk < 3; msk++) {
		iptr = (u_int32_t *)&ibits[msk * nw];
		for (i = 0; i < nfd; i += NFDBITS) {
			bits = iptr[i / NFDBITS];
			while ((j = ffs(bits)) && (fd = i + --j) < nfd) {
				bits &= ~(1U << j);

				fp = fp_get_noref_locked(p, fd);
				if (fp == NULL) {
					*countp = 0;
					error = EBADF;
					goto bad;
				}
				os_ref_retain_locked(&fp->fp_iocount);
				n++;
			}
		}
	}
	proc_fdunlock(p);

	*countp = n;
	return 0;

bad:
	if (n == 0) {
		goto out;
	}
	/* Ignore error return; it's already EBADF */
	(void)seldrop_locked(p, ibits, nfd, n, &need_wakeup);

out:
	proc_fdunlock(p);
	if (need_wakeup) {
		wakeup(&p->p_fd.fd_fpdrainwait);
	}
	return error;
}


/*
 * seldrop_locked
 *
 * Drop outstanding wait queue references set up during selscan(); drop the
 * outstanding per fileproc fp_iocount picked up during the selcount().
 *
 * Parameters:	p			Process performing the select
 *		ibits			Input bit bector of fd's
 *		nfd			Number of fd's
 *		lim			Limit to number of vector entries to
 *						consider, or -1 for "all"
 *		inselect		True if
 *		need_wakeup		Pointer to flag to set to do a wakeup
 *					if f_iocont on any descriptor goes to 0
 *
 * Returns:	0			Success
 *		EBADF			One or more fds in the bit vector
 *						were invalid, but the rest
 *						were successfully dropped
 *
 * Notes:	An fd make become bad while the proc_fdlock() is not held,
 *		if a multithreaded application closes the fd out from under
 *		the in progress select.  In this case, we still have to
 *		clean up after the set up on the remaining fds.
 */
static int
seldrop_locked(struct proc *p, u_int32_t *ibits, int nfd, int lim, int *need_wakeup)
{
	int msk, i, j, nc, fd;
	u_int32_t bits;
	struct fileproc *fp;
	u_int32_t *iptr;
	u_int nw;
	int error = 0;
	uthread_t uth = current_uthread();
	struct _select_data *seldata;

	*need_wakeup = 0;

	nw = howmany(nfd, NFDBITS);
	seldata = &uth->uu_save.uus_select_data;

	nc = 0;
	for (msk = 0; msk < 3; msk++) {
		iptr = (u_int32_t *)&ibits[msk * nw];
		for (i = 0; i < nfd; i += NFDBITS) {
			bits = iptr[i / NFDBITS];
			while ((j = ffs(bits)) && (fd = i + --j) < nfd) {
				bits &= ~(1U << j);
				/*
				 * If we've already dropped as many as were
				 * counted/scanned, then we are done.
				 */
				if (nc >= lim) {
					goto done;
				}

				/*
				 * We took an I/O reference in selcount,
				 * so the fp can't possibly be NULL.
				 */
				fp = fp_get_noref_locked_with_iocount(p, fd);
				selunlinkfp(fp, uth->uu_selset);

				nc++;

				const os_ref_count_t refc = os_ref_release_locked(&fp->fp_iocount);
				if (0 == refc) {
					panic("fp_iocount overdecrement!");
				}

				if (1 == refc) {
					/*
					 * The last iocount is responsible for clearing
					 * selconfict flag - even if we didn't set it -
					 * and is also responsible for waking up anyone
					 * waiting on iocounts to drain.
					 */
					if (fp->fp_flags & FP_SELCONFLICT) {
						fp->fp_flags &= ~FP_SELCONFLICT;
					}
					if (p->p_fd.fd_fpdrainwait) {
						p->p_fd.fd_fpdrainwait = 0;
						*need_wakeup = 1;
					}
				}
			}
		}
	}
done:
	return error;
}


static int
seldrop(struct proc *p, u_int32_t *ibits, int nfd, int lim)
{
	int error;
	int need_wakeup = 0;

	proc_fdlock(p);
	error = seldrop_locked(p, ibits, nfd, lim, &need_wakeup);
	proc_fdunlock(p);
	if (need_wakeup) {
		wakeup(&p->p_fd.fd_fpdrainwait);
	}
	return error;
}

/*
 * Record a select request.
 */
void
selrecord(__unused struct proc *selector, struct selinfo *sip, void *s_data)
{
	struct select_set *selset = current_uthread()->uu_selset;

	/* do not record if this is second pass of select */
	if (!s_data) {
		return;
	}

	if (selset == SELSPEC_RECORD_MARKER) {
		/*
		 * The kevent subsystem is trying to sniff
		 * the selinfo::si_note to attach to.
		 */
		((selspec_record_hook_t)s_data)(sip);
	} else {
		waitq_link_t *linkp = s_data;

		if (!waitq_is_valid(&sip->si_waitq)) {
			waitq_init(&sip->si_waitq, WQT_SELECT, SYNC_POLICY_FIFO);
		}

		/* note: this checks for pre-existing linkage */
		select_set_link(&sip->si_waitq, selset, linkp);
	}
}

static void
selwakeup_internal(struct selinfo *sip, long hint, wait_result_t wr)
{
	if (sip->si_flags & SI_SELSPEC) {
		/*
		 * The "primitive" lock is held.
		 * The knote lock is not held.
		 *
		 * All knotes will transition their kn_hook to NULL and we will
		 * reeinitialize the primitive's klist
		 */
		lck_spin_lock(&selspec_lock);
		knote(&sip->si_note, hint, /*autodetach=*/ true);
		lck_spin_unlock(&selspec_lock);
		sip->si_flags &= ~SI_SELSPEC;
	}

	/*
	 * After selrecord() has been called, selinfo owners must call
	 * at least one of selwakeup() or selthreadclear().
	 *
	 * Use this opportunity to deinit the waitq
	 * so that all linkages are garbage collected
	 * in a combined wakeup-all + unlink + deinit call.
	 */
	select_waitq_wakeup_and_deinit(&sip->si_waitq, NO_EVENT64, wr);
}


void
selwakeup(struct selinfo *sip)
{
	selwakeup_internal(sip, 0, THREAD_AWAKENED);
}

void
selthreadclear(struct selinfo *sip)
{
	selwakeup_internal(sip, NOTE_REVOKE, THREAD_RESTART);
}


/*
 * gethostuuid
 *
 * Description:	Get the host UUID from IOKit and return it to user space.
 *
 * Parameters:	uuid_buf		Pointer to buffer to receive UUID
 *		timeout			Timespec for timout
 *
 * Returns:	0			Success
 *		EWOULDBLOCK		Timeout is too short
 *		copyout:EFAULT		Bad user buffer
 *		mac_system_check_info:EPERM		Client not allowed to perform this operation
 *
 * Notes:	A timeout seems redundant, since if it's tolerable to not
 *		have a system UUID in hand, then why ask for one?
 */
int
gethostuuid(struct proc *p, struct gethostuuid_args *uap, __unused int32_t *retval)
{
	kern_return_t kret;
	int error;
	mach_timespec_t mach_ts;        /* for IOKit call */
	__darwin_uuid_t uuid_kern = {}; /* for IOKit call */

	/* Check entitlement */
	if (!IOCurrentTaskHasEntitlement("com.apple.private.getprivatesysid")) {
#if !defined(XNU_TARGET_OS_OSX)
#if CONFIG_MACF
		if ((error = mac_system_check_info(kauth_cred_get(), "hw.uuid")) != 0) {
			/* EPERM invokes userspace upcall if present */
			return error;
		}
#endif
#endif
	}

	/* Convert the 32/64 bit timespec into a mach_timespec_t */
	if (proc_is64bit(p)) {
		struct user64_timespec ts;
		error = copyin(uap->timeoutp, &ts, sizeof(ts));
		if (error) {
			return error;
		}
		mach_ts.tv_sec = (unsigned int)ts.tv_sec;
		mach_ts.tv_nsec = (clock_res_t)ts.tv_nsec;
	} else {
		struct user32_timespec ts;
		error = copyin(uap->timeoutp, &ts, sizeof(ts));
		if (error) {
			return error;
		}
		mach_ts.tv_sec = ts.tv_sec;
		mach_ts.tv_nsec = ts.tv_nsec;
	}

	/* Call IOKit with the stack buffer to get the UUID */
	kret = IOBSDGetPlatformUUID(uuid_kern, mach_ts);

	/*
	 * If we get it, copy out the data to the user buffer; note that a
	 * uuid_t is an array of characters, so this is size invariant for
	 * 32 vs. 64 bit.
	 */
	if (kret == KERN_SUCCESS) {
		error = copyout(uuid_kern, uap->uuid_buf, sizeof(uuid_kern));
	} else {
		error = EWOULDBLOCK;
	}

	return error;
}

/*
 * ledger
 *
 * Description:	Omnibus system call for ledger operations
 */
int
ledger(struct proc *p, struct ledger_args *args, __unused int32_t *retval)
{
#if !CONFIG_MACF
#pragma unused(p)
#endif
	int rval, pid, len, error;
	task_t task;
	proc_t proc;

	/* Finish copying in the necessary args before taking the proc lock */
	error = 0;
	len = 0;

	switch (args->cmd) {
	case LEDGER_INFO:
		break;
	case LEDGER_ENTRY_INFO:
	case LEDGER_ENTRY_INFO_V2:
		error = copyin(args->arg3, (char *)&len, sizeof(len));
		break;
	case LEDGER_TEMPLATE_INFO:
		error = copyin(args->arg2, (char *)&len, sizeof(len));
		break;
	default:
		return EINVAL;
	}

	if (error) {
		return error;
	}
	if (len < 0) {
		return EINVAL;
	}

	rval = 0;
	if (args->cmd != LEDGER_TEMPLATE_INFO) {
		pid = (int)args->arg1;
		proc = proc_find(pid);
		if (proc == NULL) {
			return ESRCH;
		}

#if CONFIG_MACF
		error = mac_proc_check_ledger(p, proc, args->cmd);
		if (error) {
			proc_rele(proc);
			return error;
		}
#endif

		task = proc_task(proc);
	}

	switch (args->cmd) {
	case LEDGER_INFO: {
		struct ledger_info info = {};

		rval = ledger_info(task, &info);
		proc_rele(proc);
		if (rval == 0) {
			rval = copyout(&info, args->arg2,
			    sizeof(info));
		}
		break;
	}

	case LEDGER_ENTRY_INFO:
	case LEDGER_ENTRY_INFO_V2: {
		bool v2 = (args->cmd == LEDGER_ENTRY_INFO_V2);
		int entry_size = (v2) ? sizeof(struct ledger_entry_info_v2) : sizeof(struct ledger_entry_info);
		void *buf;
		int sz;

		/* Settle ledger entries for memorystatus and pages grabbed */
		task_ledger_settle(task);

		rval = ledger_get_task_entry_info_multiple(task, &buf, &len, v2);
		proc_rele(proc);
		if ((rval == 0) && (len >= 0)) {
			sz = len * entry_size;
			rval = copyout(buf, args->arg2, sz);
			kfree_data(buf, sz);
		}
		if (rval == 0) {
			rval = copyout(&len, args->arg3, sizeof(len));
		}
		break;
	}

	case LEDGER_TEMPLATE_INFO: {
		void *buf;
		int sz;

		rval = ledger_template_info(&buf, &len);
		if ((rval == 0) && (len >= 0)) {
			sz = len * sizeof(struct ledger_template_info);
			rval = copyout(buf, args->arg1, sz);
			kfree_data(buf, sz);
		}
		if (rval == 0) {
			rval = copyout(&len, args->arg2, sizeof(len));
		}
		break;
	}

	default:
		panic("ledger syscall logic error -- command type %d", args->cmd);
		proc_rele(proc);
		rval = EINVAL;
	}

	return rval;
}

int
telemetry(__unused struct proc *p, struct telemetry_args *args, __unused int32_t *retval)
{
	int error = 0;

	switch (args->cmd) {
#if CONFIG_TELEMETRY
	case TELEMETRY_CMD_TIMER_EVENT:
		error = ENOTSUP;
		break;
	case TELEMETRY_CMD_PMI_SETUP:
		error = telemetry_pmi_setup((telemetry_pmi_t)args->deadline, args->interval);
		break;
	case TELEMETRY_CMD_PAGEIN_SETUP:
		error = telemetry_pagein_setup(args->deadline, args->interval);
		break;
	case TELEMETRY_CMD_PAGEIN_READ:
		error = telemetry_pagein_read((unsigned int *)retval, args->deadline, args->interval);
		break;
	case TELEMETRY_CMD_MEMORY_USAGE_SETUP:
		error = telemetry_memory_usage_setup(args->deadline, args->interval);
		break;
#endif /* CONFIG_TELEMETRY */
	case TELEMETRY_CMD_VOUCHER_NAME:
		if (thread_set_voucher_name((mach_port_name_t)args->deadline)) {
			error = EINVAL;
		}
		break;

	default:
		error = EINVAL;
		break;
	}

	return error;
}

/*
 * Logging
 *
 * Description: syscall to access kernel logging from userspace
 *
 * Args:
 *	tag - used for syncing with userspace on the version.
 *	flags - flags used by the syscall.
 *	buffer - userspace address of string to copy.
 *	size - size of buffer.
 */
int
log_data(__unused struct proc *p, struct log_data_args *args, int *retval)
{
	unsigned int tag = args->tag;
	unsigned int flags = args->flags;
	user_addr_t buffer = args->buffer;
	unsigned int size = args->size;
	int ret = 0;
	*retval = 0;

	/* Only DEXTs are suppose to use this syscall. */
	if (!task_is_driver(current_task())) {
		return EPERM;
	}

	/*
	 * Tag synchronize the syscall version with userspace.
	 * Tag == 0 => flags == OS_LOG_TYPE
	 */
	if (tag != 0) {
		return EINVAL;
	}

	/*
	 * OS_LOG_TYPE are defined in libkern/os/log.h
	 * In userspace they are defined in libtrace/os/log.h
	 */
	if (flags != OS_LOG_TYPE_DEFAULT &&
	    flags != OS_LOG_TYPE_INFO &&
	    flags != OS_LOG_TYPE_DEBUG &&
	    flags != OS_LOG_TYPE_ERROR &&
	    flags != OS_LOG_TYPE_FAULT) {
		return EINVAL;
	}

	if (size == 0) {
		return EINVAL;
	}

	/* truncate to OS_LOG_DATA_MAX_SIZE */
	if (size > OS_LOG_DATA_MAX_SIZE) {
		size = OS_LOG_DATA_MAX_SIZE;
	}

	char *log_msg = (char *)kalloc_data(size, Z_WAITOK);
	if (!log_msg) {
		return ENOMEM;
	}

	if (copyin(buffer, log_msg, size) != 0) {
		ret = EFAULT;
		goto out;
	}
	log_msg[size - 1] = '\0';

	/*
	 * This will log to dmesg and logd.
	 * The call will fail if the current
	 * process is not a driverKit process.
	 */
	os_log_driverKit(&ret, OS_LOG_DEFAULT, (os_log_type_t)flags, "%s", log_msg);

out:
	if (log_msg != NULL) {
		kfree_data(log_msg, size);
	}

	return ret;
}

/*
 * Coprocessor logging
 *
 * Description: syscall to access kernel coprocessor logging from userspace
 *
 * Args:
 *	buff - userspace address of string to copy.
 *	buff_len - size of buffer.
 *	type - log type/level
 *	uuid - log source identifier
 *	timestamp - log timestamp
 *	offset - log format offset
 *	stream_log - flag indicating stream
 */
int
oslog_coproc(__unused struct proc *p, struct oslog_coproc_args *args, int *retval)
{
	user_addr_t buff = args->buff;
	uint64_t buff_len = args->buff_len;
	uint32_t type = args->type;
	user_addr_t uuid = args->uuid;
	uint64_t timestamp = args->timestamp;
	uint32_t offset = args->offset;
	uint32_t stream_log = args->stream_log;
	char *log_buff = NULL;
	uuid_t log_uuid;

	int ret = 0;
	*retval = 0;

	const task_t __single task = proc_task(p);
	if (task == NULL || !IOTaskHasEntitlement(task, "com.apple.private.coprocessor-logging")) {
		return EPERM;
	}

	/* Only DEXTs are supposed to use this syscall. */
	if (!task_is_driver(current_task())) {
		return EPERM;
	}

	// the full message contains a 32 bit offset value, 16 byte uuid and then the provided buffer
	// entire message needs to fit within OS_LOG_BUFFER_MAX_SIZE
	// this is reflected in `log.c:os_log_coprocessor`
	uint64_t full_len;
	if (os_add_overflow(buff_len, sizeof(uuid_t) + sizeof(uint32_t), &full_len) || full_len > OS_LOG_BUFFER_MAX_SIZE) {
		return ERANGE;
	}

	log_buff = (char *)kalloc_data(buff_len, Z_WAITOK);
	if (!log_buff) {
		return ENOMEM;
	}

	ret = copyin(buff, log_buff, buff_len);
	if (ret) {
		goto out;
	}

	ret = copyin(uuid, &log_uuid, sizeof(uuid_t));
	if (ret) {
		goto out;
	}

	os_log_coprocessor(log_buff, buff_len, (os_log_type_t)type, (char *)log_uuid, timestamp, offset, stream_log);

out:
	if (log_buff != NULL) {
		kfree_data(log_buff, buff_len);
	}

	return ret;
}

/*
 * Coprocessor logging registration
 *
 * Description: syscall to access kernel coprocessor logging registration from userspace
 *
 * Args:
 *	uuid - coprocessor fw uuid to harvest
 *	file_path - file name for logd to harvest from
 *	file_path_len - file name length
 */
int
oslog_coproc_reg(__unused struct proc *p, struct oslog_coproc_reg_args *args, int *retval)
{
	user_addr_t uuid = args->uuid;
	user_addr_t file_path = args->file_path;
	size_t file_path_len = args->file_path_len;
	char *file_path_buf = NULL;
	uuid_t uuid_buf;

	int ret = 0;
	*retval = 0;

	const task_t __single task = proc_task(p);
	if (task == NULL || !IOTaskHasEntitlement(task, "com.apple.private.coprocessor-logging")) {
		return EPERM;
	}

	/* Only DEXTs are supposed to use this syscall. */
	if (!task_is_driver(current_task())) {
		return EPERM;
	}

	if (file_path_len > PATH_MAX) {
		return EINVAL;
	}

	file_path_buf = (char *)kalloc_data(file_path_len, Z_WAITOK);
	if (!file_path_buf) {
		return ENOMEM;
	}

	ret = copyin(file_path, file_path_buf, file_path_len);
	if (ret) {
		goto out;
	}

	ret = copyin(uuid, &uuid_buf, sizeof(uuid_t));
	if (ret) {
		goto out;
	}

	os_log_coprocessor_register_with_type((char *)uuid_buf, file_path_buf, os_log_coproc_register_harvest_fs_ftab);

out:
	if (file_path_buf != NULL) {
		kfree_data(file_path_buf, file_path_len);
	}

	return ret;
}

#if DEVELOPMENT || DEBUG

static int
sysctl_mpsc_test_pingpong SYSCTL_HANDLER_ARGS
{
#pragma unused(oidp, arg1, arg2)
	uint64_t value = 0;
	int error;

	error = SYSCTL_IN(req, &value, sizeof(value));
	if (error) {
		return error;
	}

	if (error == 0 && req->newptr) {
		error = mpsc_test_pingpong(value, &value);
		if (error == 0) {
			error = SYSCTL_OUT(req, &value, sizeof(value));
		}
	}

	return error;
}
SYSCTL_PROC(_kern, OID_AUTO, mpsc_test_pingpong, CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
    0, 0, sysctl_mpsc_test_pingpong, "Q", "MPSC tests: pingpong");

#endif /* DEVELOPMENT || DEBUG */

/* Telemetry, microstackshots */

#if CONFIG_TELEMETRY

SYSCTL_NODE(_kern, OID_AUTO, microstackshot, CTLFLAG_RD | CTLFLAG_LOCKED, 0,
    "microstackshot info");

extern uint32_t telemetry_buffer_size;
SYSCTL_UINT(_kern_microstackshot, OID_AUTO, buffer_size, CTLFLAG_RD | CTLFLAG_LOCKED,
    &telemetry_buffer_size, 0, "buffer capacity for microstackshots (bytes)");

#if CONFIG_CPU_COUNTERS

extern uint64_t microstackshot_pmi_period;
SYSCTL_QUAD(_kern_microstackshot, OID_AUTO, pmi_sample_period,
    CTLFLAG_RD | CTLFLAG_LOCKED, &microstackshot_pmi_period,
    "PMI sampling rate");
extern unsigned int microstackshot_pmi_counter;
SYSCTL_UINT(_kern_microstackshot, OID_AUTO, pmi_sample_counter,
    CTLFLAG_RD | CTLFLAG_LOCKED, &microstackshot_pmi_counter, 0,
    "PMI counter");

#endif /* CONFIG_CPU_COUNTERS */

#endif /* CONFIG_TELEMETRY */

/*Remote Time api*/
SYSCTL_NODE(_machdep, OID_AUTO, remotetime, CTLFLAG_RD | CTLFLAG_LOCKED, 0, "Remote time api");

#if DEVELOPMENT || DEBUG
#if CONFIG_MACH_BRIDGE_SEND_TIME
extern _Atomic uint32_t bt_init_flag;
extern uint32_t mach_bridge_timer_enable(uint32_t, int);

SYSCTL_INT(_machdep_remotetime, OID_AUTO, bridge_timer_init_flag,
    CTLFLAG_RD | CTLFLAG_LOCKED, &bt_init_flag, 0, "");

static int sysctl_mach_bridge_timer_enable SYSCTL_HANDLER_ARGS
{
#pragma unused(oidp, arg1, arg2)
	uint32_t value = 0;
	int error = 0;
	/* User is querying buffer size */
	if (req->oldptr == USER_ADDR_NULL && req->newptr == USER_ADDR_NULL) {
		req->oldidx = sizeof(value);
		return 0;
	}
	if (os_atomic_load(&bt_init_flag, acquire)) {
		if (req->newptr) {
			int new_value = 0;
			error = SYSCTL_IN(req, &new_value, sizeof(new_value));
			if (error) {
				return error;
			}
			if (new_value == 0 || new_value == 1) {
				value = mach_bridge_timer_enable(new_value, 1);
			} else {
				return EPERM;
			}
		} else {
			value = mach_bridge_timer_enable(0, 0);
		}
	}
	error = SYSCTL_OUT(req, &value, sizeof(value));
	return error;
}

SYSCTL_PROC(_machdep_remotetime, OID_AUTO, bridge_timer_enable,
    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
    0, 0, sysctl_mach_bridge_timer_enable, "I", "");

#endif /* CONFIG_MACH_BRIDGE_SEND_TIME */

static int sysctl_mach_bridge_remote_time SYSCTL_HANDLER_ARGS
{
#pragma unused(oidp, arg1, arg2)
	uint64_t ltime = 0, rtime = 0;
	if (req->oldptr == USER_ADDR_NULL) {
		req->oldidx = sizeof(rtime);
		return 0;
	}
	if (req->newptr) {
		int error = SYSCTL_IN(req, &ltime, sizeof(ltime));
		if (error) {
			return error;
		}
	}
	rtime = mach_bridge_remote_time(ltime);
	return SYSCTL_OUT(req, &rtime, sizeof(rtime));
}
SYSCTL_PROC(_machdep_remotetime, OID_AUTO, mach_bridge_remote_time,
    CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
    0, 0, sysctl_mach_bridge_remote_time, "Q", "");

#endif /* DEVELOPMENT || DEBUG */

#if CONFIG_MACH_BRIDGE_RECV_TIME
extern struct bt_params bt_params_get_latest(void);

static int sysctl_mach_bridge_conversion_params SYSCTL_HANDLER_ARGS
{
#pragma unused(oidp, arg1, arg2)
	struct bt_params params = {};
	if (req->oldptr == USER_ADDR_NULL) {
		req->oldidx = sizeof(struct bt_params);
		return 0;
	}
	if (req->newptr) {
		return EPERM;
	}
	params = bt_params_get_latest();
	return SYSCTL_OUT(req, &params, MIN(sizeof(params), req->oldlen));
}

SYSCTL_PROC(_machdep_remotetime, OID_AUTO, conversion_params,
    CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0,
    0, sysctl_mach_bridge_conversion_params, "S,bt_params", "");

#endif /* CONFIG_MACH_BRIDGE_RECV_TIME */

#if DEVELOPMENT || DEBUG

/* used for testing by exception_tests */
extern uint32_t ipc_control_port_options;
SYSCTL_INT(_kern, OID_AUTO, ipc_control_port_options,
    CTLFLAG_RD | CTLFLAG_LOCKED, &ipc_control_port_options, 0, "");

#endif /* DEVELOPMENT || DEBUG */

extern uint32_t task_exc_guard_default;

SYSCTL_INT(_kern, OID_AUTO, task_exc_guard_default,
    CTLFLAG_RD | CTLFLAG_LOCKED, &task_exc_guard_default, 0, "");


static int
sysctl_kern_tcsm_available SYSCTL_HANDLER_ARGS
{
#pragma unused(oidp, arg1, arg2)
	uint32_t value = machine_csv(CPUVN_CI) ? 1 : 0;

	if (req->newptr) {
		return EINVAL;
	}

	return SYSCTL_OUT(req, &value, sizeof(value));
}
SYSCTL_PROC(_kern, OID_AUTO, tcsm_available,
    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_MASKED | CTLFLAG_ANYBODY,
    0, 0, sysctl_kern_tcsm_available, "I", "");


static int
sysctl_kern_tcsm_enable SYSCTL_HANDLER_ARGS
{
#pragma unused(oidp, arg1, arg2)
	uint32_t soflags = 0;
#if CONFIG_SCHED_SMT
	uint32_t old_value = thread_get_no_smt() ? 1 : 0;
#else /* CONFIG_SCHED_SMT */
	uint32_t old_value = 0;
#endif /* CONFIG_SCHED_SMT */

	int error = SYSCTL_IN(req, &soflags, sizeof(soflags));
	if (error) {
		return error;
	}

	if (soflags && machine_csv(CPUVN_CI)) {
#if CONFIG_SCHED_SMT
		thread_set_no_smt(true);
#endif /* CONFIG_SCHED_SMT */
		machine_tecs(current_thread());
	}

	return SYSCTL_OUT(req, &old_value, sizeof(old_value));
}
SYSCTL_PROC(_kern, OID_AUTO, tcsm_enable,
    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_MASKED | CTLFLAG_ANYBODY,
    0, 0, sysctl_kern_tcsm_enable, "I", "");

static int
sysctl_kern_debug_get_preoslog SYSCTL_HANDLER_ARGS
{
#pragma unused(oidp, arg1, arg2)
	static bool oneshot_executed = false;
	size_t preoslog_size = 0;
	const char *preoslog = NULL;
	int ret = 0;

	// DumpPanic passes a non-zero write value when it needs oneshot behaviour
	if (req->newptr != USER_ADDR_NULL) {
		uint8_t oneshot = 0;
		int error = SYSCTL_IN(req, &oneshot, sizeof(oneshot));
		if (error) {
			return error;
		}

		if (oneshot) {
			if (!os_atomic_cmpxchg(&oneshot_executed, false, true, acq_rel)) {
				return EPERM;
			}
		}
	}

	preoslog = sysctl_debug_get_preoslog(&preoslog_size);
	if (preoslog != NULL && preoslog_size == 0) {
		sysctl_debug_free_preoslog();
		return 0;
	}

	if (preoslog == NULL || preoslog_size == 0) {
		return 0;
	}

	if (req->oldptr == USER_ADDR_NULL) {
		req->oldidx = preoslog_size;
		return 0;
	}

	ret = SYSCTL_OUT(req, preoslog, preoslog_size);
	sysctl_debug_free_preoslog();
	return ret;
}

SYSCTL_PROC(_kern, OID_AUTO, preoslog, CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_LOCKED,
    0, 0, sysctl_kern_debug_get_preoslog, "-", "");

#if DEVELOPMENT || DEBUG

static int
sysctl_kern_task_set_filter_msg_flag SYSCTL_HANDLER_ARGS
{
#pragma unused(oidp, arg1, arg2)
	int new_value, changed;
	int old_value = task_get_filter_msg_flag(current_task()) ? 1 : 0;
	int error = sysctl_io_number(req, old_value, sizeof(int), &new_value, &changed);

	if (changed) {
		task_set_filter_msg_flag(current_task(), !!new_value);
	}

	return error;
}

SYSCTL_PROC(_kern, OID_AUTO, task_set_filter_msg_flag, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
    0, 0, sysctl_kern_task_set_filter_msg_flag, "I", "");

#if CONFIG_PROC_RESOURCE_LIMITS

extern mach_port_name_t current_task_get_fatal_port_name(void);

static int
sysctl_kern_task_get_fatal_port SYSCTL_HANDLER_ARGS
{
#pragma unused(oidp, arg1, arg2)
	int port = 0;
	int flag = 0;

	if (req->oldptr == USER_ADDR_NULL) {
		req->oldidx = sizeof(mach_port_t);
		return 0;
	}

	int error = SYSCTL_IN(req, &flag, sizeof(flag));
	if (error) {
		return error;
	}

	if (flag == 1) {
		port = (int)current_task_get_fatal_port_name();
	}
	return SYSCTL_OUT(req, &port, sizeof(port));
}

SYSCTL_PROC(_machdep, OID_AUTO, task_get_fatal_port, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
    0, 0, sysctl_kern_task_get_fatal_port, "I", "");

#endif /* CONFIG_PROC_RESOURCE_LIMITS */

extern unsigned int ipc_entry_table_count_max(void);

static int
sysctl_mach_max_port_table_size SYSCTL_HANDLER_ARGS
{
#pragma unused(oidp, arg1, arg2)
	int old_value = ipc_entry_table_count_max();
	int error = sysctl_io_number(req, old_value, sizeof(int), NULL, NULL);

	return error;
}

SYSCTL_PROC(_machdep, OID_AUTO, max_port_table_size, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
    0, 0, sysctl_mach_max_port_table_size, "I", "");

#endif /* DEVELOPMENT || DEBUG */

#if defined(CONFIG_KDP_INTERACTIVE_DEBUGGING) && defined(CONFIG_KDP_COREDUMP_ENCRYPTION)

#define COREDUMP_ENCRYPTION_KEY_ENTITLEMENT "com.apple.private.coredump-encryption-key"

static int
sysctl_coredump_encryption_key_update SYSCTL_HANDLER_ARGS
{
	kern_return_t ret = KERN_SUCCESS;
	int error = 0;
	struct kdp_core_encryption_key_descriptor key_descriptor = {
		.kcekd_format = MACH_CORE_FILEHEADER_V2_FLAG_NEXT_COREFILE_KEY_FORMAT_NIST_P256,
	};

	/* Need to be root and have entitlement */
	if (!kauth_cred_issuser(kauth_cred_get()) && !IOCurrentTaskHasEntitlement(COREDUMP_ENCRYPTION_KEY_ENTITLEMENT)) {
		return EPERM;
	}

	// Sanity-check the given key length
	if (req->newlen > UINT16_MAX) {
		return EINVAL;
	}

	// It is allowed for the caller to pass in a NULL buffer.
	// This indicates that they want us to forget about any public key we might have.
	if (req->newptr) {
		key_descriptor.kcekd_size = (uint16_t) req->newlen;
		key_descriptor.kcekd_key = kalloc_data(key_descriptor.kcekd_size, Z_WAITOK);

		if (key_descriptor.kcekd_key == NULL) {
			return ENOMEM;
		}

		error = SYSCTL_IN(req, key_descriptor.kcekd_key, key_descriptor.kcekd_size);
		if (error) {
			goto out;
		}
	}

	ret = IOProvideCoreFileAccess(kdp_core_handle_new_encryption_key, (void *)&key_descriptor);
	if (KERN_SUCCESS != ret) {
		printf("Failed to handle the new encryption key. Error 0x%x", ret);
		error = EFAULT;
	}

out:
	kfree_data(key_descriptor.kcekd_key, key_descriptor.kcekd_size);
	return 0;
}

SYSCTL_PROC(_kern, OID_AUTO, coredump_encryption_key, CTLTYPE_OPAQUE | CTLFLAG_WR | CTLFLAG_LOCKED | CTLFLAG_MASKED,
    0, 0, &sysctl_coredump_encryption_key_update, "-", "Set a new encryption key for coredumps");

#endif /* CONFIG_KDP_INTERACTIVE_DEBUGGING && CONFIG_KDP_COREDUMP_ENCRYPTION*/