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
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
/*
 * Copyright (c) 2000-2015 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) 1982, 1986, 1989, 1990, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * sendfile(2) and related extensions:
 * Copyright (c) 1998, David Greenman. 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. 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.
 *
 *	@(#)uipc_syscalls.c	8.4 (Berkeley) 2/21/94
 */
/*
 * NOTICE: This file was modified by SPARTA, Inc. in 2005 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/cdefs.h>
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/filedesc.h>
#include <sys/proc_internal.h>
#include <sys/file_internal.h>
#include <sys/vnode_internal.h>
#include <sys/malloc.h>
#include <sys/mcache.h>
#include <sys/mbuf.h>
#include <kern/locks.h>
#include <sys/domain.h>
#include <sys/protosw.h>
#include <sys/signalvar.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/kernel.h>
#include <sys/uio_internal.h>
#include <sys/kauth.h>
#include <kern/task.h>
#include <sys/priv.h>
#include <sys/sysctl.h>
#include <sys/sys_domain.h>
#include <sys/types.h>

#include <security/audit/audit.h>

#include <sys/kdebug.h>
#include <sys/sysproto.h>
#include <netinet/in.h>
#include <net/route.h>
#include <netinet/in_pcb.h>

#include <os/log.h>
#include <os/ptrtools.h>

#include <os/log.h>

#if CONFIG_MACF_SOCKET_SUBSET
#include <security/mac_framework.h>
#endif /* MAC_SOCKET_SUBSET */

#define f_flag fp_glob->fg_flag
#define f_ops fp_glob->fg_ops

#define DBG_LAYER_IN_BEG        NETDBG_CODE(DBG_NETSOCK, 0)
#define DBG_LAYER_IN_END        NETDBG_CODE(DBG_NETSOCK, 2)
#define DBG_LAYER_OUT_BEG       NETDBG_CODE(DBG_NETSOCK, 1)
#define DBG_LAYER_OUT_END       NETDBG_CODE(DBG_NETSOCK, 3)
#define DBG_FNC_SENDMSG         NETDBG_CODE(DBG_NETSOCK, (1 << 8) | 1)
#define DBG_FNC_SENDTO          NETDBG_CODE(DBG_NETSOCK, (2 << 8) | 1)
#define DBG_FNC_SENDIT          NETDBG_CODE(DBG_NETSOCK, (3 << 8) | 1)
#define DBG_FNC_RECVFROM        NETDBG_CODE(DBG_NETSOCK, (5 << 8))
#define DBG_FNC_RECVMSG         NETDBG_CODE(DBG_NETSOCK, (6 << 8))
#define DBG_FNC_RECVIT          NETDBG_CODE(DBG_NETSOCK, (7 << 8))
#define DBG_FNC_SENDFILE        NETDBG_CODE(DBG_NETSOCK, (10 << 8))
#define DBG_FNC_SENDFILE_WAIT   NETDBG_CODE(DBG_NETSOCK, ((10 << 8) | 1))
#define DBG_FNC_SENDFILE_READ   NETDBG_CODE(DBG_NETSOCK, ((10 << 8) | 2))
#define DBG_FNC_SENDFILE_SEND   NETDBG_CODE(DBG_NETSOCK, ((10 << 8) | 3))
#define DBG_FNC_SENDMSG_X       NETDBG_CODE(DBG_NETSOCK, (11 << 8))
#define DBG_FNC_RECVMSG_X       NETDBG_CODE(DBG_NETSOCK, (12 << 8))

/* Forward declarations for referenced types */
__CCT_DECLARE_CONSTRAINED_PTR_TYPE(void, void, __CCT_PTR);
__CCT_DECLARE_CONSTRAINED_PTR_TYPE(uint8_t, uint8_t, __CCT_PTR);
__CCT_DECLARE_CONSTRAINED_PTR_TYPE(int32_t, int32, __CCT_REF);
__CCT_DECLARE_CONSTRAINED_PTR_TYPE(int, int, __CCT_REF);
__CCT_DECLARE_CONSTRAINED_PTR_TYPE(user_ssize_t, user_ssize, __CCT_REF);
__CCT_DECLARE_CONSTRAINED_PTR_TYPE(unsigned int, uint, __CCT_REF);
__CCT_DECLARE_CONSTRAINED_PTR_TYPE(sae_connid_t, sae_connid, __CCT_REF);
__CCT_DECLARE_CONSTRAINED_PTR_TYPE(socklen_t, socklen, __CCT_REF);
__CCT_DECLARE_CONSTRAINED_PTR_TYPE(struct setsockopt_args, setsockopt_args, __CCT_REF);
__CCT_DECLARE_CONSTRAINED_PTR_TYPE(struct connectx_args, connectx_args, __CCT_REF);
__CCT_DECLARE_CONSTRAINED_PTR_TYPE(struct disconnectx_args, disconnectx_args, __CCT_REF);
__CCT_DECLARE_CONSTRAINED_PTR_TYPE(struct cmsghdr, cmsghdr, __CCT_REF);
__CCT_DECLARE_CONSTRAINED_PTR_TYPE(struct timeval, timeval, __CCT_REF);
__CCT_DECLARE_CONSTRAINED_PTR_TYPE(struct user64_timeval, user64_timeval, __CCT_REF);
__CCT_DECLARE_CONSTRAINED_PTR_TYPE(struct user32_timeval, user32_timeval, __CCT_REF);

static int sendit(proc_ref_t, socket_ref_t, user_msghdr_ref_t, uio_t,
    int, int32_ref_t );
static int recvit(proc_ref_t, int, user_msghdr_ref_t, uio_t, user_addr_t,
    int32_ref_t);
static int connectit(socket_ref_t, sockaddr_ref_t);
static int getsockaddr(socket_ref_t, sockaddr_ref_ref_t, user_addr_t,
    size_t, boolean_t);
static int getsockaddr_s(socket_ref_t, sockaddr_storage_ref_t,
    user_addr_t, size_t, boolean_t);
#if SENDFILE
static void alloc_sendpkt(int, size_t, uint_ref_t, mbuf_ref_ref_t,
    boolean_t);
#endif /* SENDFILE */
static int connectx_nocancel(proc_ref_t, connectx_args_ref_t, int_ref_t);
static int connectitx(socket_ref_t, sockaddr_ref_t,
    sockaddr_ref_t, proc_ref_t, uint32_t, sae_associd_t,
    sae_connid_ref_t, uio_t, unsigned int, user_ssize_ref_t);
static int disconnectx_nocancel(proc_ref_t, disconnectx_args_ref_t,
    int_ref_t);
static int socket_common(proc_ref_t, int, int, int, pid_t, int32_ref_t, int);

#if DEBUG || DEVELOPMENT
static int internalize_user_msghdr_array(const void_ptr_t, int, int,
    u_int count, user_msghdr_x_ptr_t, uio_ref_ptr_t);

static void externalize_user_msghdr_array(void_ptr_t, int, int, u_int count,
    const user_msghdr_x_ptr_t, uio_ref_ptr_t);

static void free_uio_array(uio_ref_ptr_t, u_int count);
static boolean_t uio_array_is_valid(uio_ref_ptr_t, u_int count);
#endif /* DEBUG || DEVELOPMENT */
static int internalize_recv_msghdr_array(const void_ptr_t, int, int,
    u_int count, user_msghdr_x_ptr_t, recv_msg_elem_ptr_t);
static u_int externalize_recv_msghdr_array(proc_ref_t, socket_ref_t, void_ptr_t,
    u_int count, user_msghdr_x_ptr_t, recv_msg_elem_ptr_t, int_ref_t);

static recv_msg_elem_ptr_t alloc_recv_msg_array(u_int count);
static int recv_msg_array_is_valid(recv_msg_elem_ptr_t, u_int count);
static void free_recv_msg_array(recv_msg_elem_ptr_t, u_int count);
static int copyout_control(proc_ref_t, mbuf_ref_t, user_addr_t control,
    socklen_ref_t, int_ref_t, socket_ref_t);

SYSCTL_DECL(_kern_ipc);

#define SO_MAX_MSG_X_DEFAULT 256

static u_int somaxsendmsgx = SO_MAX_MSG_X_DEFAULT;
SYSCTL_UINT(_kern_ipc, OID_AUTO, maxsendmsgx,
    CTLFLAG_RW | CTLFLAG_LOCKED, &somaxsendmsgx, 0, "");

static u_int somaxrecvmsgx = SO_MAX_MSG_X_DEFAULT;
SYSCTL_UINT(_kern_ipc, OID_AUTO, maxrecvmsgx,
    CTLFLAG_RW | CTLFLAG_LOCKED, &somaxrecvmsgx, 0, "");

static u_int missingpktinfo = 0;
SYSCTL_UINT(_kern_ipc, OID_AUTO, missingpktinfo,
    CTLFLAG_RD | CTLFLAG_LOCKED, &missingpktinfo, 0, "");

static int do_recvmsg_x_donttrunc = 0;
SYSCTL_INT(_kern_ipc, OID_AUTO, do_recvmsg_x_donttrunc,
    CTLFLAG_RW | CTLFLAG_LOCKED, &do_recvmsg_x_donttrunc, 0, "");

#if DEBUG || DEVELOPMENT
static int uipc_debug = 0;
SYSCTL_INT(_kern_ipc, OID_AUTO, debug,
    CTLFLAG_RW | CTLFLAG_LOCKED, &uipc_debug, 0, "");

#define DEBUG_KERNEL_ADDRPERM(_v) (_v)
#define DBG_PRINTF(...) if (uipc_debug != 0) {  \
    os_log(OS_LOG_DEFAULT, __VA_ARGS__);        \
}
#else
#define DEBUG_KERNEL_ADDRPERM(_v) VM_KERNEL_ADDRPERM(_v)
#define DBG_PRINTF(...) do { } while (0)
#endif


/*
 * Values for sendmsg_x_mode
 * 0: default
 * 1: sendit loop one at a time
 * 2: old implementation
 */
static u_int sendmsg_x_mode = 0;
SYSCTL_UINT(_kern_ipc, OID_AUTO, sendmsg_x_mode,
    CTLFLAG_RW | CTLFLAG_LOCKED, &sendmsg_x_mode, 0, "");

/*
 * System call interface to the socket abstraction.
 */

extern const struct fileops socketops;

/*
 * Returns:	0			Success
 *		EACCES			Mandatory Access Control failure
 *	falloc:ENFILE
 *	falloc:EMFILE
 *	falloc:ENOMEM
 *	socreate:EAFNOSUPPORT
 *	socreate:EPROTOTYPE
 *	socreate:EPROTONOSUPPORT
 *	socreate:ENOBUFS
 *	socreate:ENOMEM
 *	socreate:???			[other protocol families, IPSEC]
 */
int
socket(proc_ref_t p,
    struct socket_args *uap,
    int32_ref_t retval)
{
	return socket_common(p, uap->domain, uap->type, uap->protocol,
	           proc_selfpid(), retval, 0);
}

int
socket_delegate(proc_ref_t p,
    struct socket_delegate_args *uap,
    int32_ref_t retval)
{
	return socket_common(p, uap->domain, uap->type, uap->protocol,
	           uap->epid, retval, 1);
}

static int
socket_common(proc_ref_t p,
    int domain,
    int type,
    int protocol,
    pid_t epid,
    int32_ref_t retval,
    int delegate)
{
	socket_ref_t so;
	fileproc_ref_t  fp;
	int fd, error;

	AUDIT_ARG(socket, domain, type, protocol);
#if CONFIG_MACF_SOCKET_SUBSET
	if ((error = mac_socket_check_create(kauth_cred_get(), domain,
	    type, protocol)) != 0) {
		return error;
	}
#endif /* MAC_SOCKET_SUBSET */

	if (delegate) {
		error = priv_check_cred(kauth_cred_get(),
		    PRIV_NET_PRIVILEGED_SOCKET_DELEGATE, 0);
		if (error) {
			return EACCES;
		}
	}

	error = falloc(p, &fp, &fd, vfs_context_current());
	if (error) {
		return error;
	}
	fp->f_flag = FREAD | FWRITE;
	fp->f_ops = &socketops;

	if (delegate) {
		error = socreate_delegate(domain, &so, type, protocol, epid);
	} else {
		error = socreate(domain, &so, type, protocol);
	}

	if (error) {
		fp_free(p, fd, fp);
	} else {
		fp_set_data(fp, so);

		proc_fdlock(p);
		procfdtbl_releasefd(p, fd, NULL);

		if (ENTR_SHOULDTRACE) {
			KERNEL_ENERGYTRACE(kEnTrActKernSocket, DBG_FUNC_START,
			    fd, 0, (int64_t)VM_KERNEL_ADDRPERM(so));
		}
		fp_drop(p, fd, fp, 1);
		proc_fdunlock(p);

		*retval = fd;
	}
	return error;
}

/*
 * Returns:	0			Success
 *		EDESTADDRREQ		Destination address required
 *		EBADF			Bad file descriptor
 *		EACCES			Mandatory Access Control failure
 *	file_socket:ENOTSOCK
 *	file_socket:EBADF
 *	getsockaddr:ENAMETOOLONG	Filename too long
 *	getsockaddr:EINVAL		Invalid argument
 *	getsockaddr:ENOMEM		Not enough space
 *	getsockaddr:EFAULT		Bad address
 *	sobindlock:???
 */
/* ARGSUSED */
int
bind(__unused proc_t p, struct bind_args *uap, __unused int32_ref_t retval)
{
	struct sockaddr_storage ss;
	sockaddr_ref_t  sa = NULL;
	socket_ref_t so;
	boolean_t want_free = TRUE;
	int error;

	AUDIT_ARG(fd, uap->s);
	error = file_socket(uap->s, &so);
	if (error != 0) {
		return error;
	}
	if (so == NULL) {
		error = EBADF;
		goto out;
	}
	if (uap->name == USER_ADDR_NULL) {
		error = EDESTADDRREQ;
		goto out;
	}
	if (uap->namelen > sizeof(ss)) {
		error = getsockaddr(so, &sa, uap->name, uap->namelen, TRUE);
	} else {
		error = getsockaddr_s(so, &ss, uap->name, uap->namelen, TRUE);
		if (error == 0) {
			sa = (sockaddr_ref_t)&ss;
			want_free = FALSE;
		}
	}
	if (error != 0) {
		goto out;
	}
	AUDIT_ARG(sockaddr, vfs_context_cwd(vfs_context_current()), sa);
#if CONFIG_MACF_SOCKET_SUBSET
	if ((sa != NULL && sa->sa_family == AF_SYSTEM) ||
	    (error = mac_socket_check_bind(kauth_cred_get(), so, sa)) == 0) {
		error = sobindlock(so, sa, 1);  /* will lock socket */
	}
#else
	error = sobindlock(so, sa, 1);          /* will lock socket */
#endif /* MAC_SOCKET_SUBSET */
	if (want_free) {
		free_sockaddr(sa);
	}
out:
	file_drop(uap->s);
	return error;
}

/*
 * Returns:	0			Success
 *		EBADF
 *		EACCES			Mandatory Access Control failure
 *	file_socket:ENOTSOCK
 *	file_socket:EBADF
 *	solisten:EINVAL
 *	solisten:EOPNOTSUPP
 *	solisten:???
 */
int
listen(__unused proc_ref_t p, struct listen_args *uap,
    __unused int32_ref_t retval)
{
	int error;
	socket_ref_t so;

	AUDIT_ARG(fd, uap->s);
	error = file_socket(uap->s, &so);
	if (error) {
		return error;
	}
	if (so != NULL)
#if CONFIG_MACF_SOCKET_SUBSET
	{
		error = mac_socket_check_listen(kauth_cred_get(), so);
		if (error == 0) {
			error = solisten(so, uap->backlog);
		}
	}
#else
	{ error = solisten(so, uap->backlog);}
#endif /* MAC_SOCKET_SUBSET */
	else {
		error = EBADF;
	}

	file_drop(uap->s);
	return error;
}

/*
 * Returns:	fp_get_ftype:EBADF	Bad file descriptor
 *		fp_get_ftype:ENOTSOCK	Socket operation on non-socket
 *		:EFAULT			Bad address on copyin/copyout
 *		:EBADF			Bad file descriptor
 *		:EOPNOTSUPP		Operation not supported on socket
 *		:EINVAL			Invalid argument
 *		:EWOULDBLOCK		Operation would block
 *		:ECONNABORTED		Connection aborted
 *		:EINTR			Interrupted function
 *		:EACCES			Mandatory Access Control failure
 *		falloc:ENFILE		Too many files open in system
 *		falloc:EMFILE		Too many open files
 *		falloc:ENOMEM		Not enough space
 *		0			Success
 */
int
accept_nocancel(proc_ref_t p, struct accept_nocancel_args *uap,
    int32_ref_t retval)
{
	fileproc_ref_t  fp;
	sockaddr_ref_t  sa = NULL;
	socklen_t namelen;
	int error;
	socket_ref_t  head;
	socket_ref_t so = NULL;
	lck_mtx_t *mutex_held;
	int fd = uap->s;
	int newfd;
	unsigned int fflag;
	int dosocklock = 0;

	*retval = -1;

	AUDIT_ARG(fd, uap->s);

	if (uap->name) {
		error = copyin(uap->anamelen, (caddr_t)&namelen,
		    sizeof(socklen_t));
		if (error) {
			return error;
		}
	}
	error = fp_get_ftype(p, fd, DTYPE_SOCKET, ENOTSOCK, &fp);
	if (error) {
		return error;
	}
	head = (struct socket *)fp_get_data(fp);

#if CONFIG_MACF_SOCKET_SUBSET
	if ((error = mac_socket_check_accept(kauth_cred_get(), head)) != 0) {
		goto out;
	}
#endif /* MAC_SOCKET_SUBSET */

	socket_lock(head, 1);

	if (head->so_proto->pr_getlock != NULL) {
		mutex_held = (*head->so_proto->pr_getlock)(head, PR_F_WILLUNLOCK);
		dosocklock = 1;
	} else {
		mutex_held = head->so_proto->pr_domain->dom_mtx;
		dosocklock = 0;
	}

	if ((head->so_options & SO_ACCEPTCONN) == 0) {
		if ((head->so_proto->pr_flags & PR_CONNREQUIRED) == 0) {
			error = EOPNOTSUPP;
		} else {
			/* POSIX: The socket is not accepting connections */
			error = EINVAL;
		}
		socket_unlock(head, 1);
		goto out;
	}
check_again:
	if ((head->so_state & SS_NBIO) && head->so_comp.tqh_first == NULL) {
		socket_unlock(head, 1);
		error = EWOULDBLOCK;
		goto out;
	}
	while (TAILQ_EMPTY(&head->so_comp) && head->so_error == 0) {
		if (head->so_state & SS_CANTRCVMORE) {
			head->so_error = ECONNABORTED;
			break;
		}
		if (head->so_usecount < 1) {
			panic("accept: head=%p refcount=%d", head,
			    head->so_usecount);
		}
		error = msleep((caddr_t)&head->so_timeo, mutex_held,
		    PSOCK | PCATCH, "accept", 0);
		if (head->so_usecount < 1) {
			panic("accept: 2 head=%p refcount=%d", head,
			    head->so_usecount);
		}
		if ((head->so_state & SS_DRAINING)) {
			error = ECONNABORTED;
		}
		if (error) {
			socket_unlock(head, 1);
			goto out;
		}
	}
	if (head->so_error) {
		error = head->so_error;
		head->so_error = 0;
		socket_unlock(head, 1);
		goto out;
	}

	/*
	 * At this point we know that there is at least one connection
	 * ready to be accepted. Remove it from the queue prior to
	 * allocating the file descriptor for it since falloc() may
	 * block allowing another process to accept the connection
	 * instead.
	 */
	lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);

	so_acquire_accept_list(head, NULL);
	if (TAILQ_EMPTY(&head->so_comp)) {
		so_release_accept_list(head);
		goto check_again;
	}

	so = TAILQ_FIRST(&head->so_comp);
	TAILQ_REMOVE(&head->so_comp, so, so_list);
	/*
	 * Acquire the lock of the new connection
	 * as we may be in the process of receiving
	 * a packet that may change its so_state
	 * (e.g.: a TCP FIN).
	 */
	if (dosocklock) {
		socket_lock(so, 0);
	}
	so->so_head = NULL;
	so->so_state &= ~SS_COMP;
	if (dosocklock) {
		socket_unlock(so, 0);
	}
	head->so_qlen--;
	so_release_accept_list(head);

	/* unlock head to avoid deadlock with select, keep a ref on head */
	socket_unlock(head, 0);

#if CONFIG_MACF_SOCKET_SUBSET
	/*
	 * Pass the pre-accepted socket to the MAC framework. This is
	 * cheaper than allocating a file descriptor for the socket,
	 * calling the protocol accept callback, and possibly freeing
	 * the file descriptor should the MAC check fails.
	 */
	if ((error = mac_socket_check_accepted(kauth_cred_get(), so)) != 0) {
		socket_lock(so, 1);
		so->so_state &= ~SS_NOFDREF;
		socket_unlock(so, 1);
		soclose(so);
		/* Drop reference on listening socket */
		sodereference(head);
		goto out;
	}
#endif /* MAC_SOCKET_SUBSET */

	/*
	 * Pass the pre-accepted socket to any interested socket filter(s).
	 * Upon failure, the socket would have been closed by the callee.
	 */
	if (so->so_filt != NULL && (error = soacceptfilter(so, head)) != 0) {
		/* Drop reference on listening socket */
		sodereference(head);
		/* Propagate socket filter's error code to the caller */
		goto out;
	}

	fflag = fp->f_flag;
	error = falloc(p, &fp, &newfd, vfs_context_current());
	if (error) {
		/*
		 * Probably ran out of file descriptors.
		 *
		 * <rdar://problem/8554930>
		 * Don't put this back on the socket like we used to, that
		 * just causes the client to spin. Drop the socket.
		 */
		socket_lock(so, 1);
		so->so_state &= ~SS_NOFDREF;
		socket_unlock(so, 1);
		soclose(so);
		sodereference(head);
		goto out;
	}
	*retval = newfd;
	fp->f_flag = fflag;
	fp->f_ops = &socketops;
	fp_set_data(fp, so);

	socket_lock(head, 0);
	if (dosocklock) {
		socket_lock(so, 1);
	}

	/* Sync socket non-blocking/async state with file flags */
	if (fp->f_flag & FNONBLOCK) {
		so->so_state |= SS_NBIO;
	} else {
		so->so_state &= ~SS_NBIO;
	}

	if (fp->f_flag & FASYNC) {
		so->so_state |= SS_ASYNC;
		so->so_rcv.sb_flags |= SB_ASYNC;
		so->so_snd.sb_flags |= SB_ASYNC;
	} else {
		so->so_state &= ~SS_ASYNC;
		so->so_rcv.sb_flags &= ~SB_ASYNC;
		so->so_snd.sb_flags &= ~SB_ASYNC;
	}

	(void) soacceptlock(so, &sa, 0);
	socket_unlock(head, 1);
	if (sa == NULL) {
		namelen = 0;
		if (uap->name) {
			goto gotnoname;
		}
		error = 0;
		goto releasefd;
	}
	AUDIT_ARG(sockaddr, vfs_context_cwd(vfs_context_current()), sa);

	if (uap->name) {
		socklen_t       sa_len;

		/* save sa_len before it is destroyed */
		sa_len = sa->sa_len;
		namelen = MIN(namelen, sa_len);
		error = copyout(sa, uap->name, namelen);
		if (!error) {
			/* return the actual, untruncated address length */
			namelen = sa_len;
		}
gotnoname:
		error = copyout((caddr_t)&namelen, uap->anamelen,
		    sizeof(socklen_t));
	}
	free_sockaddr(sa);

releasefd:
	/*
	 * If the socket has been marked as inactive by sosetdefunct(),
	 * disallow further operations on it.
	 */
	if (so->so_flags & SOF_DEFUNCT) {
		sodefunct(current_proc(), so,
		    SHUTDOWN_SOCKET_LEVEL_DISCONNECT_INTERNAL);
	}

	if (dosocklock) {
		socket_unlock(so, 1);
	}

	proc_fdlock(p);
	procfdtbl_releasefd(p, newfd, NULL);
	fp_drop(p, newfd, fp, 1);
	proc_fdunlock(p);

out:
	if (error == 0 && ENTR_SHOULDTRACE) {
		KERNEL_ENERGYTRACE(kEnTrActKernSocket, DBG_FUNC_START,
		    newfd, 0, (int64_t)VM_KERNEL_ADDRPERM(so));
	}

	file_drop(fd);
	return error;
}

int
accept(proc_ref_t p, struct accept_args *uap, int32_ref_t retval)
{
	__pthread_testcancel(1);
	return accept_nocancel(p, (struct accept_nocancel_args *)uap,
	           retval);
}

/*
 * Returns:	0			Success
 *		EBADF			Bad file descriptor
 *		EALREADY		Connection already in progress
 *		EINPROGRESS		Operation in progress
 *		ECONNABORTED		Connection aborted
 *		EINTR			Interrupted function
 *		EACCES			Mandatory Access Control failure
 *	file_socket:ENOTSOCK
 *	file_socket:EBADF
 *	getsockaddr:ENAMETOOLONG	Filename too long
 *	getsockaddr:EINVAL		Invalid argument
 *	getsockaddr:ENOMEM		Not enough space
 *	getsockaddr:EFAULT		Bad address
 *	soconnectlock:EOPNOTSUPP
 *	soconnectlock:EISCONN
 *	soconnectlock:???		[depends on protocol, filters]
 *	msleep:EINTR
 *
 * Imputed:	so_error		error may be set from so_error, which
 *					may have been set by soconnectlock.
 */
/* ARGSUSED */
int
connect(proc_ref_t p, struct connect_args *uap, int32_ref_t retval)
{
	__pthread_testcancel(1);
	return connect_nocancel(p, (struct connect_nocancel_args *)uap,
	           retval);
}

int
connect_nocancel(proc_t p, struct connect_nocancel_args *uap, int32_ref_t retval)
{
#pragma unused(p, retval)
	socket_ref_t so;
	struct sockaddr_storage ss;
	sockaddr_ref_t  sa = NULL;
	int error;
	int fd = uap->s;
	boolean_t dgram;

	AUDIT_ARG(fd, uap->s);
	error = file_socket(fd, &so);
	if (error != 0) {
		return error;
	}
	if (so == NULL) {
		error = EBADF;
		goto out;
	}

	/*
	 * Ask getsockaddr{_s} to not translate AF_UNSPEC to AF_INET
	 * if this is a datagram socket; translate for other types.
	 */
	dgram = (so->so_type == SOCK_DGRAM);

	/* Get socket address now before we obtain socket lock */
	if (uap->namelen > sizeof(ss)) {
		error = getsockaddr(so, &sa, uap->name, uap->namelen, !dgram);
	} else {
		error = getsockaddr_s(so, &ss, uap->name, uap->namelen, !dgram);
		if (error == 0) {
			sa = (sockaddr_ref_t)&ss;
		}
	}
	if (error != 0) {
		goto out;
	}

	error = connectit(so, sa);

	if (sa != NULL && sa != SA(&ss)) {
		free_sockaddr(sa);
	}
	if (error == ERESTART) {
		error = EINTR;
	}
out:
	file_drop(fd);
	return error;
}

static int
connectx_nocancel(proc_ref_t p, connectx_args_ref_t uap, int_ref_t retval)
{
#pragma unused(p, retval)
	struct sockaddr_storage ss, sd;
	sockaddr_ref_t  src = NULL, dst = NULL;
	socket_ref_t so;
	int error, error1, fd = uap->socket;
	boolean_t dgram;
	sae_connid_t cid = SAE_CONNID_ANY;
	struct user32_sa_endpoints ep32;
	struct user64_sa_endpoints ep64;
	struct user_sa_endpoints ep;
	user_ssize_t bytes_written = 0;
	struct user_iovec *iovp;
	uio_t auio = NULL;

	AUDIT_ARG(fd, uap->socket);
	error = file_socket(fd, &so);
	if (error != 0) {
		return error;
	}
	if (so == NULL) {
		error = EBADF;
		goto out;
	}

	if (uap->endpoints == USER_ADDR_NULL) {
		error = EINVAL;
		goto out;
	}

	if (IS_64BIT_PROCESS(p)) {
		error = copyin(uap->endpoints, (caddr_t)&ep64, sizeof(ep64));
		if (error != 0) {
			goto out;
		}

		ep.sae_srcif = ep64.sae_srcif;
		ep.sae_srcaddr = (user_addr_t)ep64.sae_srcaddr;
		ep.sae_srcaddrlen = ep64.sae_srcaddrlen;
		ep.sae_dstaddr = (user_addr_t)ep64.sae_dstaddr;
		ep.sae_dstaddrlen = ep64.sae_dstaddrlen;
	} else {
		error = copyin(uap->endpoints, (caddr_t)&ep32, sizeof(ep32));
		if (error != 0) {
			goto out;
		}

		ep.sae_srcif = ep32.sae_srcif;
		ep.sae_srcaddr = ep32.sae_srcaddr;
		ep.sae_srcaddrlen = ep32.sae_srcaddrlen;
		ep.sae_dstaddr = ep32.sae_dstaddr;
		ep.sae_dstaddrlen = ep32.sae_dstaddrlen;
	}

	/*
	 * Ask getsockaddr{_s} to not translate AF_UNSPEC to AF_INET
	 * if this is a datagram socket; translate for other types.
	 */
	dgram = (so->so_type == SOCK_DGRAM);

	/* Get socket address now before we obtain socket lock */
	if (ep.sae_srcaddr != USER_ADDR_NULL) {
		if (ep.sae_srcaddrlen > sizeof(ss)) {
			error = getsockaddr(so, &src, ep.sae_srcaddr, ep.sae_srcaddrlen, dgram);
		} else {
			error = getsockaddr_s(so, &ss, ep.sae_srcaddr, ep.sae_srcaddrlen, dgram);
			if (error == 0) {
				src = (sockaddr_ref_t)&ss;
			}
		}

		if (error) {
			goto out;
		}
	}

	if (ep.sae_dstaddr == USER_ADDR_NULL) {
		error = EINVAL;
		goto out;
	}

	/* Get socket address now before we obtain socket lock */
	if (ep.sae_dstaddrlen > sizeof(sd)) {
		error = getsockaddr(so, &dst, ep.sae_dstaddr, ep.sae_dstaddrlen, dgram);
	} else {
		error = getsockaddr_s(so, &sd, ep.sae_dstaddr, ep.sae_dstaddrlen, dgram);
		if (error == 0) {
			dst = (sockaddr_ref_t)&sd;
		}
	}

	if (error) {
		goto out;
	}

	VERIFY(dst != NULL);

	if (uap->iov != USER_ADDR_NULL) {
		/* Verify range before calling uio_create() */
		if (uap->iovcnt <= 0 || uap->iovcnt > UIO_MAXIOV) {
			error = EINVAL;
			goto out;
		}

		if (uap->len == USER_ADDR_NULL) {
			error = EINVAL;
			goto out;
		}

		/* allocate a uio to hold the number of iovecs passed */
		auio = uio_create(uap->iovcnt, 0,
		    (IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32),
		    UIO_WRITE);

		if (auio == NULL) {
			error = ENOMEM;
			goto out;
		}

		/*
		 * get location of iovecs within the uio.
		 * then copyin the iovecs from user space.
		 */
		iovp = uio_iovsaddr(auio);
		if (iovp == NULL) {
			error = ENOMEM;
			goto out;
		}
		error = copyin_user_iovec_array(uap->iov,
		    IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32,
		    uap->iovcnt, iovp);
		if (error != 0) {
			goto out;
		}

		/* finish setup of uio_t */
		error = uio_calculateresid(auio);
		if (error != 0) {
			goto out;
		}
	}

	error = connectitx(so, src, dst, p, ep.sae_srcif, uap->associd,
	    &cid, auio, uap->flags, &bytes_written);
	if (error == ERESTART) {
		error = EINTR;
	}

	if (uap->len != USER_ADDR_NULL) {
		if (IS_64BIT_PROCESS(p)) {
			error1 = copyout(&bytes_written, uap->len, sizeof(user64_size_t));
		} else {
			error1 = copyout(&bytes_written, uap->len, sizeof(user32_size_t));
		}
		/* give precedence to connectitx errors */
		if ((error1 != 0) && (error == 0)) {
			error = error1;
		}
	}

	if (uap->connid != USER_ADDR_NULL) {
		error1 = copyout(&cid, uap->connid, sizeof(cid));
		/* give precedence to connectitx errors */
		if ((error1 != 0) && (error == 0)) {
			error = error1;
		}
	}
out:
	file_drop(fd);
	if (auio != NULL) {
		uio_free(auio);
	}
	if (src != NULL && src != SA(&ss)) {
		free_sockaddr(src);
	}
	if (dst != NULL && dst != SA(&sd)) {
		free_sockaddr(dst);
	}
	return error;
}

int
connectx(proc_ref_t p, struct connectx_args *uap, int *retval)
{
	/*
	 * Due to similiarity with a POSIX interface, define as
	 * an unofficial cancellation point.
	 */
	__pthread_testcancel(1);
	return connectx_nocancel(p, uap, retval);
}

static int
connectit(struct socket *so, sockaddr_ref_t sa)
{
	int error;

	AUDIT_ARG(sockaddr, vfs_context_cwd(vfs_context_current()), sa);
#if CONFIG_MACF_SOCKET_SUBSET
	if ((error = mac_socket_check_connect(kauth_cred_get(), so, sa)) != 0) {
		return error;
	}
#endif /* MAC_SOCKET_SUBSET */

	socket_lock(so, 1);
	if ((so->so_state & SS_NBIO) && (so->so_state & SS_ISCONNECTING)) {
		error = EALREADY;
		goto out;
	}
	error = soconnectlock(so, sa, 0);
	if (error != 0) {
		goto out;
	}
	if ((so->so_state & SS_NBIO) && (so->so_state & SS_ISCONNECTING)) {
		error = EINPROGRESS;
		goto out;
	}
	while ((so->so_state & SS_ISCONNECTING) && so->so_error == 0) {
		lck_mtx_t *mutex_held;

		if (so->so_proto->pr_getlock != NULL) {
			mutex_held = (*so->so_proto->pr_getlock)(so, PR_F_WILLUNLOCK);
		} else {
			mutex_held = so->so_proto->pr_domain->dom_mtx;
		}
		error = msleep((caddr_t)&so->so_timeo, mutex_held,
		    PSOCK | PCATCH, __func__, 0);
		if (so->so_state & SS_DRAINING) {
			error = ECONNABORTED;
		}
		if (error != 0) {
			break;
		}
	}
	if (error == 0) {
		error = so->so_error;
		so->so_error = 0;
	}
out:
	socket_unlock(so, 1);
	return error;
}

static int
connectitx(struct socket *so, sockaddr_ref_t src,
    sockaddr_ref_t dst, proc_ref_t p, uint32_t ifscope,
    sae_associd_t aid, sae_connid_t *pcid, uio_t auio, unsigned int flags,
    user_ssize_t *bytes_written)
{
	int error;

	VERIFY(dst != NULL);

	AUDIT_ARG(sockaddr, vfs_context_cwd(vfs_context_current()), dst);
#if CONFIG_MACF_SOCKET_SUBSET
	if ((error = mac_socket_check_connect(kauth_cred_get(), so, dst)) != 0) {
		return error;
	}

	if (auio != NULL) {
		if ((error = mac_socket_check_send(kauth_cred_get(), so, dst)) != 0) {
			return error;
		}
	}
#endif /* MAC_SOCKET_SUBSET */

	socket_lock(so, 1);
	if ((so->so_state & SS_NBIO) && (so->so_state & SS_ISCONNECTING)) {
		error = EALREADY;
		goto out;
	}

	error = soconnectxlocked(so, src, dst, p, ifscope,
	    aid, pcid, flags, NULL, 0, auio, bytes_written);
	if (error != 0) {
		goto out;
	}
	/*
	 * If, after the call to soconnectxlocked the flag is still set (in case
	 * data has been queued and the connect() has actually been triggered,
	 * it will have been unset by the transport), we exit immediately. There
	 * is no reason to wait on any event.
	 */
	if (so->so_flags1 & SOF1_PRECONNECT_DATA) {
		error = 0;
		goto out;
	}
	if ((so->so_state & SS_NBIO) && (so->so_state & SS_ISCONNECTING)) {
		error = EINPROGRESS;
		goto out;
	}
	while ((so->so_state & SS_ISCONNECTING) && so->so_error == 0) {
		lck_mtx_t *mutex_held;

		if (so->so_proto->pr_getlock != NULL) {
			mutex_held = (*so->so_proto->pr_getlock)(so, PR_F_WILLUNLOCK);
		} else {
			mutex_held = so->so_proto->pr_domain->dom_mtx;
		}
		error = msleep((caddr_t)&so->so_timeo, mutex_held,
		    PSOCK | PCATCH, __func__, 0);
		if (so->so_state & SS_DRAINING) {
			error = ECONNABORTED;
		}
		if (error != 0) {
			break;
		}
	}
	if (error == 0) {
		error = so->so_error;
		so->so_error = 0;
	}
out:
	socket_unlock(so, 1);
	return error;
}

int
peeloff(proc_ref_t p, struct peeloff_args *uap, int *retval)
{
#pragma unused(p, uap, retval)
	/*
	 * Due to similiarity with a POSIX interface, define as
	 * an unofficial cancellation point.
	 */
	__pthread_testcancel(1);
	return 0;
}

int
disconnectx(proc_ref_t p, struct disconnectx_args *uap, int *retval)
{
	/*
	 * Due to similiarity with a POSIX interface, define as
	 * an unofficial cancellation point.
	 */
	__pthread_testcancel(1);
	return disconnectx_nocancel(p, uap, retval);
}

static int
disconnectx_nocancel(proc_ref_t p, struct disconnectx_args *uap, int *retval)
{
#pragma unused(p, retval)
	socket_ref_t so;
	int fd = uap->s;
	int error;

	error = file_socket(fd, &so);
	if (error != 0) {
		return error;
	}
	if (so == NULL) {
		error = EBADF;
		goto out;
	}

	error = sodisconnectx(so, uap->aid, uap->cid);
out:
	file_drop(fd);
	return error;
}

/*
 * Returns:	0			Success
 *	socreate:EAFNOSUPPORT
 *	socreate:EPROTOTYPE
 *	socreate:EPROTONOSUPPORT
 *	socreate:ENOBUFS
 *	socreate:ENOMEM
 *	socreate:EISCONN
 *	socreate:???			[other protocol families, IPSEC]
 *	falloc:ENFILE
 *	falloc:EMFILE
 *	falloc:ENOMEM
 *	copyout:EFAULT
 *	soconnect2:EINVAL
 *	soconnect2:EPROTOTYPE
 *	soconnect2:???			[other protocol families[
 */
int
socketpair(proc_ref_t p, struct socketpair_args *uap,
    __unused int32_ref_t retval)
{
	fileproc_ref_t  fp1, fp2;
	socket_ref_t so1, so2;
	int fd, error, sv[2];

	AUDIT_ARG(socket, uap->domain, uap->type, uap->protocol);
	error = socreate(uap->domain, &so1, uap->type, uap->protocol);
	if (error) {
		return error;
	}
	error = socreate(uap->domain, &so2, uap->type, uap->protocol);
	if (error) {
		goto free1;
	}

	error = falloc(p, &fp1, &fd, vfs_context_current());
	if (error) {
		goto free2;
	}
	fp1->f_flag = FREAD | FWRITE;
	fp1->f_ops = &socketops;
	fp_set_data(fp1, so1);
	sv[0] = fd;

	error = falloc(p, &fp2, &fd, vfs_context_current());
	if (error) {
		goto free3;
	}
	fp2->f_flag = FREAD | FWRITE;
	fp2->f_ops = &socketops;
	fp_set_data(fp2, so2);
	sv[1] = fd;

	error = soconnect2(so1, so2);
	if (error) {
		goto free4;
	}
	if (uap->type == SOCK_DGRAM) {
		/*
		 * Datagram socket connection is asymmetric.
		 */
		error = soconnect2(so2, so1);
		if (error) {
			goto free4;
		}
	}

	if ((error = copyout(sv, uap->rsv, 2 * sizeof(int))) != 0) {
		goto free4;
	}

	proc_fdlock(p);
	procfdtbl_releasefd(p, sv[0], NULL);
	procfdtbl_releasefd(p, sv[1], NULL);
	fp_drop(p, sv[0], fp1, 1);
	fp_drop(p, sv[1], fp2, 1);
	proc_fdunlock(p);

	return 0;
free4:
	fp_free(p, sv[1], fp2);
free3:
	fp_free(p, sv[0], fp1);
free2:
	(void) soclose(so2);
free1:
	(void) soclose(so1);
	return error;
}

/*
 * Returns:	0			Success
 *		EINVAL
 *		ENOBUFS
 *		EBADF
 *		EPIPE
 *		EACCES			Mandatory Access Control failure
 *	file_socket:ENOTSOCK
 *	file_socket:EBADF
 *	getsockaddr:ENAMETOOLONG	Filename too long
 *	getsockaddr:EINVAL		Invalid argument
 *	getsockaddr:ENOMEM		Not enough space
 *	getsockaddr:EFAULT		Bad address
 *	<pru_sosend>:EACCES[TCP]
 *	<pru_sosend>:EADDRINUSE[TCP]
 *	<pru_sosend>:EADDRNOTAVAIL[TCP]
 *	<pru_sosend>:EAFNOSUPPORT[TCP]
 *	<pru_sosend>:EAGAIN[TCP]
 *	<pru_sosend>:EBADF
 *	<pru_sosend>:ECONNRESET[TCP]
 *	<pru_sosend>:EFAULT
 *	<pru_sosend>:EHOSTUNREACH[TCP]
 *	<pru_sosend>:EINTR
 *	<pru_sosend>:EINVAL
 *	<pru_sosend>:EISCONN[AF_INET]
 *	<pru_sosend>:EMSGSIZE[TCP]
 *	<pru_sosend>:ENETDOWN[TCP]
 *	<pru_sosend>:ENETUNREACH[TCP]
 *	<pru_sosend>:ENOBUFS
 *	<pru_sosend>:ENOMEM[TCP]
 *	<pru_sosend>:ENOTCONN[AF_INET]
 *	<pru_sosend>:EOPNOTSUPP
 *	<pru_sosend>:EPERM[TCP]
 *	<pru_sosend>:EPIPE
 *	<pru_sosend>:EWOULDBLOCK
 *	<pru_sosend>:???[TCP]		[ignorable: mostly IPSEC/firewall/DLIL]
 *	<pru_sosend>:???[AF_INET]	[whatever a filter author chooses]
 *	<pru_sosend>:???		[value from so_error]
 *	sockargs:???
 */
static int
sendit(proc_ref_t p, struct socket *so, user_msghdr_ref_t mp, uio_t uiop,
    int flags, int32_ref_t retval)
{
	mbuf_ref_t  control = NULL;
	struct sockaddr_storage ss;
	sockaddr_ref_t  to = NULL;
	boolean_t want_free = TRUE;
	int error;
	user_ssize_t len;

	KERNEL_DEBUG(DBG_FNC_SENDIT | DBG_FUNC_START, 0, 0, 0, 0, 0);

	if (mp->msg_name != USER_ADDR_NULL) {
		if (mp->msg_namelen > sizeof(ss)) {
			error = getsockaddr(so, &to, mp->msg_name,
			    mp->msg_namelen, TRUE);
		} else {
			error = getsockaddr_s(so, &ss, mp->msg_name,
			    mp->msg_namelen, TRUE);
			if (error == 0) {
				to = (sockaddr_ref_t)&ss;
				want_free = FALSE;
			}
		}
		if (error != 0) {
			goto out;
		}
		AUDIT_ARG(sockaddr, vfs_context_cwd(vfs_context_current()), to);
	}
	if (mp->msg_control != USER_ADDR_NULL) {
		if (mp->msg_controllen < sizeof(struct cmsghdr)) {
			error = EINVAL;
			goto bad;
		}
		error = sockargs(&control, mp->msg_control,
		    mp->msg_controllen, MT_CONTROL);
		if (error != 0) {
			goto bad;
		}
	}

#if CONFIG_MACF_SOCKET_SUBSET
	/*
	 * We check the state without holding the socket lock;
	 * if a race condition occurs, it would simply result
	 * in an extra call to the MAC check function.
	 */
	if (to != NULL &&
	    !(so->so_state & SS_DEFUNCT) &&
	    (error = mac_socket_check_send(kauth_cred_get(), so, to)) != 0) {
		if (control != NULL) {
			m_freem(control);
		}

		goto bad;
	}
#endif /* MAC_SOCKET_SUBSET */

	len = uio_resid(uiop);
	error = so->so_proto->pr_usrreqs->pru_sosend(so, to, uiop, 0,
	    control, flags);
	if (error != 0) {
		if (uio_resid(uiop) != len && (error == ERESTART ||
		    error == EINTR || error == EWOULDBLOCK)) {
			error = 0;
		}
		/* Generation of SIGPIPE can be controlled per socket */
		if (error == EPIPE && !(so->so_flags & SOF_NOSIGPIPE) &&
		    !(flags & MSG_NOSIGNAL)) {
			psignal(p, SIGPIPE);
		}
	}
	if (error == 0) {
		*retval = (int)(len - uio_resid(uiop));
	}
bad:
	if (want_free) {
		free_sockaddr(to);
	}
out:
	KERNEL_DEBUG(DBG_FNC_SENDIT | DBG_FUNC_END, error, 0, 0, 0, 0);

	return error;
}

/*
 * Returns:	0			Success
 *		ENOMEM
 *	sendit:???			[see sendit definition in this file]
 *	write:???			[4056224: applicable for pipes]
 */
int
sendto(proc_ref_t p, struct sendto_args *uap, int32_ref_t retval)
{
	__pthread_testcancel(1);
	return sendto_nocancel(p, (struct sendto_nocancel_args *)uap, retval);
}

int
sendto_nocancel(proc_ref_t p,
    struct sendto_nocancel_args *uap,
    int32_ref_t retval)
{
	struct user_msghdr msg;
	int error;
	uio_t auio = NULL;
	socket_ref_t so;

	KERNEL_DEBUG(DBG_FNC_SENDTO | DBG_FUNC_START, 0, 0, 0, 0, 0);
	AUDIT_ARG(fd, uap->s);

	if (uap->flags & MSG_SKIPCFIL) {
		error = EPERM;
		goto done;
	}

	if (uap->len > LONG_MAX) {
		error = EINVAL;
		goto done;
	}

	auio = uio_create(1, 0,
	    (IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32),
	    UIO_WRITE);
	if (auio == NULL) {
		error = ENOMEM;
		goto done;
	}
	uio_addiov(auio, uap->buf, uap->len);

	msg.msg_name = uap->to;
	msg.msg_namelen = uap->tolen;
	/* no need to set up msg_iov.  sendit uses uio_t we send it */
	msg.msg_iov = 0;
	msg.msg_iovlen = 0;
	msg.msg_control = 0;
	msg.msg_flags = 0;

	error = file_socket(uap->s, &so);
	if (error) {
		goto done;
	}

	if (so == NULL) {
		error = EBADF;
	} else {
		error = sendit(p, so, &msg, auio, uap->flags, retval);
	}

	file_drop(uap->s);
done:
	if (auio != NULL) {
		uio_free(auio);
	}

	KERNEL_DEBUG(DBG_FNC_SENDTO | DBG_FUNC_END, error, *retval, 0, 0, 0);

	return error;
}

/*
 * Returns:	0			Success
 *		ENOBUFS
 *	copyin:EFAULT
 *	sendit:???			[see sendit definition in this file]
 */
int
sendmsg(proc_ref_t p, struct sendmsg_args *uap, int32_ref_t retval)
{
	__pthread_testcancel(1);
	return sendmsg_nocancel(p, (struct sendmsg_nocancel_args *)uap,
	           retval);
}

int
sendmsg_nocancel(proc_ref_t p, struct sendmsg_nocancel_args *uap,
    int32_ref_t retval)
{
	struct user32_msghdr msg32;
	struct user64_msghdr msg64;
	struct user_msghdr user_msg;
	caddr_t msghdrp;
	int     size_of_msghdr;
	int error;
	uio_t auio = NULL;
	struct user_iovec *iovp;
	socket_ref_t so;

	const bool is_p_64bit_process = IS_64BIT_PROCESS(p);

	KERNEL_DEBUG(DBG_FNC_SENDMSG | DBG_FUNC_START, 0, 0, 0, 0, 0);
	AUDIT_ARG(fd, uap->s);

	if (uap->flags & MSG_SKIPCFIL) {
		error = EPERM;
		goto done;
	}

	if (is_p_64bit_process) {
		msghdrp = (caddr_t)&msg64;
		size_of_msghdr = sizeof(msg64);
	} else {
		msghdrp = (caddr_t)&msg32;
		size_of_msghdr = sizeof(msg32);
	}
	error = copyin(uap->msg, msghdrp, size_of_msghdr);
	if (error) {
		KERNEL_DEBUG(DBG_FNC_SENDMSG | DBG_FUNC_END, error, 0, 0, 0, 0);
		return error;
	}

	if (is_p_64bit_process) {
		user_msg.msg_flags = msg64.msg_flags;
		user_msg.msg_controllen = msg64.msg_controllen;
		user_msg.msg_control = (user_addr_t)msg64.msg_control;
		user_msg.msg_iovlen = msg64.msg_iovlen;
		user_msg.msg_iov = (user_addr_t)msg64.msg_iov;
		user_msg.msg_namelen = msg64.msg_namelen;
		user_msg.msg_name = (user_addr_t)msg64.msg_name;
	} else {
		user_msg.msg_flags = msg32.msg_flags;
		user_msg.msg_controllen = msg32.msg_controllen;
		user_msg.msg_control = msg32.msg_control;
		user_msg.msg_iovlen = msg32.msg_iovlen;
		user_msg.msg_iov = msg32.msg_iov;
		user_msg.msg_namelen = msg32.msg_namelen;
		user_msg.msg_name = msg32.msg_name;
	}

	if (user_msg.msg_iovlen <= 0 || user_msg.msg_iovlen > UIO_MAXIOV) {
		KERNEL_DEBUG(DBG_FNC_SENDMSG | DBG_FUNC_END, EMSGSIZE,
		    0, 0, 0, 0);
		return EMSGSIZE;
	}

	/* allocate a uio large enough to hold the number of iovecs passed */
	auio = uio_create(user_msg.msg_iovlen, 0,
	    (is_p_64bit_process ? UIO_USERSPACE64 : UIO_USERSPACE32),
	    UIO_WRITE);
	if (auio == NULL) {
		error = ENOBUFS;
		goto done;
	}

	if (user_msg.msg_iovlen) {
		/*
		 * get location of iovecs within the uio.
		 * then copyin the iovecs from user space.
		 */
		iovp = uio_iovsaddr(auio);
		if (iovp == NULL) {
			error = ENOBUFS;
			goto done;
		}
		error = copyin_user_iovec_array(user_msg.msg_iov,
		    is_p_64bit_process ? UIO_USERSPACE64 : UIO_USERSPACE32,
		    user_msg.msg_iovlen, iovp);
		if (error) {
			goto done;
		}
		user_msg.msg_iov = CAST_USER_ADDR_T(iovp);

		/* finish setup of uio_t */
		error = uio_calculateresid(auio);
		if (error) {
			goto done;
		}
	} else {
		user_msg.msg_iov = 0;
	}

	/* msg_flags is ignored for send */
	user_msg.msg_flags = 0;

	error = file_socket(uap->s, &so);
	if (error) {
		goto done;
	}
	if (so == NULL) {
		error = EBADF;
	} else {
		error = sendit(p, so, &user_msg, auio, uap->flags, retval);
	}
	file_drop(uap->s);
done:
	if (auio != NULL) {
		uio_free(auio);
	}
	KERNEL_DEBUG(DBG_FNC_SENDMSG | DBG_FUNC_END, error, 0, 0, 0, 0);

	return error;
}

#if DEBUG || DEVELOPMENT
static int
sendmsg_x_old(proc_ref_t p, struct sendmsg_x_args *uap, user_ssize_t *retval)
{
	int error = 0;
	user_msghdr_x_ptr_t user_msg_x = NULL;
	uio_ref_ptr_t uiop = NULL;
	socket_ref_t so;
	u_int i;
	sockaddr_ref_t to = NULL;
	user_ssize_t len_before = 0, len_after;
	int need_drop = 0;
	size_t size_of_msghdr;
	void_ptr_t umsgp = NULL;
	u_int uiocnt = 0;
	int has_addr_or_ctl = 0;

	KERNEL_DEBUG(DBG_FNC_SENDMSG_X | DBG_FUNC_START, 0, 0, 0, 0, 0);

	size_of_msghdr = IS_64BIT_PROCESS(p) ?
	    sizeof(struct user64_msghdr_x) : sizeof(struct user32_msghdr_x);

	if (uap->flags & MSG_SKIPCFIL) {
		error = EPERM;
		goto out;
	}

	error = file_socket(uap->s, &so);
	if (error) {
		goto out;
	}
	need_drop = 1;
	if (so == NULL) {
		error = EBADF;
		goto out;
	}

	/*
	 * Input parameter range check
	 */
	if (uap->cnt == 0 || uap->cnt > UIO_MAXIOV) {
		error = EINVAL;
		goto out;
	}
	/*
	 * Clip to max currently allowed
	 */
	if (uap->cnt > somaxsendmsgx) {
		uap->cnt = somaxsendmsgx > 0 ? somaxsendmsgx : 1;
	}

	user_msg_x = kalloc_type(struct user_msghdr_x, uap->cnt,
	    Z_WAITOK | Z_ZERO);
	if (user_msg_x == NULL) {
		DBG_PRINTF("%s user_msg_x alloc failed", __func__);
		error = ENOMEM;
		goto out;
	}
	uiop = kalloc_type(uio_ref_t, uap->cnt, Z_WAITOK | Z_ZERO);
	if (uiop == NULL) {
		DBG_PRINTF("%s uiop alloc failed", __func__);
		error = ENOMEM;
		goto out;
	}

	umsgp = kalloc_data(uap->cnt * size_of_msghdr, Z_WAITOK | Z_ZERO);
	if (umsgp == NULL) {
		DBG_PRINTF("%s user_msg_x alloc failed", __func__);
		error = ENOMEM;
		goto out;
	}
	error = copyin(uap->msgp, umsgp, uap->cnt * size_of_msghdr);
	if (error) {
		DBG_PRINTF("%s copyin() failed", __func__);
		goto out;
	}
	error = internalize_user_msghdr_array(umsgp,
	    IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32,
	    UIO_WRITE, uap->cnt, user_msg_x, uiop);
	if (error) {
		DBG_PRINTF("%s copyin_user_msghdr_array() failed", __func__);
		goto out;
	}
	/*
	 * Make sure the size of each message iovec and
	 * the aggregate size of all the iovec is valid
	 */
	if (uio_array_is_valid(uiop, uap->cnt) == false) {
		error = EINVAL;
		goto out;
	}

	/*
	 * Sanity check on passed arguments
	 */
	for (i = 0; i < uap->cnt; i++) {
		struct user_msghdr_x *mp = user_msg_x + i;

		/*
		 * No flags on send message
		 */
		if (mp->msg_flags != 0) {
			error = EINVAL;
			goto out;
		}
		/*
		 * No support for address or ancillary data (yet)
		 */
		if (mp->msg_name != USER_ADDR_NULL || mp->msg_namelen != 0) {
			has_addr_or_ctl = 1;
		}

		if (mp->msg_control != USER_ADDR_NULL ||
		    mp->msg_controllen != 0) {
			has_addr_or_ctl = 1;
		}

#if CONFIG_MACF_SOCKET_SUBSET
		/*
		 * We check the state without holding the socket lock;
		 * if a race condition occurs, it would simply result
		 * in an extra call to the MAC check function.
		 *
		 * Note: The following check is never true taken with the
		 * current limitation that we do not accept to pass an address,
		 * this is effectively placeholder code. If we add support for
		 * addresses, we will have to check every address.
		 */
		if (to != NULL &&
		    !(so->so_state & SS_DEFUNCT) &&
		    (error = mac_socket_check_send(kauth_cred_get(), so, to))
		    != 0) {
			goto out;
		}
#endif /* MAC_SOCKET_SUBSET */
	}

	len_before = uio_array_resid(uiop, uap->cnt);

	for (i = 0; i < uap->cnt; i++) {
		struct user_msghdr_x *mp = user_msg_x + i;
		struct user_msghdr user_msg;
		uio_t auio = uiop[i];
		int32_t tmpval;

		user_msg.msg_flags = mp->msg_flags;
		user_msg.msg_controllen = mp->msg_controllen;
		user_msg.msg_control = mp->msg_control;
		user_msg.msg_iovlen = mp->msg_iovlen;
		user_msg.msg_iov = mp->msg_iov;
		user_msg.msg_namelen = mp->msg_namelen;
		user_msg.msg_name = mp->msg_name;

		error = sendit(p, so, &user_msg, auio, uap->flags,
		    &tmpval);
		if (error != 0) {
			break;
		}
		uiocnt += 1;
	}

	len_after = uio_array_resid(uiop, uap->cnt);

	VERIFY(len_after <= len_before);

	if (error != 0) {
		if (len_after != len_before && (error == ERESTART ||
		    error == EINTR || error == EWOULDBLOCK ||
		    error == ENOBUFS)) {
			error = 0;
		}
		/* Generation of SIGPIPE can be controlled per socket */
		if (error == EPIPE && !(so->so_flags & SOF_NOSIGPIPE) &&
		    !(uap->flags & MSG_NOSIGNAL)) {
			psignal(p, SIGPIPE);
		}
	}
	if (error == 0) {
		externalize_user_msghdr_array(umsgp,
		    IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32,
		    UIO_WRITE, uiocnt, user_msg_x, uiop);

		*retval = (int)(uiocnt);
	}
out:
	if (need_drop) {
		file_drop(uap->s);
	}
	kfree_data(umsgp, uap->cnt * size_of_msghdr);
	if (uiop != NULL) {
		free_uio_array(uiop, uap->cnt);
		kfree_type(uio_ref_t, uap->cnt, uiop);
	}
	kfree_type(struct user_msghdr_x, uap->cnt, user_msg_x);

	KERNEL_DEBUG(DBG_FNC_SENDMSG_X | DBG_FUNC_END, error, 0, 0, 0, 0);

	return error;
}
#endif /* DEBUG || DEVELOPMENT */

static int
internalize_user_msg_x(struct user_msghdr *user_msg, uio_t *auiop, proc_ref_t p, void_ptr_t user_msghdr_x_src)
{
	const bool is_p_64bit_process = IS_64BIT_PROCESS(p);
	uio_t auio = *auiop;
	int error;

	if (is_p_64bit_process) {
		struct user64_msghdr_x msghdrx64;

		error = copyin((user_addr_t)user_msghdr_x_src,
		    &msghdrx64, sizeof(msghdrx64));
		if (error != 0) {
			DBG_PRINTF("%s copyin() msghdrx64 failed %d",
			    __func__, error);
			goto done;
		}
		user_msg->msg_name = msghdrx64.msg_name;
		user_msg->msg_namelen = msghdrx64.msg_namelen;
		user_msg->msg_iov = msghdrx64.msg_iov;
		user_msg->msg_iovlen = msghdrx64.msg_iovlen;
		user_msg->msg_control = msghdrx64.msg_control;
		user_msg->msg_controllen = msghdrx64.msg_controllen;
	} else {
		struct user32_msghdr_x msghdrx32;

		error = copyin((user_addr_t)user_msghdr_x_src,
		    &msghdrx32, sizeof(msghdrx32));
		if (error != 0) {
			DBG_PRINTF("%s copyin() msghdrx32 failed %d",
			    __func__, error);
			goto done;
		}
		user_msg->msg_name = msghdrx32.msg_name;
		user_msg->msg_namelen = msghdrx32.msg_namelen;
		user_msg->msg_iov = msghdrx32.msg_iov;
		user_msg->msg_iovlen = msghdrx32.msg_iovlen;
		user_msg->msg_control = msghdrx32.msg_control;
		user_msg->msg_controllen = msghdrx32.msg_controllen;
	}
	/* msg_flags is ignored for send */
	user_msg->msg_flags = 0;

	if (user_msg->msg_iovlen <= 0 || user_msg->msg_iovlen > UIO_MAXIOV) {
		error = EMSGSIZE;
		DBG_PRINTF("%s bad msg_iovlen, error %d",
		    __func__, error);
		goto done;
	}
	/*
	 * Attempt to reuse the uio if large enough, otherwise we need
	 * a new one
	 */
	if (auio != NULL) {
		if (auio->uio_max_iovs >= user_msg->msg_iovlen) {
			uio_reset(auio, 0,
			    is_p_64bit_process ? UIO_USERSPACE64 : UIO_USERSPACE32,
			    UIO_WRITE);
		} else {
			uio_free(auio);
			auio = NULL;
		}
	}
	if (auio == NULL) {
		auio = uio_create(user_msg->msg_iovlen, 0,
		    is_p_64bit_process ? UIO_USERSPACE64 : UIO_USERSPACE32,
		    UIO_WRITE);
		if (auio == NULL) {
			error = ENOBUFS;
			DBG_PRINTF("%s uio_create() failed %d",
			    __func__, error);
			goto done;
		}
	}

	if (user_msg->msg_iovlen) {
		/*
		 * get location of iovecs within the uio.
		 * then copyin the iovecs from user space.
		 */
		struct user_iovec *iovp = uio_iovsaddr(auio);
		if (iovp == NULL) {
			error = ENOBUFS;
			goto done;
		}
		error = copyin_user_iovec_array(user_msg->msg_iov,
		    is_p_64bit_process ? UIO_USERSPACE64 : UIO_USERSPACE32,
		    user_msg->msg_iovlen, iovp);
		if (error != 0) {
			goto done;
		}
		user_msg->msg_iov = CAST_USER_ADDR_T(iovp);

		/* finish setup of uio_t */
		error = uio_calculateresid(auio);
		if (error) {
			goto done;
		}
	} else {
		user_msg->msg_iov = 0;
	}

done:
	*auiop = auio;
	return error;
}

static int
mbuf_packet_from_uio(socket_ref_t so, mbuf_ref_ref_t mp, uio_t auio)
{
	int error = 0;
	uint16_t headroom = 0;
	size_t bytes_to_alloc;
	mbuf_ref_t top = NULL, m;

	if (soreserveheadroom != 0) {
		headroom = so->so_pktheadroom;
	}
	bytes_to_alloc = headroom + uio_resid(auio);

	error = mbuf_allocpacket(MBUF_WAITOK, bytes_to_alloc, NULL, &top);
	if (error != 0) {
		os_log(OS_LOG_DEFAULT, "mbuf_packet_from_uio: mbuf_allocpacket %zu error %d",
		    bytes_to_alloc, error);
		goto done;
	}

	if (headroom > 0 && headroom < mbuf_maxlen(top)) {
		top->m_data += headroom;
	}

	for (m = top; m != NULL; m = m->m_next) {
		int bytes_to_copy = (int)uio_resid(auio);
		ssize_t mlen;

		if ((m->m_flags & M_EXT)) {
			mlen = m->m_ext.ext_size -
			    M_LEADINGSPACE(m);
		} else if ((m->m_flags & M_PKTHDR)) {
			mlen = MHLEN - M_LEADINGSPACE(m);
			m_add_crumb(m, PKT_CRUMB_SOSEND);
		} else {
			mlen = MLEN - M_LEADINGSPACE(m);
		}
		int len = imin((int)mlen, bytes_to_copy);

		error = uiomove(mtod(m, caddr_t), (int)len, auio);
		if (error != 0) {
			os_log(OS_LOG_DEFAULT, "mbuf_packet_from_uio: len %d error %d",
			    len, error);
			goto done;
		}
		m->m_len = len;
		top->m_pkthdr.len += len;
	}

done:
	if (error != 0) {
		m_freem(top);
	} else {
		*mp = top;
	}
	return error;
}

static int
sendit_x(proc_ref_t p, socket_ref_t so, struct sendmsg_x_args *uap, u_int *retval)
{
	int error = 0;
	uio_t auio = NULL;
	const bool is_p_64bit_process = IS_64BIT_PROCESS(p);
	void_ptr_t src;
	MBUFQ_HEAD() pktlist = {};
	size_t total_pkt_len = 0;
	u_int pkt_cnt = 0;
	int flags = uap->flags;
	mbuf_ref_t top;

	MBUFQ_INIT(&pktlist);

	*retval = 0;

	/* We re-use the uio when possible */
	auio = uio_create(1, 0,
	    (is_p_64bit_process ? UIO_USERSPACE64 : UIO_USERSPACE32),
	    UIO_WRITE);
	if (auio == NULL) {
		error = ENOBUFS;
		DBG_PRINTF("%s uio_create() failed %d",
		    __func__, error);
		goto done;
	}

	src = (void_ptr_t)uap->msgp;

	/*
	 * Create a list of packets
	 */
	for (u_int i = 0; i < uap->cnt; i++) {
		struct user_msghdr user_msg = {};
		mbuf_ref_t m = NULL;

		if (is_p_64bit_process) {
			error = internalize_user_msg_x(&user_msg, &auio, p, ((struct user64_msghdr_x *)src) + i);
			if (error != 0) {
				os_log(OS_LOG_DEFAULT, "sendit_x: internalize_user_msg_x error %d\n", error);
				goto done;
			}
		} else {
			error = internalize_user_msg_x(&user_msg, &auio, p, ((struct user32_msghdr_x *)src) + i);
			if (error != 0) {
				os_log(OS_LOG_DEFAULT, "sendit_x: internalize_user_msg_x error %d\n", error);
				goto done;
			}
		}
		/*
		 * Stop on the first datagram that is too large
		 */
		if (uio_resid(auio) > so->so_snd.sb_hiwat) {
			if (i == 0) {
				error = EMSGSIZE;
				goto done;
			}
			break;
		}
		/*
		 * An mbuf packet has the control mbuf(s) followed by data
		 * We allocate the mbufs in reverse order
		 */
		error = mbuf_packet_from_uio(so, &m, auio);
		if (error != 0) {
			os_log(OS_LOG_DEFAULT, "sendit_x: mbuf_packet_from_uio error %d\n", error);
			goto done;
		}
		total_pkt_len += m->m_pkthdr.len;

		if (user_msg.msg_control != USER_ADDR_NULL && user_msg.msg_controllen != 0) {
			mbuf_ref_t control = NULL;

			error = sockargs(&control, user_msg.msg_control, user_msg.msg_controllen, MT_CONTROL);
			if (error != 0) {
				os_log(OS_LOG_DEFAULT, "sendit_x: sockargs error %d\n", error);
				goto done;
			}
			control->m_next = m;
			m = control;
		}
		MBUFQ_ENQUEUE(&pktlist, m);

		pkt_cnt += 1;
	}

	top = MBUFQ_FIRST(&pktlist);
	MBUFQ_INIT(&pktlist);
	error = sosend_list(so, top, total_pkt_len, &pkt_cnt, flags);
	if (error != 0) {
		os_log(OS_LOG_DEFAULT, "sendit_x: sosend_list error %d\n", error);
		goto done;
	}
done:
	*retval = pkt_cnt;

	if (auio != NULL) {
		uio_free(auio);
	}
	MBUFQ_DRAIN(&pktlist);
	return error;
}

int
sendmsg_x(proc_ref_t p, struct sendmsg_x_args *uap, user_ssize_t *retval)
{
	void_ptr_t src;
	int error;
	uio_t auio = NULL;
	socket_ref_t so;
	u_int uiocnt = 0;
	const bool is_p_64bit_process = IS_64BIT_PROCESS(p);

#if DEBUG || DEVELOPMENT
	if (sendmsg_x_mode == 2) {
		return sendmsg_x_old(p, uap, retval);
	}
#endif /* DEBUG || DEVELOPMENT */

	KERNEL_DEBUG(DBG_FNC_SENDMSG_X | DBG_FUNC_START, 0, 0, 0, 0, 0);
	AUDIT_ARG(fd, uap->s);

	if (uap->flags & MSG_SKIPCFIL) {
		error = EPERM;
		goto done_no_filedrop;
	}

	error = file_socket(uap->s, &so);
	if (error) {
		goto done_no_filedrop;
	}
	if (so == NULL) {
		error = EBADF;
		goto done;
	}

	/*
	 * For an atomic datagram connected socket we can build the list of
	 * mbuf packets with sosend_list()
	 */
	if (so->so_type == SOCK_DGRAM && sosendallatonce(so) &&
	    (so->so_state & SS_ISCONNECTED) && sendmsg_x_mode != 1) {
		error = sendit_x(p, so, uap, &uiocnt);
		if (error != 0) {
			DBG_PRINTF("%s sendit_x() failed %d",
			    __func__, error);
		}
		goto done;
	}

	src = (void_ptr_t)uap->msgp;

	/* We re-use the uio when possible */
	auio = uio_create(1, 0,
	    (is_p_64bit_process ? UIO_USERSPACE64 : UIO_USERSPACE32),
	    UIO_WRITE);
	if (auio == NULL) {
		error = ENOBUFS;
		DBG_PRINTF("%s uio_create() failed %d",
		    __func__, error);
		goto done;
	}

	for (u_int i = 0; i < uap->cnt; i++) {
		struct user_msghdr user_msg = {};

		if (is_p_64bit_process) {
			error = internalize_user_msg_x(&user_msg, &auio, p, ((struct user64_msghdr_x *)src) + i);
			if (error != 0) {
				goto done;
			}
		} else {
			error = internalize_user_msg_x(&user_msg, &auio, p, ((struct user32_msghdr_x *)src) + i);
			if (error != 0) {
				goto done;
			}
		}

		int32_t len = 0;
		error = sendit(p, so, &user_msg, auio, uap->flags, &len);
		if (error != 0) {
			break;
		}
		uiocnt += 1;
	}
done:
	if (error != 0) {
		if (uiocnt != 0 && (error == ERESTART ||
		    error == EINTR || error == EWOULDBLOCK ||
		    error == ENOBUFS || error == EMSGSIZE)) {
			error = 0;
		}
		/* Generation of SIGPIPE can be controlled per socket */
		if (error == EPIPE && !(so->so_flags & SOF_NOSIGPIPE) &&
		    !(uap->flags & MSG_NOSIGNAL)) {
			psignal(p, SIGPIPE);
		}
	}
	if (error == 0) {
		*retval = (int)(uiocnt);
	}
	file_drop(uap->s);

done_no_filedrop:
	if (auio != NULL) {
		uio_free(auio);
	}
	KERNEL_DEBUG(DBG_FNC_SENDMSG_X | DBG_FUNC_END, error, 0, 0, 0, 0);

	return error;
}


static int
copyout_sa(sockaddr_ref_t fromsa, user_addr_t name, socklen_t *namelen)
{
	int error = 0;
	socklen_t sa_len = 0;
	ssize_t len;

	len = *namelen;
	if (len <= 0 || fromsa == 0) {
		len = 0;
	} else {
#ifndef MIN
#define MIN(a, b) ((a) > (b) ? (b) : (a))
#endif
		sa_len = fromsa->sa_len;
		len = MIN((unsigned int)len, sa_len);
		error = copyout(fromsa, name, (unsigned)len);
		if (error) {
			goto out;
		}
	}
	*namelen = sa_len;
out:
	return 0;
}

static int
copyout_maddr(struct mbuf *m, user_addr_t name, socklen_t *namelen)
{
	int error = 0;
	socklen_t sa_len = 0;
	ssize_t len;

	len = *namelen;
	if (len <= 0 || m == NULL) {
		len = 0;
	} else {
#ifndef MIN
#define MIN(a, b) ((a) > (b) ? (b) : (a))
#endif
		struct sockaddr *fromsa = mtod(m, struct sockaddr *);

		sa_len = fromsa->sa_len;
		len = MIN((unsigned int)len, sa_len);
		error = copyout(fromsa, name, (unsigned)len);
		if (error != 0) {
			goto out;
		}
	}
	*namelen = sa_len;
out:
	return 0;
}

static int
copyout_control(proc_ref_t p, mbuf_ref_t m, user_addr_t control,
    socklen_ref_t controllen, int_ref_t flags, socket_ref_t so)
{
	int error = 0;
	socklen_t len;
	user_addr_t ctlbuf;
	struct inpcb *inp = NULL;
	bool want_pktinfo = false;
	bool seen_pktinfo = false;

	if (so != NULL && (SOCK_DOM(so) == PF_INET6 || SOCK_DOM(so) == PF_INET)) {
		inp = sotoinpcb(so);
		want_pktinfo = (inp->inp_flags & IN6P_PKTINFO) != 0;
	}

	len = *controllen;
	*controllen = 0;
	ctlbuf = control;

	while (m && len > 0) {
		socklen_t tocopy;
		struct cmsghdr *cp = mtod(m, struct cmsghdr *);
		socklen_t cp_size = CMSG_ALIGN(cp->cmsg_len);
		socklen_t buflen = m->m_len;

		while (buflen > 0 && len > 0) {
			/*
			 * SCM_TIMESTAMP hack because  struct timeval has a
			 * different size for 32 bits and 64 bits processes
			 */
			if (cp->cmsg_level == SOL_SOCKET && cp->cmsg_type == SCM_TIMESTAMP) {
				unsigned char tmp_buffer[CMSG_SPACE(sizeof(struct user64_timeval))] = {};
				struct cmsghdr *tmp_cp = (struct cmsghdr *)(void *)tmp_buffer;
				socklen_t tmp_space;
				struct timeval *tv = (struct timeval *)(void *)CMSG_DATA(cp);

				tmp_cp->cmsg_level = SOL_SOCKET;
				tmp_cp->cmsg_type = SCM_TIMESTAMP;

				if (proc_is64bit(p)) {
					struct user64_timeval *tv64 = (struct user64_timeval *)(void *)CMSG_DATA(tmp_cp);

					os_unaligned_deref(&tv64->tv_sec) = tv->tv_sec;
					os_unaligned_deref(&tv64->tv_usec) = tv->tv_usec;

					tmp_cp->cmsg_len = CMSG_LEN(sizeof(struct user64_timeval));
					tmp_space = CMSG_SPACE(sizeof(struct user64_timeval));
				} else {
					struct user32_timeval *tv32 = (struct user32_timeval *)(void *)CMSG_DATA(tmp_cp);

					tv32->tv_sec = (user32_time_t)tv->tv_sec;
					tv32->tv_usec = tv->tv_usec;

					tmp_cp->cmsg_len = CMSG_LEN(sizeof(struct user32_timeval));
					tmp_space = CMSG_SPACE(sizeof(struct user32_timeval));
				}
				if (len >= tmp_space) {
					tocopy = tmp_space;
				} else {
					*flags |= MSG_CTRUNC;
					tocopy = len;
				}
				error = copyout(tmp_buffer, ctlbuf, tocopy);
				if (error) {
					goto out;
				}
			} else {
				/* If socket has flow tracking and socket did not request address, ignore it */
				if (SOFLOW_ENABLED(so) &&
				    ((cp->cmsg_level == IPPROTO_IP && cp->cmsg_type == IP_RECVDSTADDR && inp != NULL &&
				    !(inp->inp_flags & INP_RECVDSTADDR)) ||
				    (cp->cmsg_level == IPPROTO_IPV6 && (cp->cmsg_type == IPV6_PKTINFO || cp->cmsg_type == IPV6_2292PKTINFO) && inp &&
				    !(inp->inp_flags & IN6P_PKTINFO)))) {
					tocopy = 0;
				} else {
					if (cp_size > buflen) {
						panic("cp_size > buflen, something wrong with alignment!");
					}
					if (len >= cp_size) {
						tocopy = cp_size;
					} else {
						*flags |= MSG_CTRUNC;
						tocopy = len;
					}
					error = copyout((caddr_t) cp, ctlbuf, tocopy);
					if (error) {
						goto out;
					}
					if (want_pktinfo && cp->cmsg_level == IPPROTO_IPV6 &&
					    (cp->cmsg_type == IPV6_PKTINFO || cp->cmsg_type == IPV6_2292PKTINFO)) {
						seen_pktinfo = true;
					}
				}
			}


			ctlbuf += tocopy;
			len -= tocopy;

			buflen -= cp_size;
			cp = (struct cmsghdr *)(void *)
			    ((unsigned char *) cp + cp_size);
			cp_size = CMSG_ALIGN(cp->cmsg_len);
		}

		m = m->m_next;
	}
	*controllen = (socklen_t)(ctlbuf - control);
out:
	if (want_pktinfo && !seen_pktinfo) {
		missingpktinfo += 1;
#if (DEBUG || DEVELOPMENT)
		char pname[MAXCOMLEN];
		char local[MAX_IPv6_STR_LEN + 6];
		char remote[MAX_IPv6_STR_LEN + 6];

		proc_name(so->last_pid, pname, sizeof(MAXCOMLEN));
		if (inp->inp_vflag & INP_IPV6) {
			inet_ntop(AF_INET6, &inp->in6p_laddr.s6_addr, local, sizeof(local));
			inet_ntop(AF_INET6, &inp->in6p_faddr.s6_addr, remote, sizeof(local));
		} else {
			inet_ntop(AF_INET, &inp->inp_laddr.s_addr, local, sizeof(local));
			inet_ntop(AF_INET, &inp->inp_faddr.s_addr, remote, sizeof(local));
		}

		os_log(OS_LOG_DEFAULT,
		    "cmsg IPV6_PKTINFO missing for %s:%u > %s:%u proc %s.%u error %d\n",
		    local, ntohs(inp->inp_lport), remote, ntohs(inp->inp_fport),
		    pname, so->last_pid, error);
#endif /* (DEBUG || DEVELOPMENT) */
	}
	return error;
}

/*
 * Returns:	0			Success
 *		ENOTSOCK
 *		EINVAL
 *		EBADF
 *		EACCES			Mandatory Access Control failure
 *	copyout:EFAULT
 *	fp_lookup:EBADF
 *	<pru_soreceive>:ENOBUFS
 *	<pru_soreceive>:ENOTCONN
 *	<pru_soreceive>:EWOULDBLOCK
 *	<pru_soreceive>:EFAULT
 *	<pru_soreceive>:EINTR
 *	<pru_soreceive>:EBADF
 *	<pru_soreceive>:EINVAL
 *	<pru_soreceive>:EMSGSIZE
 *	<pru_soreceive>:???
 *
 * Notes:	Additional return values from calls through <pru_soreceive>
 *		depend on protocols other than TCP or AF_UNIX, which are
 *		documented above.
 */
static int
recvit(proc_ref_t p, int s, user_msghdr_ref_t mp, uio_t uiop,
    user_addr_t namelenp, int32_ref_t retval)
{
	ssize_t len;
	int error;
	mbuf_ref_t  control = 0;
	socket_ref_t so;
	sockaddr_ref_t  fromsa = 0;
	fileproc_ref_t  fp;

	KERNEL_DEBUG(DBG_FNC_RECVIT | DBG_FUNC_START, 0, 0, 0, 0, 0);
	if ((error = fp_get_ftype(p, s, DTYPE_SOCKET, ENOTSOCK, &fp))) {
		KERNEL_DEBUG(DBG_FNC_RECVIT | DBG_FUNC_END, error, 0, 0, 0, 0);
		return error;
	}
	so = (struct socket *)fp_get_data(fp);

#if CONFIG_MACF_SOCKET_SUBSET
	/*
	 * We check the state without holding the socket lock;
	 * if a race condition occurs, it would simply result
	 * in an extra call to the MAC check function.
	 */
	if (!(so->so_state & SS_DEFUNCT) &&
	    !(so->so_state & SS_ISCONNECTED) &&
	    !(so->so_proto->pr_flags & PR_CONNREQUIRED) &&
	    (error = mac_socket_check_receive(kauth_cred_get(), so)) != 0) {
		goto out1;
	}
#endif /* MAC_SOCKET_SUBSET */
	if (uio_resid(uiop) < 0 || uio_resid(uiop) > INT_MAX) {
		KERNEL_DEBUG(DBG_FNC_RECVIT | DBG_FUNC_END, EINVAL, 0, 0, 0, 0);
		error = EINVAL;
		goto out1;
	}

	len = uio_resid(uiop);
	error = so->so_proto->pr_usrreqs->pru_soreceive(so, &fromsa, uiop,
	    NULL, mp->msg_control ? &control : NULL,
	    &mp->msg_flags);
	if (fromsa) {
		AUDIT_ARG(sockaddr, vfs_context_cwd(vfs_context_current()),
		    fromsa);
	}
	if (error) {
		if (uio_resid(uiop) != len && (error == ERESTART ||
		    error == EINTR || error == EWOULDBLOCK)) {
			error = 0;
		}
	}
	if (error) {
		goto out;
	}

	*retval = (int32_t)(len - uio_resid(uiop));

	if (mp->msg_name) {
		error = copyout_sa(fromsa, mp->msg_name, &mp->msg_namelen);
		if (error) {
			goto out;
		}
		/* return the actual, untruncated address length */
		if (namelenp &&
		    (error = copyout((caddr_t)&mp->msg_namelen, namelenp,
		    sizeof(int)))) {
			goto out;
		}
	}

	if (mp->msg_control) {
		error = copyout_control(p, control, mp->msg_control,
		    &mp->msg_controllen, &mp->msg_flags, so);
	}
out:
	free_sockaddr(fromsa);
	if (control) {
		m_freem(control);
	}
	KERNEL_DEBUG(DBG_FNC_RECVIT | DBG_FUNC_END, error, 0, 0, 0, 0);
out1:
	fp_drop(p, s, fp, 0);
	return error;
}

/*
 * Returns:	0			Success
 *		ENOMEM
 *	copyin:EFAULT
 *	recvit:???
 *	read:???			[4056224: applicable for pipes]
 *
 * Notes:	The read entry point is only called as part of support for
 *		binary backward compatability; new code should use read
 *		instead of recv or recvfrom when attempting to read data
 *		from pipes.
 *
 *		For full documentation of the return codes from recvit, see
 *		the block header for the recvit function.
 */
int
recvfrom(proc_ref_t p, struct recvfrom_args *uap, int32_ref_t retval)
{
	__pthread_testcancel(1);
	return recvfrom_nocancel(p, (struct recvfrom_nocancel_args *)uap,
	           retval);
}

int
recvfrom_nocancel(proc_ref_t p, struct recvfrom_nocancel_args *uap,
    int32_ref_t retval)
{
	struct user_msghdr msg;
	int error;
	uio_t auio = NULL;

	KERNEL_DEBUG(DBG_FNC_RECVFROM | DBG_FUNC_START, 0, 0, 0, 0, 0);
	AUDIT_ARG(fd, uap->s);

	if (uap->fromlenaddr) {
		error = copyin(uap->fromlenaddr,
		    (caddr_t)&msg.msg_namelen, sizeof(msg.msg_namelen));
		if (error) {
			return error;
		}
	} else {
		msg.msg_namelen = 0;
	}
	msg.msg_name = uap->from;
	auio = uio_create(1, 0,
	    (IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32),
	    UIO_READ);
	if (auio == NULL) {
		return ENOMEM;
	}

	uio_addiov(auio, uap->buf, uap->len);
	/* no need to set up msg_iov.  recvit uses uio_t we send it */
	msg.msg_iov = 0;
	msg.msg_iovlen = 0;
	msg.msg_control = 0;
	msg.msg_controllen = 0;
	msg.msg_flags = uap->flags;
	error = recvit(p, uap->s, &msg, auio, uap->fromlenaddr, retval);
	if (auio != NULL) {
		uio_free(auio);
	}

	KERNEL_DEBUG(DBG_FNC_RECVFROM | DBG_FUNC_END, error, 0, 0, 0, 0);

	return error;
}

/*
 * Returns:	0			Success
 *		EMSGSIZE
 *		ENOMEM
 *	copyin:EFAULT
 *	copyout:EFAULT
 *	recvit:???
 *
 * Notes:	For full documentation of the return codes from recvit, see
 *		the block header for the recvit function.
 */
int
recvmsg(proc_ref_t p, struct recvmsg_args *uap, int32_ref_t retval)
{
	__pthread_testcancel(1);
	return recvmsg_nocancel(p, (struct recvmsg_nocancel_args *)uap,
	           retval);
}

int
recvmsg_nocancel(proc_ref_t p, struct recvmsg_nocancel_args *uap,
    int32_ref_t retval)
{
	struct user32_msghdr msg32;
	struct user64_msghdr msg64;
	struct user_msghdr user_msg;
	caddr_t msghdrp;
	int     size_of_msghdr;
	user_addr_t uiov;
	int error;
	uio_t auio = NULL;
	struct user_iovec *iovp;

	const bool is_p_64bit_process = IS_64BIT_PROCESS(p);

	KERNEL_DEBUG(DBG_FNC_RECVMSG | DBG_FUNC_START, 0, 0, 0, 0, 0);
	AUDIT_ARG(fd, uap->s);
	if (is_p_64bit_process) {
		msghdrp = (caddr_t)&msg64;
		size_of_msghdr = sizeof(msg64);
	} else {
		msghdrp = (caddr_t)&msg32;
		size_of_msghdr = sizeof(msg32);
	}
	error = copyin(uap->msg, msghdrp, size_of_msghdr);
	if (error) {
		KERNEL_DEBUG(DBG_FNC_RECVMSG | DBG_FUNC_END, error, 0, 0, 0, 0);
		return error;
	}

	/* only need to copy if user process is not 64-bit */
	if (is_p_64bit_process) {
		user_msg.msg_flags = msg64.msg_flags;
		user_msg.msg_controllen = msg64.msg_controllen;
		user_msg.msg_control = (user_addr_t)msg64.msg_control;
		user_msg.msg_iovlen = msg64.msg_iovlen;
		user_msg.msg_iov = (user_addr_t)msg64.msg_iov;
		user_msg.msg_namelen = msg64.msg_namelen;
		user_msg.msg_name = (user_addr_t)msg64.msg_name;
	} else {
		user_msg.msg_flags = msg32.msg_flags;
		user_msg.msg_controllen = msg32.msg_controllen;
		user_msg.msg_control = msg32.msg_control;
		user_msg.msg_iovlen = msg32.msg_iovlen;
		user_msg.msg_iov = msg32.msg_iov;
		user_msg.msg_namelen = msg32.msg_namelen;
		user_msg.msg_name = msg32.msg_name;
	}

	if (user_msg.msg_iovlen <= 0 || user_msg.msg_iovlen > UIO_MAXIOV) {
		KERNEL_DEBUG(DBG_FNC_RECVMSG | DBG_FUNC_END, EMSGSIZE,
		    0, 0, 0, 0);
		return EMSGSIZE;
	}

	user_msg.msg_flags = uap->flags;

	/* allocate a uio large enough to hold the number of iovecs passed */
	auio = uio_create(user_msg.msg_iovlen, 0,
	    (is_p_64bit_process ? UIO_USERSPACE64 : UIO_USERSPACE32),
	    UIO_READ);
	if (auio == NULL) {
		error = ENOMEM;
		goto done;
	}

	/*
	 * get location of iovecs within the uio.  then copyin the iovecs from
	 * user space.
	 */
	iovp = uio_iovsaddr(auio);
	if (iovp == NULL) {
		error = ENOMEM;
		goto done;
	}
	uiov = user_msg.msg_iov;
	user_msg.msg_iov = CAST_USER_ADDR_T(iovp);
	error = copyin_user_iovec_array(uiov,
	    is_p_64bit_process ? UIO_USERSPACE64 : UIO_USERSPACE32,
	    user_msg.msg_iovlen, iovp);
	if (error) {
		goto done;
	}

	/* finish setup of uio_t */
	error = uio_calculateresid(auio);
	if (error) {
		goto done;
	}

	error = recvit(p, uap->s, &user_msg, auio, 0, retval);
	if (!error) {
		user_msg.msg_iov = uiov;
		if (is_p_64bit_process) {
			msg64.msg_flags = user_msg.msg_flags;
			msg64.msg_controllen = user_msg.msg_controllen;
			msg64.msg_control = user_msg.msg_control;
			msg64.msg_iovlen = user_msg.msg_iovlen;
			msg64.msg_iov = user_msg.msg_iov;
			msg64.msg_namelen = user_msg.msg_namelen;
			msg64.msg_name = user_msg.msg_name;
		} else {
			msg32.msg_flags = user_msg.msg_flags;
			msg32.msg_controllen = user_msg.msg_controllen;
			msg32.msg_control = (user32_addr_t)user_msg.msg_control;
			msg32.msg_iovlen = user_msg.msg_iovlen;
			msg32.msg_iov = (user32_addr_t)user_msg.msg_iov;
			msg32.msg_namelen = user_msg.msg_namelen;
			msg32.msg_name = (user32_addr_t)user_msg.msg_name;
		}
		error = copyout(msghdrp, uap->msg, size_of_msghdr);
	}
done:
	if (auio != NULL) {
		uio_free(auio);
	}
	KERNEL_DEBUG(DBG_FNC_RECVMSG | DBG_FUNC_END, error, 0, 0, 0, 0);
	return error;
}

__attribute__((noinline))
static int
recvmsg_x_array(proc_ref_t p, socket_ref_t so, struct recvmsg_x_args *uap, user_ssize_t *retval)
{
	int error = EOPNOTSUPP;
	user_msghdr_x_ptr_t user_msg_x = NULL;
	recv_msg_elem_ptr_t recv_msg_array = NULL;
	user_ssize_t len_before = 0, len_after;
	size_t size_of_msghdr;
	void_ptr_t umsgp = NULL;
	u_int i;
	u_int uiocnt;
	int flags = uap->flags;

	const bool is_p_64bit_process = IS_64BIT_PROCESS(p);

	size_of_msghdr = is_p_64bit_process ?
	    sizeof(struct user64_msghdr_x) : sizeof(struct user32_msghdr_x);

	/*
	 * Support only a subset of message flags
	 */
	if (uap->flags & ~(MSG_PEEK | MSG_WAITALL | MSG_DONTWAIT | MSG_NEEDSA |  MSG_NBIO)) {
		return EOPNOTSUPP;
	}
	/*
	 * Input parameter range check
	 */
	if (uap->cnt == 0 || uap->cnt > UIO_MAXIOV) {
		error = EINVAL;
		goto out;
	}
	if (uap->cnt > somaxrecvmsgx) {
		uap->cnt = somaxrecvmsgx > 0 ? somaxrecvmsgx : 1;
	}

	user_msg_x = kalloc_type(struct user_msghdr_x, uap->cnt,
	    Z_WAITOK | Z_ZERO);
	if (user_msg_x == NULL) {
		DBG_PRINTF("%s user_msg_x alloc failed", __func__);
		error = ENOMEM;
		goto out;
	}
	recv_msg_array = alloc_recv_msg_array(uap->cnt);
	if (recv_msg_array == NULL) {
		DBG_PRINTF("%s alloc_recv_msg_array() failed", __func__);
		error = ENOMEM;
		goto out;
	}

	umsgp = kalloc_data(uap->cnt * size_of_msghdr, Z_WAITOK | Z_ZERO);
	if (umsgp == NULL) {
		DBG_PRINTF("%s umsgp alloc failed", __func__);
		error = ENOMEM;
		goto out;
	}
	error = copyin(uap->msgp, umsgp, uap->cnt * size_of_msghdr);
	if (error) {
		DBG_PRINTF("%s copyin() failed", __func__);
		goto out;
	}
	error = internalize_recv_msghdr_array(umsgp,
	    is_p_64bit_process ? UIO_USERSPACE64 : UIO_USERSPACE32,
	    UIO_READ, uap->cnt, user_msg_x, recv_msg_array);
	if (error) {
		DBG_PRINTF("%s copyin_user_msghdr_array() failed", __func__);
		goto out;
	}
	/*
	 * Make sure the size of each message iovec and
	 * the aggregate size of all the iovec is valid
	 */
	if (recv_msg_array_is_valid(recv_msg_array, uap->cnt) == 0) {
		error = EINVAL;
		goto out;
	}
	/*
	 * Sanity check on passed arguments
	 */
	for (i = 0; i < uap->cnt; i++) {
		struct user_msghdr_x *mp = user_msg_x + i;

		if (mp->msg_flags != 0) {
			error = EINVAL;
			goto out;
		}
	}
#if CONFIG_MACF_SOCKET_SUBSET
	/*
	 * We check the state without holding the socket lock;
	 * if a race condition occurs, it would simply result
	 * in an extra call to the MAC check function.
	 */
	if (!(so->so_state & SS_DEFUNCT) &&
	    !(so->so_state & SS_ISCONNECTED) &&
	    !(so->so_proto->pr_flags & PR_CONNREQUIRED) &&
	    (error = mac_socket_check_receive(kauth_cred_get(), so)) != 0) {
		goto out;
	}
#endif /* MAC_SOCKET_SUBSET */

	len_before = recv_msg_array_resid(recv_msg_array, uap->cnt);

	for (i = 0; i < uap->cnt; i++) {
		struct recv_msg_elem *recv_msg_elem;
		uio_t auio;
		sockaddr_ref_ref_t psa;
		struct mbuf **controlp;

		recv_msg_elem = recv_msg_array + i;
		auio = recv_msg_elem->uio;

		/*
		 * Do not block if we got at least one packet
		 */
		if (i > 0) {
			flags |= MSG_DONTWAIT;
		}

		psa = (recv_msg_elem->which & SOCK_MSG_SA) ?
		    &recv_msg_elem->psa : NULL;
		controlp = (recv_msg_elem->which & SOCK_MSG_CONTROL) ?
		    &recv_msg_elem->controlp : NULL;

		error = so->so_proto->pr_usrreqs->pru_soreceive(so, psa,
		    auio, NULL, controlp, &flags);
		if (error) {
			break;
		}
		/*
		 * We have some data
		 */
		recv_msg_elem->which |= SOCK_MSG_DATA;
		/*
		 * Set the messages flags for this packet
		 */
		flags &= ~MSG_DONTWAIT;
		recv_msg_elem->flags = flags;
		/*
		 * Stop on partial copy
		 */
		if (recv_msg_elem->flags & (MSG_RCVMORE | MSG_TRUNC)) {
			break;
		}
	}

	len_after = recv_msg_array_resid(recv_msg_array, uap->cnt);

	if (error) {
		if (len_after != len_before && (error == ERESTART ||
		    error == EINTR || error == EWOULDBLOCK)) {
			error = 0;
		} else {
			goto out;
		}
	}

	uiocnt = externalize_recv_msghdr_array(p, so, umsgp,
	    uap->cnt, user_msg_x, recv_msg_array, &error);
	if (error != 0) {
		goto out;
	}

	error = copyout(umsgp, uap->msgp, uap->cnt * size_of_msghdr);
	if (error) {
		DBG_PRINTF("%s copyout() failed", __func__);
		goto out;
	}
	*retval = (int)(uiocnt);

out:
	kfree_data(umsgp, uap->cnt * size_of_msghdr);
	free_recv_msg_array(recv_msg_array, uap->cnt);
	kfree_type(struct user_msghdr_x, uap->cnt, user_msg_x);

	return error;
}

int
recvmsg_x(struct proc *p, struct recvmsg_x_args *uap, user_ssize_t *retval)
{
	int error = EOPNOTSUPP;
	socket_ref_t so;
	size_t size_of_msghdrx;
	caddr_t msghdrxp;
	struct user32_msghdr_x msghdrx32 = {};
	struct user64_msghdr_x msghdrx64 = {};
	int spacetype;
	u_int i;
	uio_t auio = NULL;
	caddr_t src;
	int flags;
	struct mbuf *pkt_list = NULL, *m;
	struct mbuf *addr_list = NULL, *m_addr;
	struct mbuf *ctl_list = NULL, *control;
	u_int pktcnt;

	KERNEL_DEBUG(DBG_FNC_RECVMSG_X | DBG_FUNC_START, 0, 0, 0, 0, 0);

	error = file_socket(uap->s, &so);
	if (error) {
		goto done_no_filedrop;
	}
	if (so == NULL) {
		error = EBADF;
		goto done;
	}

#if CONFIG_MACF_SOCKET_SUBSET
	/*
	 * We check the state without holding the socket lock;
	 * if a race condition occurs, it would simply result
	 * in an extra call to the MAC check function.
	 */
	if (!(so->so_state & SS_DEFUNCT) &&
	    !(so->so_state & SS_ISCONNECTED) &&
	    !(so->so_proto->pr_flags & PR_CONNREQUIRED) &&
	    (error = mac_socket_check_receive(kauth_cred_get(), so)) != 0) {
		goto done;
	}
#endif /* MAC_SOCKET_SUBSET */

	/*
	 * With soreceive_m_list, all packets must be uniform, with address and
	 * control as they are returned in parallel lists and it's only guaranteed
	 * when pru_send_list is supported
	 */
	if (do_recvmsg_x_donttrunc != 0 || (so->so_options & SO_DONTTRUNC)) {
		error = recvmsg_x_array(p, so, uap, retval);
		goto done;
	}

	/*
	 * Input parameter range check
	 */
	if (uap->cnt == 0 || uap->cnt > UIO_MAXIOV) {
		error = EINVAL;
		goto done;
	}
	if (uap->cnt > somaxrecvmsgx) {
		uap->cnt = somaxrecvmsgx > 0 ? somaxrecvmsgx : 1;
	}

	if (IS_64BIT_PROCESS(p)) {
		msghdrxp = (caddr_t)&msghdrx64;
		size_of_msghdrx = sizeof(struct user64_msghdr_x);
		spacetype = UIO_USERSPACE64;
	} else {
		msghdrxp = (caddr_t)&msghdrx32;
		size_of_msghdrx = sizeof(struct user32_msghdr_x);
		spacetype = UIO_USERSPACE32;
	}
	src = (caddr_t)uap->msgp;

	flags = uap->flags;

	/*
	 * Only allow MSG_DONTWAIT
	 */
	if ((flags & ~(MSG_DONTWAIT | MSG_NBIO)) != 0) {
		error = EINVAL;
		goto done;
	}

	/*
	 * Receive list of packet in a single call
	 */
	pktcnt = uap->cnt;
	error = soreceive_m_list(so, &pktcnt, &addr_list, &pkt_list, &ctl_list,
	    &flags);
	if (error != 0) {
		if (pktcnt != 0 && (error == ERESTART ||
		    error == EINTR || error == EWOULDBLOCK)) {
			error = 0;
		} else {
			goto done;
		}
	}

	m_addr = addr_list;
	m = pkt_list;
	control = ctl_list;

	for (i = 0; i < pktcnt; i++) {
		struct user_msghdr user_msg;
		ssize_t len;
		struct user_iovec *iovp;
		struct mbuf *n;

		if (m->m_type != MT_OOBDATA && m->m_type != MT_DATA &&
		    m->m_type != MT_HEADER) {
			panic("%s: m %p m_type %d != MT_DATA", __func__, m, m->m_type);
		}

		error = copyin((user_addr_t)(src + i * size_of_msghdrx),
		    msghdrxp, size_of_msghdrx);
		if (error) {
			DBG_PRINTF("%s copyin() msghdrx failed %d\n",
			    __func__, error);
			goto done;
		}
		if (spacetype == UIO_USERSPACE64) {
			user_msg.msg_name = msghdrx64.msg_name;
			user_msg.msg_namelen = msghdrx64.msg_namelen;
			user_msg.msg_iov = msghdrx64.msg_iov;
			user_msg.msg_iovlen = msghdrx64.msg_iovlen;
			user_msg.msg_control = msghdrx64.msg_control;
			user_msg.msg_controllen = msghdrx64.msg_controllen;
		} else {
			user_msg.msg_name = msghdrx32.msg_name;
			user_msg.msg_namelen = msghdrx32.msg_namelen;
			user_msg.msg_iov = msghdrx32.msg_iov;
			user_msg.msg_iovlen = msghdrx32.msg_iovlen;
			user_msg.msg_control = msghdrx32.msg_control;
			user_msg.msg_controllen = msghdrx32.msg_controllen;
		}
		user_msg.msg_flags = 0;
		if (user_msg.msg_iovlen <= 0 ||
		    user_msg.msg_iovlen > UIO_MAXIOV) {
			error = EMSGSIZE;
			DBG_PRINTF("%s bad msg_iovlen, error %d\n",
			    __func__, error);
			goto done;
		}
		/*
		 * Attempt to reuse the uio if large enough, otherwise we need
		 * a new one
		 */
		if (auio != NULL) {
			if (auio->uio_max_iovs <= user_msg.msg_iovlen) {
				uio_reset(auio, 0, spacetype, UIO_READ);
			} else {
				uio_free(auio);
				auio = NULL;
			}
		}
		if (auio == NULL) {
			auio = uio_create(user_msg.msg_iovlen, 0, spacetype,
			    UIO_READ);
			if (auio == NULL) {
				error = ENOBUFS;
				DBG_PRINTF("%s uio_create() failed %d\n",
				    __func__, error);
				goto done;
			}
		}
		/*
		 * get location of iovecs within the uio then copy the iovecs
		 * from user space.
		 */
		iovp = uio_iovsaddr(auio);
		if (iovp == NULL) {
			error = ENOMEM;
			DBG_PRINTF("%s uio_iovsaddr() failed %d\n",
			    __func__, error);
			goto done;
		}
		error = copyin_user_iovec_array(user_msg.msg_iov,
		    spacetype, user_msg.msg_iovlen, iovp);
		if (error != 0) {
			DBG_PRINTF("%s copyin_user_iovec_array() failed %d\n",
			    __func__, error);
			goto done;
		}
		error = uio_calculateresid(auio);
		if (error != 0) {
			DBG_PRINTF("%s uio_calculateresid() failed %d\n",
			    __func__, error);
			goto done;
		}
		user_msg.msg_iov = CAST_USER_ADDR_T(iovp);

		len = uio_resid(auio);
		for (n = m; n != NULL; n = n->m_next) {
			user_ssize_t resid = uio_resid(auio);
			if (resid < n->m_len) {
				error = uiomove(mtod(n, caddr_t), (int)n->m_len, auio);
				if (error != 0) {
					DBG_PRINTF("%s uiomove() failed\n",
					    __func__);
					goto done;
				}
				flags |= MSG_TRUNC;
				break;
			}

			error = uiomove(mtod(n, caddr_t), (int)n->m_len, auio);
			if (error != 0) {
				DBG_PRINTF("%s uiomove() failed\n",
				    __func__);
				goto done;
			}
		}
		len -= uio_resid(auio);

		if (user_msg.msg_name != 0 && user_msg.msg_namelen != 0) {
			error = copyout_maddr(m_addr, user_msg.msg_name,
			    &user_msg.msg_namelen);
			if (error) {
				DBG_PRINTF("%s copyout_maddr()  failed\n",
				    __func__);
				goto done;
			}
		}
		if (user_msg.msg_control != 0 && user_msg.msg_controllen != 0) {
			error = copyout_control(p, control,
			    user_msg.msg_control, &user_msg.msg_controllen,
			    &user_msg.msg_flags, so);
			if (error) {
				DBG_PRINTF("%s copyout_control() failed\n",
				    __func__);
				goto done;
			}
		}
		/*
		 * Note: the original msg_iovlen and msg_iov do not change
		 */
		if (spacetype == UIO_USERSPACE64) {
			msghdrx64.msg_flags = user_msg.msg_flags;
			msghdrx64.msg_controllen = user_msg.msg_controllen;
			msghdrx64.msg_control = user_msg.msg_control;
			msghdrx64.msg_namelen = user_msg.msg_namelen;
			msghdrx64.msg_name = user_msg.msg_name;
			msghdrx64.msg_datalen = len;
		} else {
			msghdrx32.msg_flags = user_msg.msg_flags;
			msghdrx32.msg_controllen = user_msg.msg_controllen;
			msghdrx32.msg_control = (user32_addr_t) user_msg.msg_control;
			msghdrx32.msg_name = user_msg.msg_namelen;
			msghdrx32.msg_name = (user32_addr_t) user_msg.msg_name;
			msghdrx32.msg_datalen = (user32_size_t) len;
		}
		error = copyout(msghdrxp,
		    (user_addr_t)(src + i * size_of_msghdrx),
		    size_of_msghdrx);
		if (error) {
			DBG_PRINTF("%s copyout() msghdrx failed\n", __func__);
			goto done;
		}

		m = m->m_nextpkt;
		if (control != NULL) {
			control = control->m_nextpkt;
		}
		if (m_addr != NULL) {
			m_addr = m_addr->m_nextpkt;
		}
	}

	uap->flags = flags;

	*retval = (int)i;
done:
	file_drop(uap->s);

done_no_filedrop:
	if (pkt_list != NULL) {
		m_freem_list(pkt_list);
	}
	if (addr_list != NULL) {
		m_freem_list(addr_list);
	}
	if (ctl_list != NULL) {
		m_freem_list(ctl_list);
	}
	if (auio != NULL) {
		uio_free(auio);
	}

	KERNEL_DEBUG(DBG_FNC_RECVMSG_X | DBG_FUNC_END, error, 0, 0, 0, 0);

	return error;
}

/*
 * Returns:	0			Success
 *		EBADF
 *	file_socket:ENOTSOCK
 *	file_socket:EBADF
 *	soshutdown:EINVAL
 *	soshutdown:ENOTCONN
 *	soshutdown:EADDRNOTAVAIL[TCP]
 *	soshutdown:ENOBUFS[TCP]
 *	soshutdown:EMSGSIZE[TCP]
 *	soshutdown:EHOSTUNREACH[TCP]
 *	soshutdown:ENETUNREACH[TCP]
 *	soshutdown:ENETDOWN[TCP]
 *	soshutdown:ENOMEM[TCP]
 *	soshutdown:EACCES[TCP]
 *	soshutdown:EMSGSIZE[TCP]
 *	soshutdown:ENOBUFS[TCP]
 *	soshutdown:???[TCP]		[ignorable: mostly IPSEC/firewall/DLIL]
 *	soshutdown:???			[other protocol families]
 */
/* ARGSUSED */
int
shutdown(__unused proc_ref_t p, struct shutdown_args *uap,
    __unused int32_ref_t retval)
{
	socket_ref_t so;
	int error;

	AUDIT_ARG(fd, uap->s);
	error = file_socket(uap->s, &so);
	if (error) {
		return error;
	}
	if (so == NULL) {
		error = EBADF;
		goto out;
	}
	error =  soshutdown((struct socket *)so, uap->how);
out:
	file_drop(uap->s);
	return error;
}

/*
 * Returns:	0			Success
 *		EFAULT
 *		EINVAL
 *		EACCES			Mandatory Access Control failure
 *	file_socket:ENOTSOCK
 *	file_socket:EBADF
 *	sosetopt:EINVAL
 *	sosetopt:ENOPROTOOPT
 *	sosetopt:ENOBUFS
 *	sosetopt:EDOM
 *	sosetopt:EFAULT
 *	sosetopt:EOPNOTSUPP[AF_UNIX]
 *	sosetopt:???
 */
/* ARGSUSED */
int
setsockopt(proc_ref_t p, setsockopt_args_ref_t uap,
    __unused int32_ref_t retval)
{
	socket_ref_t so;
	struct sockopt sopt;
	int error;

	AUDIT_ARG(fd, uap->s);
	if (uap->val == 0 && uap->valsize != 0) {
		return EFAULT;
	}
	/* No bounds checking on size (it's unsigned) */

	error = file_socket(uap->s, &so);
	if (error) {
		return error;
	}

	sopt.sopt_dir = SOPT_SET;
	sopt.sopt_level = uap->level;
	sopt.sopt_name = uap->name;
	sopt.sopt_val = uap->val;
	sopt.sopt_valsize = uap->valsize;
	sopt.sopt_p = p;

	if (so == NULL) {
		error = EINVAL;
		goto out;
	}
#if CONFIG_MACF_SOCKET_SUBSET
	if ((error = mac_socket_check_setsockopt(kauth_cred_get(), so,
	    &sopt)) != 0) {
		goto out;
	}
#endif /* MAC_SOCKET_SUBSET */
	error = sosetoptlock(so, &sopt, 1);     /* will lock socket */
out:
	file_drop(uap->s);
	return error;
}



/*
 * Returns:	0			Success
 *		EINVAL
 *		EBADF
 *		EACCES			Mandatory Access Control failure
 *	copyin:EFAULT
 *	copyout:EFAULT
 *	file_socket:ENOTSOCK
 *	file_socket:EBADF
 *	sogetopt:???
 */
int
getsockopt(proc_ref_t p, struct getsockopt_args  *uap,
    __unused int32_ref_t retval)
{
	int             error;
	socklen_t       valsize;
	struct sockopt  sopt;
	socket_ref_t so;

	error = file_socket(uap->s, &so);
	if (error) {
		return error;
	}
	if (uap->val) {
		error = copyin(uap->avalsize, (caddr_t)&valsize,
		    sizeof(valsize));
		if (error) {
			goto out;
		}
		/* No bounds checking on size (it's unsigned) */
	} else {
		valsize = 0;
	}
	sopt.sopt_dir = SOPT_GET;
	sopt.sopt_level = uap->level;
	sopt.sopt_name = uap->name;
	sopt.sopt_val = uap->val;
	sopt.sopt_valsize = (size_t)valsize; /* checked non-negative above */
	sopt.sopt_p = p;

	if (so == NULL) {
		error = EBADF;
		goto out;
	}
#if CONFIG_MACF_SOCKET_SUBSET
	if ((error = mac_socket_check_getsockopt(kauth_cred_get(), so,
	    &sopt)) != 0) {
		goto out;
	}
#endif /* MAC_SOCKET_SUBSET */
	error = sogetoptlock((struct socket *)so, &sopt, 1);    /* will lock */
	if (error == 0) {
		valsize = (socklen_t)sopt.sopt_valsize;
		error = copyout((caddr_t)&valsize, uap->avalsize,
		    sizeof(valsize));
	}
out:
	file_drop(uap->s);
	return error;
}


/*
 * Get socket name.
 *
 * Returns:	0			Success
 *		EBADF
 *	file_socket:ENOTSOCK
 *	file_socket:EBADF
 *	copyin:EFAULT
 *	copyout:EFAULT
 *	<pru_sockaddr>:ENOBUFS[TCP]
 *	<pru_sockaddr>:ECONNRESET[TCP]
 *	<pru_sockaddr>:EINVAL[AF_UNIX]
 *	<sf_getsockname>:???
 */
/* ARGSUSED */
int
getsockname(__unused proc_ref_t p, struct getsockname_args *uap,
    __unused int32_ref_t retval)
{
	socket_ref_t so;
	sockaddr_ref_t  sa;
	socklen_t len;
	socklen_t sa_len;
	int error;

	error = file_socket(uap->fdes, &so);
	if (error) {
		return error;
	}
	error = copyin(uap->alen, (caddr_t)&len, sizeof(socklen_t));
	if (error) {
		goto out;
	}
	if (so == NULL) {
		error = EBADF;
		goto out;
	}
	sa = 0;
	socket_lock(so, 1);
	error = (*so->so_proto->pr_usrreqs->pru_sockaddr)(so, &sa);
	if (error == 0) {
		error = sflt_getsockname(so, &sa);
		if (error == EJUSTRETURN) {
			error = 0;
		}
	}
	socket_unlock(so, 1);
	if (error) {
		goto bad;
	}
	if (sa == 0) {
		len = 0;
		goto gotnothing;
	}

	sa_len = sa->sa_len;
	len = MIN(len, sa_len);
	error = copyout((caddr_t)sa, uap->asa, len);
	if (error) {
		goto bad;
	}
	/* return the actual, untruncated address length */
	len = sa_len;
gotnothing:
	error = copyout((caddr_t)&len, uap->alen, sizeof(socklen_t));
bad:
	free_sockaddr(sa);
out:
	file_drop(uap->fdes);
	return error;
}

/*
 * Get name of peer for connected socket.
 *
 * Returns:	0			Success
 *		EBADF
 *		EINVAL
 *		ENOTCONN
 *	file_socket:ENOTSOCK
 *	file_socket:EBADF
 *	copyin:EFAULT
 *	copyout:EFAULT
 *	<pru_peeraddr>:???
 *	<sf_getpeername>:???
 */
/* ARGSUSED */
int
getpeername(__unused proc_ref_t p, struct getpeername_args *uap,
    __unused int32_ref_t retval)
{
	socket_ref_t so;
	sockaddr_ref_t  sa;
	socklen_t len;
	socklen_t sa_len;
	int error;

	error = file_socket(uap->fdes, &so);
	if (error) {
		return error;
	}
	if (so == NULL) {
		error = EBADF;
		goto out;
	}

	socket_lock(so, 1);

	if ((so->so_state & (SS_CANTRCVMORE | SS_CANTSENDMORE)) ==
	    (SS_CANTRCVMORE | SS_CANTSENDMORE)) {
		/* the socket has been shutdown, no more getpeername's */
		socket_unlock(so, 1);
		error = EINVAL;
		goto out;
	}

	if ((so->so_state & (SS_ISCONNECTED | SS_ISCONFIRMING)) == 0) {
		socket_unlock(so, 1);
		error = ENOTCONN;
		goto out;
	}
	error = copyin(uap->alen, (caddr_t)&len, sizeof(socklen_t));
	if (error) {
		socket_unlock(so, 1);
		goto out;
	}
	sa = 0;
	error = (*so->so_proto->pr_usrreqs->pru_peeraddr)(so, &sa);
	if (error == 0) {
		error = sflt_getpeername(so, &sa);
		if (error == EJUSTRETURN) {
			error = 0;
		}
	}
	socket_unlock(so, 1);
	if (error) {
		goto bad;
	}
	if (sa == 0) {
		len = 0;
		goto gotnothing;
	}
	sa_len = sa->sa_len;
	len = MIN(len, sa_len);
	error = copyout(sa, uap->asa, len);
	if (error) {
		goto bad;
	}
	/* return the actual, untruncated address length */
	len = sa_len;
gotnothing:
	error = copyout((caddr_t)&len, uap->alen, sizeof(socklen_t));
bad:
	free_sockaddr(sa);
out:
	file_drop(uap->fdes);
	return error;
}

int
sockargs(struct mbuf **mp, user_addr_t data, socklen_t buflen, int type)
{
	sockaddr_ref_t sa;
	struct mbuf *m;
	int error;
	socklen_t alloc_buflen = buflen;

	if (buflen > INT_MAX / 2) {
		return EINVAL;
	}
	if (type == MT_SONAME && (buflen > SOCK_MAXADDRLEN ||
	    buflen < offsetof(struct sockaddr, sa_data[0]))) {
		return EINVAL;
	}
	if (type == MT_CONTROL && buflen < sizeof(struct cmsghdr)) {
		return EINVAL;
	}

#ifdef __LP64__
	/*
	 * The fd's in the buffer must expand to be pointers, thus we need twice
	 * as much space
	 */
	if (type == MT_CONTROL) {
		alloc_buflen = ((buflen - sizeof(struct cmsghdr)) * 2) +
		    sizeof(struct cmsghdr);
	}
#endif
	if (alloc_buflen > MLEN) {
		if (type == MT_SONAME && alloc_buflen <= 112) {
			alloc_buflen = MLEN;    /* unix domain compat. hack */
		} else if (alloc_buflen > MCLBYTES) {
			return EINVAL;
		}
	}
	m = m_get(M_WAIT, type);
	if (m == NULL) {
		return ENOBUFS;
	}
	if (alloc_buflen > MLEN) {
		MCLGET(m, M_WAIT);
		if ((m->m_flags & M_EXT) == 0) {
			m_free(m);
			return ENOBUFS;
		}
	}
	/*
	 * K64: We still copyin the original buflen because it gets expanded
	 * later and we lie about the size of the mbuf because it only affects
	 * unp_* functions
	 */
	m->m_len = buflen;
	error = copyin(data, mtod(m, caddr_t), (u_int)buflen);
	if (error) {
		(void) m_free(m);
	} else {
		*mp = m;
		if (type == MT_SONAME) {
			VERIFY(buflen <= SOCK_MAXADDRLEN);
			sa = mtod(m, sockaddr_ref_t);
			sa->sa_len = (__uint8_t)buflen;
		}
	}
	return error;
}

/*
 * Given a user_addr_t of length len, allocate and fill out a *sa.
 *
 * Returns:	0			Success
 *		ENAMETOOLONG		Filename too long
 *		EINVAL			Invalid argument
 *		ENOMEM			Not enough space
 *		copyin:EFAULT		Bad address
 */
static int
getsockaddr(struct socket *so, sockaddr_ref_ref_t namp, user_addr_t uaddr,
    size_t len, boolean_t translate_unspec)
{
	sockaddr_ref_t  sa;
	int error;

	if (len > SOCK_MAXADDRLEN) {
		return ENAMETOOLONG;
	}

	if (len < offsetof(struct sockaddr, sa_data[0])) {
		return EINVAL;
	}

	sa = (sockaddr_ref_t)alloc_sockaddr(len, Z_WAITOK | Z_NOFAIL);

	error = copyin(uaddr, (caddr_t)sa, len);
	if (error) {
		free_sockaddr(sa);
	} else {
		/*
		 * Force sa_family to AF_INET on AF_INET sockets to handle
		 * legacy applications that use AF_UNSPEC (0).  On all other
		 * sockets we leave it unchanged and let the lower layer
		 * handle it.
		 */
		if (translate_unspec && sa->sa_family == AF_UNSPEC &&
		    SOCK_CHECK_DOM(so, PF_INET) &&
		    len == sizeof(struct sockaddr_in)) {
			sa->sa_family = AF_INET;
		}
		VERIFY(len <= SOCK_MAXADDRLEN);
		sa = *&sa;
		sa->sa_len = (__uint8_t)len;
		*namp = sa;
	}
	return error;
}

static int
getsockaddr_s(struct socket *so, sockaddr_storage_ref_t ss,
    user_addr_t uaddr, size_t len, boolean_t translate_unspec)
{
	int error;

	if (ss == NULL || uaddr == USER_ADDR_NULL ||
	    len < offsetof(struct sockaddr, sa_data[0])) {
		return EINVAL;
	}

	/*
	 * sockaddr_storage size is less than SOCK_MAXADDRLEN,
	 * so the check here is inclusive.
	 */
	if (len > sizeof(*ss)) {
		return ENAMETOOLONG;
	}

	bzero(ss, sizeof(*ss));
	error = copyin(uaddr, (caddr_t)ss, len);
	if (error == 0) {
		/*
		 * Force sa_family to AF_INET on AF_INET sockets to handle
		 * legacy applications that use AF_UNSPEC (0).  On all other
		 * sockets we leave it unchanged and let the lower layer
		 * handle it.
		 */
		if (translate_unspec && ss->ss_family == AF_UNSPEC &&
		    SOCK_CHECK_DOM(so, PF_INET) &&
		    len == sizeof(struct sockaddr_in)) {
			ss->ss_family = AF_INET;
		}

		ss->ss_len = (__uint8_t)len;
	}
	return error;
}

#if DEBUG || DEVELOPMENT
int
internalize_user_msghdr_array(const void_ptr_t src, int spacetype, int direction,
    u_int count, user_msghdr_x_ptr_t dst, uio_ref_ptr_t uiop)
{
	int error = 0;
	u_int i;
	u_int namecnt = 0;
	u_int ctlcnt = 0;

	for (i = 0; i < count; i++) {
		uio_t auio;
		struct user_iovec *iovp;
		struct user_msghdr_x *user_msg = dst + i;

		if (spacetype == UIO_USERSPACE64) {
			const struct user64_msghdr_x *msghdr64;

			msghdr64 = ((const struct user64_msghdr_x *)src) + i;

			user_msg->msg_name = (user_addr_t)msghdr64->msg_name;
			user_msg->msg_namelen = msghdr64->msg_namelen;
			user_msg->msg_iov = (user_addr_t)msghdr64->msg_iov;
			user_msg->msg_iovlen = msghdr64->msg_iovlen;
			user_msg->msg_control = (user_addr_t)msghdr64->msg_control;
			user_msg->msg_controllen = msghdr64->msg_controllen;
			user_msg->msg_flags = msghdr64->msg_flags;
			user_msg->msg_datalen = (size_t)msghdr64->msg_datalen;
		} else {
			const struct user32_msghdr_x *msghdr32;

			msghdr32 = ((const struct user32_msghdr_x *)src) + i;

			user_msg->msg_name = msghdr32->msg_name;
			user_msg->msg_namelen = msghdr32->msg_namelen;
			user_msg->msg_iov = msghdr32->msg_iov;
			user_msg->msg_iovlen = msghdr32->msg_iovlen;
			user_msg->msg_control = msghdr32->msg_control;
			user_msg->msg_controllen = msghdr32->msg_controllen;
			user_msg->msg_flags = msghdr32->msg_flags;
			user_msg->msg_datalen = msghdr32->msg_datalen;
		}

		if (user_msg->msg_iovlen <= 0 ||
		    user_msg->msg_iovlen > UIO_MAXIOV) {
			error = EMSGSIZE;
			goto done;
		}
		auio = uio_create(user_msg->msg_iovlen, 0, spacetype,
		    direction);
		if (auio == NULL) {
			error = ENOMEM;
			goto done;
		}
		uiop[i] = auio;

		iovp = uio_iovsaddr(auio);
		if (iovp == NULL) {
			error = ENOMEM;
			goto done;
		}
		error = copyin_user_iovec_array(user_msg->msg_iov,
		    spacetype, user_msg->msg_iovlen, iovp);
		if (error) {
			goto done;
		}
		user_msg->msg_iov = CAST_USER_ADDR_T(iovp);

		error = uio_calculateresid(auio);
		if (error) {
			goto done;
		}
		user_msg->msg_datalen = uio_resid(auio);

		if (user_msg->msg_name && user_msg->msg_namelen) {
			namecnt++;
		}
		if (user_msg->msg_control && user_msg->msg_controllen) {
			ctlcnt++;
		}
	}
done:

	return error;
}
#endif /* DEBUG || DEVELOPMENT */

int
internalize_recv_msghdr_array(const void_ptr_t src, int spacetype, int direction,
    u_int count, user_msghdr_x_ptr_t dst,
    recv_msg_elem_ptr_t recv_msg_array)
{
	int error = 0;
	u_int i;

	for (i = 0; i < count; i++) {
		struct user_iovec *iovp;
		struct user_msghdr_x *user_msg = dst + i;
		struct recv_msg_elem *recv_msg_elem = recv_msg_array + i;

		if (spacetype == UIO_USERSPACE64) {
			const struct user64_msghdr_x *msghdr64;

			msghdr64 = ((const struct user64_msghdr_x *)src) + i;

			user_msg->msg_name = (user_addr_t)msghdr64->msg_name;
			user_msg->msg_namelen = msghdr64->msg_namelen;
			user_msg->msg_iov = (user_addr_t)msghdr64->msg_iov;
			user_msg->msg_iovlen = msghdr64->msg_iovlen;
			user_msg->msg_control = (user_addr_t)msghdr64->msg_control;
			user_msg->msg_controllen = msghdr64->msg_controllen;
			user_msg->msg_flags = msghdr64->msg_flags;
			user_msg->msg_datalen = (size_t)msghdr64->msg_datalen;
		} else {
			const struct user32_msghdr_x *msghdr32;

			msghdr32 = ((const struct user32_msghdr_x *)src) + i;

			user_msg->msg_name = msghdr32->msg_name;
			user_msg->msg_namelen = msghdr32->msg_namelen;
			user_msg->msg_iov = msghdr32->msg_iov;
			user_msg->msg_iovlen = msghdr32->msg_iovlen;
			user_msg->msg_control = msghdr32->msg_control;
			user_msg->msg_controllen = msghdr32->msg_controllen;
			user_msg->msg_flags = msghdr32->msg_flags;
			user_msg->msg_datalen = msghdr32->msg_datalen;
		}

		if (user_msg->msg_iovlen <= 0 ||
		    user_msg->msg_iovlen > UIO_MAXIOV) {
			error = EMSGSIZE;
			goto done;
		}
		recv_msg_elem->uio = uio_create(user_msg->msg_iovlen, 0,
		    spacetype, direction);
		if (recv_msg_elem->uio == NULL) {
			error = ENOMEM;
			goto done;
		}

		iovp = uio_iovsaddr(recv_msg_elem->uio);
		if (iovp == NULL) {
			error = ENOMEM;
			goto done;
		}
		error = copyin_user_iovec_array(user_msg->msg_iov,
		    spacetype, user_msg->msg_iovlen, iovp);
		if (error) {
			goto done;
		}
		user_msg->msg_iov = CAST_USER_ADDR_T(iovp);

		error = uio_calculateresid(recv_msg_elem->uio);
		if (error) {
			goto done;
		}
		user_msg->msg_datalen = uio_resid(recv_msg_elem->uio);

		if (user_msg->msg_name && user_msg->msg_namelen) {
			recv_msg_elem->which |= SOCK_MSG_SA;
		}
		if (user_msg->msg_control && user_msg->msg_controllen) {
			recv_msg_elem->which |= SOCK_MSG_CONTROL;
		}
	}
done:

	return error;
}

#if DEBUG || DEVELOPMENT
void
externalize_user_msghdr_array(void_ptr_t dst, int spacetype, int direction,
    u_int count, const user_msghdr_x_ptr_t src, uio_ref_ptr_t uiop)
{
#pragma unused(direction)
	u_int i;

	for (i = 0; i < count; i++) {
		const struct user_msghdr_x *user_msg = src + i;
		uio_t auio = uiop[i];
		user_ssize_t len = user_msg->msg_datalen - uio_resid(auio);

		if (spacetype == UIO_USERSPACE64) {
			struct user64_msghdr_x *msghdr64;

			msghdr64 = ((struct user64_msghdr_x *)dst) + i;

			msghdr64->msg_flags = user_msg->msg_flags;
			msghdr64->msg_datalen = len;
		} else {
			struct user32_msghdr_x *msghdr32;

			msghdr32 = ((struct user32_msghdr_x *)dst) + i;

			msghdr32->msg_flags = user_msg->msg_flags;
			msghdr32->msg_datalen = (user32_size_t)len;
		}
	}
}
#endif /* DEBUG || DEVELOPMENT */

u_int
externalize_recv_msghdr_array(proc_ref_t p, socket_ref_t so, void_ptr_t dst,
    u_int count, user_msghdr_x_ptr_t src,
    recv_msg_elem_ptr_t recv_msg_array, int_ref_t ret_error)
{
	u_int i;
	u_int retcnt = 0;
	int spacetype = IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32;

	*ret_error = 0;

	for (i = 0; i < count; i++) {
		struct user_msghdr_x *user_msg = src + i;
		struct recv_msg_elem *recv_msg_elem = recv_msg_array + i;
		user_ssize_t len = 0;
		int error;

		len = user_msg->msg_datalen - uio_resid(recv_msg_elem->uio);

		if ((recv_msg_elem->which & SOCK_MSG_DATA)) {
			retcnt++;

			if (recv_msg_elem->which & SOCK_MSG_SA) {
				error = copyout_sa(recv_msg_elem->psa, user_msg->msg_name,
				    &user_msg->msg_namelen);
				if (error != 0) {
					*ret_error = error;
					return 0;
				}
			}
			if (recv_msg_elem->which & SOCK_MSG_CONTROL) {
				error = copyout_control(p, recv_msg_elem->controlp,
				    user_msg->msg_control, &user_msg->msg_controllen,
				    &recv_msg_elem->flags, so);
				if (error != 0) {
					*ret_error = error;
					return 0;
				}
			}
		}

		if (spacetype == UIO_USERSPACE64) {
			struct user64_msghdr_x *msghdr64 = ((struct user64_msghdr_x *)dst) + i;

			msghdr64->msg_namelen = user_msg->msg_namelen;
			msghdr64->msg_controllen = user_msg->msg_controllen;
			msghdr64->msg_flags = recv_msg_elem->flags;
			msghdr64->msg_datalen = len;
		} else {
			struct user32_msghdr_x *msghdr32 = ((struct user32_msghdr_x *)dst) + i;

			msghdr32->msg_namelen = user_msg->msg_namelen;
			msghdr32->msg_controllen = user_msg->msg_controllen;
			msghdr32->msg_flags = recv_msg_elem->flags;
			msghdr32->msg_datalen = (user32_size_t)len;
		}
	}
	return retcnt;
}

#if DEBUG || DEVELOPMENT
void
free_uio_array(uio_ref_ptr_t uiop, u_int count)
{
	u_int i;

	for (i = 0; i < count; i++) {
		if (uiop[i] != NULL) {
			uio_free(uiop[i]);
		}
	}
}
#endif /* DEBUG || DEVELOPMENT */

/* Extern linkage requires using __counted_by instead of bptr */
__private_extern__ user_ssize_t
uio_array_resid(uio_ref_t * __counted_by(count)uiop, u_int count)
{
	user_ssize_t len = 0;
	u_int i;

	for (i = 0; i < count; i++) {
		struct uio *auio = uiop[i];

		if (auio != NULL) {
			len += uio_resid(auio);
		}
	}
	return len;
}

#if DEBUG || DEVELOPMENT
static boolean_t
uio_array_is_valid(uio_ref_ptr_t uiop, u_int count)
{
	user_ssize_t len = 0;
	u_int i;

	for (i = 0; i < count; i++) {
		struct uio *auio = uiop[i];

		if (auio != NULL) {
			user_ssize_t resid = uio_resid(auio);

			/*
			 * Sanity check on the validity of the iovec:
			 * no point of going over sb_max
			 */
			if (resid < 0 || resid > (user_ssize_t)sb_max) {
				return false;
			}

			len += resid;
			if (len < 0 || len > (user_ssize_t)sb_max) {
				return false;
			}
		}
	}
	return true;
}
#endif /* DEBUG || DEVELOPMENT */

recv_msg_elem_ptr_t
alloc_recv_msg_array(u_int count)
{
	return kalloc_type(struct recv_msg_elem, count, Z_WAITOK | Z_ZERO);
}

void
free_recv_msg_array(recv_msg_elem_ptr_t recv_msg_array, u_int count)
{
	if (recv_msg_array == NULL) {
		return;
	}
	for (uint32_t i = 0; i < count; i++) {
		struct recv_msg_elem *recv_msg_elem = recv_msg_array + i;

		if (recv_msg_elem->uio != NULL) {
			uio_free(recv_msg_elem->uio);
		}
		free_sockaddr(recv_msg_elem->psa);
		if (recv_msg_elem->controlp != NULL) {
			m_freem(recv_msg_elem->controlp);
		}
	}
	kfree_type(struct recv_msg_elem, count, recv_msg_array);
}


/* Extern linkage requires using __counted_by instead of bptr */
__private_extern__ user_ssize_t
recv_msg_array_resid(struct recv_msg_elem * __counted_by(count)recv_msg_array, u_int count)
{
	user_ssize_t len = 0;
	u_int i;

	for (i = 0; i < count; i++) {
		struct recv_msg_elem *recv_msg_elem = recv_msg_array + i;

		if (recv_msg_elem->uio != NULL) {
			len += uio_resid(recv_msg_elem->uio);
		}
	}
	return len;
}

int
recv_msg_array_is_valid(recv_msg_elem_ptr_t recv_msg_array, u_int count)
{
	user_ssize_t len = 0;
	u_int i;

	for (i = 0; i < count; i++) {
		struct recv_msg_elem *recv_msg_elem = recv_msg_array + i;

		if (recv_msg_elem->uio != NULL) {
			user_ssize_t resid = uio_resid(recv_msg_elem->uio);

			/*
			 * Sanity check on the validity of the iovec:
			 * no point of going over sb_max
			 */
			if (resid < 0 || (u_int32_t)resid > sb_max) {
				return 0;
			}

			len += resid;
			if (len < 0 || (u_int32_t)len > sb_max) {
				return 0;
			}
		}
	}
	return 1;
}

#if SENDFILE

#define SFUIOBUFS 64

/* Macros to compute the number of mbufs needed depending on cluster size */
#define HOWMANY_16K(n)  ((((unsigned int)(n) - 1) >> M16KCLSHIFT) + 1)
#define HOWMANY_4K(n)   ((((unsigned int)(n) - 1) >> MBIGCLSHIFT) + 1)

/* Upper send limit in bytes (SFUIOBUFS * PAGESIZE) */
#define SENDFILE_MAX_BYTES      (SFUIOBUFS << PGSHIFT)

/* Upper send limit in the number of mbuf clusters */
#define SENDFILE_MAX_16K        HOWMANY_16K(SENDFILE_MAX_BYTES)
#define SENDFILE_MAX_4K         HOWMANY_4K(SENDFILE_MAX_BYTES)

static void
alloc_sendpkt(int how, size_t pktlen, unsigned int *maxchunks,
    mbuf_ref_ref_t m, boolean_t jumbocl)
{
	unsigned int needed;

	if (pktlen == 0) {
		panic("%s: pktlen (%ld) must be non-zero", __func__, pktlen);
	}

	/*
	 * Try to allocate for the whole thing.  Since we want full control
	 * over the buffer size and be able to accept partial result, we can't
	 * use mbuf_allocpacket().  The logic below is similar to sosend().
	 */
	*m = NULL;
	if (pktlen > MBIGCLBYTES && jumbocl) {
		needed = MIN(SENDFILE_MAX_16K, HOWMANY_16K(pktlen));
		*m = m_getpackets_internal(&needed, 1, how, 0, M16KCLBYTES);
	}
	if (*m == NULL) {
		needed = MIN(SENDFILE_MAX_4K, HOWMANY_4K(pktlen));
		*m = m_getpackets_internal(&needed, 1, how, 0, MBIGCLBYTES);
	}

	/*
	 * Our previous attempt(s) at allocation had failed; the system
	 * may be short on mbufs, and we want to block until they are
	 * available.  This time, ask just for 1 mbuf and don't return
	 * until we get it.
	 */
	if (*m == NULL) {
		needed = 1;
		*m = m_getpackets_internal(&needed, 1, M_WAIT, 1, MBIGCLBYTES);
	}
	if (*m == NULL) {
		panic("%s: blocking allocation returned NULL", __func__);
	}

	*maxchunks = needed;
}

/*
 * sendfile(2).
 * int sendfile(int fd, int s, off_t offset, off_t *nbytes,
 *	 struct sf_hdtr *hdtr, int flags)
 *
 * Send a file specified by 'fd' and starting at 'offset' to a socket
 * specified by 's'. Send only '*nbytes' of the file or until EOF if
 * *nbytes == 0. Optionally add a header and/or trailer to the socket
 * output. If specified, write the total number of bytes sent into *nbytes.
 */
int
sendfile(proc_ref_t p, struct sendfile_args *uap, __unused int *retval)
{
	fileproc_ref_t  fp;
	vnode_ref_t  vp;
	socket_ref_t so;
	struct writev_nocancel_args nuap;
	user_ssize_t writev_retval;
	struct user_sf_hdtr user_hdtr;
	struct user32_sf_hdtr user32_hdtr;
	struct user64_sf_hdtr user64_hdtr;
	off_t off, xfsize;
	off_t nbytes = 0, sbytes = 0;
	int error = 0;
	size_t sizeof_hdtr;
	off_t file_size;
	struct vfs_context context = *vfs_context_current();

	const bool is_p_64bit_process = IS_64BIT_PROCESS(p);

	KERNEL_DEBUG_CONSTANT((DBG_FNC_SENDFILE | DBG_FUNC_START), uap->s,
	    0, 0, 0, 0);

	AUDIT_ARG(fd, uap->fd);
	AUDIT_ARG(value32, uap->s);

	/*
	 * Do argument checking. Must be a regular file in, stream
	 * type and connected socket out, positive offset.
	 */
	if ((error = fp_getfvp(p, uap->fd, &fp, &vp))) {
		goto done;
	}
	if ((fp->f_flag & FREAD) == 0) {
		error = EBADF;
		goto done1;
	}
	if (vnode_isreg(vp) == 0) {
		error = ENOTSUP;
		goto done1;
	}
	error = file_socket(uap->s, &so);
	if (error) {
		goto done1;
	}
	if (so == NULL) {
		error = EBADF;
		goto done2;
	}
	if (so->so_type != SOCK_STREAM) {
		error = EINVAL;
		goto done2;
	}
	if ((so->so_state & SS_ISCONNECTED) == 0) {
		error = ENOTCONN;
		goto done2;
	}
	if (uap->offset < 0) {
		error = EINVAL;
		goto done2;
	}
	if (uap->nbytes == USER_ADDR_NULL) {
		error = EINVAL;
		goto done2;
	}
	if (uap->flags != 0) {
		error = EINVAL;
		goto done2;
	}

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

#if CONFIG_MACF_SOCKET_SUBSET
	/* JMM - fetch connected sockaddr? */
	error = mac_socket_check_send(context.vc_ucred, so, NULL);
	if (error) {
		goto done2;
	}
#endif

	/*
	 * Get number of bytes to send
	 * Should it applies to size of header and trailer?
	 */
	error = copyin(uap->nbytes, &nbytes, sizeof(off_t));
	if (error) {
		goto done2;
	}

	/*
	 * If specified, get the pointer to the sf_hdtr struct for
	 * any headers/trailers.
	 */
	if (uap->hdtr != USER_ADDR_NULL) {
		caddr_t hdtrp;

		bzero(&user_hdtr, sizeof(user_hdtr));
		if (is_p_64bit_process) {
			hdtrp = (caddr_t)&user64_hdtr;
			sizeof_hdtr = sizeof(user64_hdtr);
		} else {
			hdtrp = (caddr_t)&user32_hdtr;
			sizeof_hdtr = sizeof(user32_hdtr);
		}
		error = copyin(uap->hdtr, hdtrp, sizeof_hdtr);
		if (error) {
			goto done2;
		}
		if (is_p_64bit_process) {
			user_hdtr.headers = user64_hdtr.headers;
			user_hdtr.hdr_cnt = user64_hdtr.hdr_cnt;
			user_hdtr.trailers = user64_hdtr.trailers;
			user_hdtr.trl_cnt = user64_hdtr.trl_cnt;
		} else {
			user_hdtr.headers = user32_hdtr.headers;
			user_hdtr.hdr_cnt = user32_hdtr.hdr_cnt;
			user_hdtr.trailers = user32_hdtr.trailers;
			user_hdtr.trl_cnt = user32_hdtr.trl_cnt;
		}

		/*
		 * Send any headers. Wimp out and use writev(2).
		 */
		if (user_hdtr.headers != USER_ADDR_NULL) {
			bzero(&nuap, sizeof(struct writev_args));
			nuap.fd = uap->s;
			nuap.iovp = user_hdtr.headers;
			nuap.iovcnt = user_hdtr.hdr_cnt;
			error = writev_nocancel(p, &nuap, &writev_retval);
			if (error) {
				goto done2;
			}
			sbytes += writev_retval;
		}
	}

	/*
	 * Get the file size for 2 reasons:
	 *  1. We don't want to allocate more mbufs than necessary
	 *  2. We don't want to read past the end of file
	 */
	if ((error = vnode_size(vp, &file_size, vfs_context_current())) != 0) {
		goto done2;
	}

	/*
	 * Simply read file data into a chain of mbufs that used with scatter
	 * gather reads. We're not (yet?) setup to use zero copy external
	 * mbufs that point to the file pages.
	 */
	socket_lock(so, 1);
	error = sblock(&so->so_snd, SBL_WAIT);
	if (error) {
		socket_unlock(so, 1);
		goto done2;
	}
	for (off = uap->offset;; off += xfsize, sbytes += xfsize) {
		mbuf_ref_t m0 = NULL;
		mbuf_t  m;
		unsigned int    nbufs = SFUIOBUFS, i;
		uio_t   auio;
		UIO_STACKBUF(uio_buf, SFUIOBUFS);               /* 1KB !!! */
		size_t  uiolen;
		user_ssize_t    rlen;
		off_t   pgoff;
		size_t  pktlen;
		boolean_t jumbocl;

		/*
		 * Calculate the amount to transfer.
		 * Align to round number of pages.
		 * Not to exceed send socket buffer,
		 * the EOF, or the passed in nbytes.
		 */
		xfsize = sbspace(&so->so_snd);

		if (xfsize <= 0) {
			if (so->so_state & SS_CANTSENDMORE) {
				error = EPIPE;
				goto done3;
			} else if ((so->so_state & SS_NBIO)) {
				error = EAGAIN;
				goto done3;
			} else {
				xfsize = PAGE_SIZE;
			}
		}

		if (xfsize > SENDFILE_MAX_BYTES) {
			xfsize = SENDFILE_MAX_BYTES;
		} else if (xfsize > PAGE_SIZE) {
			xfsize = trunc_page(xfsize);
		}
		pgoff = off & PAGE_MASK_64;
		if (pgoff > 0 && PAGE_SIZE - pgoff < xfsize) {
			xfsize = PAGE_SIZE_64 - pgoff;
		}
		if (nbytes && xfsize > (nbytes - sbytes)) {
			xfsize = nbytes - sbytes;
		}
		if (xfsize <= 0) {
			break;
		}
		if (off + xfsize > file_size) {
			xfsize = file_size - off;
		}
		if (xfsize <= 0) {
			break;
		}

		/*
		 * Attempt to use larger than system page-size clusters for
		 * large writes only if there is a jumbo cluster pool and
		 * if the socket is marked accordingly.
		 */
		jumbocl = sosendjcl && njcl > 0 &&
		    ((so->so_flags & SOF_MULTIPAGES) || sosendjcl_ignore_capab);

		socket_unlock(so, 0);
		alloc_sendpkt(M_WAIT, xfsize, &nbufs, &m0, jumbocl);
		pktlen = mbuf_pkthdr_maxlen(m0);
		if (pktlen < (size_t)xfsize) {
			xfsize = pktlen;
		}

		auio = uio_createwithbuffer(nbufs, off, UIO_SYSSPACE,
		    UIO_READ, &uio_buf[0], sizeof(uio_buf));
		if (auio == NULL) {
			DBG_PRINTF("sendfile failed. nbufs = %d. %s", nbufs,
			    "File a radar related to rdar://10146739.\n");
			mbuf_freem(m0);
			error = ENXIO;
			socket_lock(so, 0);
			goto done3;
		}

		for (i = 0, m = m0, uiolen = 0;
		    i < nbufs && m != NULL && uiolen < (size_t)xfsize;
		    i++, m = mbuf_next(m)) {
			size_t mlen = mbuf_maxlen(m);

			if (mlen + uiolen > (size_t)xfsize) {
				mlen = xfsize - uiolen;
			}
			mbuf_setlen(m, mlen);
			uio_addiov(auio, CAST_USER_ADDR_T(mbuf_datastart(m)),
			    mlen);
			uiolen += mlen;
		}

		if (xfsize != uio_resid(auio)) {
			DBG_PRINTF("sendfile: xfsize: %lld != uio_resid(auio): "
			    "%lld\n", xfsize, (long long)uio_resid(auio));
		}

		KERNEL_DEBUG_CONSTANT((DBG_FNC_SENDFILE_READ | DBG_FUNC_START),
		    uap->s, (unsigned int)((xfsize >> 32) & 0x0ffffffff),
		    (unsigned int)(xfsize & 0x0ffffffff), 0, 0);
		error = fo_read(fp, auio, FOF_OFFSET, &context);
		socket_lock(so, 0);
		if (error != 0) {
			if (uio_resid(auio) != xfsize && (error == ERESTART ||
			    error == EINTR || error == EWOULDBLOCK)) {
				error = 0;
			} else {
				mbuf_freem(m0);
				goto done3;
			}
		}
		xfsize -= uio_resid(auio);
		KERNEL_DEBUG_CONSTANT((DBG_FNC_SENDFILE_READ | DBG_FUNC_END),
		    uap->s, (unsigned int)((xfsize >> 32) & 0x0ffffffff),
		    (unsigned int)(xfsize & 0x0ffffffff), 0, 0);

		if (xfsize == 0) {
			break;
		}
		if (xfsize + off > file_size) {
			DBG_PRINTF("sendfile: xfsize: %lld + off: %lld > file_size:"
			    "%lld\n", xfsize, off, file_size);
		}
		for (i = 0, m = m0, rlen = 0;
		    i < nbufs && m != NULL && rlen < xfsize;
		    i++, m = mbuf_next(m)) {
			size_t mlen = mbuf_maxlen(m);

			if (rlen + mlen > (size_t)xfsize) {
				mlen = xfsize - rlen;
			}
			mbuf_setlen(m, mlen);

			rlen += mlen;
		}
		mbuf_pkthdr_setlen(m0, xfsize);

retry_space:
		/*
		 * Make sure that the socket is still able to take more data.
		 * CANTSENDMORE being true usually means that the connection
		 * was closed. so_error is true when an error was sensed after
		 * a previous send.
		 * The state is checked after the page mapping and buffer
		 * allocation above since those operations may block and make
		 * any socket checks stale. From this point forward, nothing
		 * blocks before the pru_send (or more accurately, any blocking
		 * results in a loop back to here to re-check).
		 */
		if ((so->so_state & SS_CANTSENDMORE) || so->so_error) {
			if (so->so_state & SS_CANTSENDMORE) {
				error = EPIPE;
			} else {
				error = so->so_error;
				so->so_error = 0;
			}
			m_freem(m0);
			goto done3;
		}
		/*
		 * Wait for socket space to become available. We do this just
		 * after checking the connection state above in order to avoid
		 * a race condition with sbwait().
		 */
		if (sbspace(&so->so_snd) < (long)so->so_snd.sb_lowat) {
			if (so->so_state & SS_NBIO) {
				m_freem(m0);
				error = EAGAIN;
				goto done3;
			}
			KERNEL_DEBUG_CONSTANT((DBG_FNC_SENDFILE_WAIT |
			    DBG_FUNC_START), uap->s, 0, 0, 0, 0);
			error = sbwait(&so->so_snd);
			KERNEL_DEBUG_CONSTANT((DBG_FNC_SENDFILE_WAIT |
			    DBG_FUNC_END), uap->s, 0, 0, 0, 0);
			/*
			 * An error from sbwait usually indicates that we've
			 * been interrupted by a signal. If we've sent anything
			 * then return bytes sent, otherwise return the error.
			 */
			if (error) {
				m_freem(m0);
				goto done3;
			}
			goto retry_space;
		}

		mbuf_ref_t  control = NULL;
		{
			/*
			 * Socket filter processing
			 */

			error = sflt_data_out(so, NULL, &m0, &control, 0);
			if (error) {
				if (error == EJUSTRETURN) {
					error = 0;
					continue;
				}
				goto done3;
			}
			/*
			 * End Socket filter processing
			 */
		}
		KERNEL_DEBUG_CONSTANT((DBG_FNC_SENDFILE_SEND | DBG_FUNC_START),
		    uap->s, 0, 0, 0, 0);
		error = (*so->so_proto->pr_usrreqs->pru_send)(so, 0, m0,
		    NULL, control, p);
		KERNEL_DEBUG_CONSTANT((DBG_FNC_SENDFILE_SEND | DBG_FUNC_START),
		    uap->s, 0, 0, 0, 0);
		if (error) {
			goto done3;
		}
	}
	sbunlock(&so->so_snd, FALSE);   /* will unlock socket */
	/*
	 * Send trailers. Wimp out and use writev(2).
	 */
	if (uap->hdtr != USER_ADDR_NULL &&
	    user_hdtr.trailers != USER_ADDR_NULL) {
		bzero(&nuap, sizeof(struct writev_args));
		nuap.fd = uap->s;
		nuap.iovp = user_hdtr.trailers;
		nuap.iovcnt = user_hdtr.trl_cnt;
		error = writev_nocancel(p, &nuap, &writev_retval);
		if (error) {
			goto done2;
		}
		sbytes += writev_retval;
	}
done2:
	file_drop(uap->s);
done1:
	file_drop(uap->fd);
done:
	if (uap->nbytes != USER_ADDR_NULL) {
		/* XXX this appears bogus for some early failure conditions */
		copyout(&sbytes, uap->nbytes, sizeof(off_t));
	}
	KERNEL_DEBUG_CONSTANT((DBG_FNC_SENDFILE | DBG_FUNC_END), uap->s,
	    (unsigned int)((sbytes >> 32) & 0x0ffffffff),
	    (unsigned int)(sbytes & 0x0ffffffff), error, 0);
	return error;
done3:
	sbunlock(&so->so_snd, FALSE);   /* will unlock socket */
	goto done2;
}


#endif /* SENDFILE */