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
/*
 * Copyright (c) 2000-2021 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@
 */
/*
 * @OSF_COPYRIGHT@
 */
/*
 * Mach Operating System
 * Copyright (c) 1991,1990,1989,1988 Carnegie Mellon University
 * All Rights Reserved.
 *
 * Permission to use, copy, modify and distribute this software and its
 * documentation is hereby granted, provided that both the copyright
 * notice and this permission notice appear in all copies of the
 * software, derivative works or modified versions, and any portions
 * thereof, and that both notices appear in supporting documentation.
 *
 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
 * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
 *
 * Carnegie Mellon requests users of this software to return to
 *
 *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
 *  School of Computer Science
 *  Carnegie Mellon University
 *  Pittsburgh PA 15213-3890
 *
 * any improvements or extensions that they make and grant Carnegie Mellon
 * the rights to redistribute these changes.
 */
/*
 */
/*
 *	File:	vm/vm_user.c
 *	Author:	Avadis Tevanian, Jr., Michael Wayne Young
 *
 *	User-exported virtual memory functions.
 */

/*
 * There are three implementations of the "XXX_allocate" functionality in
 * the kernel: mach_vm_allocate (for any task on the platform), vm_allocate
 * (for a task with the same address space size, especially the current task),
 * and vm32_vm_allocate (for the specific case of a 32-bit task). vm_allocate
 * in the kernel should only be used on the kernel_task. vm32_vm_allocate only
 * makes sense on platforms where a user task can either be 32 or 64, or the kernel
 * task can be 32 or 64. mach_vm_allocate makes sense everywhere, and is preferred
 * for new code.
 *
 * The entrypoints into the kernel are more complex. All platforms support a
 * mach_vm_allocate-style API (subsystem 4800) which operates with the largest
 * size types for the platform. On platforms that only support U32/K32,
 * subsystem 4800 is all you need. On platforms that support both U32 and U64,
 * subsystem 3800 is used disambiguate the size of parameters, and they will
 * always be 32-bit and call into the vm32_vm_allocate APIs. On non-U32/K32 platforms,
 * the MIG glue should never call into vm_allocate directly, because the calling
 * task and kernel_task are unlikely to use the same size parameters
 *
 * New VM call implementations should be added here and to mach_vm.defs
 * (subsystem 4800), and use mach_vm_* "wide" types.
 */

#include <debug.h>

#include <mach/boolean.h>
#include <mach/kern_return.h>
#include <mach/mach_types.h>    /* to get vm_address_t */
#include <mach/memory_object.h>
#include <mach/std_types.h>     /* to get pointer_t */
#include <mach/upl.h>
#include <mach/vm_attributes.h>
#include <mach/vm_param.h>
#include <mach/vm_statistics.h>
#include <mach/mach_syscalls.h>
#include <mach/sdt.h>
#include <mach/memory_entry.h>

#include <mach/host_priv_server.h>
#include <mach/mach_vm_server.h>
#include <mach/memory_entry_server.h>
#include <mach/vm_map_server.h>

#include <kern/host.h>
#include <kern/kalloc.h>
#include <kern/task.h>
#include <kern/misc_protos.h>
#include <vm/vm_fault.h>
#include <vm/vm_map_internal.h>
#include <vm/vm_map_lock_internal.h>
#include <vm/vm_object_xnu.h>
#include <vm/vm_kern.h>
#include <vm/vm_page_internal.h>
#include <vm/memory_object_internal.h>
#include <vm/vm_pageout_internal.h>
#include <vm/vm_protos.h>
#include <vm/vm_purgeable_internal.h>
#include <vm/vm_memory_entry_xnu.h>
#include <vm/vm_kern_internal.h>
#include <vm/vm_iokit.h>
#include <vm/vm_sanitize_internal.h>
#if CONFIG_DEFERRED_RECLAIM
#include <vm/vm_reclaim_internal.h>
#endif /* CONFIG_DEFERRED_RECLAIM */
#include <vm/vm_init_xnu.h>

#include <san/kasan.h>

#include <libkern/OSDebug.h>
#include <IOKit/IOBSD.h>
#include <sys/kdebug_triage.h>

#include <sys/code_signing.h> /* for is_address_space_debugged */

/*
 *	mach_vm_allocate allocates "zero fill" memory in the specfied
 *	map.
 */
kern_return_t
mach_vm_allocate_external(
	vm_map_t                map,
	mach_vm_offset_ut      *addr,
	mach_vm_size_ut         size,
	int                     flags)
{
	vm_map_kernel_flags_t vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;

	/* filter out any kernel-only flags */
	if (flags & ~VM_FLAGS_USER_ALLOCATE) {
		ktriage_record(thread_tid(current_thread()),
		    KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM,
		    KDBG_TRIAGE_RESERVED,
		    KDBG_TRIAGE_VM_ALLOCATE_KERNEL_BADFLAGS_ERROR),
		    KERN_INVALID_ARGUMENT /* arg */);
		return KERN_INVALID_ARGUMENT;
	}

	vm_map_kernel_flags_set_vmflags(&vmk_flags, flags);

	return mach_vm_allocate_kernel(map, addr, size, vmk_flags);
}

/*
 *	vm_allocate
 *	Legacy routine that allocates "zero fill" memory in the specfied
 *	map (which is limited to the same size as the kernel).
 */
kern_return_t
vm_allocate_external(
	vm_map_t        map,
	vm_offset_ut   *addr,
	vm_size_ut      size,
	int             flags)
{
	return mach_vm_allocate_external(map, addr, size, flags);
}

/*
 *	mach_vm_deallocate -
 *	deallocates the specified range of addresses in the
 *	specified address map.
 */
kern_return_t
mach_vm_deallocate_external(
	vm_map_t                map,
	mach_vm_offset_ut       start_u,
	mach_vm_size_ut         size_u)
{
	return mach_vm_deallocate_kernel(map, start_u, size_u);
}

/*
 *	vm_deallocate -
 *	deallocates the specified range of addresses in the
 *	specified address map (limited to addresses the same
 *	size as the kernel).
 */
kern_return_t
vm_deallocate(
	vm_map_t                map,
	vm_offset_ut            start,
	vm_size_ut              size)
{
	return mach_vm_deallocate_external(map, start, size);
}

/*
 *	mach_vm_inherit -
 *	Sets the inheritance of the specified range in the
 *	specified map.
 */
kern_return_t
mach_vm_inherit(
	vm_map_t                map,
	mach_vm_offset_ut       start_u,
	mach_vm_size_ut         size_u,
	vm_inherit_ut           new_inheritance_u)
{
	if (map == VM_MAP_NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	if (VM_SANITIZE_UNSAFE_IS_ZERO(size_u)) {
		return KERN_SUCCESS;
	}

	return vm_map_inherit(map,
	           start_u,
	           vm_sanitize_compute_ut_end(start_u, size_u),
	           new_inheritance_u);
}

/*
 *	vm_inherit -
 *	Sets the inheritance of the specified range in the
 *	specified map (range limited to addresses
 */
kern_return_t
vm_inherit(
	vm_map_t                map,
	vm_offset_ut            start_u,
	vm_size_ut              size_u,
	vm_inherit_ut           new_inheritance_u)
{
	return mach_vm_inherit(map, start_u, size_u, new_inheritance_u);
}

/*
 *	mach_vm_protect -
 *	Sets the protection of the specified range in the
 *	specified map.
 */

kern_return_t
mach_vm_protect(
	vm_map_t                map,
	mach_vm_address_ut      start_u,
	mach_vm_size_ut         size_u,
	boolean_t               set_maximum,
	vm_prot_ut              new_protection_u)
{
	if (map == VM_MAP_NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	if (VM_SANITIZE_UNSAFE_IS_ZERO(size_u)) {
		return KERN_SUCCESS;
	}

	return vm_map_protect(map,
	           start_u,
	           vm_sanitize_compute_ut_end(start_u, size_u),
	           set_maximum,
	           new_protection_u);
}

/*
 *	vm_protect -
 *	Sets the protection of the specified range in the
 *	specified map. Addressability of the range limited
 *	to the same size as the kernel.
 */

kern_return_t
vm_protect(
	vm_map_t                map,
	vm_offset_ut            start_u,
	vm_size_ut              size_u,
	boolean_t               set_maximum,
	vm_prot_ut              new_protection_u)
{
	return mach_vm_protect(map, start_u, size_u, set_maximum, new_protection_u);
}

/*
 * mach_vm_machine_attributes -
 * Handle machine-specific attributes for a mapping, such
 * as cachability, migrability, etc.
 */
kern_return_t
mach_vm_machine_attribute(
	vm_map_t                map,
	mach_vm_address_ut      addr_u,
	mach_vm_size_ut         size_u,
	vm_machine_attribute_t  attribute,
	vm_machine_attribute_val_t *value) /* IN/OUT */
{
	if (map == VM_MAP_NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	if (VM_SANITIZE_UNSAFE_IS_ZERO(size_u)) {
		return KERN_SUCCESS;
	}

	return vm_map_machine_attribute(map,
	           addr_u,
	           vm_sanitize_compute_ut_end(addr_u, size_u),
	           attribute,
	           value);
}

/*
 * vm_machine_attribute -
 * Handle machine-specific attributes for a mapping, such
 * as cachability, migrability, etc. Limited addressability
 * (same range limits as for the native kernel map).
 */
kern_return_t
vm_machine_attribute(
	vm_map_t                map,
	vm_address_ut           addr_u,
	vm_size_ut              size_u,
	vm_machine_attribute_t  attribute,
	vm_machine_attribute_val_t *value) /* IN/OUT */
{
	return mach_vm_machine_attribute(map, addr_u, size_u, attribute, value);
}

/*
 * mach_vm_read -
 * Read/copy a range from one address space and return it to the caller.
 *
 * It is assumed that the address for the returned memory is selected by
 * the IPC implementation as part of receiving the reply to this call.
 * If IPC isn't used, the caller must deal with the vm_map_copy_t object
 * that gets returned.
 *
 * JMM - because of mach_msg_type_number_t, this call is limited to a
 * single 4GB region at this time.
 *
 */
kern_return_t
mach_vm_read(
	vm_map_t                map,
	mach_vm_address_ut      addr,
	mach_vm_size_ut         size,
	pointer_ut             *data,
	mach_msg_type_number_t *data_size)
{
	kern_return_t   error;
	vm_map_copy_t   ipc_address;

	if (map == VM_MAP_NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	/*
	 * mach_msg_type_number_t is a signed int,
	 * make sure we do not overflow it.
	 */
	if (!VM_SANITIZE_UNSAFE_FITS(size, mach_msg_type_number_t)) {
		return KERN_INVALID_ARGUMENT;
	}

	error = vm_map_copyin(map, addr, size, FALSE, &ipc_address);

	if (KERN_SUCCESS == error) {
		VM_SANITIZE_UT_SET(*data, (pointer_t) ipc_address);
		/* On success we know size was validated by vm_map_copyin. */
		*data_size =
		    (mach_msg_type_number_t)VM_SANITIZE_UNSAFE_UNWRAP(size);
	}
	return error;
}

/*
 * vm_read -
 * Read/copy a range from one address space and return it to the caller.
 * Limited addressability (same range limits as for the native kernel map).
 *
 * It is assumed that the address for the returned memory is selected by
 * the IPC implementation as part of receiving the reply to this call.
 * If IPC isn't used, the caller must deal with the vm_map_copy_t object
 * that gets returned.
 */
kern_return_t
vm_read(
	vm_map_t                map,
	vm_address_ut           addr,
	vm_size_ut              size,
	pointer_ut             *data,
	mach_msg_type_number_t *data_size)
{
	return mach_vm_read(map, addr, size, data, data_size);
}

/*
 * mach_vm_read_list -
 * Read/copy a list of address ranges from specified map.
 *
 * MIG does not know how to deal with a returned array of
 * vm_map_copy_t structures, so we have to do the copyout
 * manually here.
 */
kern_return_t
mach_vm_read_list(
	vm_map_t                        map,
	mach_vm_read_entry_t            data_list,
	natural_t                       count)
{
	mach_msg_type_number_t  i;
	kern_return_t   error;
	vm_map_copy_t   copy;

	if (map == VM_MAP_NULL ||
	    count > VM_MAP_ENTRY_MAX) {
		return KERN_INVALID_ARGUMENT;
	}

	error = KERN_SUCCESS;
	for (i = 0; i < count; i++) {
		vm_map_address_t map_addr;
		vm_map_size_t map_size;

		map_addr = (vm_map_address_t)(data_list[i].address);
		map_size = (vm_map_size_t)(data_list[i].size);

		if (map_size != 0) {
			error = vm_map_copyin(map,
			    map_addr,
			    map_size,
			    FALSE,              /* src_destroy */
			    &copy);
			if (KERN_SUCCESS == error) {
				error = vm_map_copyout(
					current_task()->map,
					&map_addr,
					copy);
				if (KERN_SUCCESS == error) {
					data_list[i].address = map_addr;
					continue;
				}
				vm_map_copy_discard(copy);
			}
		}
		data_list[i].address = (mach_vm_address_t)0;
		data_list[i].size = (mach_vm_size_t)0;
	}
	return error;
}

/*
 * vm_read_list -
 * Read/copy a list of address ranges from specified map.
 *
 * MIG does not know how to deal with a returned array of
 * vm_map_copy_t structures, so we have to do the copyout
 * manually here.
 *
 * The source and destination ranges are limited to those
 * that can be described with a vm_address_t (i.e. same
 * size map as the kernel).
 *
 * JMM - If the result of the copyout is an address range
 * that cannot be described with a vm_address_t (i.e. the
 * caller had a larger address space but used this call
 * anyway), it will result in a truncated address being
 * returned (and a likely confused caller).
 */

kern_return_t
vm_read_list(
	vm_map_t                map,
	vm_read_entry_t data_list,
	natural_t               count)
{
	mach_msg_type_number_t  i;
	kern_return_t   error;
	vm_map_copy_t   copy;

	if (map == VM_MAP_NULL ||
	    count > VM_MAP_ENTRY_MAX) {
		return KERN_INVALID_ARGUMENT;
	}

	error = KERN_SUCCESS;
	for (i = 0; i < count; i++) {
		vm_map_address_t map_addr;
		vm_map_size_t map_size;

		map_addr = (vm_map_address_t)(data_list[i].address);
		map_size = (vm_map_size_t)(data_list[i].size);

		if (map_size != 0) {
			error = vm_map_copyin(map,
			    map_addr,
			    map_size,
			    FALSE,              /* src_destroy */
			    &copy);
			if (KERN_SUCCESS == error) {
				error = vm_map_copyout(current_task()->map,
				    &map_addr,
				    copy);
				if (KERN_SUCCESS == error) {
					data_list[i].address =
					    CAST_DOWN(vm_offset_t, map_addr);
					continue;
				}
				vm_map_copy_discard(copy);
			}
		}
		data_list[i].address = (mach_vm_address_t)0;
		data_list[i].size = (mach_vm_size_t)0;
	}
	return error;
}

/*
 * mach_vm_read_overwrite -
 * Overwrite a range of the current map with data from the specified
 * map/address range.
 *
 * In making an assumption that the current thread is local, it is
 * no longer cluster-safe without a fully supportive local proxy
 * thread/task (but we don't support cluster's anymore so this is moot).
 */

kern_return_t
mach_vm_read_overwrite(
	vm_map_t                map,
	mach_vm_address_ut      address,
	mach_vm_size_ut         size,
	mach_vm_address_ut      data,
	mach_vm_size_ut        *data_size)
{
	kern_return_t   error;
	vm_map_copy_t   copy;

	if (map == VM_MAP_NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	error = vm_map_copyin(map, address, size, FALSE, &copy);

	if (KERN_SUCCESS == error) {
		if (copy) {
			assert(VM_SANITIZE_UNSAFE_IS_EQUAL(size, copy->size));
		}

		error = vm_map_copy_overwrite(current_thread()->map,
		    data,
		    copy,
		    size,
#if HAS_MTE
		    FALSE,
#endif
		    FALSE);
		if (KERN_SUCCESS == error) {
			*data_size = size;
			return error;
		}
		vm_map_copy_discard(copy);
	}
	return error;
}

/*
 * vm_read_overwrite -
 * Overwrite a range of the current map with data from the specified
 * map/address range.
 *
 * This routine adds the additional limitation that the source and
 * destination ranges must be describable with vm_address_t values
 * (i.e. the same size address spaces as the kernel, or at least the
 * the ranges are in that first portion of the respective address
 * spaces).
 */

kern_return_t
vm_read_overwrite(
	vm_map_t                map,
	vm_address_ut           address,
	vm_size_ut              size,
	vm_address_ut           data,
	vm_size_ut             *data_size)
{
	return mach_vm_read_overwrite(map, address, size, data, data_size);
}

/*
 * mach_vm_update_pointers_with_remote_tags -
 */
#if HAS_MTE
/*
 * Iterate a pointer list and rewrite the
 * pointers to contain the correct MTE tags.
 */
#endif /* HAS_MTE */

kern_return_t
mach_vm_update_pointers_with_remote_tags(
	__unused vm_map_t map,
	__unused mach_vm_offset_list_t in_pointer_list,
	__unused mach_msg_type_number_t in_pointer_listCnt,
	__unused mach_vm_offset_list_t out_pointer_list,
	__unused mach_msg_type_number_t *out_pointer_listCnt)
{
	if (!in_pointer_list
	    || !out_pointer_list
	    || in_pointer_listCnt > VM_OFFSET_LIST_MAX
	    /* The length of the output pointer list must match the input pointer list */
	    || !out_pointer_listCnt
	    || *out_pointer_listCnt != in_pointer_listCnt
	    ) {
		return KERN_INVALID_ARGUMENT;
	}

	if (!map || !map->pmap) {
		return KERN_INVALID_ARGUMENT;
	}

#if HAS_MTE
	/* This API is intended for debuggers, so ensure the target is debugged */
	vm_map_ilk_lock(map);
	task_t map_task = map->owning_task;
	bool is_debugged = map_task && is_address_space_debugged(get_bsdtask_info(map_task));
	vm_map_ilk_unlock(map);
	if (!is_debugged) {
		return KERN_INVALID_ARGUMENT;
	}

	vm_map_switch_context_t ctx = vm_map_switch_to(map);

	for (mach_msg_type_number_t i = 0; i < in_pointer_listCnt; i++) {
		mach_vm_offset_t unsigned_address = (mach_vm_offset_t)in_pointer_list[i];
		vm_map_address_t signed_address = 0;
		/* Note that inputs pointing to non-MTE objects safely return canonical tags */
		int ret = copyin_mte_load_tag(unsigned_address, &signed_address);
		if (ret != 0) {
			/* Perhaps an invalid address, just leave the output slot as zero. */
			continue;
		}
		out_pointer_list[i] = signed_address;
	}

	vm_map_switch_back(ctx);

	return KERN_SUCCESS;
#endif /* HAS_MTE */
	return KERN_FAILURE;
}

/*
 * mach_vm_write -
 * Overwrite the specified address range with the data provided
 * (from the current map).
 */
kern_return_t
mach_vm_write(
	vm_map_t                map,
	mach_vm_address_ut      address,
	pointer_ut              data_u,
	mach_msg_type_number_t  size)
{
	if (map == VM_MAP_NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	/*
	 * data is created by the kernel's MIG server from a userspace buffer,
	 * so it is safe to unwrap.
	 */
	vm_map_copy_t data = (vm_map_copy_t) VM_SANITIZE_UNSAFE_UNWRAP(data_u);

	return vm_map_copy_overwrite(map,
	           address,
	           data,
	           size,
#if HAS_MTE
	           TRUE, /* sec_override */
#endif
	           FALSE /* interruptible XXX */);
}

/*
 * vm_write -
 * Overwrite the specified address range with the data provided
 * (from the current map).
 *
 * The addressability of the range of addresses to overwrite is
 * limited bu the use of a vm_address_t (same size as kernel map).
 * Either the target map is also small, or the range is in the
 * low addresses within it.
 */
kern_return_t
vm_write(
	vm_map_t                map,
	vm_address_ut           address,
	pointer_ut              data,
	mach_msg_type_number_t  size)
{
	return mach_vm_write(map, address, data, size);
}

/*
 * mach_vm_copy -
 * Overwrite one range of the specified map with the contents of
 * another range within that same map (i.e. both address ranges
 * are "over there").
 */
kern_return_t
mach_vm_copy(
	vm_map_t                map,
	mach_vm_address_ut      source_address,
	mach_vm_size_ut         size,
	mach_vm_address_ut      dest_address)
{
	vm_map_copy_t copy;
	kern_return_t kr;

	if (map == VM_MAP_NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	kr = vm_map_copyin(map, source_address, size, FALSE, &copy);

	if (KERN_SUCCESS == kr) {
		if (copy) {
			assert(VM_SANITIZE_UNSAFE_IS_EQUAL(size, copy->size));
		}

		kr = vm_map_copy_overwrite(map,
		    dest_address,
		    copy,
		    size,
#if HAS_MTE
		    FALSE /* interruptible XXX */,
#endif
		    FALSE);

		if (KERN_SUCCESS != kr) {
			vm_map_copy_discard(copy);
		}
	}
	return kr;
}

kern_return_t
vm_copy(
	vm_map_t                map,
	vm_address_ut           source_address,
	vm_size_ut              size,
	vm_address_ut           dest_address)
{
	return mach_vm_copy(map, source_address, size, dest_address);
}

/*
 * mach_vm_reallocate -
 * Reallocate the source range into a (possibly new) range within the same map,
 * where the destination is of equal or greater size than the source.
 */
kern_return_t
mach_vm_reallocate(
	vm_map_t                map,
	mach_vm_address_ut      src,
	mach_vm_size_ut         src_size,
	mach_vm_address_ut     *dst_inout,
	mach_vm_size_ut         dst_size,
	mach_vm_offset_ut       align_mask,
	int                     options,
	int                     flags)
{
	if (map == VM_MAP_NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	return vm_map_reallocate(map, src, src_size, dst_inout, dst_size, align_mask, options, flags);
}

kern_return_t
vm_reallocate(
	vm_map_t                map,
	vm_address_ut           src,
	vm_size_ut              src_size,
	vm_address_ut          *dst_inout,
	vm_size_ut              dst_size,
	vm_offset_ut            align_mask,
	int                     options,
	int                     flags)
{
	kern_return_t kr;
	mach_vm_address_ut dst_inout_mach;

	dst_inout_mach = (mach_vm_address_ut)(*dst_inout);
	kr = mach_vm_reallocate(map, src, src_size, &dst_inout_mach, dst_size, align_mask, options, flags);
	*dst_inout = (vm_address_ut) dst_inout_mach;

	return kr;
}

/*
 * mach_vm_map -
 * Map some range of an object into an address space.
 *
 * The object can be one of several types of objects:
 *	NULL - anonymous memory
 *	a named entry - a range within another address space
 *	                or a range within a memory object
 *	a whole memory object
 *
 */
kern_return_t
mach_vm_map_external(
	vm_map_t                target_map,
	mach_vm_offset_ut      *address,
	mach_vm_size_ut         initial_size,
	mach_vm_offset_ut       mask,
	int                     flags,
	ipc_port_t              port,
	memory_object_offset_ut offset,
	boolean_t               copy,
	vm_prot_ut              cur_protection,
	vm_prot_ut              max_protection,
	vm_inherit_ut           inheritance)
{
	vm_map_kernel_flags_t vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;

	/* filter out any kernel-only flags */
	if (flags & ~VM_FLAGS_USER_MAP) {
		return KERN_INVALID_ARGUMENT;
	}

	vm_map_kernel_flags_set_vmflags(&vmk_flags, flags);
	/* range_id is set by mach_vm_map_kernel */
	return mach_vm_map_kernel(target_map, address, initial_size, mask,
	           vmk_flags, port, offset, copy,
	           cur_protection, max_protection,
	           inheritance);
}

/* legacy interface */
__attribute__((always_inline))
kern_return_t
vm_map_64_external(
	vm_map_t                target_map,
	vm_offset_ut           *address,
	vm_size_ut              size,
	vm_offset_ut            mask,
	int                     flags,
	ipc_port_t              port,
	memory_object_offset_ut offset,
	boolean_t               copy,
	vm_prot_ut              cur_protection,
	vm_prot_ut              max_protection,
	vm_inherit_ut           inheritance)
{
	return mach_vm_map_external(target_map, address,
	           size, mask, flags, port, offset, copy,
	           cur_protection, max_protection, inheritance);
}

/* temporary, until world build */
__attribute__((always_inline))
kern_return_t
vm_map_external(
	vm_map_t                target_map,
	vm_offset_ut           *address,
	vm_size_ut              size,
	vm_offset_ut            mask,
	int                     flags,
	ipc_port_t              port,
	vm_offset_ut            offset,
	boolean_t               copy,
	vm_prot_ut              cur_protection,
	vm_prot_ut              max_protection,
	vm_inherit_ut           inheritance)
{
	return mach_vm_map_external(target_map, address,
	           size, mask, flags, port, offset, copy,
	           cur_protection, max_protection, inheritance);
}

static __attribute__((always_inline, warn_unused_result))
kern_return_t
mach_vm_remap_new_external_sanitize(
	vm_map_t                target_map,
	vm_prot_ut              cur_protection_u,
	vm_prot_ut              max_protection_u,
	vm_prot_t              *cur_protection,
	vm_prot_t              *max_protection)
{
	return vm_sanitize_cur_and_max_prots(cur_protection_u, max_protection_u,
	           VM_SANITIZE_CALLER_VM_MAP_REMAP, target_map,
	           cur_protection, max_protection);
}

/*
 * mach_vm_remap_new -
 * Behaves like vm_remap, except
 * - VM_FLAGS_RETURN_DATA_ADDR is always set (vmf_return_data_addr flag)
 *      the return address has the same offset-in-page as the input address
 * - {cur,max}_protection are in/out.
 *   in legacy mode, protection is an out argument which needs to be initialized
 *   to PROT_NONE and then gets the minimum protection that was found in the new
 *   mapping. in new mode, the protection that is requested in these arguments
 *   is set to the new mapping (mod policies that apply to restrict that)
 *   and the out arguments receive the protected that was eventually set.
 * - From the user perspective src can be a task read port (vm_map_read_t)
 *   to read VM_PROT_READ memory instead of a task control port which is needed
 *   by legacy vm_remap
 */
kern_return_t
mach_vm_remap_new_external(
	vm_map_t                target_map,
	mach_vm_offset_ut      *address,
	mach_vm_size_ut         size,
	mach_vm_offset_ut       mask,
	int                     flags,
	mach_port_t             src_tport,
	mach_vm_offset_ut       memory_address,
	boolean_t               copy,
	vm_prot_ut             *cur_protection_u,   /* IN/OUT */
	vm_prot_ut             *max_protection_u,   /* IN/OUT */
	vm_inherit_ut           inheritance)
{
	vm_map_kernel_flags_t   vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
	vm_map_t                src_map;
	vm_prot_t               cur_protection, max_protection;
	kern_return_t           kr;

	if (target_map == VM_MAP_NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	/* filter out any kernel-only flags */
	if (flags & ~VM_FLAGS_USER_REMAP) {
		return KERN_INVALID_ARGUMENT;
	}

	vm_map_kernel_flags_set_vmflags(&vmk_flags,
	    flags | VM_FLAGS_RETURN_DATA_ADDR);

	/*
	 * We don't need cur_protection here, but sanitizing it before
	 * enforcing W^X below matches historical error codes better.
	 */
	kr = mach_vm_remap_new_external_sanitize(target_map,
	    *cur_protection_u,
	    *max_protection_u,
	    &cur_protection,
	    &max_protection);
	if (__improbable(kr != KERN_SUCCESS)) {
		return vm_sanitize_get_kr(kr);
	}

	if ((max_protection & (VM_PROT_WRITE | VM_PROT_EXECUTE)) ==
	    (VM_PROT_WRITE | VM_PROT_EXECUTE)) {
		/*
		 * XXX FBDP TODO
		 * enforce target's "wx" policies
		 */
		return KERN_PROTECTION_FAILURE;
	}

	if (copy || max_protection == VM_PROT_READ || max_protection == VM_PROT_NONE) {
		src_map = convert_port_to_map_read(src_tport);
	} else {
		src_map = convert_port_to_map(src_tport);
	}

	/* range_id is set by vm_map_remap */
	kr = vm_map_remap(target_map,
	    address,
	    size,
	    mask,
	    vmk_flags,
	    src_map,
	    memory_address,
	    copy,
	    cur_protection_u,    /* IN/OUT */
	    max_protection_u,    /* IN/OUT */
	    inheritance);

	vm_map_deallocate(src_map);

	if (kr == KERN_SUCCESS) {
		ipc_port_release_send(src_tport);  /* consume on success */
	}
	return kr;
}

/*
 * mach_vm_remap -
 * Remap a range of memory from one task into another,
 * to another address range within the same task, or
 * over top of itself (with altered permissions and/or
 * as an in-place copy of itself).
 * @arg cur_protection, max_protection
 *		IN: must be VM_PROT_NONE
 *		OUT: The least protection from the newly mapped region
 */
kern_return_t
mach_vm_remap_external(
	vm_map_t                target_map,
	mach_vm_offset_ut      *address,
	mach_vm_size_ut         size,
	mach_vm_offset_ut       mask,
	int                     flags,
	vm_map_t                src_map,
	mach_vm_offset_ut       memory_address,
	boolean_t               copy,
	vm_prot_ut             *cur_protection,    /* OUT */
	vm_prot_ut             *max_protection,    /* OUT */
	vm_inherit_ut           inheritance)
{
	vm_map_kernel_flags_t vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;

	/* filter out any kernel-only flags */
	if (flags & ~VM_FLAGS_USER_REMAP) {
		return KERN_INVALID_ARGUMENT;
	}

	vm_map_kernel_flags_set_vmflags(&vmk_flags, flags);

	*cur_protection = vm_sanitize_wrap_prot(VM_PROT_NONE);
	*max_protection = vm_sanitize_wrap_prot(VM_PROT_NONE);
	vmk_flags.vmkf_remap_legacy_mode = true;

	/* range_id is set by vm_map_remap */
	return vm_map_remap(target_map,
	           address,
	           size,
	           mask,
	           vmk_flags,
	           src_map,
	           memory_address,
	           copy,
	           cur_protection,
	           max_protection,
	           inheritance);
}

/*
 * vm_remap_new -
 * see: mach_vm_remap_new_external()
 */
kern_return_t
vm_remap_new_external(
	vm_map_t                target_map,
	vm_offset_ut           *address,
	vm_size_ut              size,
	vm_offset_ut            mask,
	int                     flags,
	mach_port_t             src_tport,
	vm_offset_ut            memory_address,
	boolean_t               copy,
	vm_prot_ut             *cur_protection,       /* IN/OUT */
	vm_prot_ut             *max_protection,       /* IN/OUT */
	vm_inherit_ut           inheritance)
{
	return mach_vm_remap_new_external(target_map,
	           address,
	           size,
	           mask,
	           flags,
	           src_tport,
	           memory_address,
	           copy,
	           cur_protection, /* IN/OUT */
	           max_protection, /* IN/OUT */
	           inheritance);
}

/*
 * vm_remap -
 * see: mach_vm_remap_external()
 */
kern_return_t
vm_remap_external(
	vm_map_t                target_map,
	vm_offset_ut           *address,
	vm_size_ut              size,
	vm_offset_ut            mask,
	int                     flags,
	vm_map_t                src_map,
	vm_offset_ut            memory_address,
	boolean_t               copy,
	vm_prot_ut             *cur_protection,    /* OUT */
	vm_prot_ut             *max_protection,    /* OUT */
	vm_inherit_ut           inheritance)
{
	return mach_vm_remap_external(target_map, address,
	           size, mask, flags, src_map, memory_address, copy,
	           cur_protection, max_protection, inheritance);
}

/*
 * NOTE: these routine (and this file) will no longer require mach_host_server.h
 * when mach_vm_wire and vm_wire are changed to use ledgers.
 */
#include <mach/mach_host_server.h>
/*
 *	mach_vm_wire
 *	Specify that the range of the virtual address space
 *	of the target task must not cause page faults for
 *	the indicated accesses.
 *
 *	[ To unwire the pages, specify VM_PROT_NONE. ]
 */
kern_return_t
mach_vm_wire_external(
	host_priv_t             host_priv,
	vm_map_t                map,
	mach_vm_address_ut      start,
	mach_vm_size_ut         size,
	vm_prot_ut              access)
{
	kern_return_t     rc;
	mach_vm_offset_ut end;

	if (host_priv == HOST_PRIV_NULL) {
		return KERN_INVALID_HOST;
	}

	if (map == VM_MAP_NULL) {
		return KERN_INVALID_TASK;
	}

	end = vm_sanitize_compute_ut_end(start, size);
	if (VM_SANITIZE_UNSAFE_IS_ZERO(access)) {
		rc = vm_map_unwire_impl(map, start, end, true,
		    VM_SANITIZE_CALLER_VM_UNWIRE_USER);
	} else {
		rc = vm_map_wire_impl(map, start, end, access,
		    VM_KERN_MEMORY_MLOCK, true, NULL, VM_SANITIZE_CALLER_VM_WIRE_USER);
	}

	return rc;
}

/*
 *	vm_wire -
 *	Specify that the range of the virtual address space
 *	of the target task must not cause page faults for
 *	the indicated accesses.
 *
 *	[ To unwire the pages, specify VM_PROT_NONE. ]
 */
kern_return_t
vm_wire(
	host_priv_t             host_priv,
	vm_map_t                map,
	vm_offset_ut            start,
	vm_size_ut              size,
	vm_prot_ut              access)
{
	return mach_vm_wire_external(host_priv, map, start, size, access);
}

/*
 *	vm_msync
 *
 *	Synchronises the memory range specified with its backing store
 *	image by either flushing or cleaning the contents to the appropriate
 *	memory manager.
 *
 *	interpretation of sync_flags
 *	VM_SYNC_INVALIDATE	- discard pages, only return precious
 *				  pages to manager.
 *
 *	VM_SYNC_INVALIDATE & (VM_SYNC_SYNCHRONOUS | VM_SYNC_ASYNCHRONOUS)
 *				- discard pages, write dirty or precious
 *				  pages back to memory manager.
 *
 *	VM_SYNC_SYNCHRONOUS | VM_SYNC_ASYNCHRONOUS
 *				- write dirty or precious pages back to
 *				  the memory manager.
 *
 *	VM_SYNC_CONTIGUOUS	- does everything normally, but if there
 *				  is a hole in the region, and we would
 *				  have returned KERN_SUCCESS, return
 *				  KERN_INVALID_ADDRESS instead.
 *
 *	RETURNS
 *	KERN_INVALID_TASK		Bad task parameter
 *	KERN_INVALID_ARGUMENT		both sync and async were specified.
 *	KERN_SUCCESS			The usual.
 *	KERN_INVALID_ADDRESS		There was a hole in the region.
 */

kern_return_t
mach_vm_msync(
	vm_map_t                map,
	mach_vm_address_ut      address_u,
	mach_vm_size_ut         size_u,
	vm_sync_t               sync_flags)
{
	if (map == VM_MAP_NULL) {
		return KERN_INVALID_TASK;
	}

	if (VM_SANITIZE_UNSAFE_IS_ZERO(size_u)) {
		return KERN_SUCCESS;
	}

	return vm_map_msync(map, address_u, size_u, sync_flags);
}

/*
 *	vm_msync
 *
 *	Synchronises the memory range specified with its backing store
 *	image by either flushing or cleaning the contents to the appropriate
 *	memory manager.
 *
 *	interpretation of sync_flags
 *	VM_SYNC_INVALIDATE	- discard pages, only return precious
 *				  pages to manager.
 *
 *	VM_SYNC_INVALIDATE & (VM_SYNC_SYNCHRONOUS | VM_SYNC_ASYNCHRONOUS)
 *				- discard pages, write dirty or precious
 *				  pages back to memory manager.
 *
 *	VM_SYNC_SYNCHRONOUS | VM_SYNC_ASYNCHRONOUS
 *				- write dirty or precious pages back to
 *				  the memory manager.
 *
 *	VM_SYNC_CONTIGUOUS	- does everything normally, but if there
 *				  is a hole in the region, and we would
 *				  have returned KERN_SUCCESS, return
 *				  KERN_INVALID_ADDRESS instead.
 *
 *	The addressability of the range is limited to that which can
 *	be described by a vm_address_t.
 *
 *	RETURNS
 *	KERN_INVALID_TASK		Bad task parameter
 *	KERN_INVALID_ARGUMENT		both sync and async were specified.
 *	KERN_SUCCESS			The usual.
 *	KERN_INVALID_ADDRESS		There was a hole in the region.
 */

kern_return_t
vm_msync(
	vm_map_t        map,
	vm_address_ut   address_u,
	vm_size_ut      size_u,
	vm_sync_t       sync_flags)
{
	return mach_vm_msync(map, address_u, size_u, sync_flags);
}


__static_testable int
vm_map_toggle_entry_reuse(vm_map_t map, int toggle, int *old_value)
{
	vm_map_store_rsv_t rsv;

	vmlp_api_start(VM_TOGGLE_ENTRY_REUSE);
	assert(!map->is_nested_map);

	if (toggle == VM_TOGGLE_GETVALUE && old_value != NULL) {
		*old_value = map->disable_vmentry_reuse;
	} else if (toggle == VM_TOGGLE_SET) {
		vm_map_ilk_lock(map);
		vm_map_store_find_space(map,
		    (struct mach_vm_range){ vm_map_min(map), vm_map_max(map) },
		    VM_MAP_KERNEL_FLAGS_NONE, PAGE_SIZE_64, PAGE_MASK_64, &rsv);
		map->disable_vmentry_reuse = true;
		map->highest_entry_end     = vmsr_start(rsv);
		vm_map_ilk_unlock(map);
	} else if (toggle == VM_TOGGLE_CLEAR) {
		vm_map_ilk_lock(map);
		map->disable_vmentry_reuse = false;
		map->highest_entry_end     = 0;
		vm_map_ilk_unlock(map);
	} else {
		vmlp_api_end(VM_TOGGLE_ENTRY_REUSE, KERN_INVALID_ARGUMENT);
		return KERN_INVALID_ARGUMENT;
	}

	vmlp_api_end(VM_TOGGLE_ENTRY_REUSE, KERN_SUCCESS);
	return KERN_SUCCESS;
}

int
vm_toggle_entry_reuse(int toggle, int *old_value)
{
	return vm_map_toggle_entry_reuse(current_map(), toggle, old_value);
}


static __attribute__((always_inline, warn_unused_result))
kern_return_t
mach_vm_behavior_set_sanitize(
	vm_map_t                map,
	mach_vm_offset_ut       start_u,
	mach_vm_size_ut         size_u,
	vm_behavior_ut          new_behavior_u,
	mach_vm_offset_t       *start,
	mach_vm_offset_t       *end,
	mach_vm_size_t         *size,
	vm_behavior_t          *new_behavior)
{
	mach_vm_offset_t align_mask;
	kern_return_t    kr;

	kr = vm_sanitize_behavior(new_behavior_u, VM_SANITIZE_CALLER_VM_BEHAVIOR_SET, new_behavior);
	if (__improbable(kr != KERN_SUCCESS)) {
		return kr;
	}

	/* Choose alignment of addr/size based on the behavior being set. */
	switch (*new_behavior) {
	case VM_BEHAVIOR_REUSABLE:
	case VM_BEHAVIOR_REUSE:
	case VM_BEHAVIOR_CAN_REUSE:
	case VM_BEHAVIOR_ZERO:
		/*
		 * Align to the hardware page size, to allow
		 * malloc() to maximize the amount of re-usability,
		 * even on systems with larger software page size.
		 */
		align_mask = PAGE_MASK;
		break;
	default:
		align_mask = VM_MAP_PAGE_MASK(map);
		break;
	}
#if CONFIG_KERNEL_TAGGING || HAS_MTE_EMULATION_SHIMS
	start_u = vm_sanitize_canonicalize_ut_addr(map, start_u);
#endif /* CONFIG_KERNEL_TAGGING || HAS_MTE_EMULATION_SHIMS */

	kr = vm_sanitize_addr_size(start_u, size_u, VM_SANITIZE_CALLER_VM_BEHAVIOR_SET,
	    align_mask, map, VM_SANITIZE_FLAGS_SIZE_ZERO_SUCCEEDS, start, end, size);
	if (__improbable(kr != KERN_SUCCESS)) {
		return kr;
	}

	return KERN_SUCCESS;
}

/*
 *	mach_vm_behavior_set
 *
 *	Sets the paging behavior attribute for the  specified range
 *	in the specified map.
 *
 *	This routine will fail with KERN_INVALID_ADDRESS if any address
 *	in [start,start+size) is not a valid allocated memory region.
 */
kern_return_t
mach_vm_behavior_set(
	vm_map_t                map,
	mach_vm_offset_ut       start_u,
	mach_vm_size_ut         size_u,
	vm_behavior_ut          new_behavior_u)
{
	kern_return_t    kr;
	mach_vm_offset_t start, end;
	mach_vm_size_t   size;
	vm_behavior_t    new_behavior;

	if (map == VM_MAP_NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	kr = mach_vm_behavior_set_sanitize(map,
	    start_u, size_u, new_behavior_u,
	    &start, &end, &size, &new_behavior);
	if (__improbable(kr != KERN_SUCCESS)) {
		return vm_sanitize_get_kr(kr);
	}

	return vm_map_behavior_set(map,
	           start,
	           end,
	           new_behavior);
}

/*
 *	vm_behavior_set
 *
 *	Sets the paging behavior attribute for the  specified range
 *	in the specified map.
 *
 *	This routine will fail with KERN_INVALID_ADDRESS if any address
 *	in [start,start+size) is not a valid allocated memory region.
 *
 *	This routine is potentially limited in addressibility by the
 *	use of vm_offset_t (if the map provided is larger than the
 *	kernel's).
 */
kern_return_t
vm_behavior_set(
	vm_map_t                map,
	vm_offset_ut            start,
	vm_size_ut              size,
	vm_behavior_ut          new_behavior)
{
	return mach_vm_behavior_set(map,
	           start,
	           size,
	           new_behavior);
}

/*
 *	mach_vm_region:
 *
 *	User call to obtain information about a region in
 *	a task's address map. Currently, only one flavor is
 *	supported.
 *
 *	XXX The reserved and behavior fields cannot be filled
 *	    in until the vm merge from the IK is completed, and
 *	    vm_reserve is implemented.
 *
 *	XXX Dependency: syscall_vm_region() also supports only one flavor.
 */

kern_return_t
mach_vm_region(
	vm_map_t                map,
	mach_vm_offset_ut      *address_u,      /* IN/OUT */
	mach_vm_size_ut        *size_u,         /* OUT */
	vm_region_flavor_t      flavor,         /* IN */
	vm_region_info_t        info,           /* OUT */
	mach_msg_type_number_t *count,          /* IN/OUT */
	mach_port_t            *object_name)    /* OUT */
{
	if (VM_MAP_NULL == map) {
		return KERN_INVALID_ARGUMENT;
	}

	/* legacy conversion */
	if (VM_REGION_BASIC_INFO == flavor) {
		flavor = VM_REGION_BASIC_INFO_64;
	}

	return vm_map_region(map, address_u, size_u, flavor, info, count,
	           object_name);
}

static inline kern_return_t
vm_region_get_kern_return(
	kern_return_t           kr,
	vm_offset_ut            addr_u,
	vm_size_ut              size_u)
{
	vm_offset_ut end_u = vm_sanitize_compute_ut_end(addr_u, size_u);

	if (KERN_SUCCESS == kr && VM_SANITIZE_UNSAFE_UNWRAP(end_u) > VM_MAX_ADDRESS) {
		return KERN_INVALID_ADDRESS;
	}
	return kr;
}

/*
 *	vm_region_64 and vm_region:
 *
 *	User call to obtain information about a region in
 *	a task's address map. Currently, only one flavor is
 *	supported.
 *
 *	XXX The reserved and behavior fields cannot be filled
 *	    in until the vm merge from the IK is completed, and
 *	    vm_reserve is implemented.
 *
 *	XXX Dependency: syscall_vm_region() also supports only one flavor.
 */

kern_return_t
vm_region_64(
	vm_map_t                map,
	vm_offset_ut           *address_u,      /* IN/OUT */
	vm_size_ut             *size_u,         /* OUT */
	vm_region_flavor_t      flavor,         /* IN */
	vm_region_info_t        info,           /* OUT */
	mach_msg_type_number_t *count,          /* IN/OUT */
	mach_port_t            *object_name)    /* OUT */
{
	kern_return_t kr;

	kr = mach_vm_region(map, address_u, size_u, flavor, info, count,
	    object_name);

	return vm_region_get_kern_return(kr, *address_u, *size_u);
}

kern_return_t
vm_region(
	vm_map_t                map,
	vm_address_ut          *address_u,      /* IN/OUT */
	vm_size_ut             *size_u,         /* OUT */
	vm_region_flavor_t      flavor,         /* IN */
	vm_region_info_t        info,           /* OUT */
	mach_msg_type_number_t *count,          /* IN/OUT */
	mach_port_t            *object_name)    /* OUT */
{
	kern_return_t kr;

	if (VM_MAP_NULL == map) {
		return KERN_INVALID_ARGUMENT;
	}

	kr = vm_map_region(map, address_u, size_u, flavor, info, count,
	    object_name);

	return vm_region_get_kern_return(kr, *address_u, *size_u);
}

/*
 *	vm_region_recurse: A form of vm_region which follows the
 *	submaps in a target map
 *
 */
kern_return_t
mach_vm_region_recurse(
	vm_map_t                map,
	mach_vm_address_ut     *address_u,
	mach_vm_size_ut        *size_u,
	uint32_t               *depth,
	vm_region_recurse_info_t info,
	mach_msg_type_number_t *infoCnt)
{
	if (VM_MAP_NULL == map) {
		return KERN_INVALID_ARGUMENT;
	}

	return vm_map_region_recurse_64(map, address_u, size_u, depth,
	           (vm_region_submap_info_64_t)info, infoCnt);
}

/*
 *	vm_region_recurse: A form of vm_region which follows the
 *	submaps in a target map
 *
 */
kern_return_t
vm_region_recurse_64(
	vm_map_t                map,
	vm_address_ut          *address_u,
	vm_size_ut             *size_u,
	uint32_t               *depth,
	vm_region_recurse_info_64_t info,
	mach_msg_type_number_t *infoCnt)
{
	kern_return_t kr;

	kr = mach_vm_region_recurse(map, address_u, size_u, depth,
	    (vm_region_recurse_info_t)info, infoCnt);

	return vm_region_get_kern_return(kr, *address_u, *size_u);
}

kern_return_t
vm_region_recurse(
	vm_map_t                map,
	vm_offset_ut           *address_u,      /* IN/OUT */
	vm_size_ut             *size_u,         /* OUT */
	natural_t              *depth,          /* IN/OUT */
	vm_region_recurse_info_t info32,        /* IN/OUT */
	mach_msg_type_number_t *infoCnt)        /* IN/OUT */
{
	vm_region_submap_info_data_64_t info64;
	vm_region_submap_info_t info;
	kern_return_t           kr;

	if (VM_MAP_NULL == map || *infoCnt < VM_REGION_SUBMAP_INFO_COUNT) {
		return KERN_INVALID_ARGUMENT;
	}

	info = (vm_region_submap_info_t)info32;
	*infoCnt = VM_REGION_SUBMAP_INFO_COUNT_64;

	kr = vm_map_region_recurse_64(map, address_u, size_u,
	    depth, &info64, infoCnt);

	info->protection = info64.protection;
	info->max_protection = info64.max_protection;
	info->inheritance = info64.inheritance;
	info->offset = (uint32_t)info64.offset; /* trouble-maker */
	info->user_tag = info64.user_tag;
	info->pages_resident = info64.pages_resident;
	info->pages_shared_now_private = info64.pages_shared_now_private;
	info->pages_swapped_out = info64.pages_swapped_out;
	info->pages_dirtied = info64.pages_dirtied;
	info->ref_count = info64.ref_count;
	info->shadow_depth = info64.shadow_depth;
	info->external_pager = info64.external_pager;
	info->share_mode = info64.share_mode;
	info->is_submap = info64.is_submap;
	info->behavior = info64.behavior;
	info->object_id = info64.object_id;
	info->user_wired_count = info64.user_wired_count;

	*infoCnt = VM_REGION_SUBMAP_INFO_COUNT;

	return vm_region_get_kern_return(kr, *address_u, *size_u);
}

kern_return_t
mach_vm_purgable_control(
	vm_map_t                map,
	mach_vm_offset_ut       address_u,
	vm_purgable_t           control,
	int                    *state)
{
	if (VM_MAP_NULL == map) {
		return KERN_INVALID_ARGUMENT;
	}

	switch (control) {
	case VM_PURGABLE_SET_STATE:
	case VM_PURGABLE_GET_STATE:
	case VM_PURGABLE_PURGE_ALL:
		break;
	case VM_PURGABLE_SET_STATE_FROM_KERNEL:
	default:
		/* not allowed from user-space */
		return KERN_INVALID_ARGUMENT;
	}

	return vm_map_purgable_control(map, address_u, control, state);
}

kern_return_t
mach_vm_purgable_control_external(
	mach_port_t             target_tport,
	mach_vm_offset_ut       address_u,
	vm_purgable_t           control,
	int                    *state)
{
	vm_map_t map;
	kern_return_t kr;

	if (control == VM_PURGABLE_GET_STATE) {
		map = convert_port_to_map_read(target_tport);
	} else {
		map = convert_port_to_map(target_tport);
	}

	kr = mach_vm_purgable_control(map, address_u, control, state);
	vm_map_deallocate(map);

	return kr;
}

kern_return_t
vm_purgable_control_external(
	mach_port_t             target_tport,
	vm_offset_ut            address,
	vm_purgable_t           control,
	int                     *state)
{
	return mach_vm_purgable_control_external(target_tport, address, control, state);
}


kern_return_t
mach_vm_page_query(
	vm_map_t                map,
	mach_vm_offset_ut       offset_u,
	int                    *disposition,
	int                    *ref_count)
{
	kern_return_t                   kr;
	vm_page_info_basic_data_t       info;
	mach_msg_type_number_t          count;

	if (VM_MAP_NULL == map) {
		return KERN_INVALID_ARGUMENT;
	}

	count = VM_PAGE_INFO_BASIC_COUNT;
	kr = vm_map_page_info(map, offset_u, VM_PAGE_INFO_BASIC,
	    (vm_page_info_t) &info, &count);
	if (kr == KERN_SUCCESS) {
		*disposition = info.disposition;
		*ref_count = info.ref_count;
	} else {
		*disposition = 0;
		*ref_count = 0;
	}

	return kr;
}

kern_return_t
vm_map_page_query(
	vm_map_t                map,
	vm_offset_ut            offset,
	int                    *disposition,
	int                    *ref_count)
{
	return mach_vm_page_query(map, offset, disposition, ref_count);
}

static __attribute__((always_inline, warn_unused_result))
kern_return_t
mach_vm_page_range_query_sanitize(
	mach_vm_offset_ut       address_u,
	mach_vm_size_ut         size_u,
	int                     effective_page_mask,
	mach_vm_address_ut      dispositions_addr_u,
	mach_vm_size_ut         dispositions_count_u,
	mach_vm_offset_t       *start,
	mach_vm_size_t         *size,
	mach_vm_address_t      *dispositions_addr,
	mach_vm_size_t         *disp_buf_req_size)
{
	mach_vm_offset_t  end;
	mach_vm_size_t    dispositions_count;
	mach_vm_address_t discard;

	/*
	 * There are no alignment requirements on
	 * dispositions_addr_u/dispositions_count_u, those are derived into
	 * inputs into copyout. So it is safe to unwrap them. We do want to
	 * check that the range starting at dispositions_addr_u and ending
	 * after dispositions_count_u integers is sound (i.e., doesn't wrap
	 * around due to integer overflow).
	 */
	*dispositions_addr = VM_SANITIZE_UNSAFE_UNWRAP(dispositions_addr_u);
	dispositions_count = VM_SANITIZE_UNSAFE_UNWRAP(dispositions_count_u);
	if (
		os_mul_overflow(
			dispositions_count,
			sizeof(int),
			disp_buf_req_size) ||
		os_add_overflow(
			*dispositions_addr,
			*disp_buf_req_size,
			&discard)) {
		return KERN_INVALID_ARGUMENT;
	}

	return vm_sanitize_addr_size(address_u, size_u,
	           VM_SANITIZE_CALLER_VM_MAP_PAGE_RANGE_QUERY,
	           effective_page_mask,
	           VM_SANITIZE_FLAGS_SIZE_ZERO_FALLTHROUGH, start,
	           &end, size);
}

kern_return_t
mach_vm_page_range_query(
	vm_map_t                map,
	mach_vm_offset_ut       address_u,
	mach_vm_size_ut         size_u,
	mach_vm_address_ut      dispositions_addr_u,
	mach_vm_size_ut        *dispositions_count_u)
{
	kern_return_t           kr;
	int                     num_pages = 0, i = 0;
	mach_vm_size_t          curr_sz = 0, copy_sz = 0;
	mach_vm_size_t          disp_buf_req_size = 0, disp_buf_total_size = 0;
	mach_msg_type_number_t  count = 0;
	mach_vm_address_t       dispositions_addr;

	void                    *info = NULL;
	void                    *local_disp = NULL;
	vm_map_size_t           info_size = 0, local_disp_size = 0;
	mach_vm_offset_t        start = 0;
	vm_map_size_t           size;
	int                     effective_page_shift, effective_page_size, effective_page_mask;

	if (map == VM_MAP_NULL || dispositions_count_u == NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	effective_page_shift = vm_self_region_page_shift_safely(map);
	if (effective_page_shift == -1) {
		return KERN_INVALID_ARGUMENT;
	}
	effective_page_size = (1 << effective_page_shift);
	effective_page_mask = effective_page_size - 1;

	kr = mach_vm_page_range_query_sanitize(address_u,
	    size_u,
	    effective_page_mask,
	    dispositions_addr_u,
	    *dispositions_count_u,
	    &start,
	    &size,
	    &dispositions_addr,
	    &disp_buf_req_size);
	if (__improbable(kr != KERN_SUCCESS)) {
		return vm_sanitize_get_kr(kr);
	}

	if (disp_buf_req_size == 0 || size == 0) {
		return KERN_SUCCESS;
	}

	/*
	 * For large requests, we will go through them
	 * MAX_PAGE_RANGE_QUERY chunk at a time.
	 */

	curr_sz = MIN(size, MAX_PAGE_RANGE_QUERY);
	num_pages = (int) (curr_sz >> effective_page_shift);

	info_size = num_pages * sizeof(vm_page_info_basic_data_t);
	info = kalloc_data(info_size, Z_WAITOK);

	local_disp_size = num_pages * sizeof(int);
	local_disp = kalloc_data(local_disp_size, Z_WAITOK);

	if (info == NULL || local_disp == NULL) {
		kr = KERN_RESOURCE_SHORTAGE;
		goto out;
	}

	while (size) {
		count = VM_PAGE_INFO_BASIC_COUNT;
		kr = vm_map_page_range_info_internal(
			map,
			start,
			vm_map_round_page(start + curr_sz, effective_page_mask),
			effective_page_shift,
			VM_PAGE_INFO_BASIC,
			(vm_page_info_t) info,
			&count);

		assert(kr == KERN_SUCCESS);

		for (i = 0; i < num_pages; i++) {
			((int*)local_disp)[i] = ((vm_page_info_basic_t)info)[i].disposition;
		}

		copy_sz = MIN(disp_buf_req_size, num_pages * sizeof(int) /* an int per page */);
		kr = copyout(local_disp, (mach_vm_address_t)dispositions_addr, copy_sz);

		start += curr_sz;
		disp_buf_req_size -= copy_sz;
		disp_buf_total_size += copy_sz;

		if (kr != 0) {
			break;
		}

		if ((disp_buf_req_size == 0) || (curr_sz >= size)) {
			/*
			 * We might have inspected the full range OR
			 * more than it esp. if the user passed in
			 * non-page aligned start/size and/or if we
			 * descended into a submap. We are done here.
			 */

			size = 0;
		} else {
			dispositions_addr += copy_sz;

			size -= curr_sz;

			curr_sz = MIN(vm_map_round_page(size, effective_page_mask), MAX_PAGE_RANGE_QUERY);
			num_pages = (int)(curr_sz >> effective_page_shift);
		}
	}

	VM_SANITIZE_UT_SET(
		*dispositions_count_u,
		disp_buf_total_size / sizeof(int));

out:
	kfree_data(local_disp, local_disp_size);
	kfree_data(info, info_size);
	return kr;
}

kern_return_t
mach_vm_page_info(
	vm_map_t                map,
	mach_vm_address_ut      address,
	vm_page_info_flavor_t   flavor,
	vm_page_info_t          info,
	mach_msg_type_number_t  *count)
{
	kern_return_t   kr;

	if (map == VM_MAP_NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	kr = vm_map_page_info(map, address, flavor, info, count);
	return kr;
}

/*
 *	task_wire (Obsolete)
 */
kern_return_t
task_wire(
	vm_map_t        map,
	boolean_t       must_wire __unused)
{
	if (map == VM_MAP_NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	return KERN_NOT_SUPPORTED;
}

kern_return_t
vm_map_exec_lockdown(
	vm_map_t        map)
{
	vmlp_api_start(VM_MAP_EXEC_LOCKDOWN);

	if (map == VM_MAP_NULL) {
		vmlp_api_end(VM_MAP_EXEC_LOCKDOWN, KERN_INVALID_ARGUMENT);
		return KERN_INVALID_ARGUMENT;
	}

	vm_map_ilk_lock(map);
	map->map_disallow_new_exec = TRUE;
	vm_map_ilk_unlock(map);

	vmlp_api_end(VM_MAP_EXEC_LOCKDOWN, KERN_SUCCESS);
	return KERN_SUCCESS;
}

#if XNU_PLATFORM_MacOSX
kern_return_t
vm_region_object_create(
	__unused vm_map_t target_map,
	__unused vm_size_t size,
	__unused ipc_port_t *object_handle)
{
	return KERN_NOT_SUPPORTED;
}
#endif /* XNU_PLATFORM_MacOSX */

extern boolean_t proc_is_simulated(struct proc *p);

kern_return_t
mach_vm_deferred_reclamation_buffer_allocate(
	task_t           task,
	mach_vm_address_ut *address,
	uint64_t *next_deadline,
	uint32_t initial_capacity,
	uint32_t max_capacity)
{
#if CONFIG_DEFERRED_RECLAIM
	if (task != current_task()) {
		/* Remote buffer operations are not supported*/
		return MACH_SEND_INVALID_DEST;
	}

	struct proc *p = task_get_proc_raw(task);
	if (proc_is_simulated(p)) {
		return KERN_NOT_SUPPORTED;
	}

	return vm_deferred_reclamation_buffer_allocate_internal(task, address, next_deadline, initial_capacity, max_capacity);
#else
	(void) task;
	(void) address;
	(void) size;
	return KERN_NOT_SUPPORTED;
#endif /* CONFIG_DEFERRED_RECLAIM */
}

kern_return_t
mach_vm_deferred_reclamation_buffer_flush(
	task_t task,
	uint32_t num_entries_to_reclaim,
	uint64_t *bytes_reclaimed_out,
	uint64_t *next_deadline_out)
{
#if CONFIG_DEFERRED_RECLAIM
	kern_return_t kr;
	size_t bytes_reclaimed = 0;
	uint64_t next_deadline;

	if (task != current_task()) {
		/* Remote buffer operations are not supported */
		return MACH_SEND_INVALID_DEST;
	}
	if (bytes_reclaimed_out == NULL || next_deadline_out == 0) {
		return KERN_INVALID_ARGUMENT;
	}

	kr = vm_deferred_reclamation_buffer_flush_internal(task, num_entries_to_reclaim, &bytes_reclaimed, &next_deadline);
	*bytes_reclaimed_out = (uint64_t)bytes_reclaimed;
	*next_deadline_out = next_deadline;
	return kr;
#else
	(void) task;
	(void) num_entries_to_reclaim;
	return KERN_NOT_SUPPORTED;
#endif /* CONFIG_DEFERRED_RECLAIM */
}

kern_return_t
mach_vm_deferred_reclamation_buffer_resize(task_t task,
    uint32_t new_len,
    uint64_t *bytes_reclaimed_out,
    uint64_t *next_deadline_out)
{
#if CONFIG_DEFERRED_RECLAIM
	mach_error_t err;
	size_t bytes_reclaimed = 0;
	uint64_t next_deadline;

	if (task != current_task()) {
		/* Remote buffer operations are not supported */
		return MACH_SEND_INVALID_DEST;
	}
	if (bytes_reclaimed_out == NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	err = vm_deferred_reclamation_buffer_resize_internal(task, new_len, &bytes_reclaimed, &next_deadline);
	*bytes_reclaimed_out = (uint64_t)bytes_reclaimed;
	*next_deadline_out = next_deadline;
	return err;
#else
	(void) task;
	(void) size;
	return KERN_NOT_SUPPORTED;
#endif /* CONFIG_DEFERRED_RECLAIM */
}

kern_return_t
mach_vm_deferred_reclamation_buffer_query(task_t task,
    mach_vm_address_ut *addr_out_ut,
    mach_vm_size_ut *size_out_ut)
{
#if CONFIG_DEFERRED_RECLAIM
	return vm_deferred_reclamation_buffer_query_internal(task, addr_out_ut, size_out_ut);
#else /* CONFIG_DEFERRED_RECLAIM */
	(void) task;
	(void) addr_out_ut;
	(void) size_out_ut;
	return KERN_NOT_SUPPORTED;
#endif /* !CONFIG_DEFERRED_RECLAIM */
}

#if CONFIG_MAP_RANGES

extern void qsort(void *a, size_t n, size_t es, int (*cmp)(const void *, const void *));

static int
vm_map_user_range_cmp(const void *e1, const void *e2)
{
	const struct vm_map_user_range *r1 = e1;
	const struct vm_map_user_range *r2 = e2;

	if (r1->vmur_min_address != r2->vmur_min_address) {
		return r1->vmur_min_address < r2->vmur_min_address ? -1 : 1;
	}

	return 0;
}

static int
mach_vm_range_recipe_v1_cmp(const void *e1, const void *e2)
{
	const mach_vm_range_recipe_v1_t *r1 = e1;
	const mach_vm_range_recipe_v1_t *r2 = e2;

	if (r1->range.min_address != r2->range.min_address) {
		return r1->range.min_address < r2->range.min_address ? -1 : 1;
	}

	return 0;
}

static inline __result_use_check kern_return_t
mach_vm_range_create_v1_sanitize(
	vm_map_t                map,
	mach_vm_range_recipe_v1_ut *recipe_u,
	uint32_t count,
	mach_vm_range_recipe_v1_t **recipe_p)
{
	kern_return_t kr;

	for (size_t i = 0; i < count; i++) {
		vm_map_offset_t start, end;
		vm_map_size_t size;
		mach_vm_range_ut * range_u = &recipe_u[i].range_u;
#if HAS_MTE || HAS_MTE_EMULATION_SHIMS
		kr = vm_sanitize_validate_non_canonical_ut_addr(map, range_u->min_address_u);
		if (kr != KERN_SUCCESS) {
			return kr;
		}

		kr = vm_sanitize_validate_non_canonical_ut_addr(map, range_u->max_address_u);
		if (kr != KERN_SUCCESS) {
			return kr;
		}
#endif /* HAS_MTE || HAS_MTE_EMULATION_SHIMS */

		kr = vm_sanitize_addr_end(
			range_u->min_address_u,
			range_u->max_address_u,
			VM_SANITIZE_CALLER_MACH_VM_RANGE_CREATE,
			map,
			VM_SANITIZE_FLAGS_SIZE_ZERO_FAILS
			| VM_SANITIZE_FLAGS_CHECK_ALIGNED_START
			| VM_SANITIZE_FLAGS_CHECK_ALIGNED_SIZE,
			&start, &end, &size); // Ignore return values
		if (__improbable(kr != KERN_SUCCESS)) {
			return kr;
		}
	}
	/*
	 * Sanitization only checked properties of recipe_u.
	 * We can now see it through the lens of the safe type.
	 * The cast is undefined behavior, but of the kind VM sanitization
	 * relies on anyway, so we don't expect this to cause issues.
	 */
	*recipe_p = (mach_vm_range_recipe_v1_t *)recipe_u;

	return KERN_SUCCESS;
}

bool
vm_map_in_user_range_voids(
	vm_map_t                map,
	vm_address_t            addr,
	vm_size_t               size)
{
	struct mach_vm_range void1 = {
		.min_address = map->default_range.max_address,
		.max_address = map->data_range.min_address,
	};
	struct mach_vm_range void2 = {
		.min_address = map->data_range.max_address,
#if XNU_TARGET_OS_IOS && EXTENDED_USER_VA_SUPPORT
		.max_address = MACH_VM_JUMBO_ADDRESS,
#else /* !XNU_TARGET_OS_IOS || !EXTENDED_USER_VA_SUPPORT */
		.max_address = vm_map_max(map),
#endif /* XNU_TARGET_OS_IOS && EXTENDED_USER_VA_SUPPORT */
	};

	return map->uses_user_ranges &&
	       (mach_vm_range_contains(&void1, addr, size) ||
	       mach_vm_range_contains(&void2, addr, size));
}

/*!
 * @function mach_vm_range_create_v1()
 *
 * @brief
 * Handle the backend for mach_vm_range_create() for the
 * MACH_VM_RANGE_FLAVOR_V1 flavor.
 *
 * @description
 * This call allows to create "ranges" in the map of a task
 * that have special semantics/policies around placement of
 * new allocations (in the vm_map_locate_space() sense).
 *
 * @returns
 * - KERN_SUCCESS on success
 * - KERN_INVALID_ARGUMENT for incorrect arguments
 * - KERN_NO_SPACE if the maximum amount of ranges would be exceeded
 * - KERN_MEMORY_PRESENT if any of the requested ranges
 *   overlaps with existing ranges or allocations in the map.
 */
static kern_return_t
mach_vm_range_create_v1(
	vm_map_t                   map,
	mach_vm_range_recipe_v1_ut *recipe_u,
	uint32_t                   new_count)
{
	mach_vm_range_recipe_v1_t *recipe;
	vm_map_user_range_t table;
	kern_return_t kr = KERN_SUCCESS;
	uint16_t count;

	vmlp_api_start(MACH_VM_RANGE_CREATE_V1);

	kr = mach_vm_range_create_v1_sanitize(map, recipe_u, new_count, &recipe);
	if (__improbable(kr != KERN_SUCCESS)) {
		kr = vm_sanitize_get_kr(kr);
		vmlp_api_end(MACH_VM_RANGE_CREATE_V1, kr);
		return kr;
	}

	qsort(recipe, new_count, sizeof(mach_vm_range_recipe_v1_t),
	    mach_vm_range_recipe_v1_cmp);

	/*
	 * Step 1: Validate that the recipes have no intersections.
	 */

	for (size_t i = 0; i < new_count; i++) {
		mach_vm_range_t r = &recipe[i].range;
		mach_vm_size_t s;

		if (recipe[i].flags) {
			vmlp_api_end(MACH_VM_RANGE_CREATE_V1, KERN_INVALID_ARGUMENT);
			return KERN_INVALID_ARGUMENT;
		}

		static_assert((int)UMEM_RANGE_ID_FIXED == MACH_VM_RANGE_FIXED);
		switch (recipe[i].range_tag) {
		case MACH_VM_RANGE_FIXED:
			break;
		default:
			vmlp_api_end(MACH_VM_RANGE_CREATE_V1, KERN_INVALID_ARGUMENT);
			return KERN_INVALID_ARGUMENT;
		}

		s = mach_vm_range_size(r);
		if (!vm_map_in_user_range_voids(map, r->min_address, s)) {
			vmlp_api_end(MACH_VM_RANGE_CREATE_V1, KERN_INVALID_ARGUMENT);
			return KERN_INVALID_ARGUMENT;
		}

		if (i > 0 && recipe[i - 1].range.max_address >
		    recipe[i].range.min_address) {
			vmlp_api_end(MACH_VM_RANGE_CREATE_V1, KERN_INVALID_ARGUMENT);
			return KERN_INVALID_ARGUMENT;
		}
	}

	vm_map_ilk_lock(map);

	table = map->extra_ranges;
	count = map->extra_ranges_count;

	if (count + new_count > VM_MAP_EXTRA_RANGES_MAX) {
		kr = KERN_NO_SPACE;
		goto out_unlock;
	}

	/*
	 * Step 2: Check that there is no intersection with existing ranges.
	 */

	for (size_t i = 0, j = 0; i < new_count && j < count;) {
		mach_vm_range_t     r1 = &recipe[i].range;
		vm_map_user_range_t r2 = &table[j];

		if (r1->max_address <= r2->vmur_min_address) {
			i++;
		} else if (r2->vmur_max_address <= r1->min_address) {
			j++;
		} else {
			kr = KERN_MEMORY_PRESENT;
			goto out_unlock;
		}
	}

	/*
	 * Step 3: commit the new ranges.
	 */

	static_assert(VM_MAP_EXTRA_RANGES_MAX * sizeof(struct vm_map_user_range) <=
	    KALLOC_SAFE_ALLOC_SIZE);

	table = krealloc_data(table,
	    count * sizeof(struct vm_map_user_range),
	    (count + new_count) * sizeof(struct vm_map_user_range),
	    Z_ZERO | Z_WAITOK | Z_NOFAIL);

	for (size_t i = 0; i < new_count; i++) {
		static_assert(MACH_VM_MAX_ADDRESS < (1ull << 56));

		table[count + i] = (struct vm_map_user_range){
			.vmur_min_address = recipe[i].range.min_address,
			.vmur_max_address = recipe[i].range.max_address,
			.vmur_range_id    = (vm_map_range_id_t)recipe[i].range_tag,
		};
	}

	qsort(table, count + new_count,
	    sizeof(struct vm_map_user_range), vm_map_user_range_cmp);

	map->extra_ranges_count += new_count;
	map->extra_ranges = table;

out_unlock:
	vm_map_ilk_unlock(map);

	if (kr == KERN_SUCCESS) {
		for (size_t i = 0; i < new_count; i++) {
			vm_map_kernel_flags_t vmk_flags = {
				.vmf_fixed = true,
				.vmf_overwrite = true,
				.vmkf_overwrite_immutable = true,
				.vm_tag = recipe[i].vm_tag,
			};
			__assert_only kern_return_t kr2;

			vmlp_range_event(map, recipe[i].range.min_address, recipe[i].range.max_address - recipe[i].range.min_address);

			kr2 = vm_map_enter(map, &recipe[i].range.min_address,
			    mach_vm_range_size(&recipe[i].range),
			    0, vmk_flags, VM_OBJECT_NULL, 0, FALSE,
			    VM_PROT_NONE, VM_PROT_ALL,
			    VM_INHERIT_DEFAULT);
			assert(kr2 == KERN_SUCCESS);
		}
	}
	vmlp_api_end(MACH_VM_RANGE_CREATE_V1, kr);
	return kr;
}

kern_return_t
mach_vm_range_create(
	vm_map_t                map,
	mach_vm_range_flavor_t  flavor,
	mach_vm_range_recipes_raw_t recipe,
	natural_t               size)
{
	if (map != current_map()) {
		return KERN_INVALID_ARGUMENT;
	}

	if (!map->uses_user_ranges) {
		return KERN_NOT_SUPPORTED;
	}

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

	if (flavor == MACH_VM_RANGE_FLAVOR_V1) {
		mach_vm_range_recipe_v1_ut *array;

		if (size % sizeof(mach_vm_range_recipe_v1_ut)) {
			return KERN_INVALID_ARGUMENT;
		}

		size /= sizeof(mach_vm_range_recipe_v1_ut);
		if (size > VM_MAP_EXTRA_RANGES_MAX) {
			return KERN_NO_SPACE;
		}

		array = (mach_vm_range_recipe_v1_ut *)recipe;
		return mach_vm_range_create_v1(map, array, size);
	}

	return KERN_INVALID_ARGUMENT;
}

#else /* !CONFIG_MAP_RANGES */

kern_return_t
mach_vm_range_create(
	vm_map_t                map,
	mach_vm_range_flavor_t  flavor,
	mach_vm_range_recipes_raw_t recipe,
	natural_t               size)
{
#pragma unused(map, flavor, recipe, size)
	return KERN_NOT_SUPPORTED;
}

#endif /* !CONFIG_MAP_RANGES */

/*
 * These symbols are looked up at runtime by vmware, VirtualBox,
 * despite not being exported in the symbol sets.
 */

#if defined(__x86_64__)

extern typeof(mach_vm_remap_external) mach_vm_remap;
extern typeof(mach_vm_map_external) mach_vm_map;
extern typeof(vm_map_external) vm_map;

kern_return_t
mach_vm_map(
	vm_map_t                target_map,
	mach_vm_offset_ut      *address,
	mach_vm_size_ut         initial_size,
	mach_vm_offset_ut       mask,
	int                     flags,
	ipc_port_t              port,
	memory_object_offset_ut offset,
	boolean_t               copy,
	vm_prot_ut              cur_protection,
	vm_prot_ut              max_protection,
	vm_inherit_ut           inheritance)
{
	return mach_vm_map_external(target_map, address, initial_size, mask, flags, port,
	           offset, copy, cur_protection, max_protection, inheritance);
}

kern_return_t
mach_vm_remap(
	vm_map_t                target_map,
	mach_vm_offset_ut      *address,
	mach_vm_size_ut         size,
	mach_vm_offset_ut       mask,
	int                     flags,
	vm_map_t                src_map,
	mach_vm_offset_ut       memory_address,
	boolean_t               copy,
	vm_prot_ut             *cur_protection,   /* OUT */
	vm_prot_ut             *max_protection,   /* OUT */
	vm_inherit_ut           inheritance)
{
	return mach_vm_remap_external(target_map, address, size, mask, flags, src_map, memory_address,
	           copy, cur_protection, max_protection, inheritance);
}

kern_return_t
vm_map(
	vm_map_t                target_map,
	vm_offset_ut           *address,
	vm_size_ut              size,
	vm_offset_ut            mask,
	int                     flags,
	ipc_port_t              port,
	vm_offset_ut            offset,
	boolean_t               copy,
	vm_prot_ut              cur_protection,
	vm_prot_ut              max_protection,
	vm_inherit_ut           inheritance)
{
	return mach_vm_map(target_map, address,
	           size, mask, flags, port, offset, copy,
	           cur_protection, max_protection, inheritance);
}

#endif /* __x86_64__ */