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
#include <stdio.h>
#include <signal.h>
#include <sys/proc.h>
#include <sys/sysctl.h>
#include <sys/kern_memorystatus.h>
#include <sys/kern_memorystatus_freeze.h>
#include <time.h>
#include <mach-o/dyld.h>
#include <mach/host_info.h>
#include <mach/mach.h>
#include <mach/mach_vm.h>
#include <mach/shared_region.h>
#include <mach/vm_page_size.h>
#include <os/reason_private.h>
#include <TargetConditionals.h>
#include <sys/coalition.h>
#include <spawn_private.h>

#ifdef T_NAMESPACE
#undef T_NAMESPACE
#endif
#include <darwintest.h>
#include <darwintest_utils.h>

#include "memorystatus_assertion_helpers.h"
#include "test_utils.h"

T_GLOBAL_META(
	T_META_NAMESPACE("xnu.memorystatus"),
	T_META_RADAR_COMPONENT_NAME("xnu"),
	T_META_RADAR_COMPONENT_VERSION("VM"),
	T_META_CHECK_LEAKS(false),
	T_META_RUN_CONCURRENTLY(false)
	);

#define MEM_SIZE_MB                     10
#define NUM_ITERATIONS          5
#define FREEZE_PAGES_MAX 256

#define HAS_FREEZER ((TARGET_OS_IOS && !TARGET_OS_XR) || TARGET_OS_WATCH)

#define CREATE_LIST(X) \
	X(SUCCESS) \
	X(TOO_FEW_ARGUMENTS) \
	X(SYSCTL_VM_PAGESIZE_FAILED) \
	X(VM_PAGESIZE_IS_ZERO) \
	X(DISPATCH_SOURCE_CREATE_FAILED) \
	X(INITIAL_SIGNAL_TO_PARENT_FAILED) \
	X(SIGNAL_TO_PARENT_FAILED) \
	X(MEMORYSTATUS_CONTROL_FAILED) \
	X(IS_FREEZABLE_NOT_AS_EXPECTED) \
	X(MEMSTAT_PRIORITY_CHANGE_FAILED) \
	X(INVALID_ALLOCATE_PAGES_ARGUMENTS) \
	X(FROZEN_BIT_SET) \
	X(FROZEN_BIT_NOT_SET) \
	X(MEMORYSTATUS_CONTROL_ERROR) \
	X(UNABLE_TO_ALLOCATE) \
	X(EXIT_CODE_MAX) \

#define EXIT_CODES_ENUM(VAR) VAR,
enum exit_codes_num {
	CREATE_LIST(EXIT_CODES_ENUM)
};

#define EXIT_CODES_STRING(VAR) #VAR,
static const char *exit_codes_str[] = {
	CREATE_LIST(EXIT_CODES_STRING)
};

static int
get_vmpage_size(void)
{
	int vmpage_size;
	size_t size = sizeof(vmpage_size);
	int ret = sysctlbyname("vm.pagesize", &vmpage_size, &size, NULL, 0);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "failed to query vm.pagesize");
	T_QUIET; T_ASSERT_GT(vmpage_size, 0, "vm.pagesize is not > 0");
	return vmpage_size;
}

static pid_t child_pid = -1;
static int freeze_count = 0;

void move_to_idle_band(pid_t);
void run_freezer_test(int);
void freeze_helper_process(void);
/* Gets and optionally sets the freeze pages max threshold */
int sysctl_freeze_pages_max(int* new_value);

/* NB: in_shared_region and get_rprvt are pulled from the memorystatus unit test.
 * We're moving away from those unit tests, so they're copied here.
 */

/* Cribbed from 'top'... */
static int
in_shared_region(mach_vm_address_t addr, cpu_type_t type)
{
	mach_vm_address_t base = 0, size = 0;

	switch (type) {
	case CPU_TYPE_ARM:
		base = SHARED_REGION_BASE_ARM;
		size = SHARED_REGION_SIZE_ARM;
		break;

	case CPU_TYPE_ARM64:
		base = SHARED_REGION_BASE_ARM64;
		size = SHARED_REGION_SIZE_ARM64;
		break;


	case CPU_TYPE_X86_64:
		base = SHARED_REGION_BASE_X86_64;
		size = SHARED_REGION_SIZE_X86_64;
		break;

	case CPU_TYPE_I386:
		base = SHARED_REGION_BASE_I386;
		size = SHARED_REGION_SIZE_I386;
		break;

	case CPU_TYPE_POWERPC:
		base = SHARED_REGION_BASE_PPC;
		size = SHARED_REGION_SIZE_PPC;
		break;

	case CPU_TYPE_POWERPC64:
		base = SHARED_REGION_BASE_PPC64;
		size = SHARED_REGION_SIZE_PPC64;
		break;

	default: {
		int t = type;

		fprintf(stderr, "unknown CPU type: 0x%x\n", t);
		abort();
	}
	}

	return addr >= base && addr < (base + size);
}

static int orig_freezer;

static void
restore_freezer() {
	int ret;
	T_LOG("Restoring original vm.freeze_enabled value (%d)...", orig_freezer);
	ret = sysctlbyname("vm.freeze_enabled", NULL, NULL, &orig_freezer, sizeof(orig_freezer));
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "Enabling freezer via sysctl");
}

static void
check_for_and_enable_freezer() {
	int ret, freeze_enabled;
	size_t size = sizeof(freeze_enabled);

	ret = sysctlbyname("vm.freeze_enabled", &freeze_enabled, &size, NULL, 0);
	T_QUIET; T_ASSERT_POSIX_ZERO(ret, "Could not find vm.freeze_enabled");

	if (!freeze_enabled) {
		T_LOG("Freezer not enabled, enabling...");
		orig_freezer = freeze_enabled;
		freeze_enabled = 1;
		ret = sysctlbyname("vm.freeze_enabled", NULL, NULL, &freeze_enabled, sizeof(freeze_enabled));
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "Enabling freezer via sysctl");
		T_ATEND(restore_freezer);
	}
}

/* Get the resident private memory of the given pid */
static unsigned long long
get_rprvt(pid_t pid)
{
	mach_port_name_t task;
	kern_return_t kr;

	mach_vm_size_t rprvt = 0;
	mach_vm_size_t empty = 0;
	mach_vm_size_t fw_private = 0;
	mach_vm_size_t pagesize = vm_kernel_page_size;  // The vm_region page info is reported
	                                                // in terms of vm_kernel_page_size.
	mach_vm_size_t regs = 0;

	mach_vm_address_t addr;
	mach_vm_size_t size;

	int split = 0;

	kr = task_for_pid(mach_task_self(), pid, &task);
	T_QUIET; T_ASSERT_TRUE(kr == KERN_SUCCESS, "Unable to get task_for_pid of child");

	for (addr = 0;; addr += size) {
		vm_region_top_info_data_t info;
		mach_msg_type_number_t count = VM_REGION_TOP_INFO_COUNT;
		mach_port_t object_name;

		kr = mach_vm_region(task, &addr, &size, VM_REGION_TOP_INFO, (vm_region_info_t)&info, &count, &object_name);
		if (kr != KERN_SUCCESS) {
			break;
		}

#if   defined (__arm64__)
		if (in_shared_region(addr, CPU_TYPE_ARM64)) {
#else
		if (in_shared_region(addr, CPU_TYPE_ARM)) {
#endif
			// Private Shared
			fw_private += info.private_pages_resident * pagesize;

			/*
			 * Check if this process has the globally shared
			 * text and data regions mapped in.  If so, set
			 * split to TRUE and avoid checking
			 * again.
			 */
			if (split == FALSE && info.share_mode == SM_EMPTY) {
				vm_region_basic_info_data_64_t  b_info;
				mach_vm_address_t b_addr = addr;
				mach_vm_size_t b_size = size;
				count = VM_REGION_BASIC_INFO_COUNT_64;

				kr = mach_vm_region(task, &b_addr, &b_size, VM_REGION_BASIC_INFO_64, (vm_region_info_t)&b_info, &count, &object_name);
				if (kr != KERN_SUCCESS) {
					break;
				}

				if (b_info.reserved) {
					split = TRUE;
				}
			}

			/*
			 * Short circuit the loop if this isn't a shared
			 * private region, since that's the only region
			 * type we care about within the current address
			 * range.
			 */
			if (info.share_mode != SM_PRIVATE) {
				continue;
			}
		}

		regs++;

		/*
		 * Update counters according to the region type.
		 */

		if (info.share_mode == SM_COW && info.ref_count == 1) {
			// Treat single reference SM_COW as SM_PRIVATE
			info.share_mode = SM_PRIVATE;
		}

		switch (info.share_mode) {
		case SM_LARGE_PAGE:
		// Treat SM_LARGE_PAGE the same as SM_PRIVATE
		// since they are not shareable and are wired.
		case SM_PRIVATE:
			rprvt += info.private_pages_resident * pagesize;
			rprvt += info.shared_pages_resident * pagesize;
			break;

		case SM_EMPTY:
			empty += size;
			break;

		case SM_COW:
		case SM_SHARED:
			if (pid == 0) {
				// Treat kernel_task specially
				if (info.share_mode == SM_COW) {
					rprvt += info.private_pages_resident * pagesize;
				}
				break;
			}

			if (info.share_mode == SM_COW) {
				rprvt += info.private_pages_resident * pagesize;
			}
			break;

		default:
			assert(0);
			break;
		}
	}

	return rprvt;
}

void
move_to_idle_band(pid_t pid)
{
	memorystatus_priority_properties_t props;
	/*
	 * Freezing a process also moves it to an elevated jetsam band in order to protect it from idle exits.
	 * So we move the child process to the idle band to mirror the typical 'idle app being frozen' scenario.
	 */
	props.priority = JETSAM_PRIORITY_IDLE;
	props.user_data = 0;

	/*
	 * This requires us to run as root (in the absence of entitlement).
	 * Hence the T_META_ASROOT(true) in the T_HELPER_DECL.
	 */
	if (memorystatus_control(MEMORYSTATUS_CMD_SET_PRIORITY_PROPERTIES, pid, 0, &props, sizeof(props))) {
		exit(MEMSTAT_PRIORITY_CHANGE_FAILED);
	}
}

void
freeze_helper_process(void)
{
	size_t length;
	int ret, freeze_enabled, errno_freeze_sysctl;
	uint64_t resident_memory_before, resident_memory_after, vmpage_size;
	vmpage_size = (uint64_t) get_vmpage_size();
	resident_memory_before = get_rprvt(child_pid) / vmpage_size;

	T_LOG("Freezing child pid %d", child_pid);
	ret = sysctlbyname("kern.memorystatus_freeze", NULL, NULL, &child_pid, sizeof(child_pid));
	errno_freeze_sysctl = errno;
	sleep(1);

	/*
	 * The child process toggles its freezable state on each iteration.
	 * So a failure for every alternate freeze is expected.
	 */
	if (freeze_count % 2) {
		length = sizeof(freeze_enabled);
		T_QUIET; T_ASSERT_POSIX_SUCCESS(sysctlbyname("vm.freeze_enabled", &freeze_enabled, &length, NULL, 0),
		    "failed to query vm.freeze_enabled");
		if (freeze_enabled) {
			errno = errno_freeze_sysctl;
			T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "sysctl kern.memorystatus_freeze failed");
		} else {
			/* If freezer is disabled, skip the test. This can happen due to disk space shortage. */
			T_LOG("Freeze has been disabled. Terminating early.");
			T_END;
		}
		resident_memory_after = get_rprvt(child_pid) / vmpage_size;
		uint64_t freeze_pages_max = (uint64_t) sysctl_freeze_pages_max(NULL);
		T_QUIET; T_ASSERT_LT(resident_memory_after, resident_memory_before, "Freeze didn't reduce resident memory set");
		if (resident_memory_before > freeze_pages_max) {
			T_QUIET; T_ASSERT_LE(resident_memory_before - resident_memory_after, freeze_pages_max, "Freeze pages froze more than the threshold.");
		}
		ret = sysctlbyname("kern.memorystatus_thaw", NULL, NULL, &child_pid, sizeof(child_pid));
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "sysctl kern.memorystatus_thaw failed");
	} else {
		T_QUIET; T_ASSERT_TRUE(ret != KERN_SUCCESS, "Freeze should have failed");
		T_LOG("Freeze failed as expected");
	}

	freeze_count++;

	T_QUIET; T_ASSERT_POSIX_SUCCESS(kill(child_pid, SIGUSR1), "failed to send SIGUSR1 to child process");
}

void
run_freezer_test(int num_pages)
{
	int ret;
	char sz_str[50];
	char **launch_tool_args;
	char testpath[PATH_MAX];
	uint32_t testpath_buf_size;
	dispatch_source_t ds_freeze, ds_proc;

	signal(SIGUSR1, SIG_IGN);
	ds_freeze = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, dispatch_get_main_queue());
	T_QUIET; T_ASSERT_NOTNULL(ds_freeze, "dispatch_source_create (ds_freeze)");

	dispatch_source_set_event_handler(ds_freeze, ^{
		if (freeze_count < NUM_ITERATIONS) {
		        freeze_helper_process();
		} else {
		        kill(child_pid, SIGKILL);
		        dispatch_source_cancel(ds_freeze);
		}
	});
	dispatch_activate(ds_freeze);

	testpath_buf_size = sizeof(testpath);
	ret = _NSGetExecutablePath(testpath, &testpath_buf_size);
	T_QUIET; T_ASSERT_POSIX_ZERO(ret, "_NSGetExecutablePath");
	T_LOG("Executable path: %s", testpath);

	sprintf(sz_str, "%d", num_pages);
	launch_tool_args = (char *[]){
		testpath,
		"-n",
		"allocate_pages",
		"--",
		sz_str,
		NULL
	};

	/* Spawn the child process. Suspend after launch until the exit proc handler has been set up. */
	ret = dt_launch_tool(&child_pid, launch_tool_args, true, NULL, NULL);
	if (ret != 0) {
		T_LOG("dt_launch tool returned %d with error code %d", ret, errno);
	}
	T_QUIET; T_ASSERT_POSIX_SUCCESS(child_pid, "dt_launch_tool");

	ds_proc = dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC, (uintptr_t)child_pid, DISPATCH_PROC_EXIT, dispatch_get_main_queue());
	T_QUIET; T_ASSERT_NOTNULL(ds_proc, "dispatch_source_create (ds_proc)");

	dispatch_source_set_event_handler(ds_proc, ^{
		int status = 0, code = 0;
		pid_t rc = waitpid(child_pid, &status, 0);
		T_QUIET; T_ASSERT_EQ(rc, child_pid, "waitpid");
		code = WEXITSTATUS(status);

		if (code == 0) {
		        T_END;
		} else if (code > 0 && code < EXIT_CODE_MAX) {
		        T_ASSERT_FAIL("Child exited with %s", exit_codes_str[code]);
		} else {
		        T_ASSERT_FAIL("Child exited with unknown exit code %d", code);
		}
	});
	dispatch_activate(ds_proc);

	T_QUIET; T_ASSERT_POSIX_SUCCESS(kill(child_pid, SIGCONT), "failed to send SIGCONT to child process");
	dispatch_main();
}

static void
allocate_pages(int num_pages)
{
	int i, j, vmpgsize;
	char val;
	__block int num_iter = 0;
	__block char **buf;
	dispatch_source_t ds_signal;
	vmpgsize = get_vmpage_size();
	if (num_pages < 1) {
		printf("Invalid number of pages to allocate: %d\n", num_pages);
		exit(INVALID_ALLOCATE_PAGES_ARGUMENTS);
	}

	buf = (char**)malloc(sizeof(char*) * (size_t)num_pages);

	/* Gives us the compression ratio we see in the typical case (~2.7) */
	for (j = 0; j < num_pages; j++) {
		buf[j] = (char*)malloc((size_t)vmpgsize * sizeof(char));
		val = 0;
		for (i = 0; i < vmpgsize; i += 16) {
			memset(&buf[j][i], val, 16);
			if (i < 3400 * (vmpgsize / 4096)) {
				val++;
			}
		}
	}

	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), dispatch_get_main_queue(), ^{
		/* Signal to the parent that we're done allocating and it's ok to freeze us */
		printf("[%d] Sending initial signal to parent to begin freezing\n", getpid());
		if (kill(getppid(), SIGUSR1) != 0) {
		        exit(INITIAL_SIGNAL_TO_PARENT_FAILED);
		}
	});

	signal(SIGUSR1, SIG_IGN);
	ds_signal = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, dispatch_get_main_queue());
	if (ds_signal == NULL) {
		exit(DISPATCH_SOURCE_CREATE_FAILED);
	}

	dispatch_source_set_event_handler(ds_signal, ^{
		int current_state, new_state;
		volatile int tmp;

		/* Make sure all the pages are accessed before trying to freeze again */
		for (int x = 0; x < num_pages; x++) {
		        tmp = buf[x][0];
		}

		current_state = memorystatus_control(MEMORYSTATUS_CMD_GET_PROCESS_IS_FREEZABLE, getpid(), 0, NULL, 0);
		/* Sysprocs start off as unfreezable. Verify that first. */
		if (num_iter == 0 && current_state != 0) {
		        exit(IS_FREEZABLE_NOT_AS_EXPECTED);
		}

		/* Toggle freezable state */
		new_state = (current_state) ? 0: 1;
		printf("[%d] Changing state from %s to %s\n", getpid(),
		(current_state) ? "freezable": "unfreezable", (new_state) ? "freezable": "unfreezable");
		if (memorystatus_control(MEMORYSTATUS_CMD_SET_PROCESS_IS_FREEZABLE, getpid(), (uint32_t)new_state, NULL, 0) != KERN_SUCCESS) {
		        exit(MEMORYSTATUS_CONTROL_FAILED);
		}

		/* Verify that the state has been set correctly */
		current_state = memorystatus_control(MEMORYSTATUS_CMD_GET_PROCESS_IS_FREEZABLE, getpid(), 0, NULL, 0);
		if (new_state != current_state) {
		        exit(IS_FREEZABLE_NOT_AS_EXPECTED);
		}
		num_iter++;

		if (kill(getppid(), SIGUSR1) != 0) {
		        exit(SIGNAL_TO_PARENT_FAILED);
		}
	});
	dispatch_activate(ds_signal);
	move_to_idle_band(getpid());

	dispatch_main();
}

T_HELPER_DECL(allocate_pages,
    "allocates pages to freeze",
    T_META_ASROOT(true)) {
	if (argc < 1) {
		exit(TOO_FEW_ARGUMENTS);
	}

	int num_pages = atoi(argv[0]);
	allocate_pages(num_pages);
}

T_DECL(memorystatus_freeze_default_state, "Test that the freezer is enabled or disabled as expected by default.", T_META_ASROOT(true), T_META_TAG_VM_NOT_PREFERRED) {

#if TARGET_OS_IOS || TARGET_OS_WATCH
	bool expected_freeze_enabled = true;
#else
	bool expected_freeze_enabled = false;
#endif


	int freeze_enabled;
	size_t length = sizeof(freeze_enabled);
	int ret = sysctlbyname("vm.freeze_enabled", &freeze_enabled, &length, NULL, 0);

	if (ret != 0) {
		if (expected_freeze_enabled) {
			T_ASSERT_FAIL("Expected freezer enabled but did not find sysctl vm.freeze_enabled");
		} else {
			T_PASS("Did not expect freezer to be enabled and did not find sysctl vm.freeze_enabled");
		}
	} else {
		T_ASSERT_EQ(freeze_enabled, expected_freeze_enabled, "Expected freezer sysctl status %d, got %d", expected_freeze_enabled, freeze_enabled);
	}
}

T_DECL(freeze, "VM freezer test",
	T_META_ENABLED(HAS_FREEZER),
	T_META_ASROOT(true),
	T_META_TAG_VM_NOT_PREFERRED) {
	check_for_and_enable_freezer();
	run_freezer_test(
		(MEM_SIZE_MB << 20) / get_vmpage_size());
}

static int old_freeze_pages_max = 0;
static void
reset_freeze_pages_max(void)
{
	if (old_freeze_pages_max != 0) {
		sysctl_freeze_pages_max(&old_freeze_pages_max);
	}
}

int
sysctl_freeze_pages_max(int* new_value)
{
	static int set_end_handler = false;
	int freeze_pages_max, ret;
	size_t size = sizeof(freeze_pages_max);
	ret = sysctlbyname("kern.memorystatus_freeze_pages_max", &freeze_pages_max, &size, new_value, size);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "Unable to query kern.memorystatus_freeze_pages_max");
	if (!set_end_handler) {
		// Save the original value and instruct darwintest to restore it after the test completes
		old_freeze_pages_max = freeze_pages_max;
		T_ATEND(reset_freeze_pages_max);
		set_end_handler = true;
	}
	return old_freeze_pages_max;
}

T_DECL(freeze_over_max_threshold, "Max Freeze Threshold is Enforced",
	T_META_ENABLED(HAS_FREEZER),
	T_META_ASROOT(true),
	T_META_TAG_VM_NOT_PREFERRED) {
	int freeze_pages_max = FREEZE_PAGES_MAX;
	check_for_and_enable_freezer();
	sysctl_freeze_pages_max(&freeze_pages_max);
	run_freezer_test(FREEZE_PAGES_MAX * 2);
}

T_HELPER_DECL(frozen_background, "Frozen background process",
	T_META_ENABLED(HAS_FREEZER),
	T_META_ASROOT(true)) {
	kern_return_t kern_ret;
	check_for_and_enable_freezer();
	/* Set the process to freezable */
	kern_ret = memorystatus_control(MEMORYSTATUS_CMD_SET_PROCESS_IS_FREEZABLE, getpid(), 1, NULL, 0);
	T_QUIET; T_ASSERT_EQ(kern_ret, KERN_SUCCESS, "set process is freezable");
	/* Signal to our parent that we can be frozen */
	if (kill(getppid(), SIGUSR1) != 0) {
		T_LOG("Unable to signal to parent process!");
		exit(1);
	}
	while (1) {
		;
	}
}

static void
freeze_process(pid_t pid)
{
	int ret, freeze_enabled, errno_freeze_sysctl;
	size_t length;
	T_LOG("Freezing pid %d", pid);

	ret = sysctlbyname("kern.memorystatus_freeze", NULL, NULL, &pid, sizeof(pid));
	errno_freeze_sysctl = errno;
	length = sizeof(freeze_enabled);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(sysctlbyname("vm.freeze_enabled", &freeze_enabled, &length, NULL, 0),
	    "failed to query vm.freeze_enabled");
	if (freeze_enabled) {
		errno = errno_freeze_sysctl;
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "sysctl kern.memorystatus_freeze failed");
	} else {
		/* If freezer is disabled, skip the test. This can happen due to disk space shortage. */
		T_LOG("Freeze has been disabled. Terminating early.");
		T_END;
	}
}

static uint32_t max_frozen_demotions_daily_default;

static void
reset_max_frozen_demotions_daily(void)
{
	int sysctl_ret = sysctlbyname("kern.memorystatus_max_freeze_demotions_daily", NULL, NULL, &max_frozen_demotions_daily_default, sizeof(max_frozen_demotions_daily_default));
	T_QUIET; T_ASSERT_POSIX_SUCCESS(sysctl_ret, "set kern.memorystatus_max_freeze_demotions_daily to default");
}

static void
allow_unlimited_demotions(void)
{
	size_t size = sizeof(max_frozen_demotions_daily_default);
	uint32_t new_value = UINT32_MAX;
	int sysctl_ret = sysctlbyname("kern.memorystatus_max_freeze_demotions_daily", &max_frozen_demotions_daily_default, &size, &new_value, sizeof(new_value));
	T_QUIET; T_ASSERT_POSIX_SUCCESS(sysctl_ret, "kern.memorystatus_max_freeze_demotions_daily = UINT32_MAX");
	T_ATEND(reset_max_frozen_demotions_daily);
}

static void
memorystatus_assertion_test_demote_frozen(void)
{
	/*
	 * Test that if we assert a priority on a process, freeze it, and then demote all frozen processes, it does not get demoted below the asserted priority.
	 * Then remove thee assertion, and ensure it gets demoted properly.
	 */
	/* these values will remain fixed during testing */
	int             active_limit_mb = 15;   /* arbitrary */
	int             inactive_limit_mb = 7;  /* arbitrary */
	__block int             demote_value = 1;
	/* Launch the child process, and elevate its priority */
	int requestedpriority;
	dispatch_source_t ds_signal, ds_exit;
	requestedpriority = JETSAM_PRIORITY_FREEZER;
	allow_unlimited_demotions();

	/* Wait for the child process to tell us that it's ready, and then freeze it */
	signal(SIGUSR1, SIG_IGN);
	ds_signal = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, dispatch_get_main_queue());
	T_QUIET; T_ASSERT_NOTNULL(ds_signal, "dispatch_source_create");
	dispatch_source_set_event_handler(ds_signal, ^{
		int sysctl_ret;
		/* Freeze the process, trigger agressive demotion, and check that it hasn't been demoted. */
		freeze_process(child_pid);
		/* Agressive demotion */
		sysctl_ret = sysctlbyname("kern.memorystatus_demote_frozen_processes", NULL, NULL, &demote_value, sizeof(demote_value));
		T_QUIET; T_ASSERT_POSIX_SUCCESS(sysctl_ret, "sysctl kern.memorystatus_demote_frozen_processes succeeded");
		/* Check */
		(void)check_properties(child_pid, requestedpriority, inactive_limit_mb, 0x0, ASSERTION_STATE_IS_SET, "Priority was set");
		T_LOG("Relinquishing our assertion.");
		/* Relinquish our assertion, and check that it gets demoted. */
		relinquish_assertion_priority(child_pid, 0x0);
		(void)check_properties(child_pid, JETSAM_PRIORITY_AGING_BAND2, inactive_limit_mb, 0x0, ASSERTION_STATE_IS_RELINQUISHED, "Assertion was reqlinquished.");
		/* Kill the child */
		T_QUIET; T_ASSERT_POSIX_SUCCESS(kill(child_pid, SIGKILL), "Killed child process");
		T_END;
	});

	/* Launch the child process and set the initial properties on it. */
	child_pid = launch_background_helper("frozen_background", false, true);
	set_memlimits(child_pid, active_limit_mb, inactive_limit_mb, false, false);
	set_assertion_priority(child_pid, requestedpriority, 0x0);
	(void)check_properties(child_pid, requestedpriority, active_limit_mb, 0x0, ASSERTION_STATE_IS_SET, "Priority was set");
	/* Listen for exit. */
	ds_exit = dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC, (uintptr_t)child_pid, DISPATCH_PROC_EXIT, dispatch_get_main_queue());
	dispatch_source_set_event_handler(ds_exit, ^{
		int status = 0, code = 0;
		pid_t rc = waitpid(child_pid, &status, 0);
		T_QUIET; T_ASSERT_EQ(rc, child_pid, "waitpid");
		code = WEXITSTATUS(status);
		T_QUIET; T_ASSERT_EQ(code, 0, "Child exited cleanly");
		T_END;
	});

	dispatch_activate(ds_exit);
	dispatch_activate(ds_signal);
	dispatch_main();
}

T_DECL(assertion_test_demote_frozen, "demoted frozen process goes to asserted priority.",
	/* T_META_ENABLED(HAS_FREEZER), */
	T_META_ASROOT(true),
	T_META_TAG_VM_NOT_PREFERRED,
	T_META_ENABLED(false) /* rdar://133461319 */)
{
	check_for_and_enable_freezer();
	memorystatus_assertion_test_demote_frozen();
}

static unsigned int
get_freeze_daily_pages_max(void)
{
	unsigned int memorystatus_freeze_daily_mb_max;
	size_t length = sizeof(memorystatus_freeze_daily_mb_max);
	int ret = sysctlbyname("kern.memorystatus_freeze_daily_mb_max", &memorystatus_freeze_daily_mb_max, &length, NULL, 0);
	T_ASSERT_POSIX_SUCCESS(ret, "kern.memorystatus_freeze_daily_mb_max");
	return memorystatus_freeze_daily_mb_max * 1024UL * 1024UL / vm_kernel_page_size;
}

static uint64_t
get_budget_multiplier(void)
{
	uint64_t budget_multiplier = 0;
	size_t size = sizeof(budget_multiplier);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(sysctlbyname("kern.memorystatus_freeze_budget_multiplier", &budget_multiplier, &size, NULL, 0),
	    "get kern.memorystatus_freeze_budget_multiplier");
	return budget_multiplier;
}
static void
set_budget_multiplier(uint64_t multiplier)
{
	T_QUIET; T_ASSERT_POSIX_SUCCESS(sysctlbyname("kern.memorystatus_freeze_budget_multiplier", NULL, NULL, &multiplier, sizeof(multiplier)),
	    "set kern.memorystatus_freeze_budget_multiplier");
}

static uint64_t original_budget_multiplier;
static void
reset_budget_multiplier(void)
{
	set_budget_multiplier(original_budget_multiplier);
}

static unsigned int
get_memorystatus_swap_all_apps(void)
{
	unsigned int memorystatus_swap_all_apps;
	size_t length = sizeof(memorystatus_swap_all_apps);
	int ret = sysctlbyname("kern.memorystatus_swap_all_apps", &memorystatus_swap_all_apps, &length, NULL, 0);
	T_ASSERT_POSIX_SUCCESS(ret, "kern.memorystatus_swap_all_apps");
	return memorystatus_swap_all_apps;
}

T_DECL(budget_replenishment, "budget replenishes properly",
	T_META_ENABLED(HAS_FREEZER),
    T_META_REQUIRES_SYSCTL_NE("kern.memorystatus_freeze_daily_mb_max", UINT32_MAX),
	T_META_TAG_VM_NOT_PREFERRED) {
	size_t length;
	int ret;
	static unsigned int kTestIntervalSecs = 60 * 60 * 32; // 32 Hours
	unsigned int memorystatus_freeze_daily_pages_max;
	static unsigned int kFixedPointFactor = 100;
	static unsigned int kNumSecondsInDay = 60 * 60 * 24;
	unsigned int new_budget, expected_new_budget_pages;
	size_t new_budget_ln;
	vm_size_t page_size = vm_kernel_page_size;

	check_for_and_enable_freezer();

	original_budget_multiplier = get_budget_multiplier();
	T_ATEND(reset_budget_multiplier);
	set_budget_multiplier(100);
	/*
	 * Calculate a new budget as if the previous interval expired kTestIntervalSecs
	 * ago and we used up its entire budget.
	 */
	length = sizeof(kTestIntervalSecs);
	new_budget_ln = sizeof(new_budget);
	ret = sysctlbyname("vm.memorystatus_freeze_calculate_new_budget", &new_budget, &new_budget_ln, &kTestIntervalSecs, length);
	T_ASSERT_POSIX_SUCCESS(ret, "vm.memorystatus_freeze_calculate_new_budget");

	memorystatus_freeze_daily_pages_max = get_freeze_daily_pages_max();
	T_LOG("memorystatus_freeze_daily_pages_max %u", memorystatus_freeze_daily_pages_max);
	T_LOG("page_size %lu", page_size);

	/*
	 * We're kTestIntervalSecs past a new interval. Which means we are owed kNumSecondsInDay
	 * seconds of budget.
	 */
	expected_new_budget_pages = memorystatus_freeze_daily_pages_max;
	T_LOG("expected_new_budget_pages before %u", expected_new_budget_pages);
	T_ASSERT_EQ(kTestIntervalSecs, 60 * 60 * 32, "kTestIntervalSecs did not change");
	expected_new_budget_pages += ((kTestIntervalSecs * kFixedPointFactor) / (kNumSecondsInDay)
	    * memorystatus_freeze_daily_pages_max) / kFixedPointFactor;
	if (get_memorystatus_swap_all_apps()) {
		/*
		 * memorystatus_swap_all_apps is enabled; the budget is unlimited
		 */
		expected_new_budget_pages = UINT32_MAX;
	}
	T_LOG("expected_new_budget_pages after %u", expected_new_budget_pages);
	T_LOG("memorystatus_freeze_daily_pages_max after %u", memorystatus_freeze_daily_pages_max);

	T_QUIET; T_ASSERT_EQ(new_budget, expected_new_budget_pages, "Calculate new budget behaves correctly.");
}

static void
get_frozen_list(global_frozen_procs_t *frozen_procs)
{
	int bytes_written;
	bytes_written = memorystatus_control(MEMORYSTATUS_CMD_FREEZER_CONTROL, 0, FREEZER_CONTROL_GET_PROCS, frozen_procs, sizeof(global_frozen_procs_t));
	T_QUIET; T_ASSERT_LE((size_t) bytes_written, sizeof(global_frozen_procs_t), "Didn't overflow buffer");
	T_QUIET; T_ASSERT_GT(bytes_written, 0, "Wrote someting");
}

static bool
is_proc_in_frozen_list(pid_t pid, char* name, size_t name_len)
{
	bool found = false;
	global_frozen_procs_t *frozen_procs = malloc(sizeof(global_frozen_procs_t));
	T_QUIET; T_ASSERT_NOTNULL(frozen_procs, "malloc");

	get_frozen_list(frozen_procs);

	for (size_t i = 0; i < frozen_procs->gfp_num_frozen; i++) {
		if (frozen_procs->gfp_procs[i].fp_pid == pid) {
			found = true;
			strlcpy(name, frozen_procs->gfp_procs[i].fp_name, name_len);
		}
	}
	return found;
}

static void
unset_testing_pid(void)
{
	int ret;
	ret = memorystatus_control(MEMORYSTATUS_CMD_SET_TESTING_PID, 0, MEMORYSTATUS_FLAGS_UNSET_TESTING_PID, NULL, 0);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, 0, "Drop ownership of jetsam snapshot");
}

static void
set_testing_pid(void)
{
	int ret;
	ret = memorystatus_control(MEMORYSTATUS_CMD_SET_TESTING_PID, 0, MEMORYSTATUS_FLAGS_SET_TESTING_PID, NULL, 0);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "Take ownership of jetsam snapshot");
	T_ATEND(unset_testing_pid);
}

/*
 * Retrieve a jetsam snapshot.
 *
 * return:
 *      pointer to snapshot.
 *
 *	Caller is responsible for freeing snapshot.
 */
static
memorystatus_jetsam_snapshot_t *
get_jetsam_snapshot(uint32_t flags, bool empty_allowed)
{
	memorystatus_jetsam_snapshot_t * snapshot = NULL;
	int ret;
	uint32_t size;

	ret = memorystatus_control(MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT, 0, flags, NULL, 0);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, 0, "Get jetsam snapshot size");
	size = (uint32_t) ret;
	if (size == 0 && empty_allowed) {
		return snapshot;
	}

	snapshot = (memorystatus_jetsam_snapshot_t*)malloc(size);
	T_QUIET; T_ASSERT_NOTNULL(snapshot, "Allocate snapshot of size %d", size);

	ret = memorystatus_control(MEMORYSTATUS_CMD_GET_JETSAM_SNAPSHOT, 0, flags, snapshot, size);
	T_QUIET; T_ASSERT_GT(size, 0, "Get jetsam snapshot");

	if (((size - sizeof(memorystatus_jetsam_snapshot_t)) / sizeof(memorystatus_jetsam_snapshot_entry_t)) != snapshot->entry_count) {
		T_FAIL("Malformed snapshot: %d! Expected %ld + %zd x %ld = %ld\n", size,
		    sizeof(memorystatus_jetsam_snapshot_t), snapshot->entry_count, sizeof(memorystatus_jetsam_snapshot_entry_t),
		    sizeof(memorystatus_jetsam_snapshot_t) + (snapshot->entry_count * sizeof(memorystatus_jetsam_snapshot_entry_t)));
		if (snapshot) {
			free(snapshot);
		}
	}

	return snapshot;
}

/*
 * Look for the given pid in the snapshot.
 *
 * return:
 *     pointer to pid's entry or NULL if pid is not found.
 *
 * Caller has ownership of snapshot before and after call.
 */
static
memorystatus_jetsam_snapshot_entry_t *
get_jetsam_snapshot_entry(memorystatus_jetsam_snapshot_t *snapshot, pid_t pid)
{
	T_QUIET; T_ASSERT_NOTNULL(snapshot, "Got snapshot");
	for (size_t i = 0; i < snapshot->entry_count; i++) {
		memorystatus_jetsam_snapshot_entry_t *curr = &(snapshot->entries[i]);
		if (curr->pid == pid) {
			return curr;
		}
	}

	return NULL;
}

static void
resume_and_kill_proc(pid_t pid)
{
	int ret = pid_resume(pid);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "proc resumed after freeze");
	T_QUIET; T_ASSERT_POSIX_SUCCESS(kill(pid, SIGKILL), "Killed process");
}

static void
resume_and_kill_child(void)
{
	/* Used for test cleanup. proc might not be suspended so pid_resume might fail. */
	pid_resume(child_pid);
	kill(child_pid, SIGKILL);
}

static dispatch_source_t
run_block_after_signal(int sig, dispatch_block_t block)
{
	dispatch_source_t ds_signal;
	signal(sig, SIG_IGN);
	ds_signal = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, (uintptr_t) sig, 0, dispatch_get_main_queue());
	T_QUIET; T_ASSERT_NOTNULL(ds_signal, "dispatch_source_create");
	dispatch_source_set_event_handler(ds_signal, block);
	return ds_signal;
}

/*
 * Launches the child & runs the given block after the child signals.
 * If exit_with_child is true, the test will exit when the child exits.
 */
static void
test_after_background_helper_launches(bool exit_with_child, const char* variant, dispatch_block_t test_block)
{
	dispatch_source_t ds_signal, ds_exit;

	ds_signal = run_block_after_signal(SIGUSR1, test_block);
	/* Launch the child process. */
	child_pid = launch_background_helper(variant, false, true);
	T_ATEND(resume_and_kill_child);
	/* Listen for exit. */
	if (exit_with_child) {
		ds_exit = dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC, (uintptr_t)child_pid, DISPATCH_PROC_EXIT, dispatch_get_main_queue());
		dispatch_source_set_event_handler(ds_exit, ^{
			int status = 0, code = 0;
			pid_t rc = waitpid(child_pid, &status, 0);
			T_QUIET; T_ASSERT_EQ(rc, child_pid, "waitpid");
			code = WEXITSTATUS(status);
			if (code != 0) {
			        T_LOG("Child exited with error: %s", exit_codes_str[code]);
			}
			T_QUIET; T_ASSERT_EQ(code, 0, "Child exited cleanly");
			T_END;
		});

		dispatch_activate(ds_exit);
	}
	dispatch_activate(ds_signal);
}

T_DECL(get_frozen_procs, "List processes in the freezer",
	T_META_ENABLED(HAS_FREEZER),
	T_META_TAG_VM_NOT_PREFERRED) {

	check_for_and_enable_freezer();
	test_after_background_helper_launches(true, "frozen_background", ^{
		proc_name_t name;
		/* Place the child in the idle band so that it gets elevated like a typical app. */
		move_to_idle_band(child_pid);
		/* Freeze the process, and check that it's in the list of frozen processes. */
		freeze_process(child_pid);
		/* Check */
		T_QUIET; T_ASSERT_TRUE(is_proc_in_frozen_list(child_pid, name, sizeof(name)), "Found proc in frozen list");
		T_QUIET; T_EXPECT_EQ_STR(name, "memorystatus_freeze_test", "Proc has correct name");
		/* Kill the child */
		T_QUIET; T_ASSERT_POSIX_SUCCESS(kill(child_pid, SIGKILL), "Killed child process");
		T_END;
	});
	dispatch_main();
}

T_DECL(frozen_to_swap_accounting, "jetsam snapshot has frozen_to_swap accounting",
	T_META_ENABLED(HAS_FREEZER),
	T_META_TAG_VM_NOT_PREFERRED) {
	static const size_t kSnapshotSleepDelay = 5;
	static const size_t kFreezeToDiskMaxDelay = 60;


	check_for_and_enable_freezer();
	test_after_background_helper_launches(true, "frozen_background", ^{
		memorystatus_jetsam_snapshot_t *snapshot = NULL;
		memorystatus_jetsam_snapshot_entry_t *child_entry = NULL;
		/* Place the child in the idle band so that it gets elevated like a typical app. */
		move_to_idle_band(child_pid);
		freeze_process(child_pid);
		/*
		 * Wait until the child's pages get paged out to disk.
		 * If we don't see any pages get sent to disk before kFreezeToDiskMaxDelay seconds,
		 * something is either wrong with the compactor or the accounting.
		 */
		for (size_t i = 0; i < kFreezeToDiskMaxDelay / kSnapshotSleepDelay; i++) {
		        snapshot = get_jetsam_snapshot(MEMORYSTATUS_FLAGS_SNAPSHOT_ON_DEMAND, false);
		        child_entry = get_jetsam_snapshot_entry(snapshot, child_pid);
		        T_QUIET; T_ASSERT_NOTNULL(child_entry, "Found child in snapshot");
		        if (child_entry->jse_frozen_to_swap_pages > 0) {
		                break;
			}
		        free(snapshot);
		        sleep(kSnapshotSleepDelay);
		}
		T_QUIET; T_ASSERT_GT(child_entry->jse_frozen_to_swap_pages, 0ULL, "child has some pages in swap");
		free(snapshot);
		/* Kill the child */
		T_QUIET; T_ASSERT_POSIX_SUCCESS(kill(child_pid, SIGKILL), "Killed child process");
		T_END;
	});
	dispatch_main();
}

T_DECL(freezer_snapshot, "App kills are recorded in the freezer snapshot",
	T_META_ENABLED(HAS_FREEZER),
	T_META_TAG_VM_NOT_PREFERRED) {
	check_for_and_enable_freezer();

	/* Take ownership of the snapshot to ensure we don't race with another process trying to consume them. */
	set_testing_pid();

	test_after_background_helper_launches(false, "frozen_background", ^{
		int ret;
		memorystatus_jetsam_snapshot_t *snapshot = NULL;
		memorystatus_jetsam_snapshot_entry_t *child_entry = NULL;

		ret = memorystatus_control(MEMORYSTATUS_CMD_TEST_JETSAM, child_pid, 0, 0, 0);
		T_ASSERT_POSIX_SUCCESS(ret, "jetsam'd the child");

		snapshot = get_jetsam_snapshot(MEMORYSTATUS_FLAGS_SNAPSHOT_FREEZER, false);
		T_ASSERT_NOTNULL(snapshot, "Got freezer snapshot");
		child_entry = get_jetsam_snapshot_entry(snapshot, child_pid);
		T_QUIET; T_ASSERT_NOTNULL(child_entry, "Child is in freezer snapshot");
		T_QUIET; T_ASSERT_EQ(child_entry->killed, (unsigned long long) JETSAM_REASON_GENERIC, "Child entry was killed");

		free(snapshot);
		T_END;
	});
	dispatch_main();
}

T_DECL(freezer_snapshot_consume, "Freezer snapshot is consumed on read",
	T_META_ENABLED(HAS_FREEZER),
	T_META_TAG_VM_NOT_PREFERRED) {
	check_for_and_enable_freezer();

	/* Take ownership of the snapshot to ensure we don't race with another process trying to consume them. */
	set_testing_pid();

	test_after_background_helper_launches(false, "frozen_background", ^{
		int ret;
		memorystatus_jetsam_snapshot_t *snapshot = NULL;
		memorystatus_jetsam_snapshot_entry_t *child_entry = NULL;

		ret = memorystatus_control(MEMORYSTATUS_CMD_TEST_JETSAM, child_pid, 0, 0, 0);
		T_ASSERT_POSIX_SUCCESS(ret, "jetsam'd the child");

		snapshot = get_jetsam_snapshot(MEMORYSTATUS_FLAGS_SNAPSHOT_FREEZER, false);
		T_ASSERT_NOTNULL(snapshot, "Got first freezer snapshot");
		child_entry = get_jetsam_snapshot_entry(snapshot, child_pid);
		T_QUIET; T_ASSERT_NOTNULL(child_entry, "Child is in first freezer snapshot");

		snapshot = get_jetsam_snapshot(MEMORYSTATUS_FLAGS_SNAPSHOT_FREEZER, true);
		if (snapshot != NULL) {
		        child_entry = get_jetsam_snapshot_entry(snapshot, child_pid);
		        T_QUIET; T_ASSERT_NULL(child_entry, "Child is not in second freezer snapshot");
		}

		free(snapshot);
		T_END;
	});
	dispatch_main();
}

T_DECL(freezer_snapshot_frozen_state, "Frozen state is recorded in freezer snapshot",
	T_META_ENABLED(HAS_FREEZER),
	T_META_TAG_VM_NOT_PREFERRED) {
	check_for_and_enable_freezer();

	/* Take ownership of the snapshot to ensure we don't race with another process trying to consume them. */
	set_testing_pid();

	test_after_background_helper_launches(false, "frozen_background", ^{
		int ret;
		memorystatus_jetsam_snapshot_t *snapshot = NULL;
		memorystatus_jetsam_snapshot_entry_t *child_entry = NULL;

		move_to_idle_band(child_pid);
		freeze_process(child_pid);

		ret = memorystatus_control(MEMORYSTATUS_CMD_TEST_JETSAM, child_pid, 0, 0, 0);
		T_ASSERT_POSIX_SUCCESS(ret, "jetsam'd the child");

		snapshot = get_jetsam_snapshot(MEMORYSTATUS_FLAGS_SNAPSHOT_FREEZER, false);
		T_ASSERT_NOTNULL(snapshot, "Got freezer snapshot");
		child_entry = get_jetsam_snapshot_entry(snapshot, child_pid);
		T_QUIET; T_ASSERT_NOTNULL(child_entry, "Child is in freezer snapshot");
		T_QUIET; T_ASSERT_TRUE(child_entry->state & kMemorystatusFrozen, "Child entry's frozen bit is set");

		free(snapshot);
		T_END;
	});
	dispatch_main();
}

T_DECL(freezer_snapshot_thaw_state, "Thaw count is recorded in freezer snapshot",
	T_META_ENABLED(HAS_FREEZER),
	T_META_TAG_VM_NOT_PREFERRED) {
	check_for_and_enable_freezer();

	/* Take ownership of the snapshot to ensure we don't race with another process trying to consume them. */
	set_testing_pid();

	test_after_background_helper_launches(false, "frozen_background", ^{
		int ret;
		memorystatus_jetsam_snapshot_t *snapshot = NULL;
		memorystatus_jetsam_snapshot_entry_t *child_entry = NULL;

		move_to_idle_band(child_pid);
		ret = pid_suspend(child_pid);
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "child suspended");
		freeze_process(child_pid);
		ret = pid_resume(child_pid);
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "child resumed after freeze");

		ret = memorystatus_control(MEMORYSTATUS_CMD_TEST_JETSAM, child_pid, 0, 0, 0);
		T_ASSERT_POSIX_SUCCESS(ret, "jetsam'd the child");

		snapshot = get_jetsam_snapshot(MEMORYSTATUS_FLAGS_SNAPSHOT_FREEZER, false);
		T_ASSERT_NOTNULL(snapshot, "Got freezer snapshot");
		child_entry = get_jetsam_snapshot_entry(snapshot, child_pid);
		T_QUIET; T_ASSERT_NOTNULL(child_entry, "Child is in freezer snapshot");
		T_QUIET; T_ASSERT_TRUE(child_entry->state & kMemorystatusFrozen, "Child entry's frozen bit is still set after thaw");
		T_QUIET; T_ASSERT_TRUE(child_entry->state & kMemorystatusWasThawed, "Child entry was thawed");
		T_QUIET; T_ASSERT_EQ(child_entry->jse_thaw_count, 1ULL, "Child entry's thaw count was incremented");

		free(snapshot);
		T_END;
	});
	dispatch_main();
}

T_HELPER_DECL(check_frozen, "Check frozen state", T_META_ASROOT(true)) {
	int kern_ret;
	dispatch_source_t ds_signal;
	__block int is_frozen;
	/* Set the process to freezable */
	kern_ret = memorystatus_control(MEMORYSTATUS_CMD_SET_PROCESS_IS_FREEZABLE, getpid(), 1, NULL, 0);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(kern_ret, "set process is freezable");

	/* We should not be frozen yet. */
	is_frozen = memorystatus_control(MEMORYSTATUS_CMD_GET_PROCESS_IS_FROZEN, getpid(), 0, NULL, 0);
	if (is_frozen == -1) {
		T_LOG("memorystatus_control error: %s", strerror(errno));
		exit(MEMORYSTATUS_CONTROL_ERROR);
	}
	if (is_frozen) {
		exit(FROZEN_BIT_SET);
	}

	ds_signal = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, dispatch_get_main_queue());
	if (ds_signal == NULL) {
		exit(DISPATCH_SOURCE_CREATE_FAILED);
	}

	dispatch_source_set_event_handler(ds_signal, ^{
		/* We should now be frozen. */
		is_frozen = memorystatus_control(MEMORYSTATUS_CMD_GET_PROCESS_IS_FROZEN, getpid(), 0, NULL, 0);
		if (is_frozen == -1) {
		        T_LOG("memorystatus_control error: %s", strerror(errno));
		        exit(MEMORYSTATUS_CONTROL_ERROR);
		}
		if (!is_frozen) {
		        exit(FROZEN_BIT_NOT_SET);
		}
		exit(SUCCESS);
	});
	dispatch_activate(ds_signal);

	sig_t sig_ret = signal(SIGUSR1, SIG_IGN);
	T_QUIET; T_WITH_ERRNO; T_ASSERT_NE(sig_ret, SIG_ERR, "signal(SIGUSR1, SIG_IGN)");

	/* Signal to our parent that we can be frozen */
	if (kill(getppid(), SIGUSR1) != 0) {
		T_LOG("Unable to signal to parent process!");
		exit(SIGNAL_TO_PARENT_FAILED);
	}

	dispatch_main();
}

T_DECL(memorystatus_get_process_is_frozen, "MEMORYSTATUS_CMD_GET_PROCESS_IS_FROZEN returns correct state",
	T_META_ENABLED(HAS_FREEZER),
	T_META_TAG_VM_NOT_PREFERRED) {

	check_for_and_enable_freezer();
	test_after_background_helper_launches(true, "check_frozen", ^{
		int ret;
		/* Freeze the child, resume it, and signal it to check its state */
		move_to_idle_band(child_pid);
		ret = pid_suspend(child_pid);
		T_ASSERT_POSIX_SUCCESS(ret, "child suspended");
		freeze_process(child_pid);
		ret = pid_resume(child_pid);
		T_ASSERT_POSIX_SUCCESS(ret, "child resumed after freeze");

		kill(child_pid, SIGUSR1);
		/* The child will checks its own frozen state & exit. */
	});
	dispatch_main();
}

static unsigned int freeze_pages_min_old;
static int throttle_enabled_old;
static void
cleanup_memorystatus_freeze_top_process(void)
{
	sysctlbyname("kern.memorystatus_freeze_pages_min", NULL, NULL, &freeze_pages_min_old, sizeof(freeze_pages_min_old));
	sysctlbyname("kern.memorystatus_freeze_throttle_enabled", NULL, NULL, &throttle_enabled_old, sizeof(throttle_enabled_old));
}

/*
 * Disables heuristics that could prevent us from freezing the child via memorystatus_freeze_top_process.
 */
static void
memorystatus_freeze_top_process_setup(void)
{
	size_t freeze_pages_min_size = sizeof(freeze_pages_min_old);
	unsigned int freeze_pages_min_new = 0;
	size_t throttle_enabled_old_size = sizeof(throttle_enabled_old);
	int throttle_enabled_new = 1, ret;

	ret = sysctlbyname("kern.memorystatus_freeze_pages_min", &freeze_pages_min_old, &freeze_pages_min_size, &freeze_pages_min_new, sizeof(freeze_pages_min_new));
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "set kern.memorystatus_freeze_pages_min");
	ret = sysctlbyname("kern.memorystatus_freeze_throttle_enabled", &throttle_enabled_old, &throttle_enabled_old_size, &throttle_enabled_new, sizeof(throttle_enabled_new));
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "set kern.memorystatus_freeze_throttle_enabled");
	T_ATEND(cleanup_memorystatus_freeze_top_process);
	/* Take ownership of the freezer probabilities for the duration of the test so that we don't race with dasd. */
	set_testing_pid();
}

/*
 * Moves the proc to the idle band and suspends it.
 */
static void
prepare_proc_for_freezing(pid_t pid)
{
	move_to_idle_band(pid);
	int ret = pid_suspend(pid);
	T_ASSERT_POSIX_SUCCESS(ret, "proc suspended");
}

#define P_MEMSTAT_FROZEN 0x00000002
static void
verify_proc_frozen_state(pid_t pid, bool expected)
{
	memorystatus_jetsam_snapshot_t *snapshot = get_jetsam_snapshot(MEMORYSTATUS_FLAGS_SNAPSHOT_ON_DEMAND, false);
	memorystatus_jetsam_snapshot_entry_t *entry = get_jetsam_snapshot_entry(snapshot, pid);
	T_ASSERT_NOTNULL(entry, "%d is in snapshot", pid);
	bool is_frozen = (entry->state & P_MEMSTAT_FROZEN) != 0;
	if (is_frozen != expected) {
		T_LOG("%s frozen state is wrong. Expected %d, got %d. Skip reason: %d. Jetsam band: %d", entry->name, expected, is_frozen, entry->jse_freeze_skip_reason, entry->priority);
	}
	T_ASSERT_EQ(is_frozen, expected, "%s frozen state", entry->name);
	free(snapshot);
}

static void
verify_proc_is_frozen(pid_t pid)
{
	verify_proc_frozen_state(pid, true);
}

static void
verify_proc_not_frozen(pid_t pid)
{
	verify_proc_frozen_state(pid, false);
}

T_DECL(memorystatus_freeze_top_process, "memorystatus_freeze_top_process chooses the correct process",
	T_META_ENABLED(HAS_FREEZER),
    T_META_ASROOT(true),
    T_META_REQUIRES_SYSCTL_EQ("kern.development", 1),
	T_META_TAG_VM_NOT_PREFERRED) {
	T_SKIP("Skipping flaky test"); // rdar://76986376
	int32_t memorystatus_freeze_band = 0;
	size_t memorystatus_freeze_band_size = sizeof(memorystatus_freeze_band);
	__block errno_t ret;
	__block int maxproc;
	size_t maxproc_size = sizeof(maxproc);

	check_for_and_enable_freezer();
	ret = sysctlbyname("kern.maxproc", &maxproc, &maxproc_size, NULL, 0);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "kern.maxproc");
	ret = sysctlbyname("kern.memorystatus_freeze_jetsam_band", &memorystatus_freeze_band, &memorystatus_freeze_band_size, NULL, 0);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "kern.memorystatus_freeze_jetsam_band");

	memorystatus_freeze_top_process_setup();
	test_after_background_helper_launches(true, "frozen_background", ^{
		int32_t child_band = JETSAM_PRIORITY_DEFAULT;
		prepare_proc_for_freezing(child_pid);

		size_t buffer_len = sizeof(memorystatus_properties_entry_v1_t) * (size_t) maxproc;
		memorystatus_properties_entry_v1_t *properties_list = malloc(buffer_len);
		T_QUIET; T_ASSERT_NOTNULL(properties_list, "malloc properties array");
		size_t properties_list_len = 0;
		/* The child needs to age down into the idle band before it's eligible to be frozen. */
		T_LOG("Waiting for child to age into the idle band.");
		while (child_band != JETSAM_PRIORITY_IDLE) {
		        memset(properties_list, 0, buffer_len);
		        properties_list_len = 0;
		        memorystatus_jetsam_snapshot_t *snapshot = get_jetsam_snapshot(MEMORYSTATUS_FLAGS_SNAPSHOT_ON_DEMAND, false);

		        bool found = false;
		        for (size_t i = 0; i < snapshot->entry_count; i++) {
		                memorystatus_jetsam_snapshot_entry_t *snapshot_entry = &snapshot->entries[i];
		                if (snapshot_entry->priority <= memorystatus_freeze_band && !snapshot_entry->killed) {
		                        pid_t pid = snapshot_entry->pid;
		                        memorystatus_properties_entry_v1_t *property_entry = &properties_list[properties_list_len++];
		                        property_entry->version = 1;
		                        property_entry->pid = pid;
		                        if (pid == child_pid) {
		                                found = true;
		                                property_entry->use_probability = 1;
		                                child_band = snapshot_entry->priority;
					} else {
		                                property_entry->use_probability = 0;
					}
		                        strncpy(property_entry->proc_name, snapshot_entry->name, MAXCOMLEN);
		                        property_entry->proc_name[MAXCOMLEN] = '\0';
				}
			}
		        T_QUIET; T_ASSERT_TRUE(found, "Child is in on demand snapshot");
		        free(snapshot);
		}
		ret = memorystatus_control(MEMORYSTATUS_CMD_GRP_SET_PROPERTIES, 0, MEMORYSTATUS_FLAGS_GRP_SET_PROBABILITY, properties_list, sizeof(memorystatus_properties_entry_v1_t) * properties_list_len);
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "MEMORYSTATUS_FLAGS_GRP_SET_PROBABILITY");
		free(properties_list);
		int val = 1;
		ret = sysctlbyname("vm.memorystatus_freeze_top_process", NULL, NULL, &val, sizeof(val));
		T_ASSERT_POSIX_SUCCESS(ret, "freeze_top_process");

		verify_proc_is_frozen(child_pid);
		resume_and_kill_proc(child_pid);
		T_END;
	});
	dispatch_main();
}
static unsigned int use_ordered_list_original;
static unsigned int use_demotion_list_original;
static void
reset_ordered_freeze_mode(void)
{
	sysctlbyname("kern.memorystatus_freezer_use_ordered_list", NULL, NULL, &use_ordered_list_original, sizeof(use_ordered_list_original));
}

static void
reset_ordered_demote_mode(void)
{
	sysctlbyname("kern.memorystatus_freezer_use_demotion_list", NULL, NULL, &use_demotion_list_original, sizeof(use_demotion_list_original));
}

static void
enable_ordered_freeze_mode(void)
{
	int ret;
	int val = 1;
	size_t size = sizeof(use_ordered_list_original);
	ret = sysctlbyname("kern.memorystatus_freezer_use_ordered_list", &use_ordered_list_original, &size, &val, sizeof(val));
	T_ASSERT_POSIX_SUCCESS(ret, "kern.memorystatus_freezer_use_ordered_list");
	T_ATEND(reset_ordered_freeze_mode);
}

static void
enable_ordered_demote_mode(void)
{
	int ret;
	int val = 1;
	size_t size = sizeof(use_demotion_list_original);
	ret = sysctlbyname("kern.memorystatus_freezer_use_demotion_list", &use_demotion_list_original, &size, &val, sizeof(val));
	T_ASSERT_POSIX_SUCCESS(ret, "kern.memorystatus_freezer_use_demotion_list");
	T_ATEND(reset_ordered_demote_mode);
}

static void
construct_child_freeze_entry(memorystatus_properties_freeze_entry_v1 *entry)
{
	memset(entry, 0, sizeof(memorystatus_properties_freeze_entry_v1));
	entry->version = 1;
	entry->pid = child_pid;
	entry->priority = 1;

	/* Get the child's name. */
	memorystatus_jetsam_snapshot_t *snapshot = get_jetsam_snapshot(MEMORYSTATUS_FLAGS_SNAPSHOT_ON_DEMAND, false);
	memorystatus_jetsam_snapshot_entry_t *snapshot_entry = get_jetsam_snapshot_entry(snapshot, child_pid);
	strncpy(entry->proc_name, snapshot_entry->name, sizeof(entry->proc_name));
	free(snapshot);
}

T_DECL(memorystatus_freeze_top_process_ordered, "memorystatus_freeze_top_process chooses the correct process when using an ordered list",
	T_META_ENABLED(HAS_FREEZER),
    T_META_ASROOT(true),
    T_META_REQUIRES_SYSCTL_EQ("kern.development", 1),
	T_META_TAG_VM_NOT_PREFERRED) {
	check_for_and_enable_freezer();
	memorystatus_freeze_top_process_setup();
	enable_ordered_freeze_mode();
	test_after_background_helper_launches(true, "frozen_background", ^{
		int ret, val = 1;
		memorystatus_properties_freeze_entry_v1 entries[1];

		construct_child_freeze_entry(&entries[0]);
		prepare_proc_for_freezing(child_pid);

		T_LOG("Telling kernel to freeze %s", entries[0].proc_name);
		ret = memorystatus_control(MEMORYSTATUS_CMD_GRP_SET_PROPERTIES, 0, MEMORYSTATUS_FLAGS_GRP_SET_FREEZE_PRIORITY, entries, sizeof(entries));
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "MEMORYSTATUS_FLAGS_GRP_SET_FREEZE_PRIORITY");

		ret = sysctlbyname("vm.memorystatus_freeze_top_process", NULL, NULL, &val, sizeof(val));
		T_ASSERT_POSIX_SUCCESS(ret, "freeze_top_process");

		verify_proc_is_frozen(child_pid);
		resume_and_kill_proc(child_pid);

		T_END;
	});
	dispatch_main();
}

static void
memorystatus_freeze_top_process_ordered_wrong_pid(pid_t (^pid_for_entry)(pid_t))
{
	memorystatus_freeze_top_process_setup();
	enable_ordered_freeze_mode();
	test_after_background_helper_launches(true, "frozen_background", ^{
		int ret, val = 1;
		memorystatus_properties_freeze_entry_v1 entries[1];

		construct_child_freeze_entry(&entries[0]);
		entries[0].pid = pid_for_entry(child_pid);
		prepare_proc_for_freezing(child_pid);

		T_LOG("Telling kernel to freeze %s", entries[0].proc_name);
		ret = memorystatus_control(MEMORYSTATUS_CMD_GRP_SET_PROPERTIES, 0, MEMORYSTATUS_FLAGS_GRP_SET_FREEZE_PRIORITY, entries, sizeof(entries));
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "MEMORYSTATUS_FLAGS_GRP_SET_FREEZE_PRIORITY");

		ret = sysctlbyname("vm.memorystatus_freeze_top_process", NULL, NULL, &val, sizeof(val));
		T_ASSERT_POSIX_SUCCESS(ret, "freeze_top_process");

		verify_proc_is_frozen(child_pid);
		resume_and_kill_proc(child_pid);

		T_END;
	});
	dispatch_main();
}

/*
 * Try both with a pid that's used by another process
 * and a pid that is likely unused.
 * In both cases the child should still get frozen.
 */
T_DECL(memorystatus_freeze_top_process_ordered_reused_pid, "memorystatus_freeze_top_process is resilient to pid changes",
	T_META_ENABLED(HAS_FREEZER),
	T_META_REQUIRES_SYSCTL_EQ("kern.development", 1),
    T_META_ASROOT(true),
	T_META_TAG_VM_NOT_PREFERRED) {
	check_for_and_enable_freezer();
	memorystatus_freeze_top_process_ordered_wrong_pid(^(__unused pid_t child) {
		return 1;
	});
}

T_DECL(memorystatus_freeze_top_process_ordered_wrong_pid, "memorystatus_freeze_top_process is resilient to pid changes",
	T_META_ENABLED(HAS_FREEZER),
    T_META_ASROOT(true),
    T_META_REQUIRES_SYSCTL_EQ("kern.development", 1),
	T_META_TAG_VM_NOT_PREFERRED) {
	check_for_and_enable_freezer();
	memorystatus_freeze_top_process_ordered_wrong_pid(^(__unused pid_t child) {
		return child + 1000;
	});
}

T_DECL(memorystatus_freeze_demote_ordered, "memorystatus_demote_frozen_processes_using_demote_list chooses the correct process",
	T_META_ENABLED(HAS_FREEZER),
    T_META_ASROOT(true),
    T_META_REQUIRES_SYSCTL_EQ("kern.development", 1),
	T_META_TAG_VM_NOT_PREFERRED) {
	check_for_and_enable_freezer();
	memorystatus_freeze_top_process_setup();
	enable_ordered_freeze_mode();
	enable_ordered_demote_mode();
	test_after_background_helper_launches(true, "frozen_background", ^{
		int ret, val = 1;
		int32_t memorystatus_freeze_band = 0;
		size_t memorystatus_freeze_band_size = sizeof(memorystatus_freeze_band);
		memorystatus_jetsam_snapshot_t *snapshot = NULL;
		memorystatus_jetsam_snapshot_entry_t *child_entry = NULL;
		memorystatus_properties_freeze_entry_v1 entries[1];

		ret = sysctlbyname("kern.memorystatus_freeze_jetsam_band", &memorystatus_freeze_band, &memorystatus_freeze_band_size, NULL, 0);
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "kern.memorystatus_freeze_jetsam_band");

		construct_child_freeze_entry(&entries[0]);
		prepare_proc_for_freezing(child_pid);

		T_LOG("Telling kernel to freeze %s", entries[0].proc_name);
		ret = memorystatus_control(MEMORYSTATUS_CMD_GRP_SET_PROPERTIES, 0, MEMORYSTATUS_FLAGS_GRP_SET_FREEZE_PRIORITY, entries, sizeof(entries));
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "MEMORYSTATUS_FLAGS_GRP_SET_FREEZE_PRIORITY");

		ret = sysctlbyname("vm.memorystatus_freeze_top_process", NULL, NULL, &val, sizeof(val));
		T_ASSERT_POSIX_SUCCESS(ret, "freeze_top_process");

		verify_proc_is_frozen(child_pid);

		/*
		 * Place the child at the head of the demotion list.
		 */
		T_LOG("Telling kernel to demote %s", entries[0].proc_name);
		ret = memorystatus_control(MEMORYSTATUS_CMD_GRP_SET_PROPERTIES, 0, MEMORYSTATUS_FLAGS_GRP_SET_DEMOTE_PRIORITY, entries, sizeof(entries));
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "MEMORYSTATUS_FLAGS_GRP_SET_DEMOTE_PRIORITY");

		/* Resume the child */
		ret = pid_resume(child_pid);
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "child resumed after freeze");

		/* Trigger a demotion check */
		val = 1;
		ret = sysctlbyname("kern.memorystatus_demote_frozen_processes", NULL, NULL, &val, sizeof(val));
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "sysctl kern.memorystatus_demote_frozen_processes succeeded");

		/* Verify that the child was demoted */
		snapshot = get_jetsam_snapshot(MEMORYSTATUS_FLAGS_SNAPSHOT_ON_DEMAND, false);
		child_entry = get_jetsam_snapshot_entry(snapshot, child_pid);
		T_QUIET; T_ASSERT_NOTNULL(child_entry, "Found child in snapshot");
		T_QUIET; T_ASSERT_LT(child_entry->priority, memorystatus_freeze_band, "child was demoted");
		free(snapshot);

		T_QUIET; T_ASSERT_POSIX_SUCCESS(kill(child_pid, SIGKILL), "Killed process");

		T_END;
	});
	dispatch_main();
}

static int
memorystatus_freezer_thaw_percentage(void)
{
	int val;
	size_t size = sizeof(val);
	int ret = sysctlbyname("kern.memorystatus_freezer_thaw_percentage", &val, &size, NULL, 0);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "failed to query kern.memorystatus_freezer_thaw_percentage");
	return val;
}

static void
reset_interval(void)
{
	uint32_t freeze_daily_budget_mb = 0;
	size_t size = sizeof(freeze_daily_budget_mb);
	int ret;
	uint64_t new_budget;
	ret = sysctlbyname("kern.memorystatus_freeze_daily_mb_max", &freeze_daily_budget_mb, &size, NULL, 0);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "failed to query kern.memorystatus_freeze_daily_mb_max");
	new_budget = (freeze_daily_budget_mb * (1UL << 20) / vm_page_size);
	ret = sysctlbyname("kern.memorystatus_freeze_budget_pages_remaining", NULL, NULL, &new_budget, sizeof(new_budget));
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "failed to set kern.memorystatus_freeze_budget_pages_remaining");
}

static pid_t second_child;
static void
cleanup_memorystatus_freezer_thaw_percentage(void)
{
	kill(second_child, SIGKILL);
}

T_DECL(memorystatus_freezer_thaw_percentage, "memorystatus_freezer_thaw_percentage updates correctly",
	T_META_ENABLED(HAS_FREEZER),
    T_META_ASROOT(true),
    T_META_REQUIRES_SYSCTL_EQ("kern.development", 1),
	T_META_TAG_VM_NOT_PREFERRED) {
	__block dispatch_source_t first_signal_block;
	check_for_and_enable_freezer();
	/* Take ownership of the freezer probabilities for the duration of the test so that nothing new gets frozen by dasd. */
	set_testing_pid();
	reset_interval();

	/* Spawn one child that will remain frozen throughout the whole test & another that will be thawed. */
	first_signal_block = run_block_after_signal(SIGUSR1, ^{
		move_to_idle_band(second_child);
		__block int ret = pid_suspend(second_child);
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "child suspended");
		freeze_process(second_child);
		T_QUIET; T_ASSERT_EQ(memorystatus_freezer_thaw_percentage(), 0, "thaw percentage is still 0 after freeze");
		dispatch_source_cancel(first_signal_block);
		test_after_background_helper_launches(true, "frozen_background", ^{
			reset_interval();
			T_QUIET; T_ASSERT_EQ(memorystatus_freezer_thaw_percentage(), 0, "new interval starts with a thaw percentage of 0");
			move_to_idle_band(child_pid);
			ret = pid_suspend(child_pid);
			T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "child suspended");
			freeze_process(child_pid);
			ret = pid_resume(child_pid);
			T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "child resumed after freeze");
			int percentage_after_thaw = memorystatus_freezer_thaw_percentage();
			T_QUIET; T_ASSERT_GT(percentage_after_thaw, 0, "thaw percentage is higher after thaw");

			ret = pid_suspend(child_pid);
			T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "child suspended");
			freeze_process(child_pid);
			ret = pid_resume(child_pid);
			T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "child resumed after freeze");
			T_QUIET; T_ASSERT_EQ(memorystatus_freezer_thaw_percentage(), percentage_after_thaw, "thaw percentage is unchanged after second thaw");

			ret = pid_suspend(child_pid);
			T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "child suspended");
			freeze_process(child_pid);
			reset_interval();
			T_QUIET; T_ASSERT_EQ(memorystatus_freezer_thaw_percentage(), 0, "new interval starts with a 0 thaw percentage");
			ret = pid_resume(child_pid);
			T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "child resumed after freeze");
			T_QUIET; T_ASSERT_GT(memorystatus_freezer_thaw_percentage(), 0, "thaw percentage goes back up in new interval");

			T_QUIET; T_ASSERT_POSIX_SUCCESS(kill(child_pid, SIGKILL), "failed to kill child");
			T_END;
		});
	});

	second_child = launch_background_helper("frozen_background", false, true);
	T_ATEND(cleanup_memorystatus_freezer_thaw_percentage);
	dispatch_activate(first_signal_block);
	dispatch_main();
}

static uint64_t
get_budget_pages_remaining(void)
{
	uint64_t pages_remaining = 0;
	size_t size = sizeof(pages_remaining);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(sysctlbyname("kern.memorystatus_freeze_budget_pages_remaining", &pages_remaining, &size, NULL, 0),
	    "get kern.memorystatus_freeze_budget_pages_remaining");
	return pages_remaining;
}

static void
set_budget_pages_remaining(uint64_t pages_remaining)
{
	T_QUIET; T_ASSERT_POSIX_SUCCESS(sysctlbyname("kern.memorystatus_freeze_budget_pages_remaining", NULL, NULL, &pages_remaining, sizeof(pages_remaining)),
	    "get kern.memorystatus_freeze_budget_pages_remaining");
}

static void
set_freeze_enabled(int freeze_enabled)
{
	size_t length = sizeof(freeze_enabled);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(sysctlbyname("vm.freeze_enabled", NULL, NULL, &freeze_enabled, length),
	    "enable vm.freeze_enabled");
}

static void
enable_freeze(void)
{
	set_freeze_enabled(1);
}

T_DECL(memorystatus_freeze_budget_multiplier, "memorystatus_budget_multiplier multiplies budget",
    T_META_ASROOT(true),
    T_META_REQUIRES_SYSCTL_NE("kern.memorystatus_freeze_daily_mb_max", UINT32_MAX),
    T_META_REQUIRES_SYSCTL_EQ("kern.development", 1),
	T_META_ENABLED(HAS_FREEZER),
    T_META_ENABLED(false && HAS_FREEZER) /* rdar://87165483 */,
	T_META_TAG_VM_NOT_PREFERRED) {
	/* Disable freezer so that the budget doesn't change out from underneath us. */
	int freeze_enabled = 0;
	size_t length = sizeof(freeze_enabled);
	uint64_t freeze_daily_pages_max;
	check_for_and_enable_freezer();
	T_ATEND(enable_freeze);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(sysctlbyname("vm.freeze_enabled", NULL, NULL, &freeze_enabled, length),
	    "disable vm.freeze_enabled");
	freeze_daily_pages_max = get_freeze_daily_pages_max();
	original_budget_multiplier = get_budget_multiplier();
	T_ATEND(reset_budget_multiplier);
	set_budget_multiplier(100);
	T_QUIET; T_ASSERT_EQ(get_budget_pages_remaining(), freeze_daily_pages_max, "multiplier=100%%");
	set_budget_multiplier(50);
	T_QUIET; T_ASSERT_EQ(get_budget_pages_remaining(), freeze_daily_pages_max / 2, "multiplier=50%%");
	set_budget_multiplier(200);
	T_QUIET; T_ASSERT_EQ(get_budget_pages_remaining(), freeze_daily_pages_max * 2, "multiplier=200%%");
}

T_DECL(memorystatus_freeze_set_dasd_trial_identifiers, "set dasd trial identifiers",
	T_META_ENABLED(HAS_FREEZER),
    T_META_ASROOT(true),
	T_META_TAG_VM_NOT_PREFERRED) {
#define TEST_STR "freezer-das-trial"
	memorystatus_freezer_trial_identifiers_v1 identifiers = {0};
	identifiers.version = 1;
	check_for_and_enable_freezer();
	strncpy(identifiers.treatment_id, TEST_STR, sizeof(identifiers.treatment_id));
	strncpy(identifiers.experiment_id, TEST_STR, sizeof(identifiers.treatment_id));
	identifiers.deployment_id = 2;
	int ret = memorystatus_control(MEMORYSTATUS_CMD_FREEZER_CONTROL, 0, FREEZER_CONTROL_SET_DASD_TRIAL_IDENTIFIERS, &identifiers, sizeof(identifiers));
	T_WITH_ERRNO; T_ASSERT_EQ(ret, 0, "FREEZER_CONTROL_SET_DASD_TRIAL_IDENTIFIERS");
}

T_DECL(memorystatus_reset_freezer_state, "FREEZER_CONTROL_RESET_STATE kills frozen proccesses",
	T_META_ENABLED(HAS_FREEZER),
    T_META_ASROOT(true),
    T_META_REQUIRES_SYSCTL_EQ("kern.development", 1),
	T_META_TAG_VM_NOT_PREFERRED) {
	check_for_and_enable_freezer();
	/* Take ownership of the freezer probabilities for the duration of the test so that nothing new gets frozen by dasd. */
	set_testing_pid();
	reset_interval();

	test_after_background_helper_launches(false, "frozen_background", ^{
		proc_name_t name;
		int ret;

		/* Freeze the child and verify they're frozen. */
		move_to_idle_band(child_pid);
		ret = pid_suspend(child_pid);
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "child suspended");
		freeze_process(child_pid);
		T_QUIET; T_ASSERT_TRUE(is_proc_in_frozen_list(child_pid, name, sizeof(name)), "Found proc in frozen list");
		T_QUIET; T_EXPECT_EQ_STR(name, "memorystatus_freeze_test", "Proc has correct name");
		/* Set the budget to 0. */
		set_budget_pages_remaining(0);

		/* FREEZER_CONTROL_RESET_STATE */
		ret = memorystatus_control(MEMORYSTATUS_CMD_FREEZER_CONTROL, 0, FREEZER_CONTROL_RESET_STATE, NULL, 0);
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "FREEZER_CONRTOL_RESET_STATE");

		/* Verify budget resets to a non-zero value. Some devices may have a configured
		 * budget of 0. Skip this assertion if so. */
		uint64_t budget_after_reset = get_budget_pages_remaining();
#if TARGET_OS_XR
		T_QUIET; T_ASSERT_EQ(budget_after_reset, 0ULL, "freeze budget after reset == 0");
#else
		T_QUIET; T_ASSERT_GT(budget_after_reset, 0ULL, "freeze budget after reset > 0");
#endif
		/*
		 * Verify child has been killed
		 * Note that the task termination isn't synchronous with the RESET_STATE call so we may
		 * block in waitpid temporarily.
		 */
		int stat;
		while (true) {
		        pid_t wait_p = waitpid(child_pid, &stat, 0);
		        if (wait_p == child_pid) {
		                break;
			}
		}
		T_QUIET; T_ASSERT_TRUE(WIFSIGNALED(stat), "child was signaled");
		T_QUIET; T_ASSERT_EQ(WTERMSIG(stat), SIGKILL, "Child received SIGKILL");

		T_END;
	});
	dispatch_main();
}

static void
dock_proc(pid_t pid)
{
	int ret;
	ret = memorystatus_control(MEMORYSTATUS_CMD_ELEVATED_INACTIVEJETSAMPRIORITY_ENABLE, pid, 0, NULL, 0);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "dock_proc");
}

T_DECL(memorystatus_freeze_skip_docked, "memorystatus_freeze_top_process does not freeze docked processes",
	T_META_ENABLED(HAS_FREEZER && !TARGET_OS_WATCH),
    T_META_ASROOT(true),
    T_META_REQUIRES_SYSCTL_EQ("kern.development", 1),
	T_META_TAG_VM_NOT_PREFERRED) {
	check_for_and_enable_freezer();
	memorystatus_freeze_top_process_setup();
	enable_ordered_freeze_mode();
	test_after_background_helper_launches(true, "frozen_background", ^{
		int ret, val = 1;
		memorystatus_properties_freeze_entry_v1 entries[1];

		dock_proc(child_pid);
		construct_child_freeze_entry(&entries[0]);
		prepare_proc_for_freezing(child_pid);

		T_LOG("Telling kernel to freeze %s", entries[0].proc_name);
		ret = memorystatus_control(MEMORYSTATUS_CMD_GRP_SET_PROPERTIES, 0, MEMORYSTATUS_FLAGS_GRP_SET_FREEZE_PRIORITY, entries, sizeof(entries));
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "MEMORYSTATUS_FLAGS_GRP_SET_FREEZE_PRIORITY");

		ret = sysctlbyname("vm.memorystatus_freeze_top_process", NULL, NULL, &val, sizeof(val));
		T_ASSERT_EQ(errno, ESRCH, "freeze_top_process errno");
		T_ASSERT_EQ(ret, -1, "freeze_top_process");

		verify_proc_not_frozen(child_pid);
		resume_and_kill_proc(child_pid);

		T_END;
	});
	dispatch_main();
}

T_HELPER_DECL(corpse_generation, "Generate a large corpse", T_META_ASROOT(false)) {
	/*
	 * Allocate and fault in a bunch of memory so that it takes a while
	 * to generate our corpse.
	 */
	size_t bytes_to_allocate = 304 * (1UL << 20);
	size_t block_size = 8 * (1UL << 20);
	for (size_t i = 0; i < bytes_to_allocate / block_size; i++) {
		unsigned char *ptr = malloc(block_size);
		if (ptr == NULL) {
			T_LOG("Unable to allocate memory in child process!");
			exit(UNABLE_TO_ALLOCATE);
		}
		for (size_t j = 0; j < block_size / vm_page_size; j++) {
			*ptr = (unsigned char) j;
			ptr += vm_page_size;
		}
	}
	dispatch_source_t ds_signal = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, dispatch_get_main_queue());
	if (ds_signal == NULL) {
		T_LOG("Unable to create dispatch source");
		exit(DISPATCH_SOURCE_CREATE_FAILED);
	}
	dispatch_source_set_event_handler(ds_signal, ^{
		uint64_t val = 1;
		/*
		 * We should now be frozen.
		 * Simulate a crash so that our P_MEMSTAT_SKIP bit gets set temporarily.
		 * The parent process will try to kill us due to disk space shortage in parallel.
		 */
		os_fault_with_payload(OS_REASON_LIBSYSTEM, OS_REASON_LIBSYSTEM_CODE_FAULT,
		&val, sizeof(val), "freeze_test", 0);
	});
	dispatch_activate(ds_signal);

	sig_t sig_ret = signal(SIGUSR1, SIG_IGN);
	T_QUIET; T_WITH_ERRNO; T_ASSERT_NE(sig_ret, SIG_ERR, "signal(SIGUSR1, SIG_IGN)");

	/* Signal to our parent that we can be frozen */
	if (kill(getppid(), SIGUSR1) != 0) {
		T_LOG("Unable to signal to parent process!");
		exit(SIGNAL_TO_PARENT_FAILED);
	}
	dispatch_main();
}

T_DECL(memorystatus_disable_freeze_corpse, "memorystatus_disable_freeze with parallel corpse creation",
	T_META_ENABLED(HAS_FREEZER),
    T_META_ASROOT(true),
    T_META_REQUIRES_SYSCTL_EQ("kern.development", 1),
	T_META_TAG_VM_NOT_PREFERRED) {
	/*
	 * In the past, we've had race conditions w.r.t. killing on disk space shortage
	 * and corpse generation of frozen processes.
	 * This test spwans a frozen helper
	 * which generates a large corpse (which should take in the 10s to 100s of m.s. to complete)
	 * while the test process triggers disk space kills.
	 * We should see that the test process is jetsammed successfully.
	 */
	check_for_and_enable_freezer();
	test_after_background_helper_launches(false, "corpse_generation", ^{
		int ret, val, stat;
		/* Place the child in the idle band so that it gets elevated like a typical app. */
		move_to_idle_band(child_pid);
		ret = pid_suspend(child_pid);
		T_ASSERT_POSIX_SUCCESS(ret, "child suspended");
		freeze_process(child_pid);

		ret = pid_resume(child_pid);
		T_ASSERT_POSIX_SUCCESS(ret, "child resumed after freeze");

		kill(child_pid, SIGUSR1);

		T_ATEND(enable_freeze);
		val = 0;
		ret = sysctlbyname("vm.freeze_enabled", NULL, NULL, &val, sizeof(val));
		T_ASSERT_POSIX_SUCCESS(ret, "freeze disabled");
		/*
		 * Verify child has been killed
		 * Note that the task termination isn't synchronous with the freeze_enabled call so we may
		 * block in waitpid temporarily.
		 */
		while (true) {
		        pid_t wait_p = waitpid(child_pid, &stat, 0);
		        if (wait_p == child_pid) {
		                break;
			}
		}
		T_QUIET; T_ASSERT_TRUE(WIFSIGNALED(stat), "child was signaled");
		T_QUIET; T_ASSERT_EQ(WTERMSIG(stat), SIGKILL, "Child received SIGKILL");

		T_END;
	});
	dispatch_main();
}

static int original_unrestrict_coalitions_val;

static void
unrestrict_coalitions()
{
	int ret, val = 1;
	size_t val_size = sizeof(val);
	size_t original_unrestrict_coalitions_size = sizeof(original_unrestrict_coalitions_val);
	ret = sysctlbyname("kern.unrestrict_coalitions", &original_unrestrict_coalitions_val, &original_unrestrict_coalitions_size, &val, val_size);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "unrestrict_coalitions");
}

static void
reset_unrestrict_coalitions()
{
	size_t size = sizeof(original_unrestrict_coalitions_val);
	int ret = sysctlbyname("kern.unrestrict_coalitions", NULL, NULL, &original_unrestrict_coalitions_val, size);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "unrestrict_coalitions");
}

static uint64_t
create_coalition(int type)
{
	uint64_t id = 0;
	uint32_t flags = 0;
	uint64_t param[2];
	int ret;

	COALITION_CREATE_FLAGS_SET_TYPE(flags, type);
	ret = coalition_create(&id, flags);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "coalition_create");
	T_QUIET; T_ASSERT_GE(id, 0ULL, "coalition_create returned a valid id");

	/* disable notifications for this coalition so launchd doesn't freak out */
	param[0] = id;
	param[1] = 0;
	ret = sysctlbyname("kern.coalition_notify", NULL, NULL, param, sizeof(param));
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "kern.coalition_notify");

	return id;
}

static uint64_t jetsam_coal, resource_coal;

#define COAL_MAX_MEMBERS 50
#define MAX_XPC_SERVICE_FREEZE 10 /* xnu will only freeze 10 XPC services per coalition. */
int n_coalition_members;
pid_t coalition_members[COAL_MAX_MEMBERS];

/*
 * Spawns the given command as the leader of the given coalitions.
 * Process will start in a stopped state (waiting for SIGCONT)
 */
static pid_t
spawn_coalition_member(const char *path, char *const *argv, int role, short spawn_flags)
{
	int ret;
	posix_spawnattr_t attr;
	extern char **environ;
	pid_t new_pid = 0;
	kern_return_t kr;

	ret = posix_spawnattr_init(&attr);
	T_QUIET; T_ASSERT_POSIX_ZERO(ret, "posix_spawnattr_init failed with %s", strerror(ret));

	ret = posix_spawnattr_setcoalition_np(&attr, jetsam_coal,
	    COALITION_TYPE_JETSAM, role);
	T_QUIET; T_ASSERT_POSIX_ZERO(ret, "posix_spawnattr_setcoalition_np failed with %s", strerror(ret));
	ret = posix_spawnattr_setcoalition_np(&attr, resource_coal,
	    COALITION_TYPE_RESOURCE, role);
	T_QUIET; T_ASSERT_POSIX_ZERO(ret, "posix_spawnattr_setcoalition_np failed with %s", strerror(ret));

	ret = posix_spawnattr_setflags(&attr, spawn_flags);
	T_QUIET; T_ASSERT_POSIX_ZERO(ret, "posix_spawnattr_setflags failed with %s", strerror(ret));

	ret = posix_spawn(&new_pid, path, NULL, &attr, argv, environ);
	T_QUIET; T_ASSERT_POSIX_ZERO(ret, "posix_spawn failed with %s", strerror(ret));

	ret = posix_spawnattr_destroy(&attr);
	T_QUIET; T_ASSERT_POSIX_ZERO(ret, "posix_spawnattr_destroy failed with %s\n", strerror(ret));

	kr = memorystatus_control(MEMORYSTATUS_CMD_SET_PROCESS_IS_MANAGED, new_pid, 1, NULL, 0);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "memorystatus_control");

	return new_pid;
}

static pid_t
get_coalition_leader(pid_t p)
{
	static const size_t kMaxPids = 500;
	int ret;
	int pid_list[kMaxPids];
	size_t pid_list_size = sizeof(pid_list);

	int iparam[3];
#define p_type  iparam[0]
#define p_order iparam[1]
#define p_pid   iparam[2]
	p_type = COALITION_TYPE_JETSAM;
	p_order = COALITION_SORT_DEFAULT;
	p_pid = p;

	ret = sysctlbyname("kern.coalition_pid_list", pid_list, &pid_list_size, iparam, sizeof(iparam));
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "sysctl kern.coalition_pid_list");
	T_QUIET; T_ASSERT_LE(pid_list_size, kMaxPids * sizeof(int), "coalition is small enough");

	for (size_t i = 0; i < pid_list_size / sizeof(int); i++) {
		int curr_pid = pid_list[i];
		int roles[COALITION_NUM_TYPES] = {};
		size_t roles_size = sizeof(roles);

		ret = sysctlbyname("kern.coalition_roles", roles, &roles_size, &curr_pid, sizeof(curr_pid));
		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "sysctl kern.coalition_roles");
		if (roles[COALITION_TYPE_JETSAM] == COALITION_TASKROLE_LEADER) {
			return curr_pid;
		}
	}

	T_FAIL("No leader in coalition!");
	return 0;
}

void
setup_coalitions() {
}

void
coal_foreach(void (^callback)(pid_t)) {
	for (int i = 0; i < n_coalition_members; i++) {
		callback(coalition_members[i]);
	}
}

void
kill_all_coalition_members() {
	int __block ret;
	T_LOG("Killing coalition members...");
	coal_foreach(^(pid_t pid){
		ret = kill(pid, SIGKILL);
		T_QUIET; T_EXPECT_POSIX_SUCCESS(ret, "kill");
	});
}

void
spawn_coalition_and_run(dispatch_block_t after_spawn) {
	int ret, __block i = 0;
	static uint32_t path_size;
	static char pathbuf[PATH_MAX];
	dispatch_source_t sig_source;
	pid_t leader_pid;

	/* Setup coalitions */
	jetsam_coal = create_coalition(COALITION_TYPE_JETSAM);
	resource_coal = create_coalition(COALITION_TYPE_RESOURCE);

	path_size = sizeof(pathbuf);
	ret = _NSGetExecutablePath(pathbuf, &path_size);
	T_QUIET; T_ASSERT_POSIX_ZERO(ret, "_NSGetExecutablePath");
	static char *const args[] = {
		pathbuf,
		"-n",
		"frozen_background",
		NULL
	};

	T_ATEND(kill_all_coalition_members);

	sig_source = run_block_after_signal(SIGUSR1, ^{
		i++;
		if (i < n_coalition_members) {
			/* Spawn next child */
			coalition_members[i] = spawn_coalition_member(pathbuf, args, COALITION_TASKROLE_XPC, 0);
		} else {
			after_spawn();
		}
	});
	dispatch_activate(sig_source);

	/* Spawn leader */
	child_pid = spawn_coalition_member(pathbuf, args, COALITION_TASKROLE_LEADER, 0);
	coalition_members[0] = child_pid;

	/* Double-check the coalition was set up correctly */
	leader_pid = get_coalition_leader(child_pid);
	T_ASSERT_EQ(child_pid, leader_pid, "Child is leader of coalition");
}

static void
kill_all_frozen()
{
	/* Disabling and re-enabling the freezer will evict all frozen processes. */
	set_freeze_enabled(0);
	set_freeze_enabled(1);
}

static unsigned int
get_used_freezer_slots ()
{
	int ret;
	unsigned int frozen_procs;
	size_t frozen_procs_size = sizeof(frozen_procs);

	ret = sysctlbyname("kern.memorystatus_freeze_count", &frozen_procs, &frozen_procs_size, NULL, 0);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "get kern.memorystatus_freeze_count");

	return frozen_procs;
}

static void
setup_coalition_freezing()
{

	/* Setup freezer. Set ordered freeze mode and kill all frozen procs. */
	memorystatus_freeze_top_process_setup();
	enable_ordered_freeze_mode();
}

static uint32_t
get_max_freezer_slots()
{
	int ret;
	uint32_t max_freeze_processes = 0;
	size_t max_freeze_processes_len = sizeof(max_freeze_processes);
	ret = sysctlbyname("kern.memorystatus_freeze_processes_max", &max_freeze_processes, &max_freeze_processes_len, NULL, 0);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "kern.memorystatus_freeze_processes_max");
	return max_freeze_processes;
}

static int orig_freezer_slots = -1;
static void restore_freezer_slots(void);

static void
set_max_freezer_slots(uint32_t max_freeze_processes)
{
	int ret;
	if (orig_freezer_slots == -1) {
		orig_freezer_slots = get_max_freezer_slots();
		T_ATEND(restore_freezer_slots);
	}
	ret = sysctlbyname("kern.memorystatus_freeze_processes_max", NULL, NULL, &max_freeze_processes, sizeof(max_freeze_processes));
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "set kern.memorystatus_freeze_processes_max");
}

static void
restore_freezer_slots(void)
{
	set_max_freezer_slots(orig_freezer_slots);
}

static void
prepare_coalition_for_freezing(void)
{
	coal_foreach(^(pid_t pid){
		prepare_proc_for_freezing(pid);
	});
}

static int
freeze_coalition_leader(void)
{
	int ret, val = 1;
	memorystatus_properties_freeze_entry_v1 entry;
	construct_child_freeze_entry(&entry);
	ret = memorystatus_control(MEMORYSTATUS_CMD_GRP_SET_PROPERTIES, 0, MEMORYSTATUS_FLAGS_GRP_SET_FREEZE_PRIORITY, &entry, sizeof(entry));
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "MEMORYSTATUS_FLAGS_GRP_SET_FREEZE_PRIORITY");
	return sysctlbyname("vm.memorystatus_freeze_top_process", NULL, NULL, &val, sizeof(val));

}

#define TEST_MAX_FREEZER_SLOTS 8
#define N_UNFROZEN_MEMBERS 3

T_DECL(memorystatus_coalition_freeze, "Freezing a coalition leader should freeze all of its XPC service members",
	T_META_ENABLED(HAS_FREEZER),
	T_META_ASROOT(true),
	T_META_REQUIRES_SYSCTL_EQ("kern.development", 1),
	T_META_TAG_VM_NOT_PREFERRED)
{
	check_for_and_enable_freezer();
	unrestrict_coalitions();
	T_ATEND(reset_unrestrict_coalitions);
	setup_coalition_freezing();
	set_max_freezer_slots(TEST_MAX_FREEZER_SLOTS);
	kill_all_frozen();
	T_QUIET; T_ASSERT_EQ(get_used_freezer_slots(), 0, "No freezer slots used");

	/* Spawn max freezer slots coalition members */
	n_coalition_members = TEST_MAX_FREEZER_SLOTS;
	static_assert(TEST_MAX_FREEZER_SLOTS <= COAL_MAX_MEMBERS);
	static_assert(TEST_MAX_FREEZER_SLOTS < MAX_XPC_SERVICE_FREEZE);

	/* Create our coalitions and spawn the leader / "XPC service" members */
	spawn_coalition_and_run(^{
		int i, ret, n_coal_frozen = 0;
		memorystatus_jetsam_snapshot_t *snapshot;
		memorystatus_jetsam_snapshot_entry_t *entry;

		/* Freeze coalition */
		prepare_coalition_for_freezing();
		ret = freeze_coalition_leader();
		T_EXPECT_POSIX_SUCCESS(ret, "freeze_coalition_leader");

		snapshot = get_jetsam_snapshot(MEMORYSTATUS_FLAGS_SNAPSHOT_ON_DEMAND, false);
		for (i = 0; i < n_coalition_members; i++) {
			entry = get_jetsam_snapshot_entry(snapshot, coalition_members[i]);
			if (entry->state & P_MEMSTAT_FROZEN) {
				n_coal_frozen++;
			}
		}
		T_ASSERT_EQ(n_coal_frozen, n_coalition_members, "All coalition members frozen");

		T_END;
	});
	dispatch_main();
}

T_DECL(memorystatus_coalition_freezer_slot_limit, "Exhausting freezer slots and freezing a large coalition should not exceed slots",
	T_META_ENABLED(HAS_FREEZER),
	T_META_ASROOT(true),
	T_META_REQUIRES_SYSCTL_EQ("kern.development", 1),
	T_META_TAG_VM_NOT_PREFERRED)
{
	check_for_and_enable_freezer();
	unrestrict_coalitions();
	T_ATEND(reset_unrestrict_coalitions);
	setup_coalition_freezing();
	set_max_freezer_slots(TEST_MAX_FREEZER_SLOTS);
	kill_all_frozen();
	T_QUIET; T_ASSERT_EQ(get_used_freezer_slots(), 0, "No freezer slots used");

	/* Spawn max freezer slots + 1 coalition members */
	n_coalition_members = TEST_MAX_FREEZER_SLOTS + N_UNFROZEN_MEMBERS;
	static_assert(TEST_MAX_FREEZER_SLOTS + N_UNFROZEN_MEMBERS <= COAL_MAX_MEMBERS);
	static_assert(TEST_MAX_FREEZER_SLOTS < MAX_XPC_SERVICE_FREEZE);

	/* Create our coalitions and spawn the leader / "XPC service" members */
	spawn_coalition_and_run(^{
		int i, ret, n_coal_frozen = 0;
		memorystatus_jetsam_snapshot_t *snapshot;
		memorystatus_jetsam_snapshot_entry_t *entry;

		/* Freeze coalition */
		prepare_coalition_for_freezing();
		ret = freeze_coalition_leader();
		T_EXPECT_POSIX_SUCCESS(ret, "freeze_coalition_leader");

		/* Ensure coalition leader is frozen */
		verify_proc_is_frozen(coalition_members[0]);

		/* Make sure freezer did not exceed its slots */
		snapshot = get_jetsam_snapshot(MEMORYSTATUS_FLAGS_SNAPSHOT_ON_DEMAND, false);
		for (i = 0; i < n_coalition_members; i++) {
			entry = get_jetsam_snapshot_entry(snapshot, coalition_members[i]);
			if (entry->state & P_MEMSTAT_FROZEN) {
				n_coal_frozen++;
			}
		}
		T_ASSERT_EQ(n_coal_frozen, n_coalition_members - N_UNFROZEN_MEMBERS, "N_UNFROZEN_MEMBERS coalition members remain unfrozen");

		T_END;
	});
	dispatch_main();
}

pid_t helper_pid;
static void
kill_helper()
{
	int ret = kill(helper_pid, SIGUSR2);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "kill(helper_pid, SIGUSR2)");
}

T_DECL(memorystatus_two_coalition_freeze, "Exhausting freezer slots with one coalition and freezing another should fail",
	T_META_ENABLED(HAS_FREEZER),
	T_META_ASROOT(true),
	T_META_REQUIRES_SYSCTL_EQ("kern.development", 1),
	T_META_TAG_VM_NOT_PREFERRED)
{
	dispatch_source_t sig_disp, exit_disp;

	check_for_and_enable_freezer();
	unrestrict_coalitions();
	T_ATEND(reset_unrestrict_coalitions);
	setup_coalition_freezing();
	set_max_freezer_slots(TEST_MAX_FREEZER_SLOTS);
	kill_all_frozen();
	T_QUIET; T_ASSERT_EQ(get_used_freezer_slots(), 0, "No freezer slots used");

	/* Spawn max freezer slots coalition members */
	n_coalition_members = TEST_MAX_FREEZER_SLOTS;
	static_assert(TEST_MAX_FREEZER_SLOTS <= COAL_MAX_MEMBERS);
	static_assert(TEST_MAX_FREEZER_SLOTS < MAX_XPC_SERVICE_FREEZE);

	sig_disp = run_block_after_signal(SIGUSR2, ^{
		/* After our child signals, we can try spawning and freezing our coalition */
		spawn_coalition_and_run(^{
			int i, ret, n_coal_frozen = 0;
			memorystatus_jetsam_snapshot_t *snapshot;
			memorystatus_jetsam_snapshot_entry_t *entry;

			/* Freeze coalition */
			prepare_coalition_for_freezing();
			ret = freeze_coalition_leader();
			T_EXPECT_POSIX_FAILURE(ret, ESRCH, "freeze_coalition_leader");

			/* Make sure freezer did not freeze anyone */
			snapshot = get_jetsam_snapshot(MEMORYSTATUS_FLAGS_SNAPSHOT_ON_DEMAND, false);
			for (i = 0; i < n_coalition_members; i++) {
				entry = get_jetsam_snapshot_entry(snapshot, coalition_members[i]);
				if (entry->state & P_MEMSTAT_FROZEN) {
					n_coal_frozen++;
				}
			}

			T_ASSERT_EQ(n_coal_frozen, 0, "all coalition members remain unfrozen");

			T_END;
		});
	});
	dispatch_activate(sig_disp);


	/* Spawn helper and wait for it to spawn its coalition and freeze it */
	helper_pid = launch_background_helper("coalition_freezer", false, false);
	T_ATEND(kill_helper);

	exit_disp = dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC, (uintptr_t)helper_pid, DISPATCH_PROC_EXIT, dispatch_get_main_queue());
	dispatch_source_set_event_handler(exit_disp, ^{
		int status = 0, code = 0;
		pid_t rc = waitpid(child_pid, &status, 0);
		T_QUIET; T_ASSERT_EQ(rc, child_pid, "waitpid");
		code = WEXITSTATUS(status);
		if (code != 0) {
		        T_LOG("Helper exited with error: %s", exit_codes_str[code]);
		}
		T_QUIET; T_ASSERT_EQ(code, 0, "Helper exited cleanly");
	});
	dispatch_activate(exit_disp);

	dispatch_main();
}

T_HELPER_DECL(coalition_freezer, "Spawns a coalition and freezes it",
	T_META_ASROOT(true))
{
	dispatch_source_t sig_disp;

	/* The parent will have already set up the freezer for us. */
	n_coalition_members = TEST_MAX_FREEZER_SLOTS;
	spawn_coalition_and_run(^{
		prepare_coalition_for_freezing();
		freeze_coalition_leader();
		kill(getppid(), SIGUSR2);
	});

	sig_disp = run_block_after_signal(SIGUSR2, ^{
		kill_all_coalition_members();
		exit(0);
	});
	dispatch_activate(sig_disp);

	dispatch_main();
}

T_DECL(do_fastwake_warmup_all,
    "Test kern.memorystatus_do_fastwake_warmup_all",
    T_META_ASROOT(true),
    T_META_ENABLED(false /* rdar://149557081 !TARGET_OS_OSX && !TARGET_OS_BRIDGE */))
{
	int val = 1;
	int ret = sysctlbyname("kern.memorystatus_do_fastwake_warmup_all", NULL, NULL, &val, sizeof(val));
	T_ASSERT_POSIX_SUCCESS(ret, "sysctl(kern.memorystatus_do_fastwake_warmup_all)");

	struct vm_compressor_q_lens cstats;
	mach_msg_type_number_t count = VM_COMPRESSOR_Q_LENS_COUNT;

	kern_return_t kr = host_info(mach_host_self(), HOST_VM_COMPRESSOR_Q_LENS,
	    (host_info_t)&cstats, &count);
	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "host_info(HOST_VM_COMPRESSOR_Q_LENS)");

	T_EXPECT_EQ(cstats.qcc_swappedout_count, 0, "Zero swapped-out segments after fastwake warmup");
	T_EXPECT_EQ(cstats.qcc_swappedout_sparse_count, 0, "Zero sparse swapped-out segments after fastwake warmup");
}