Loading...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 | /* * Copyright (c) 2000-2020 Apple Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ /* * @OSF_COPYRIGHT@ */ /* * Mach Operating System * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University * All Rights Reserved. * * Permission to use, copy, modify and distribute this software and its * documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie Mellon * the rights to redistribute these changes. */ /* */ /* * File: vm/vm_page.c * Author: Avadis Tevanian, Jr., Michael Wayne Young * * Resident memory management module. */ #include <debug.h> #include <libkern/OSDebug.h> #include <mach/clock_types.h> #include <mach/vm_prot.h> #include <mach/vm_statistics.h> #include <mach/sdt.h> #include <kern/counter.h> #include <kern/exclaves_memory.h> #include <kern/host_statistics.h> #include <kern/sched_prim.h> #include <kern/policy_internal.h> #include <kern/task.h> #include <kern/thread.h> #include <kern/kalloc.h> #include <kern/zalloc_internal.h> #include <kern/ledger.h> #include <kern/ecc.h> #include <vm/pmap.h> #include <vm/vm_init_xnu.h> #include <vm/vm_map_internal.h> #include <vm/vm_page_internal.h> #include <vm/vm_pageout_internal.h> #include <vm/vm_kern_xnu.h> /* kmem_alloc() */ #include <vm/vm_compressor_pager_internal.h> #include <kern/misc_protos.h> #include <mach_debug/zone_info.h> #include <vm/cpm_internal.h> #include <pexpert/pexpert.h> #include <pexpert/device_tree.h> #include <san/kasan.h> #include <vm/vm_log.h> #include <libkern/coreanalytics/coreanalytics.h> #include <libkern/kernel_mach_header.h> #include <kern/backtrace.h> #include <kern/telemetry.h> #include <vm/vm_protos_internal.h> #include <vm/memory_object.h> #include <vm/vm_purgeable_internal.h> #include <vm/vm_compressor_internal.h> #include <vm/vm_iokit.h> #include <vm/vm_object_internal.h> #if HAS_MTE #include <arm64/mte.h> #include <vm/vm_mteinfo_internal.h> #endif /* HAS_MTE */ #include <vm/vm_map_lock_internal.h> #if defined (__x86_64__) #include <i386/misc_protos.h> #endif #if CONFIG_SPTM #include <arm64/sptm/sptm.h> #endif #if CONFIG_PHANTOM_CACHE #include <vm/vm_phantom_cache_internal.h> #endif #if HIBERNATION #include <IOKit/IOHibernatePrivate.h> #include <machine/pal_hibernate.h> #endif /* HIBERNATION */ #if CONFIG_SECLUDED_MEMORY static_assert(!XNU_VM_HAS_LOPAGE, "VM_PAGE_ON_SECLUDED_Q and VM_PAGE_ON_FREE_LOPAGE_Q alias"); #endif #include <sys/kdebug.h> #if defined(HAS_APPLE_PAC) #include <ptrauth.h> #endif #if defined(__arm64__) #include <arm/cpu_internal.h> #endif /* defined(__arm64__) */ /* * During single threaded early boot we don't initialize all pages. * This avoids some delay during boot. They'll be initialized and * added to the free list as needed or after we are multithreaded by * what becomes the pageout thread. * * This slows down booting the DEBUG kernel, particularly on * large memory systems, but is worthwhile in deterministically * trapping uninitialized memory usage. */ #if DEBUG static TUNABLE(uint32_t, fillval, "fill", 0xDEB8F177); #else static TUNABLE(uint32_t, fillval, "fill", 0); #endif #if MACH_ASSERT TUNABLE(bool, vm_check_refs_on_alloc, "vm_check_refs_on_alloc", false); #endif /* MACH_ASSERT */ extern boolean_t vm_pageout_running; extern thread_t vm_pageout_scan_thread; extern bool vps_dynamic_priority_enabled; const uint16_t vm_page_inactive_states = BIT(VM_PAGE_ON_INACTIVE_INTERNAL_Q) | BIT(VM_PAGE_ON_INACTIVE_EXTERNAL_Q) | BIT(VM_PAGE_ON_INACTIVE_CLEANED_Q); const uint16_t vm_page_active_or_inactive_states = vm_page_inactive_states | #if CONFIG_SECLUDED_MEMORY BIT(VM_PAGE_ON_SECLUDED_Q) | #endif /* CONFIG_SECLUDED_MEMORY */ BIT(VM_PAGE_ON_ACTIVE_Q); const uint16_t vm_page_non_speculative_pageable_states = vm_page_active_or_inactive_states | BIT(VM_PAGE_ON_THROTTLED_Q); const uint16_t vm_page_pageable_states = vm_page_non_speculative_pageable_states | BIT(VM_PAGE_ON_SPECULATIVE_Q); #if CONFIG_SECLUDED_MEMORY struct vm_page_secluded_data vm_page_secluded; #endif /* CONFIG_SECLUDED_MEMORY */ #if HIBERNATION static bool hibernate_rebuild_needed = false; #endif /* HIBERNATION */ extern struct memory_object_pager_ops shared_region_pager_ops; struct vm_page_pcpu PERCPU_DATA(vm_page_pcpu); SCALABLE_COUNTER_DEFINE(vm_cpu_free_count); boolean_t hibernate_cleaning_in_progress = FALSE; atomic_counter_t vm_guard_count; #if XNU_VM_HAS_LOPAGE /* * this interface exists to support hardware controllers * incapable of generating DMAs with more than 32 bits * of address on platforms with physical memory > 4G... */ vm_page_queue_head_t vm_lopage_queue_free VM_PAGE_PACKED_ALIGNED; uint32_t vm_lopage_free_count = 0; uint32_t vm_lopage_free_limit = 0; uint32_t vm_lopage_lowater = 0; bool vm_lopage_refill = false; bool vm_lopage_needed = false; unsigned int vm_lopages_allocated_q = 0; unsigned int vm_lopages_allocated_cpm_success = 0; unsigned int vm_lopages_allocated_cpm_failed = 0; #endif /* XNU_VM_HAS_LOPAGE */ int speculative_age_index = 0; int speculative_steal_index = 0; struct vm_speculative_age_q vm_page_queue_speculative[VM_PAGE_RESERVED_SPECULATIVE_AGE_Q + 1]; boolean_t hibernation_vmqueues_inspection = FALSE; /* Tracks if the hibernation code is looking at the VM queues. * Updated and checked behind the vm_page_queues_lock. */ static void vm_page_free_prepare(vm_page_t page); #if HAS_MTE void vm_page_wire_boot_tags(void); #endif /* HAS_MTE */ static void vm_tag_init(void); /* for debugging purposes */ SECURITY_READ_ONLY_EARLY(uint32_t) vm_packed_from_vm_pages_array_mask = VM_PAGE_PACKED_FROM_ARRAY; SECURITY_READ_ONLY_EARLY(vm_packing_params_t) vm_page_packing_params = VM_PACKING_PARAMS(VM_PAGE_PACKED_PTR); SECURITY_READ_ONLY_EARLY(vm_packing_params_t) vme_packing_params = VM_PACKING_PARAMS(VME_PACKED_PTR); SECURITY_READ_ONLY_EARLY(vm_packing_params_t) vmn_packing_params = VM_PACKING_PARAMS(VMN_PACKED_PTR); /* * Associated with page of user-allocatable memory is a * page structure. */ /* * These variables record the values returned by vm_page_bootstrap, * for debugging purposes. The implementation of pmap_steal_memory * and pmap_startup here also uses them internally. */ vm_offset_t virtual_space_start; vm_offset_t virtual_space_end; uint32_t vm_page_pages; /* * The vm_page_lookup() routine, which provides for fast * (virtual memory object, offset) to page lookup, employs * the following hash table. The vm_page_{insert,remove} * routines install and remove associations in the table. * [This table is often called the virtual-to-physical, * or VP, table.] */ typedef struct { vm_page_packed_t page_list; #if MACH_PAGE_HASH_STATS int cur_count; /* current count */ int hi_count; /* high water mark */ #endif /* MACH_PAGE_HASH_STATS */ } vm_page_bucket_t; #define BUCKETS_PER_LOCK 4 SECURITY_READ_ONLY_LATE(vm_page_bucket_t *) vm_page_buckets; /* Array of buckets */ SECURITY_READ_ONLY_LATE(unsigned int) vm_page_bucket_count = 0; /* How big is array? */ SECURITY_READ_ONLY_LATE(unsigned int) vm_page_hash_mask; /* Mask for hash function */ SECURITY_READ_ONLY_LATE(unsigned int) vm_page_hash_shift; /* Shift for hash function */ SECURITY_READ_ONLY_LATE(uint32_t) vm_page_bucket_hash; /* Basic bucket hash */ SECURITY_READ_ONLY_LATE(unsigned int) vm_page_bucket_lock_count = 0; /* How big is array of locks? */ #ifndef VM_TAG_ACTIVE_UPDATE #error VM_TAG_ACTIVE_UPDATE #endif #ifndef VM_TAG_SIZECLASSES #error VM_TAG_SIZECLASSES #endif /* for debugging */ SECURITY_READ_ONLY_LATE(bool) vm_tag_active_update = VM_TAG_ACTIVE_UPDATE; SECURITY_READ_ONLY_LATE(hw_lck_ticket_t *) vm_page_bucket_locks; vm_allocation_site_t vm_allocation_sites_static[VM_KERN_MEMORY_FIRST_DYNAMIC + 1]; vm_allocation_site_t * vm_allocation_sites[VM_MAX_TAG_VALUE]; #if VM_TAG_SIZECLASSES static vm_allocation_zone_total_t **vm_allocation_zone_totals; #endif /* VM_TAG_SIZECLASSES */ vm_tag_t vm_allocation_tag_highest; #if VM_PAGE_BUCKETS_CHECK boolean_t vm_page_buckets_check_ready = FALSE; #if VM_PAGE_FAKE_BUCKETS vm_page_bucket_t *vm_page_fake_buckets; /* decoy buckets */ vm_map_offset_t vm_page_fake_buckets_start, vm_page_fake_buckets_end; #endif /* VM_PAGE_FAKE_BUCKETS */ #endif /* VM_PAGE_BUCKETS_CHECK */ #if MACH_PAGE_HASH_STATS /* This routine is only for debug. It is intended to be called by * hand by a developer using a kernel debugger. This routine prints * out vm_page_hash table statistics to the kernel debug console. */ void hash_debug(void) { int i; int numbuckets = 0; int highsum = 0; int maxdepth = 0; for (i = 0; i < vm_page_bucket_count; i++) { if (vm_page_buckets[i].hi_count) { numbuckets++; highsum += vm_page_buckets[i].hi_count; if (vm_page_buckets[i].hi_count > maxdepth) { maxdepth = vm_page_buckets[i].hi_count; } } } printf("Total number of buckets: %d\n", vm_page_bucket_count); printf("Number used buckets: %d = %d%%\n", numbuckets, 100 * numbuckets / vm_page_bucket_count); printf("Number unused buckets: %d = %d%%\n", vm_page_bucket_count - numbuckets, 100 * (vm_page_bucket_count - numbuckets) / vm_page_bucket_count); printf("Sum of bucket max depth: %d\n", highsum); printf("Average bucket depth: %d.%2d\n", highsum / vm_page_bucket_count, highsum % vm_page_bucket_count); printf("Maximum bucket depth: %d\n", maxdepth); } #endif /* MACH_PAGE_HASH_STATS */ /* * The virtual page size is currently implemented as a runtime * variable, but is constant once initialized using vm_set_page_size. * This initialization must be done in the machine-dependent * bootstrap sequence, before calling other machine-independent * initializations. * * All references to the virtual page size outside this * module must use the PAGE_SIZE, PAGE_MASK and PAGE_SHIFT * constants. */ #if defined(__arm64__) vm_size_t page_size; vm_size_t page_mask; int page_shift; #else vm_size_t page_size = PAGE_SIZE; vm_size_t page_mask = PAGE_MASK; int page_shift = PAGE_SHIFT; #endif SECURITY_READ_ONLY_LATE(vm_page_t) vm_pages; #if XNU_VM_HAS_DELAYED_PAGES vm_page_t vm_pages_end; uint32_t vm_pages_count; #else SECURITY_READ_ONLY_LATE(vm_page_t) vm_pages_end; SECURITY_READ_ONLY_LATE(uint32_t) vm_pages_count; #endif /* XNU_VM_HAS_DELAYED_PAGES */ #if XNU_VM_HAS_LINEAR_PAGES_ARRAY SECURITY_READ_ONLY_LATE(ppnum_t) vm_pages_first_pnum; #endif /* XNU_VM_HAS_LINEAR_PAGES_ARRAY */ #if HAS_MTE SECURITY_READ_ONLY_LATE(vm_page_t) vm_pages_tag_storage; SECURITY_READ_ONLY_LATE(vm_page_t) vm_pages_tag_storage_end; #endif /* HAS_MTE */ #if CONFIG_SPTM /* * When used, these 128bit (MAX_COLORS bits) masks represent a "cluster" * of contiguous free physical pages. * * For each cluster, there is an enqueue "index", which is -1 when there is no * free page in the cluster, or the index in [0, 128) of the page that is * enqueued on the vm_page_free_queue to represent the entire cluster. * * Grouping pages this way has the double nice effect to reduce doubly linked * list (the worst data structure known to man when considering cache misses) * manipulations, and also to mechanically make the VM serve more "contiguous" * pages naturally. */ static_assert(XNU_VM_HAS_LINEAR_PAGES_ARRAY); SECURITY_READ_ONLY_LATE(__uint128_t *) _vm_pages_free_masks; SECURITY_READ_ONLY_LATE(int8_t *) _vm_pages_free_enqueue_idx; #endif /* CONFIG_SPTM */ /* * Resident pages that represent real memory * are allocated from a set of free lists, * one per color. */ SECURITY_READ_ONLY_LATE(unsigned int) vm_colors; SECURITY_READ_ONLY_LATE(unsigned int) vm_color_mask; /* mask is == (vm_colors-1) */ unsigned int vm_cache_geometry_colors = 0; /* set by hw dependent code during startup */ unsigned int vm_free_magazine_refill_limit = 0; struct vm_page_free_queue vm_page_queue_free; unsigned int vm_page_free_wanted; unsigned int vm_page_free_wanted_privileged; #if CONFIG_SECLUDED_MEMORY unsigned int vm_page_free_wanted_secluded; #endif /* CONFIG_SECLUDED_MEMORY */ unsigned int vm_page_free_count; unsigned int vm_page_realtime_count; /* * Occasionally, the virtual memory system uses * resident page structures that do not refer to * real pages, for example to leave a page with * important state information in the VP table. * * These page structures are allocated the way * most other kernel structures are. */ SECURITY_READ_ONLY_LATE(zone_t) vm_page_zone; vm_locks_array_t vm_page_locks; LCK_ATTR_DECLARE(vm_page_lck_attr, 0, 0); LCK_GRP_DECLARE(vm_page_lck_grp_free, "vm_page_free"); LCK_GRP_DECLARE(vm_page_lck_grp_queue, "vm_page_queue"); LCK_GRP_DECLARE(vm_page_lck_grp_local, "vm_page_queue_local"); LCK_GRP_DECLARE(vm_page_lck_grp_purge, "vm_page_purge"); LCK_GRP_DECLARE(vm_page_lck_grp_bucket, "vm_page_bucket"); LCK_SPIN_DECLARE_ATTR(vm_objects_wired_lock, &vm_page_lck_grp_bucket, &vm_page_lck_attr); LCK_TICKET_DECLARE(vm_allocation_sites_lock, &vm_page_lck_grp_bucket); unsigned int vm_page_local_q_soft_limit = 250; unsigned int vm_page_local_q_hard_limit = 500; struct vpl *__zpercpu vm_page_local_q; /* N.B. Guard and fictitious pages must not * be assigned a zero phys_page value. */ /* * Fictitious pages don't have a physical address, * but we must initialize phys_page to something. * For debugging, this should be a strange value * that the pmap module can recognize in assertions. */ const ppnum_t vm_page_fictitious_addr = (ppnum_t) -1; /* * Guard pages are not accessible so they don't * need a physical address, but we need to enter * one in the pmap. * Let's make it recognizable and make sure that * we don't use a real physical page with that * physical address. */ const ppnum_t vm_page_guard_addr = (ppnum_t) -2; /* * Resident page structures are also chained on * queues that are used by the page replacement * system (pageout daemon). These queues are * defined here, but are shared by the pageout * module. The inactive queue is broken into * file backed and anonymous for convenience as the * pageout daemon often assignes a higher * importance to anonymous pages (less likely to pick) */ vm_page_queue_head_t vm_page_queue_active VM_PAGE_PACKED_ALIGNED; vm_page_queue_head_t vm_page_queue_inactive VM_PAGE_PACKED_ALIGNED; #if CONFIG_SECLUDED_MEMORY vm_page_queue_head_t vm_page_queue_secluded VM_PAGE_PACKED_ALIGNED; #endif /* CONFIG_SECLUDED_MEMORY */ vm_page_queue_head_t vm_page_queue_anonymous VM_PAGE_PACKED_ALIGNED; /* inactive memory queue for anonymous pages */ vm_page_queue_head_t vm_page_queue_throttled VM_PAGE_PACKED_ALIGNED; queue_head_t vm_objects_wired; vm_page_queue_head_t vm_page_queue_donate VM_PAGE_PACKED_ALIGNED; uint32_t vm_page_donate_mode; uint32_t vm_page_donate_target, vm_page_donate_target_high, vm_page_donate_target_low; uint32_t vm_page_donate_count; bool vm_page_donate_queue_ripe; vm_page_queue_head_t vm_page_queue_background VM_PAGE_PACKED_ALIGNED; uint32_t vm_page_background_target; uint32_t vm_page_background_target_snapshot; uint32_t vm_page_background_count; uint64_t vm_page_background_promoted_count; uint32_t vm_page_background_internal_count; uint32_t vm_page_background_external_count; uint32_t vm_page_background_mode; uint32_t vm_page_background_exclude_external; unsigned int vm_page_active_count; unsigned int vm_page_inactive_count; unsigned int vm_page_kernelcache_count; #if CONFIG_SECLUDED_MEMORY unsigned int vm_page_secluded_count; unsigned int vm_page_secluded_count_free; unsigned int vm_page_secluded_count_inuse; unsigned int vm_page_secluded_count_over_target; #endif /* CONFIG_SECLUDED_MEMORY */ unsigned int vm_page_anonymous_count; unsigned int vm_page_throttled_count; unsigned int vm_page_speculative_count; unsigned int vm_page_wire_count; unsigned int vm_page_wire_count_on_boot = 0; unsigned int vm_page_stolen_count = 0; unsigned int vm_page_wire_count_initial; unsigned int vm_page_gobble_count = 0; unsigned int vm_page_kern_lpage_count = 0; uint64_t booter_size; /* external so it can be found in core dumps */ #define VM_PAGE_WIRE_COUNT_WARNING 0 #define VM_PAGE_GOBBLE_COUNT_WARNING 0 SCALABLE_COUNTER_DEFINE(vm_page_purgeable_count); SCALABLE_COUNTER_DEFINE(vm_page_purgeable_wired_count); uint64_t vm_page_purged_count = 0; /* total count of purged pages */ unsigned int vm_page_xpmapped_external_count = 0; SCALABLE_COUNTER_DEFINE(vm_page_external_count); SCALABLE_COUNTER_DEFINE(vm_page_internal_count); unsigned int vm_page_pageable_external_count = 0; unsigned int vm_page_pageable_internal_count = 0; #if DEVELOPMENT || DEBUG unsigned int vm_page_speculative_recreated = 0; unsigned int vm_page_speculative_created = 0; unsigned int vm_page_speculative_used = 0; #endif _Atomic unsigned int vm_page_shared_region_count = 0; _Atomic unsigned int vm_page_swapped_count = 0; _Atomic uint64_t vm_page_swap_count = 0; vm_page_queue_head_t vm_page_queue_cleaned VM_PAGE_PACKED_ALIGNED; unsigned int vm_page_cleaned_count = 0; uint64_t max_valid_dma_address = 0xffffffffffffffffULL; ppnum_t max_valid_low_ppnum = PPNUM_MAX; /* * Several page replacement parameters are also * shared with this module, so that page allocation * can trigger the pageout daemon. */ unsigned int vm_page_free_target = 0; unsigned int vm_page_free_min = 0; unsigned int vm_page_throttle_limit = 0; unsigned int vm_page_inactive_target = 0; #if CONFIG_SECLUDED_MEMORY unsigned int vm_page_secluded_target = 0; #endif /* CONFIG_SECLUDED_MEMORY */ unsigned int vm_page_anonymous_min = 0; unsigned int vm_page_free_reserved = 0; /* * The VM system has a couple of heuristics for deciding * that pages are "uninteresting" and should be placed * on the inactive queue as likely candidates for replacement. * These variables let the heuristics be controlled at run-time * to make experimentation easier. */ boolean_t vm_page_deactivate_hint = TRUE; struct vm_page_stats_reusable vm_page_stats_reusable; /* * vm_set_page_size: * * Sets the page size, perhaps based upon the memory * size. Must be called before any use of page-size * dependent functions. * * Sets page_shift and page_mask from page_size. */ void vm_set_page_size(void) { page_size = PAGE_SIZE; page_mask = PAGE_MASK; page_shift = PAGE_SHIFT; if ((page_mask & page_size) != 0) { panic("vm_set_page_size: page size not a power of two"); } for (page_shift = 0;; page_shift++) { if ((1U << page_shift) == page_size) { break; } } } #if HAS_MTE bool vm_page_is_tag_storage_pnum(vm_page_t mem, ppnum_t pnum) { return pmap_in_tag_storage_range(pnum) && !mteinfo_tag_storage_disabled(mem); } #endif /* * @abstract * Given a page, returns the memory class of that page. */ static vm_memory_class_t vm_page_get_memory_class(vm_page_t mem __unused, ppnum_t pnum __unused) { assert(!vm_page_is_fictitious(mem)); #if XNU_VM_HAS_LOPAGE if (mem->vmp_lopage) { return VM_MEMORY_CLASS_LOPAGE; } #endif /* XNU_VM_HAS_LOPAGE */ #if HAS_MTE if (mem->vmp_using_mte) { return VM_MEMORY_CLASS_TAGGED; } else if (!mte_enabled() || !pmap_in_tag_storage_range(pnum)) { return VM_MEMORY_CLASS_REGULAR; } else if (mteinfo_tag_storage_disabled(mem)) { return VM_MEMORY_CLASS_DEAD_TAG_STORAGE; } else { return VM_MEMORY_CLASS_TAG_STORAGE; } #else /* !HAS_MTE */ return VM_MEMORY_CLASS_REGULAR; #endif /* !HAS_MTE */ } /* * vm_page_is_restricted: * * Checks if a given vm_page_t is a restricted page. */ inline bool vm_page_is_restricted(vm_page_t mem) { ppnum_t pn = VM_PAGE_GET_PHYS_PAGE(mem); return pmap_is_page_restricted(pn); } #ifdef __x86_64__ #define MAX_CLUMP_SIZE 16 #define DEFAULT_CLUMP_SIZE 4 unsigned int vm_clump_size, vm_clump_mask, vm_clump_shift, vm_clump_promote_threshold; #if DEVELOPMENT || DEBUG unsigned long vm_clump_stats[MAX_CLUMP_SIZE + 1]; unsigned long vm_clump_allocs, vm_clump_inserts, vm_clump_inrange, vm_clump_promotes; static inline void vm_clump_update_stats(unsigned int c) { assert(c <= vm_clump_size); if (c > 0 && c <= vm_clump_size) { vm_clump_stats[c] += c; } vm_clump_allocs += c; } #endif /* if DEVELOPMENT || DEBUG */ /* Called once to setup the VM clump knobs */ static void vm_page_setup_clump( void ) { unsigned int override, n; vm_clump_size = DEFAULT_CLUMP_SIZE; if (PE_parse_boot_argn("clump_size", &override, sizeof(override))) { vm_clump_size = override; } if (vm_clump_size > MAX_CLUMP_SIZE) { panic("vm_page_setup_clump:: clump_size is too large!"); } if (vm_clump_size < 1) { panic("vm_page_setup_clump:: clump_size must be >= 1"); } if ((vm_clump_size & (vm_clump_size - 1)) != 0) { panic("vm_page_setup_clump:: clump_size must be a power of 2"); } vm_clump_promote_threshold = vm_clump_size; vm_clump_mask = vm_clump_size - 1; for (vm_clump_shift = 0, n = vm_clump_size; n > 1; n >>= 1, vm_clump_shift++) { ; } #if DEVELOPMENT || DEBUG bzero(vm_clump_stats, sizeof(vm_clump_stats)); vm_clump_allocs = vm_clump_inserts = vm_clump_inrange = vm_clump_promotes = 0; #endif /* if DEVELOPMENT || DEBUG */ } #endif /* __x86_64__ */ void vm_page_free_queue_init(vm_page_free_queue_t free_queue) { for (unsigned int color = 0; color < MAX_COLORS; color++) { vm_page_queue_init(&free_queue->vmpfq_queues[color].qhead); } } /*! * @function vm_page_free_queue_for_class() * * @abstract * Returns the appropriate free queue for the given class and page color. */ __pure2 static vm_page_queue_t vm_page_free_queue_for_class(vm_memory_class_t mem_class, unsigned int color) { switch (mem_class) { case VM_MEMORY_CLASS_REGULAR: #if HAS_MTE case VM_MEMORY_CLASS_TAGGED: case VM_MEMORY_CLASS_TAG_STORAGE: if (mte_enabled()) { return NULL; } OS_FALLTHROUGH; case VM_MEMORY_CLASS_DEAD_TAG_STORAGE: #endif return &vm_page_queue_free.vmpfq_queues[color].qhead; #if XNU_VM_HAS_LOPAGE case VM_MEMORY_CLASS_LOPAGE: return &vm_lopage_queue_free; #endif /* XNU_VM_HAS_LOPAGE */ #if CONFIG_SECLUDED_MEMORY case VM_MEMORY_CLASS_SECLUDED: return &vm_page_queue_secluded; #endif } } __pure2 static bool vm_page_free_queue_has_colors(vm_memory_class_t mem_class) { switch (mem_class) { case VM_MEMORY_CLASS_REGULAR: #if HAS_MTE case VM_MEMORY_CLASS_TAGGED: case VM_MEMORY_CLASS_TAG_STORAGE: case VM_MEMORY_CLASS_DEAD_TAG_STORAGE: #endif return true; #if XNU_VM_HAS_LOPAGE case VM_MEMORY_CLASS_LOPAGE: return false; #endif /* XNU_VM_HAS_LOPAGE */ #if CONFIG_SECLUDED_MEMORY case VM_MEMORY_CLASS_SECLUDED: return false; #endif } } #if CONFIG_SECLUDED_MEMORY static bool vm_page_secluded_pool_eligible(vm_memory_class_t class) { switch (class) { #if XNU_VM_HAS_LOPAGE case VM_MEMORY_CLASS_LOPAGE: return false; #endif /* XNU_VM_HAS_LOPAGE */ #if HAS_MTE case VM_MEMORY_CLASS_TAG_STORAGE: case VM_MEMORY_CLASS_TAGGED: return false; #endif /* HAS_MTE */ default: return true; } } static bool vm_page_secluded_pool_depleted(void) { if (vm_page_free_count <= vm_page_free_reserved) { return false; } if (num_tasks_can_use_secluded_mem) { return false; } return vm_page_secluded_count < vm_page_secluded_target; } #endif /* CONFIG_SECLUDED_MEMORY */ #if HIBERNATION __attribute__((overloadable)) static void vm_page_free_queue_foreach(vm_page_queue_t queue, void (^block)(vm_page_t)) { vm_page_t page; vm_page_queue_iterate(queue, page, vmp_pageq) { block(page); } } __attribute__((overloadable)) static void vm_page_free_queue_foreach(vm_page_free_queue_t queue, void (^block)(vm_page_t)) { for (unsigned int color = 0; color < vm_colors; color++) { vm_page_free_queue_foreach(&queue->vmpfq_queues[color].qhead, block); } } #endif /* HIBERNATION */ #if CONFIG_SPTM static inline uint32_t vm_pages_free_mask_len(void) { extern pmap_paddr_t real_avail_end; uint64_t pnums = atop(real_avail_end) - pmap_first_pnum; static_assert(8 * sizeof(__uint128_t) == MAX_COLORS); return (uint32_t)((pnums + MAX_COLORS - 1) / MAX_COLORS); } static inline int8_t vm_pages_free_mask_bit(ppnum_t pnum) { return (int8_t)(pnum & (MAX_COLORS - 1)); } static inline uint32_t vm_pages_free_mask_index(ppnum_t pnum) { return (pnum - pmap_first_pnum) / MAX_COLORS; } __pure2 static inline __uint128_t * vm_pages_free_masks(void) { return _vm_pages_free_masks; } __pure2 static inline bitmap_t * vm_pages_free_masks_as_bitmap(uint32_t index) { /* * this conversion is gross but helps with codegen for bit-wise * accesses where the __uint128_t type is really yielding poor code. * * This conversion is only legal on little endian architectures. */ #ifndef __LITTLE_ENDIAN__ #error unsupported configuration #endif return (bitmap_t *)(_vm_pages_free_masks + index); } __pure2 static inline int8_t * vm_pages_free_enqueue_idx(uint32_t index) { return &_vm_pages_free_enqueue_idx[index]; } /*! * @brief * Return the position of the next bit in "circular" order for a given cluster * of pages, starting at and including @c bit. */ static inline int8_t vm_pages_free_mask_next_bit(uint32_t index, int8_t bit) { __uint128_t value = vm_pages_free_masks()[index]; __uint128_t mask = ((__uint128_t)1 << bit) - 1; if (value == 0) { return -1; } if (value & ~mask) { value &= ~mask; } if ((uint64_t)value) { return (int8_t)__builtin_ctzll((uint64_t)value); } return 64 + (int8_t)__builtin_ctzll((uint64_t)(value >> 64)); } static inline bool vm_pages_free_mask_test(uint32_t index, int8_t bit) { return bitmap_test(vm_pages_free_masks_as_bitmap(index), bit); } static inline void vm_pages_free_mask_set(uint32_t index, int8_t bit) { assert(!vm_pages_free_mask_test(index, bit)); bitmap_set(vm_pages_free_masks_as_bitmap(index), bit); } static inline void vm_pages_free_mask_clear(uint32_t index, int8_t bit) { assert(vm_pages_free_mask_test(index, bit)); bitmap_clear(vm_pages_free_masks_as_bitmap(index), bit); } #endif /* CONFIG_SPTM */ __attribute__((always_inline)) void vm_page_free_queue_enter(vm_memory_class_t class, vm_page_t mem, ppnum_t pnum) { bool enter_first; unsigned int color; vm_page_queue_t queue; if (startup_phase >= STARTUP_SUB_KMEM) { LCK_MTX_ASSERT(&vm_page_queue_free_lock, LCK_MTX_ASSERT_OWNED); } assert(!pmap_is_noencrypt(VM_PAGE_GET_PHYS_PAGE(mem))); assert(mem->vmp_pageq.next == 0 && mem->vmp_pageq.prev == 0 && mem->vmp_listq.next == 0 && mem->vmp_listq.prev == 0 && mem->vmp_specialq.next == 0 && mem->vmp_specialq.prev == 0 && mem->vmp_next_m == 0 && mem->vmp_object == 0 && mem->vmp_wire_count == 0 && mem->vmp_busy && !mem->vmp_tabled && !mem->vmp_laundry && !mem->vmp_pmapped && !mem->vmp_wpmapped && !mem->vmp_realtime); switch (class) { #if XNU_VM_HAS_LOPAGE case VM_MEMORY_CLASS_LOPAGE: mem->vmp_q_state = VM_PAGE_ON_FREE_LOPAGE_Q; mem->vmp_on_specialq = VM_PAGE_SPECIAL_Q_EMPTY; mem->vmp_lopage = true; mem->vmp_canonical = true; enter_first = true; break; #endif /* XNU_VM_HAS_LOPAGE */ #if CONFIG_SECLUDED_MEMORY case VM_MEMORY_CLASS_SECLUDED: if (startup_phase >= STARTUP_SUB_KMEM) { LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); } #if HAS_MTE assert(!mem->vmp_using_mte); #endif /* HAS_MTE */ mem->vmp_q_state = VM_PAGE_ON_SECLUDED_Q; mem->vmp_on_specialq = VM_PAGE_SPECIAL_Q_EMPTY; mem->vmp_lopage = false; mem->vmp_canonical = true; enter_first = true; break; #endif default: mem->vmp_q_state = VM_PAGE_ON_FREE_Q; mem->vmp_on_specialq = VM_PAGE_SPECIAL_Q_EMPTY; mem->vmp_lopage = false; mem->vmp_canonical = true; enter_first = false; break; } #if HAS_MTE if (mte_enabled()) { switch (class) { case VM_MEMORY_CLASS_REGULAR: return mteinfo_covered_page_set_free(pnum, false); case VM_MEMORY_CLASS_TAGGED: return mteinfo_covered_page_set_free(pnum, true); case VM_MEMORY_CLASS_TAG_STORAGE: return mteinfo_tag_storage_set_inactive(mem, false); default: break; } } #endif /* HAS_MTE */ color = VM_PAGE_GET_COLOR_PNUM(pnum); queue = vm_page_free_queue_for_class(class, color); #if CONFIG_SPTM if (class == VM_MEMORY_CLASS_REGULAR && vm_pages_free_masks()) { uint32_t index = vm_pages_free_mask_index(pnum); int8_t bit = vm_pages_free_mask_bit(pnum); if (vm_pages_free_masks()[index] == 0) { vm_page_queue_enter(queue, mem, vmp_pageq); *vm_pages_free_enqueue_idx(index) = bit; } vm_pages_free_mask_set(index, bit); } else #endif /* CONFIG_SPTM */ if (enter_first) { vm_page_queue_enter_first(queue, mem, vmp_pageq); } else { #if defined(__x86_64__) vm_page_queue_enter_clump(queue, mem); #else vm_page_queue_enter(queue, mem, vmp_pageq); #endif } switch (class) { case VM_MEMORY_CLASS_REGULAR: VM_COUNTER_INC(&vm_page_queue_free.vmpfq_count); VM_COUNTER_INC(&vm_page_free_count); break; #if HAS_MTE case VM_MEMORY_CLASS_DEAD_TAG_STORAGE: VM_COUNTER_INC(&vm_page_queue_free.vmpfq_count); VM_COUNTER_INC(&vm_page_free_unmanaged_tag_storage_count); /* these do not participate to the vm page free count */ break; #endif #if XNU_VM_HAS_LOPAGE case VM_MEMORY_CLASS_LOPAGE: VM_COUNTER_INC(&vm_lopage_free_count); if (vm_lopage_free_count >= vm_lopage_free_limit) { vm_lopage_refill = false; } break; #endif /* XNU_VM_HAS_LOPAGE */ #if CONFIG_SECLUDED_MEMORY case VM_MEMORY_CLASS_SECLUDED: vm_page_secluded_count++; vm_page_secluded_count_free++; VM_PAGE_SECLUDED_COUNT_OVER_TARGET_UPDATE(); break; #endif /* CONFIG_SECLUDED_MEMORY */ default: __builtin_unreachable(); } } /*! * @typedef vmp_free_list_result_t * * @discussion * This data structure is used by vm_page_free_queue_add_list to track * how many pages were freed to which free lists, so that it can then drive * which waiters we are going to wake up. * * uint8_t counters are enough because we never free more than 64 pages at * a time, and this allows for the data structure to be passed by register. */ typedef struct { uint8_t vmpr_regular; #if HAS_MTE uint8_t vmpr_taggable; uint8_t vmpr_tag_storage; #endif /* HAS_MTE */ uint8_t vmpr_lopage; #if CONFIG_SECLUDED_MEMORY uint8_t vmpr_secluded; #endif /* CONFIG_SECLUDED_MEMORY */ } vmp_free_list_result_t; /*! * @abstract * Returns whether there are any threads blocked in VM_PAGE_WAIT(). * * @discussion * The page free queue lock must be held. */ static bool vm_page_free_queue_has_any_waiters(void) { uint32_t result = 0; result |= vm_page_free_wanted; result |= vm_page_free_wanted_privileged; #if HAS_MTE result |= vm_page_free_wanted_tagged; result |= vm_page_free_wanted_tagged_privileged; #endif /* HAS_MTE */ #if CONFIG_SECLUDED_MEMORY result |= vm_page_free_wanted_secluded; #endif /* CONFIG_SECLUDED_MEMORY */ return result != 0; } void vm_page_free_wakeup(event_t event, uint32_t n) { if (vps_dynamic_priority_enabled) { if (n == UINT32_MAX) { wakeup_all_with_inheritor(event, THREAD_AWAKENED); } else { while (n-- > 0) { wakeup_one_with_inheritor(event, THREAD_AWAKENED, LCK_WAKE_DO_NOT_TRANSFER_PUSH, NULL); } } } else { thread_wakeup_nthreads(event, n); } } /*! * @abstract * Helper to wakeup threads in VM_PAGE_WAIT() given * a vm_page_free_queue_enter_list() result. * * @discussion * The page free queue lock must be held, and is unlocked on return. * * @param vmpr The result of a vm_page_free_queue_enter_list() call. */ __attribute__((noinline)) static void vm_page_free_queue_handle_wakeups_and_unlock(vmp_free_list_result_t vmpr) { unsigned int need_wakeup = 0; unsigned int need_priv_wakeup = 0; #if CONFIG_SECLUDED_MEMORY unsigned int need_wakeup_secluded = 0; #endif /* CONFIG_SECLUDED_MEMORY */ unsigned int unpriv_limit; #if HAS_MTE unsigned int need_tagged_wakeup = 0; unsigned int need_priv_tagged_wakeup = 0; unsigned int unpriv_tagged_limit; unsigned int n; bool wakeup_refill_thread = false; #endif /* HAS_MTE */ #define DONATE_TO_WAITERS(wake, count, waiters_count, limit) ({ \ uint32_t __n = MIN(MIN(waiters_count, vmpr.count), limit); \ waiters_count -= __n; \ vmpr.count -= __n; \ wake += __n; \ __n; \ }) /* * Step 1: privileged waiters get to be satisfied first */ #if HAS_MTE if (vm_page_free_wanted_tagged_privileged) { DONATE_TO_WAITERS(need_priv_tagged_wakeup, vmpr_taggable, vm_page_free_wanted_tagged_privileged, UINT32_MAX); /* * If we will not wake up privileged threads, and there are * tagged privileged waiters, we need the refill thread to do * an emergency activation or reclaim to fulfill this need. * * We need to at least have 2 extra free pages because the * reclaim path might require to relocate a page to give us one. */ if (!need_priv_tagged_wakeup && vm_page_free_count >= vm_page_free_taggable_count + 2) { wakeup_refill_thread = true; } } #endif /* HAS_MTE */ if (vm_page_free_wanted_privileged) { DONATE_TO_WAITERS(need_priv_wakeup, vmpr_regular, vm_page_free_wanted_privileged, UINT32_MAX); #if HAS_MTE DONATE_TO_WAITERS(need_priv_wakeup, vmpr_taggable, vm_page_free_wanted_privileged, UINT32_MAX); #endif /* HAS_MTE */ } /* * Step 2: the privileged reserve needs to be replenished * * Let's make sure that we only wake up regular threads * for free pages above the reserve threshold. */ if (vm_page_free_count <= vm_page_free_reserved) { unpriv_limit = 0; } else { unpriv_limit = vm_page_free_count - vm_page_free_reserved; } #if HAS_MTE if (vm_page_free_taggable_count <= vm_page_free_reserved) { unpriv_tagged_limit = 0; } else { unpriv_tagged_limit = vm_page_free_taggable_count - vm_page_free_reserved; } #endif /* HAS_MTE */ /* * Step 3: satisfy secluded waiters, using the secluded pool first, * regular pages second. */ #if CONFIG_SECLUDED_MEMORY if (vm_page_free_wanted_secluded) { DONATE_TO_WAITERS(need_wakeup_secluded, vmpr_secluded, vm_page_free_wanted_secluded, UINT32_MAX); unpriv_limit -= DONATE_TO_WAITERS(need_wakeup_secluded, vmpr_regular, vm_page_free_wanted_secluded, unpriv_limit); if (vm_page_free_wanted_secluded == 0) { need_wakeup_secluded = UINT32_MAX; } } #endif /* CONFIG_SECLUDED_MEMORY */ /* * Step 4: satisfy regular demand last. */ #if HAS_MTE if (vm_page_free_wanted_tagged) { n = DONATE_TO_WAITERS(need_tagged_wakeup, vmpr_taggable, vm_page_free_wanted_tagged, MIN(unpriv_limit, unpriv_tagged_limit)); unpriv_limit -= n; unpriv_tagged_limit -= n; if (vm_page_free_wanted_tagged == 0) { need_tagged_wakeup = UINT32_MAX; } else if (vm_page_free_count >= MAX(vm_page_free_taggable_count + 2, vm_page_free_min)) { /* * If we still have tagged waiters, and that rebalancing * pages would get us above vm_page_free_min, then wake * up the refill thread to help do that rebalance. */ wakeup_refill_thread = true; } } #endif /* HAS_MTE */ if (vm_page_free_wanted) { unpriv_limit -= DONATE_TO_WAITERS(need_wakeup, vmpr_regular, vm_page_free_wanted, unpriv_limit); #if HAS_MTE n = DONATE_TO_WAITERS(need_wakeup, vmpr_taggable, vm_page_free_wanted, MIN(unpriv_limit, unpriv_tagged_limit)); unpriv_limit -= n; unpriv_tagged_limit -= n; #endif /* HAS_MTE */ if (vm_page_free_wanted == 0) { need_wakeup = UINT32_MAX; } } /* * We have updated waiter counts, and if that release page happens * from the context of a thread that's super low priority we might * starve waking up privileged threads. * * While we hold the free page lock, such threads would wake us up via * the mutex priority inheritance mechanism, but as soon as we drop the * lock all bets are off. * * To avoid this priority inversion that could really hurt the VM, * disable preemption until we've woken up everyone. */ disable_preemption(); vm_free_page_unlock(); /* * Dispatch privileged wakeups * * There shouldn't be that many VM-privileged threads, * so let's wake them all up, even if we don't quite * have enough pages to satisfy them all. */ if (need_priv_wakeup) { vm_page_free_wakeup(&vm_page_free_wanted_privileged, UINT32_MAX); } if (need_wakeup) { vm_page_free_wakeup(&vm_page_free_count, need_wakeup); } #if HAS_MTE if (need_priv_tagged_wakeup) { vm_page_free_wakeup(&vm_page_free_wanted_tagged_privileged, UINT32_MAX); } if (need_tagged_wakeup) { vm_page_free_wakeup(&vm_page_free_wanted_tagged, need_tagged_wakeup); } if (wakeup_refill_thread) { mteinfo_wake_fill_thread(); } #endif /* HAS_MTE */ #if CONFIG_SECLUDED_MEMORY if (need_wakeup_secluded) { vm_page_free_wakeup(&vm_page_free_wanted_secluded, need_wakeup_secluded); } #endif /* CONFIG_SECLUDED_MEMORY */ enable_preemption(); #undef DONATE_TO_WAITERS } /* * @abstract * Given a list of pages, put each page on whichever global free queue is * appropriate. * * @discussion * Must be called with the VM free page lock unlocked. * * The list must contain less than 255 elements. */ #if HAS_MTE /* * To put it more bluntly: this will demux pages onto the free tag storage * queue or the global free queue, as appropriate. If we start freeing tagged * pages onto the free tagged queue, this function should be updated to deal * with that too. */ #endif /* HAS_MTE */ static void vm_page_free_queue_enter_list(vm_page_list_t list, vmp_release_options_t opts) { bool page_queues_unlock = false; bool page_queues_locked = false; bool do_secluded = false; vmp_free_list_result_t result = { }; vm_page_t mem; LCK_MTX_ASSERT(&vm_page_queue_lock, (opts & VMP_RELEASE_Q_LOCKED) ? LCK_MTX_ASSERT_OWNED : LCK_MTX_ASSERT_NOTOWNED); /* * Hibernation and startup do not really need the lock because * these are single threaded paths, so from the PoV of that function, * it's as if VMP_RELEASE_Q_LOCKED was passed. */ page_queues_locked = (opts & (VMP_RELEASE_STARTUP | VMP_RELEASE_HIBERNATE | VMP_RELEASE_Q_LOCKED)); #if CONFIG_SECLUDED_MEMORY do_secluded = vm_page_secluded_pool_depleted(); #if HAS_MTE if (do_secluded && list.vmpl_has_tagged && (opts & VMP_RELEASE_Q_LOCKED) == 0) { /* * Try to do the untagging so that pages become eligible * for the secluded pool while holding the least amount * of locks possible. * * This does mean we shouldn't do this retyping if the page * queue lock is held for real. The only path doing this * right now is vm_page_free() which is one page at a time, * so it's probably "fine" to not contribute these to the * secluded pool. * * Note that we don't update `vmp_using_mte` or the list * `vmpl_has_[un]tagged` fields until we have the free queue * lock. We also need to update MTE Info about these * tagging changes. */ const unified_page_list_t pmap_batch_list = { .page_slist = list.vmpl_head, .type = UNIFIED_PAGE_LIST_TYPE_VM_PAGE_LIST, }; pmap_unmake_tagged_pages(&pmap_batch_list); } #endif /* HAS_MTE */ #endif /* CONFIG_SECLUDED_MEMORY */ if (!page_queues_locked && (list.vmpl_has_realtime || do_secluded)) { vm_page_lock_queues(); page_queues_locked = true; page_queues_unlock = true; } if (opts & VMP_RELEASE_STARTUP) { LCK_MTX_ASSERT(&vm_page_queue_free_lock, LCK_MTX_ASSERT_OWNED); } else { vm_free_page_lock_spin(); } #if CONFIG_SECLUDED_MEMORY && HAS_MTE if (do_secluded && list.vmpl_has_tagged && (opts & VMP_RELEASE_Q_LOCKED) == 0) { /* * Update the pages and list metadata, as well as MTE Info. * * Since secluded pages are managed separately from the global * free queue, we don't want MTE Info to think these pages are * free, so we just clear the tagging. */ vm_page_list_foreach(mem, list) { if (mem->vmp_using_mte) { mteinfo_covered_page_clear_tagged(VM_PAGE_GET_PHYS_PAGE(mem)); } mem->vmp_using_mte = false; } list.vmpl_has_tagged = false; list.vmpl_has_untagged = true; } #endif /* CONFIG_SECLUDED_MEMORY && HAS_MTE */ vm_page_list_foreach_consume(mem, &list) { ppnum_t pnum = VM_PAGE_GET_PHYS_PAGE(mem); vm_memory_class_t class = vm_page_get_memory_class(mem, pnum); if (mem->vmp_realtime) { mem->vmp_realtime = false; VM_COUNTER_DEC(&vm_page_realtime_count); } #if XNU_VM_HAS_LOPAGE if ((class == VM_MEMORY_CLASS_REGULAR || class == VM_MEMORY_CLASS_LOPAGE) && vm_lopage_refill && vm_lopage_free_count < vm_lopage_free_limit && pnum < max_valid_low_ppnum) { class = VM_MEMORY_CLASS_LOPAGE; } else { class = VM_MEMORY_CLASS_REGULAR; } #endif /* XNU_VM_HAS_LOPAGE */ #if CONFIG_SECLUDED_MEMORY /* * XXX FBDP TODO: also avoid refilling secluded queue * when some IOKit objects are already grabbing from it... */ if (page_queues_locked && vm_page_secluded_pool_eligible(class) && vm_page_secluded_pool_depleted()) { class = VM_MEMORY_CLASS_SECLUDED; } #endif /* CONFIG_SECLUDED_MEMORY */ vm_page_free_queue_enter(class, mem, pnum); switch (class) { case VM_MEMORY_CLASS_REGULAR: #if HAS_MTE if (mte_enabled() && mteinfo_covered_page_taggable(pnum)) { result.vmpr_taggable++; break; } OS_FALLTHROUGH; case VM_MEMORY_CLASS_DEAD_TAG_STORAGE: #endif /* HAS_MTE */ result.vmpr_regular++; break; #if HAS_MTE case VM_MEMORY_CLASS_TAGGED: result.vmpr_taggable++; break; case VM_MEMORY_CLASS_TAG_STORAGE: result.vmpr_tag_storage++; break; #endif /* HAS_MTE */ #if XNU_VM_HAS_LOPAGE case VM_MEMORY_CLASS_LOPAGE: result.vmpr_lopage++; break; #endif /* XNU_VM_HAS_LOPAGE */ #if CONFIG_SECLUDED_MEMORY case VM_MEMORY_CLASS_SECLUDED: result.vmpr_secluded++; continue; #endif /* CONFIG_SECLUDED_MEMORY */ } } if (page_queues_unlock) { vm_page_unlock_queues(); } vm_pageout_vminfo.vm_page_pages_freed += list.vmpl_count; VM_DEBUG_CONSTANT_EVENT(vm_page_release, DBG_VM_PAGE_RELEASE, DBG_FUNC_NONE, list.vmpl_count, 0, 0, 0); if (opts & VMP_RELEASE_STARTUP) { /* * On purpose skip the VM_CHECK_MEMORYSTATUS, * pmap_startup() will do it, * and the caller holds the free queue lock the whole time. */ return; } if (vm_page_free_queue_has_any_waiters()) { vm_page_free_queue_handle_wakeups_and_unlock(result); } else { vm_free_page_unlock(); } if ((opts & VMP_RELEASE_HIBERNATE) == 0) { /* * Skip VM_CHECK_MEMORYSTATUS here as * hibernate_rebuild_vm_structs() will run it after the last flush. */ VM_CHECK_MEMORYSTATUS; } } __attribute__((always_inline)) void vm_page_free_queue_remove( vm_memory_class_t class, vm_page_t mem, ppnum_t pnum, vm_page_q_state_t q_state) { unsigned int color; vm_page_queue_t queue; if (startup_phase >= STARTUP_SUB_KMEM) { LCK_MTX_ASSERT(&vm_page_queue_free_lock, LCK_MTX_ASSERT_OWNED); } mem->vmp_q_state = q_state; #if HAS_MTE if (mte_enabled()) { switch (class) { case VM_MEMORY_CLASS_REGULAR: return mteinfo_covered_page_set_used(pnum, false); case VM_MEMORY_CLASS_TAGGED: return mteinfo_covered_page_set_used(pnum, true); case VM_MEMORY_CLASS_TAG_STORAGE: return mteinfo_tag_storage_set_claimed(mem); default: break; } } #endif /* HAS_MTE */ color = VM_PAGE_GET_COLOR_PNUM(pnum); queue = vm_page_free_queue_for_class(class, color); #if CONFIG_SPTM if (class == VM_MEMORY_CLASS_REGULAR && vm_pages_free_masks()) { uint32_t index = vm_pages_free_mask_index(pnum); int8_t bit = vm_pages_free_mask_bit(pnum); vm_pages_free_mask_clear(index, bit); if (*vm_pages_free_enqueue_idx(index) == bit) { vm_page_queue_remove(queue, mem, vmp_pageq); bit = vm_pages_free_mask_next_bit(index, bit); *vm_pages_free_enqueue_idx(index) = bit; if (bit != -1) { assert(vm_pages_free_mask_test(index, bit)); pnum = (pnum & -MAX_COLORS) + bit; mem = vm_page_find_canonical(pnum); color = VM_PAGE_GET_COLOR_PNUM(pnum); queue = vm_page_free_queue_for_class(class, color); vm_page_queue_enter(queue, mem, vmp_pageq); } } } else #endif /* CONFIG_SPTM */ { vm_page_queue_remove(queue, mem, vmp_pageq); } switch (class) { case VM_MEMORY_CLASS_REGULAR: VM_COUNTER_DEC(&vm_page_queue_free.vmpfq_count); VM_COUNTER_DEC(&vm_page_free_count); break; #if HAS_MTE case VM_MEMORY_CLASS_DEAD_TAG_STORAGE: VM_COUNTER_DEC(&vm_page_queue_free.vmpfq_count); VM_COUNTER_DEC(&vm_page_free_unmanaged_tag_storage_count); /* these do not participate to the vm page free count */ break; #endif /* HAS_MTE */ #if XNU_VM_HAS_LOPAGE case VM_MEMORY_CLASS_LOPAGE: VM_COUNTER_DEC(&vm_lopage_free_count); vm_lopages_allocated_q += 1; if (vm_lopage_free_count < vm_lopage_lowater) { vm_lopage_refill = true; } break; #endif /* XNU_VM_HAS_LOPAGE */ default: __builtin_unreachable(); } } vm_page_list_t vm_page_free_queue_grab( vm_page_pcpu_t vmp_pcpu, vm_grab_options_t options __unused, vm_memory_class_t class, unsigned int num_pages, vm_page_q_state_t q_state) { unsigned int color; #if defined(__x86_64__) unsigned int clump_end = 1; unsigned int sub_count = 0; #endif /* __x86_64__ */ vm_page_list_t list = { }; if (startup_phase >= STARTUP_SUB_KMEM) { LCK_MTX_ASSERT(&vm_page_queue_free_lock, LCK_MTX_ASSERT_OWNED); } assert(get_preemption_level() != 0); assert3u(q_state, <, VM_PAGE_NUM_Q_STATES); #if HAS_MTE if (mte_enabled() && class != VM_MEMORY_CLASS_DEAD_TAG_STORAGE) { return mteinfo_free_queue_grab(vmp_pcpu, options, class, num_pages, q_state); } #endif /* HAS_MTE */ color = vmp_pcpu->start_color; /* Get the pages. */ while (list.vmpl_count < num_pages) { uint32_t color_offset = 1; vm_page_queue_t queue; vm_page_t mem; queue = vm_page_free_queue_for_class(class, color); if (!vm_page_free_queue_has_colors(class)) { assert(!vm_page_queue_empty(queue)); color_offset = 0; } while (vm_page_queue_empty(queue)) { color = (color + 1) & vm_color_mask; queue = vm_page_free_queue_for_class(class, color); } #if defined(__x86_64__) if (class == VM_MEMORY_CLASS_REGULAR) { /* * x86_64 uses a bespoke free queue scheme, where the free path * tries to cluster clumps of contiguous pages together on * the free queue to optimize for the platform's memory * controller. */ vm_page_queue_remove_first_with_clump(queue, mem, clump_end); sub_count++; if (clump_end) { #if DEVELOPMENT || DEBUG vm_clump_update_stats(sub_count); #endif /* !DEVELOPMENT && !DEBUG */ sub_count = 0; } else { /* Only change colors at the end of a clump. */ color_offset = 0; } } else #endif /* !defined(__x86_64__) */ { /* Other targets default to rotating colors after each pop. */ vm_page_queue_remove_first(queue, mem, vmp_pageq); } #if CONFIG_SPTM if (vm_pages_free_masks()) { ppnum_t pnum = VM_PAGE_GET_PHYS_PAGE(mem); ppnum_t first_pnum = pnum & -MAX_COLORS; uint32_t index = vm_pages_free_mask_index(pnum); int8_t bit = vm_pages_free_mask_bit(pnum); for (;;) { vm_pages_free_mask_clear(index, bit); mem->vmp_q_state = q_state; vm_page_list_push(&list, mem); bit = (bit + 1) & (MAX_COLORS - 1); if (!vm_pages_free_mask_test(index, bit) || num_pages <= list.vmpl_count) { break; } mem = vm_page_find_canonical(first_pnum + bit); } color = bit & vm_color_mask; bit = vm_pages_free_mask_next_bit(index, bit); *vm_pages_free_enqueue_idx(index) = bit; if (bit != -1) { assert(vm_pages_free_mask_test(index, bit)); mem = vm_page_find_canonical(first_pnum + bit); queue = vm_page_free_queue_for_class(class, bit & vm_color_mask); vm_page_queue_enter_first(queue, mem, vmp_pageq); } } else #endif /* CONFIG_SPTM */ { /* Set the page to the client's desired queue state. */ mem->vmp_q_state = q_state; vm_page_list_push(&list, mem); color = (color + color_offset) & vm_color_mask; } } switch (class) { case VM_MEMORY_CLASS_REGULAR: VM_COUNTER_SUB(&vm_page_queue_free.vmpfq_count, list.vmpl_count); VM_COUNTER_SUB(&vm_page_free_count, list.vmpl_count); break; #if HAS_MTE case VM_MEMORY_CLASS_DEAD_TAG_STORAGE: VM_COUNTER_SUB(&vm_page_queue_free.vmpfq_count, list.vmpl_count); VM_COUNTER_SUB(&vm_page_free_unmanaged_tag_storage_count, list.vmpl_count); /* these do not participate to the vm page free count */ break; #endif /* HAS_MTE */ #if XNU_VM_HAS_LOPAGE case VM_MEMORY_CLASS_LOPAGE: VM_COUNTER_SUB(&vm_lopage_free_count, list.vmpl_count); vm_lopages_allocated_q += list.vmpl_count; if (vm_lopage_free_count < vm_lopage_lowater) { vm_lopage_refill = true; } break; #endif /* XNU_VM_HAS_LOPAGE */ default: __builtin_unreachable(); } /* Record the next page color the CPU should try to get. */ vmp_pcpu->start_color = color; #if defined(__x86_64__) && (DEVELOPMENT || DEBUG) vm_clump_update_stats(sub_count); #endif /* defined(__x86_64__) && (DEVELOPMENT || DEBUG) */ return list; } #define COLOR_GROUPS_TO_STEAL 4 /* Called once during statup, once the cache geometry is known. */ static void vm_page_set_colors( void ) { unsigned int n, override; #if defined (__x86_64__) /* adjust #colors because we need to color outside the clump boundary */ vm_cache_geometry_colors >>= vm_clump_shift; #endif if (PE_parse_boot_argn("colors", &override, sizeof(override))) { /* colors specified as a boot-arg? */ n = override; } else if (vm_cache_geometry_colors) { /* do we know what the cache geometry is? */ n = vm_cache_geometry_colors; } else { n = DEFAULT_COLORS; /* use default if all else fails */ } if (n == 0) { n = 1; } if (n > MAX_COLORS) { n = MAX_COLORS; } /* the count must be a power of 2 */ if ((n & (n - 1)) != 0) { n = DEFAULT_COLORS; /* use default if all else fails */ } vm_colors = n; vm_color_mask = n - 1; vm_free_magazine_refill_limit = vm_colors * COLOR_GROUPS_TO_STEAL; #if defined (__x86_64__) /* adjust for reduction in colors due to clumping and multiple cores */ if (real_ncpus) { vm_free_magazine_refill_limit *= (vm_clump_size * real_ncpus); } #endif } #if XNU_VM_HAS_DELAYED_PAGES static uint32_t vm_delayed_count = 0; /* when non-zero, indicates we may have more pages to init */ static ppnum_t delay_above_pnum = PPNUM_MAX; /* * For x86 first 8 Gig initializes quickly and gives us lots of lowmem + mem above to start off with. * If ARM ever uses delayed page initialization, this value may need to be quite different. */ #define DEFAULT_DELAY_ABOVE_PHYS_GB (8) /* * When we have to dip into more delayed pages due to low memory, free up * a large chunk to get things back to normal. This avoids contention on the * delayed code allocating page by page. */ #define VM_DELAY_PAGE_CHUNK ((1024 * 1024 * 1024) / PAGE_SIZE) /* * Get and initialize the next delayed page. */ __attribute__((noinline)) static vm_page_t vm_get_delayed_page(vm_grab_options_t grab_options) { vm_page_t p; ppnum_t pnum; /* * Get a new page if we have one. */ vm_free_page_lock(); if (vm_delayed_count == 0) { vm_free_page_unlock(); return NULL; } if (!pmap_next_page(&pnum)) { vm_delayed_count = 0; vm_free_page_unlock(); return NULL; } assert(vm_delayed_count > 0); --vm_delayed_count; #if defined(__x86_64__) /* x86 cluster code requires increasing phys_page in vm_pages[] */ if (vm_pages_count > 0) { assert(pnum > vm_page_get(vm_pages_count - 1)->vmp_phys_page); } #endif p = vm_page_get(vm_pages_count); assert(p < vm_pages_end); vm_page_init(p, pnum); ++vm_pages_count; ++vm_page_pages; vm_free_page_unlock(); /* * These pages were initially counted as wired, undo that now. */ if (grab_options & VM_PAGE_GRAB_Q_LOCK_HELD) { LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); } else { LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_NOTOWNED); vm_page_lockspin_queues(); } --vm_page_wire_count; --vm_page_wire_count_initial; if (vm_page_wire_count_on_boot != 0) { --vm_page_wire_count_on_boot; } if (!(grab_options & VM_PAGE_GRAB_Q_LOCK_HELD)) { vm_page_unlock_queues(); } if (fillval) { fillPage(pnum, fillval); } return p; } /* * Free all remaining delayed pages to the free lists. */ void vm_free_delayed_pages(void) { vm_page_t p; vm_page_t list = NULL; uint_t cnt = 0; vm_offset_t start_free_va; int64_t free_size; while ((p = vm_get_delayed_page(VM_PAGE_GRAB_OPTIONS_NONE)) != NULL) { if (vm_himemory_mode) { vm_page_release(p, VMP_RELEASE_NONE); } else { p->vmp_snext = list; list = p; } ++cnt; } /* * Free the pages in reverse order if not himemory mode. * Hence the low memory pages will be first on free lists. (LIFO) */ while (list != NULL) { p = list; list = p->vmp_snext; p->vmp_snext = NULL; vm_page_release(p, VMP_RELEASE_NONE); } #if DEVELOPMENT || DEBUG kprintf("vm_free_delayed_pages: initialized %d free pages\n", cnt); #endif /* * Free up any unused full pages at the end of the vm_pages[] array */ start_free_va = round_page((vm_offset_t)vm_page_get(vm_pages_count)); #if defined(__x86_64__) /* * Since x86 might have used large pages for vm_pages[], we can't * free starting in the middle of a partially used large page. */ if (pmap_query_pagesize(kernel_pmap, start_free_va) == I386_LPGBYTES) { start_free_va = ((start_free_va + I386_LPGMASK) & ~I386_LPGMASK); } #endif if (start_free_va < (vm_offset_t)vm_pages_end) { free_size = trunc_page((vm_offset_t)vm_pages_end - start_free_va); if (free_size > 0) { ml_static_mfree(start_free_va, (vm_offset_t)free_size); vm_pages_end = (void *)start_free_va; /* * Note there's no locking here, as only this thread will ever change this value. * The reader, vm_page_diagnose, doesn't grab any locks for the counts it looks at. */ vm_page_stolen_count -= (free_size >> PAGE_SHIFT); #if DEVELOPMENT || DEBUG kprintf("Freeing final unused %ld bytes from vm_pages[] at 0x%lx\n", (long)free_size, (long)start_free_va); #endif } } } /* * Try and free up enough delayed pages to match a contig memory allocation. */ static void vm_free_delayed_pages_contig( uint_t npages, ppnum_t max_pnum, ppnum_t pnum_mask) { vm_page_t p; ppnum_t pnum; uint_t cnt = 0; /* * Treat 0 as the absolute max page number. */ if (max_pnum == 0) { max_pnum = PPNUM_MAX; } /* * Free till we get a properly aligned start page */ for (;;) { p = vm_get_delayed_page(VM_PAGE_GRAB_OPTIONS_NONE); if (p == NULL) { return; } pnum = VM_PAGE_GET_PHYS_PAGE(p); vm_page_release(p, VMP_RELEASE_NONE); if (pnum >= max_pnum) { return; } if ((pnum & pnum_mask) == 0) { break; } } /* * Having a healthy pool of free pages will help performance. We don't * want to fall back to the delayed code for every page allocation. */ if (vm_page_free_count < VM_DELAY_PAGE_CHUNK) { npages += VM_DELAY_PAGE_CHUNK; } /* * Now free up the pages */ for (cnt = 1; cnt < npages; ++cnt) { p = vm_get_delayed_page(VM_PAGE_GRAB_OPTIONS_NONE); if (p == NULL) { return; } vm_page_release(p, VMP_RELEASE_NONE); } } #endif /* XNU_VM_HAS_DELAYED_PAGES */ #define ROUNDUP_NEXTP2(X) (1U << (32 - __builtin_clz((X) - 1))) void vm_page_init_local_q(unsigned int num_cpus) { struct vpl *t_local_q; /* * no point in this for a uni-processor system */ if (num_cpus >= 2) { ml_cpu_info_t cpu_info; /* * Force the allocation alignment to a cacheline, * because the `vpl` struct has a lock and will be taken * cross CPU so we want to isolate the rest of the per-CPU * data to avoid false sharing due to this lock being taken. */ ml_cpu_get_info(&cpu_info); t_local_q = zalloc_percpu_permanent(sizeof(struct vpl), cpu_info.cache_line_size - 1); zpercpu_foreach(lq, t_local_q) { VPL_LOCK_INIT(lq, &vm_page_lck_grp_local, &vm_page_lck_attr); vm_page_queue_init(&lq->vpl_queue); } /* make the initialization visible to all cores */ os_atomic_store(&vm_page_local_q, t_local_q, release); } } /* * vm_init_before_launchd * * This should be called right before launchd is loaded. */ void vm_init_before_launchd(void) { vm_page_lockspin_queues(); vm_page_wire_count_on_boot = vm_page_wire_count; vm_page_unlock_queues(); } /* * vm_page_bootstrap: * * Initializes the resident memory module. * * Allocates memory for the page cells, and * for the object/offset-to-page hash table headers. * Each page cell is initialized and placed on the free list. * Returns the range of available kernel virtual memory. */ __startup_func void vm_page_bootstrap( vm_offset_t *startp, vm_offset_t *endp) { unsigned int i; unsigned int log1; unsigned int log2; unsigned int size; /* * Initialize the page queues. */ lck_mtx_init(&vm_page_queue_free_lock, &vm_page_lck_grp_free, &vm_page_lck_attr); lck_mtx_init(&vm_page_queue_lock, &vm_page_lck_grp_queue, &vm_page_lck_attr); lck_mtx_init(&vm_purgeable_queue_lock, &vm_page_lck_grp_purge, &vm_page_lck_attr); for (i = 0; i < PURGEABLE_Q_TYPE_MAX; i++) { int group; purgeable_queues[i].token_q_head = 0; purgeable_queues[i].token_q_tail = 0; for (group = 0; group < NUM_VOLATILE_GROUPS; group++) { queue_init(&purgeable_queues[i].objq[group]); } purgeable_queues[i].type = i; purgeable_queues[i].new_pages = 0; #if MACH_ASSERT purgeable_queues[i].debug_count_tokens = 0; purgeable_queues[i].debug_count_objects = 0; #endif } ; purgeable_nonvolatile_count = 0; queue_init(&purgeable_nonvolatile_queue); vm_page_free_queue_init(&vm_page_queue_free); #if XNU_VM_HAS_LOPAGE vm_page_queue_init(&vm_lopage_queue_free); #endif /* XNU_VM_HAS_LOPAGE */ vm_page_queue_init(&vm_page_queue_active); vm_page_queue_init(&vm_page_queue_inactive); #if CONFIG_SECLUDED_MEMORY vm_page_queue_init(&vm_page_queue_secluded); #endif /* CONFIG_SECLUDED_MEMORY */ vm_page_queue_init(&vm_page_queue_cleaned); vm_page_queue_init(&vm_page_queue_throttled); vm_page_queue_init(&vm_page_queue_anonymous); queue_init(&vm_objects_wired); for (i = 0; i <= vm_page_max_speculative_age_q; i++) { vm_page_queue_init(&vm_page_queue_speculative[i].age_q); vm_page_queue_speculative[i].age_ts.tv_sec = 0; vm_page_queue_speculative[i].age_ts.tv_nsec = 0; } vm_page_queue_init(&vm_page_queue_donate); vm_page_queue_init(&vm_page_queue_background); vm_page_background_count = 0; vm_page_background_internal_count = 0; vm_page_background_external_count = 0; vm_page_background_promoted_count = 0; vm_page_background_target = (unsigned int)(atop_64(max_mem) / 25); if (vm_page_background_target > VM_PAGE_BACKGROUND_TARGET_MAX) { vm_page_background_target = VM_PAGE_BACKGROUND_TARGET_MAX; } #if defined(__LP64__) vm_page_background_mode = VM_PAGE_BG_ENABLED; vm_page_donate_mode = VM_PAGE_DONATE_ENABLED; #else vm_page_background_mode = VM_PAGE_BG_DISABLED; vm_page_donate_mode = VM_PAGE_DONATE_DISABLED; #endif vm_page_background_exclude_external = 0; PE_parse_boot_argn("vm_page_bg_mode", &vm_page_background_mode, sizeof(vm_page_background_mode)); PE_parse_boot_argn("vm_page_bg_exclude_external", &vm_page_background_exclude_external, sizeof(vm_page_background_exclude_external)); PE_parse_boot_argn("vm_page_bg_target", &vm_page_background_target, sizeof(vm_page_background_target)); if (vm_page_background_mode != VM_PAGE_BG_DISABLED && vm_page_background_mode != VM_PAGE_BG_ENABLED) { vm_page_background_mode = VM_PAGE_BG_DISABLED; } PE_parse_boot_argn("vm_page_donate_mode", &vm_page_donate_mode, sizeof(vm_page_donate_mode)); if (vm_page_donate_mode != VM_PAGE_DONATE_DISABLED && vm_page_donate_mode != VM_PAGE_DONATE_ENABLED) { vm_page_donate_mode = VM_PAGE_DONATE_DISABLED; } vm_page_donate_target_high = VM_PAGE_DONATE_TARGET_HIGHWATER; vm_page_donate_target_low = VM_PAGE_DONATE_TARGET_LOWWATER; vm_page_donate_target = vm_page_donate_target_high; vm_page_donate_count = 0; vm_page_free_wanted = 0; vm_page_free_wanted_privileged = 0; #if CONFIG_SECLUDED_MEMORY vm_page_free_wanted_secluded = 0; #endif /* CONFIG_SECLUDED_MEMORY */ #if defined (__x86_64__) /* this must be called before vm_page_set_colors() */ vm_page_setup_clump(); #endif vm_page_set_colors(); for (vm_tag_t t = 0; t < VM_KERN_MEMORY_FIRST_DYNAMIC; t++) { vm_allocation_sites_static[t].refcount = 2; vm_allocation_sites_static[t].tag = t; vm_allocation_sites[t] = &vm_allocation_sites_static[t]; } vm_allocation_sites_static[VM_KERN_MEMORY_FIRST_DYNAMIC].refcount = 2; vm_allocation_sites_static[VM_KERN_MEMORY_FIRST_DYNAMIC].tag = VM_KERN_MEMORY_ANY; vm_allocation_sites[VM_KERN_MEMORY_ANY] = &vm_allocation_sites_static[VM_KERN_MEMORY_FIRST_DYNAMIC]; /* * Steal memory for the map and zone subsystems. * * make sure initialize_ram_ranges() has run before we steal pages for the first time on arm */ (void)pmap_free_pages(); kernel_startup_initialize_upto(STARTUP_SUB_PMAP_STEAL); /* * Allocate (and initialize) the virtual-to-physical * table hash buckets. * * The number of buckets should be a power of two to * get a good hash function. The following computation * chooses the first power of two that is greater * than the number of physical pages in the system. */ vm_page_bucket_count = 1u << fls(pmap_free_pages()); vm_page_hash_mask = vm_page_bucket_count - 1; vm_page_bucket_lock_count = (vm_page_bucket_count + BUCKETS_PER_LOCK - 1) / BUCKETS_PER_LOCK; /* * Calculate object shift value for hashing algorithm: * O = log2(sizeof(struct vm_object)) * B = log2(vm_page_bucket_count) * hash shifts the object left by * B/2 - O */ size = vm_page_bucket_count; for (log1 = 0; size > 1; log1++) { size /= 2; } size = sizeof(struct vm_object); for (log2 = 0; size > 1; log2++) { size /= 2; } vm_page_hash_shift = log1 / 2 - log2 + 1; vm_page_bucket_hash = 1 << ((log1 + 1) >> 1); /* Get (ceiling of sqrt of table size) */ vm_page_bucket_hash |= 1 << ((log1 + 1) >> 2); /* Get (ceiling of quadroot of table size) */ vm_page_bucket_hash |= 1; /* Set bit and add 1 - always must be 1 to insure unique series */ if (vm_page_hash_mask & vm_page_bucket_count) { printf("vm_page_bootstrap: WARNING -- strange page hash\n"); } #if VM_PAGE_BUCKETS_CHECK #if VM_PAGE_FAKE_BUCKETS /* * Allocate a decoy set of page buckets, to detect * any stomping there. */ vm_page_fake_buckets = (vm_page_bucket_t *) pmap_steal_memory(vm_page_bucket_count * sizeof(vm_page_bucket_t), 0); vm_page_fake_buckets_start = (vm_map_offset_t) vm_page_fake_buckets; vm_page_fake_buckets_end = vm_map_round_page((vm_page_fake_buckets_start + (vm_page_bucket_count * sizeof(vm_page_bucket_t))), PAGE_MASK); char *cp; for (cp = (char *)vm_page_fake_buckets_start; cp < (char *)vm_page_fake_buckets_end; cp++) { *cp = 0x5a; } #endif /* VM_PAGE_FAKE_BUCKETS */ #endif /* VM_PAGE_BUCKETS_CHECK */ kernel_debug_string_early("vm_page_buckets"); vm_page_buckets = (vm_page_bucket_t *) pmap_steal_memory(vm_page_bucket_count * sizeof(vm_page_bucket_t), 0); kernel_debug_string_early("vm_page_bucket_locks"); vm_page_bucket_locks = (hw_lck_ticket_t *) pmap_steal_memory(vm_page_bucket_lock_count * sizeof(hw_lck_ticket_t), 0); for (i = 0; i < vm_page_bucket_count; i++) { vm_page_bucket_t *bucket = &vm_page_buckets[i]; bucket->page_list = VM_PAGE_PACK_PTR(VM_PAGE_NULL); #if MACH_PAGE_HASH_STATS bucket->cur_count = 0; bucket->hi_count = 0; #endif /* MACH_PAGE_HASH_STATS */ } for (i = 0; i < vm_page_bucket_lock_count; i++) { hw_lck_ticket_init(&vm_page_bucket_locks[i], &vm_page_lck_grp_bucket); } vm_tag_init(); #if VM_PAGE_BUCKETS_CHECK vm_page_buckets_check_ready = TRUE; #endif /* VM_PAGE_BUCKETS_CHECK */ /* * Machine-dependent code allocates the resident page table. * It uses vm_page_init to initialize the page frames. * The code also returns to us the virtual space available * to the kernel. We don't trust the pmap module * to get the alignment right. */ kernel_debug_string_early("pmap_startup"); pmap_startup(&virtual_space_start, &virtual_space_end); virtual_space_start = round_page(virtual_space_start); virtual_space_end = trunc_page(virtual_space_end); *startp = virtual_space_start; *endp = virtual_space_end; /* * Compute the initial "wire" count. * Up until now, the pages which have been set aside are not under * the VM system's control, so although they aren't explicitly * wired, they nonetheless can't be moved. At this moment, * all VM managed pages are "free", courtesy of pmap_startup. */ assert((unsigned int) atop_64(max_mem) == atop_64(max_mem)); vm_page_wire_count = ((unsigned int) atop_64(max_mem)) - vm_page_free_count - vm_lopage_free_count; #if CONFIG_SECLUDED_MEMORY vm_page_wire_count -= vm_page_secluded_count; #endif #if HAS_MTE /* * Discount any tag storage pages that we have set aside in * vm_page_release_startup(). */ vm_page_wire_count -= pmap_tag_storage_in_range_count(); #endif vm_page_wire_count_initial = vm_page_wire_count; /* capture this for later use */ booter_size = ml_get_booter_memory_size(); printf("vm_page_bootstrap: %d free pages, %d wired pages" #if XNU_VM_HAS_DELAYED_PAGES ", (up to %d of which are delayed free)" #endif /* XNU_VM_HAS_DELAYED_PAGES */ "%c", vm_page_free_count, vm_page_wire_count, #if XNU_VM_HAS_DELAYED_PAGES vm_delayed_count, #endif /* XNU_VM_HAS_DELAYED_PAGES */ '\n'); kernel_debug_string_early("vm_page_bootstrap complete"); } #ifndef MACHINE_PAGES /* * This is the early boot time allocator for data structures needed to bootstrap the VM system. * On x86 it will allocate large pages if size is sufficiently large. We don't need to do this * on ARM yet, due to the combination of a large base page size and smaller RAM devices. */ __static_testable void * pmap_steal_memory_internal( vm_size_t size, vm_size_t alignment, boolean_t might_free, unsigned int flags, pmap_mapping_type_t mapping_type) { kern_return_t kr; vm_offset_t addr; vm_offset_t end = 0; vm_offset_t map_addr; ppnum_t phys_page; unsigned int pmap_flags; if (size > UINT64_MAX - sizeof(void *)) { panic("pmap_steal_memory(): size: 0x%lx", size); } /* * Size needs to be aligned to word size. */ size = (size + sizeof(void *) - 1) & ~(sizeof(void *) - 1); /* * Alignment defaults to word size if not specified. */ if (alignment == 0) { alignment = sizeof(void*); } /* * Alignment must be no greater than a page and must be a power of two. */ assert(alignment <= PAGE_SIZE); assert((alignment & (alignment - 1)) == 0); /* * On the first call, get the initial values for virtual address space * and page align them. */ if (virtual_space_start == virtual_space_end) { pmap_virtual_space(&virtual_space_start, &virtual_space_end); virtual_space_start = round_page(virtual_space_start); virtual_space_end = trunc_page(virtual_space_end); #if defined(__x86_64__) /* * Release remaining unused section of preallocated KVA and the 4K page tables * that map it. This makes the VA available for large page mappings. */ Idle_PTs_release(virtual_space_start, virtual_space_end); #endif } /* * Allocate the virtual space for this request. On x86, we'll align to a large page * address if the size is big enough to back with at least 1 large page. */ #if defined(__x86_64__) if (size >= I386_LPGBYTES) { virtual_space_start = ((virtual_space_start + I386_LPGMASK) & ~I386_LPGMASK); } #endif virtual_space_start = (virtual_space_start + (alignment - 1)) & ~(alignment - 1); addr = virtual_space_start; virtual_space_start += size; //kprintf("pmap_steal_memory: %08lX - %08lX; size=%08lX\n", (long)addr, (long)virtual_space_start, (long)size); /* (TEST/DEBUG) */ /* * Allocate and map physical pages to back the new virtual space. */ map_addr = round_page(addr); if (os_add_overflow(addr, size, &end)) { panic("pmap_steal_memory() overflow, addr: %lx, size: 0x%lx", addr, size); } while (map_addr < end) { #if defined(__x86_64__) /* * Back with a large page if properly aligned on x86 */ if ((map_addr & I386_LPGMASK) == 0 && map_addr + I386_LPGBYTES <= addr + size && pmap_pre_expand_large(kernel_pmap, map_addr) == KERN_SUCCESS && pmap_next_page_large(&phys_page) == KERN_SUCCESS) { kr = pmap_enter(kernel_pmap, map_addr, phys_page, VM_PROT_READ | VM_PROT_WRITE, VM_PROT_NONE, VM_WIMG_USE_DEFAULT | VM_MEM_SUPERPAGE, FALSE, mapping_type); if (kr != KERN_SUCCESS) { panic("pmap_steal_memory: pmap_enter() large failed, new_addr=%#lx, phys_page=%u", (unsigned long)map_addr, phys_page); } map_addr += I386_LPGBYTES; vm_page_wire_count += I386_LPGBYTES >> PAGE_SHIFT; vm_page_stolen_count += I386_LPGBYTES >> PAGE_SHIFT; vm_page_kern_lpage_count++; continue; } #endif if (!pmap_next_page_hi(&phys_page, might_free)) { panic("pmap_steal_memory() size: 0x%llx", (uint64_t)size); } #if defined(__x86_64__) pmap_pre_expand(kernel_pmap, map_addr); #endif pmap_flags = flags ? flags : VM_WIMG_USE_DEFAULT; #if HAS_MTE if (pmap_flags & VM_MEM_MAP_MTE) { mteinfo_covered_page_set_stolen_tagged(phys_page); pmap_make_tagged_page(phys_page); /* Force the canonical tag. */ mte_store_tag((void *)phystokv(ptoa(phys_page)), PAGE_SIZE); } #endif /* HAS_MTE */ kr = pmap_enter(kernel_pmap, map_addr, phys_page, VM_PROT_READ | VM_PROT_WRITE, VM_PROT_NONE, pmap_flags, FALSE, mapping_type); if (kr != KERN_SUCCESS) { panic("pmap_steal_memory() pmap_enter failed, map_addr=%#lx, phys_page=%u", (unsigned long)map_addr, phys_page); } map_addr += PAGE_SIZE; /* * Account for newly stolen memory */ vm_page_wire_count++; vm_page_stolen_count++; } #if defined(__x86_64__) /* * The call with might_free is currently the last use of pmap_steal_memory*(). * Notify the pmap layer to record which high pages were allocated so far. */ if (might_free) { pmap_hi_pages_done(); } #endif #if KASAN kasan_notify_address(round_page(addr), size); #endif return (void *) addr; } __mockable void * pmap_steal_memory( vm_size_t size, vm_size_t alignment) { return pmap_steal_memory_internal(size, alignment, FALSE, 0, PMAP_MAPPING_TYPE_RESTRICTED); } __mockable void * pmap_steal_freeable_memory( vm_size_t size) { return pmap_steal_memory_internal(size, 0, TRUE, 0, PMAP_MAPPING_TYPE_RESTRICTED); } #if HAS_MTE void * pmap_steal_zone_memory( vm_size_t size, vm_size_t alignment) { return pmap_steal_memory_internal(size, alignment, FALSE, VM_MEM_MAP_MTE, PMAP_MAPPING_TYPE_RESTRICTED); } #endif /* HAS_MTE */ #if CONFIG_SECLUDED_MEMORY /* boot-args to control secluded memory */ TUNABLE_DT(unsigned int, secluded_mem_mb, "/defaults", "kern.secluded_mem_mb", "secluded_mem_mb", 0, TUNABLE_DT_NONE); /* IOKit can use secluded memory */ TUNABLE(bool, secluded_for_iokit, "secluded_for_iokit", true); /* apps can use secluded memory */ TUNABLE(bool, secluded_for_apps, "secluded_for_apps", true); /* filecache can use seclude memory */ TUNABLE(secluded_filecache_mode_t, secluded_for_filecache, "secluded_for_filecache", SECLUDED_FILECACHE_RDONLY); uint64_t secluded_shutoff_trigger = 0; uint64_t secluded_shutoff_headroom = 150 * 1024 * 1024; /* original value from N56 */ #endif /* CONFIG_SECLUDED_MEMORY */ #if defined(__arm64__) extern void patch_low_glo_vm_page_info(void *, void *, uint32_t); #endif void vm_page_release_startup(vm_page_t mem); __mockable void pmap_startup( vm_offset_t *startp, vm_offset_t *endp) { unsigned int npages; ppnum_t phys_page; uint64_t mem_sz; uint64_t start_ns; uint64_t now_ns; uint32_t divisor; #if XNU_VM_HAS_DELAYED_PAGES uint_t low_page_count = 0; #endif /* XNU_VM_HAS_DELAYED_PAGES */ /* * make sure we are aligned on a 64 byte boundary * for VM_PAGE_PACK_PTR (it clips off the low-order * 6 bits of the pointer) */ if (virtual_space_start != virtual_space_end) { virtual_space_start = round_page(virtual_space_start); } /* * We calculate how many page frames we will have * and then allocate the page structures in one chunk. * * Note that the calculation here doesn't take into account * the memory needed to map what's being allocated, i.e. the page * table entries. So the actual number of pages we get will be * less than this. To do someday: include that in the computation. * * Also for ARM, we don't use the count of free_pages, but rather the * range from last page to first page (ignore holes due to retired pages). */ /* * Initialize and release the page frames. */ kernel_debug_string_early("page_frame_init"); absolutetime_to_nanoseconds(mach_absolute_time(), &start_ns); if (fillval) { kprintf("Filling vm_pages with pattern: 0x%x\n", fillval); } #if XNU_VM_HAS_LINEAR_PAGES_ARRAY mem_sz = ptoa(pmap_free_pages_span()); #if HAS_MTE if (!mte_enabled()) #endif /* HAS_MTE */ #if CONFIG_SPTM { uint32_t count = vm_pages_free_mask_len(); _vm_pages_free_masks = pmap_steal_memory(count * sizeof(__uint128_t), sizeof(__uint128_t)); _vm_pages_free_enqueue_idx = pmap_steal_memory(count, sizeof(uint8_t)); bzero(_vm_pages_free_masks, count * sizeof(__uint128_t)); memset(_vm_pages_free_enqueue_idx, 0xff, count); } #endif /* CONFIG_SPTM */ #else mem_sz = ptoa(pmap_free_pages()); #endif mem_sz += round_page(virtual_space_start) - virtual_space_start; /* Account for any slop */ divisor = PAGE_SIZE + sizeof(struct vm_page); npages = (uint32_t)((mem_sz + divisor - 1) / divisor); /* scaled to include the vm_page_ts */ vm_pages = pmap_steal_freeable_memory(npages * sizeof(struct vm_page)); vm_pages_end = vm_page_get(npages); #if CONFIG_SECLUDED_MEMORY /* * Figure out how much secluded memory to have before we start * release pages to free lists. * The default, if specified nowhere else, is no secluded mem. */ vm_page_secluded_target = (unsigned int)atop_64(secluded_mem_mb * 1024ULL * 1024ULL); /* * Allow a really large app to effectively use secluded memory until it exits. */ if (vm_page_secluded_target != 0) { /* * Get an amount from boot-args, else use 1/2 of max_mem. * 1/2 max_mem was chosen from a Peace daemon tentpole test which * used munch to induce jetsam thrashing of false idle daemons on N56. */ int secluded_shutoff_mb; if (PE_parse_boot_argn("secluded_shutoff_mb", &secluded_shutoff_mb, sizeof(secluded_shutoff_mb))) { secluded_shutoff_trigger = (uint64_t)secluded_shutoff_mb * 1024 * 1024; } else { secluded_shutoff_trigger = max_mem / 2; } /* ensure the headroom value is sensible and avoid underflows */ assert(secluded_shutoff_trigger == 0 || secluded_shutoff_trigger > secluded_shutoff_headroom); } #endif /* CONFIG_SECLUDED_MEMORY */ #if defined(__x86_64__) /* * Decide how much memory we delay freeing at boot time. */ uint32_t delay_above_gb; if (!PE_parse_boot_argn("delay_above_gb", &delay_above_gb, sizeof(delay_above_gb))) { delay_above_gb = DEFAULT_DELAY_ABOVE_PHYS_GB; } if (delay_above_gb == 0) { delay_above_pnum = PPNUM_MAX; } else { delay_above_pnum = delay_above_gb * (1024 * 1024 * 1024 / PAGE_SIZE); } /* make sure we have sane breathing room: 1G above low memory */ if (delay_above_pnum <= max_valid_low_ppnum) { delay_above_pnum = max_valid_low_ppnum + ((1024 * 1024 * 1024) >> PAGE_SHIFT); } if (delay_above_pnum < PPNUM_MAX) { printf("pmap_startup() delaying init/free of page nums > 0x%x\n", delay_above_pnum); } #endif /* defined(__x86_64__) */ vm_free_page_lock(); for (uint32_t i = 0; i < npages && pmap_next_page(&phys_page); i++) { #if XNU_VM_HAS_DELAYED_PAGES if (phys_page < max_valid_low_ppnum) { ++low_page_count; } /* Are we at high enough pages to delay the rest? */ if (low_page_count > vm_lopage_free_limit && phys_page > delay_above_pnum) { vm_delayed_count = pmap_free_pages(); assert3u(vm_pages_count + vm_delayed_count, <=, npages); break; } #endif /* XNU_VM_HAS_DELAYED_PAGES */ #if XNU_VM_HAS_LINEAR_PAGES_ARRAY if (i == 0) { vm_pages_first_pnum = phys_page; patch_low_glo_vm_page_info(vm_pages, vm_pages_end, vm_pages_first_pnum); #if HAS_MTE if (mte_enabled()) { vm_pages_tag_storage = vm_page_get( (mte_tag_storage_start_pnum - vm_pages_first_pnum)); vm_pages_tag_storage_end = vm_tag_storage_page_get(mte_tag_storage_count); assert3p(vm_pages_tag_storage_end, <=, vm_pages_end); } #endif /* HAS_MTE */ } #else /* The x86 clump freeing code requires increasing ppn's to work correctly */ if (i > 0) { assert(phys_page > vm_page_get(i - 1)->vmp_phys_page); } #endif /* !XNU_VM_HAS_LINEAR_PAGES_ARRAY */ ++vm_pages_count; vm_page_init(vm_page_get(i), phys_page); if (fillval) { fillPage(phys_page, fillval); } if (vm_himemory_mode) { vm_page_release_startup(vm_page_get(i)); } } vm_page_pages = vm_pages_count; /* used to report to user space */ if (!vm_himemory_mode) { for (uint32_t i = npages; i-- > 0;) { /* skip retired pages */ if (!VMP_ERROR_GET(vm_page_get(i))) { vm_page_release_startup(vm_page_get(i)); } } } vm_free_page_unlock(); absolutetime_to_nanoseconds(mach_absolute_time(), &now_ns); printf("pmap_startup() init/release time: %lld microsec\n", (now_ns - start_ns) / NSEC_PER_USEC); #if XNU_VM_HAS_DELAYED_PAGES printf("pmap_startup() delayed init/release of %d pages\n", vm_delayed_count); #endif /* XNU_VM_HAS_DELAYED_PAGES */ /* * Validate packing will work properly. This needs to be done last * after vm_pages_count has been computed. */ if (npages >= VM_PAGE_PACKED_FROM_ARRAY) { panic("pmap_startup(): too many pages to support vm_page packing"); } if ((vm_page_t)VM_PAGE_UNPACK_PTR(VM_PAGE_PACK_PTR(vm_pages)) != vm_pages) { panic("VM_PAGE_PACK_PTR failed on vm_pages - %p", vm_pages); } if ((vm_page_t)VM_PAGE_UNPACK_PTR(VM_PAGE_PACK_PTR(vm_page_get(vm_pages_count - 1))) != vm_page_get(vm_pages_count - 1)) { panic("VM_PAGE_PACK_PTR failed on vm_pages_end - %p", vm_page_get(vm_pages_count - 1)); } VM_CHECK_MEMORYSTATUS; /* * We have to re-align virtual_space_start, * because pmap_steal_memory has been using it. */ virtual_space_start = round_page(virtual_space_start); *startp = virtual_space_start; *endp = virtual_space_end; } #endif /* MACHINE_PAGES */ /* * Create the zone that represents the vm_pages[] array. Nothing ever allocates * or frees to this zone. It's just here for reporting purposes via zprint command. * This needs to be done after all initially delayed pages are put on the free lists. */ void vm_pages_array_finalize(void) { (void)zone_create_ext("vm pages array", sizeof(struct vm_page), ZC_KASAN_NOREDZONE | ZC_KASAN_NOQUARANTINE, ZONE_ID_VM_PAGES, ^(zone_t z) { uint64_t vm_page_zone_pages, vm_page_array_zone_data_size; zone_set_exhaustible(z, 0, true); /* * Reflect size and usage information for vm_pages[]. */ z->z_elems_avail = (uint32_t)(vm_pages_end - vm_pages); z->z_elems_free = z->z_elems_avail - vm_pages_count; zpercpu_get_cpu(z->z_stats, 0)->zs_mem_allocated = vm_pages_count * sizeof(struct vm_page); vm_page_array_zone_data_size = (uint64_t)vm_pages_end - (uint64_t)vm_pages; vm_page_zone_pages = atop(round_page((vm_offset_t)vm_page_array_zone_data_size)); z->z_wired_cur += vm_page_zone_pages; z->z_wired_hwm = z->z_wired_cur; z->z_va_cur = z->z_wired_cur; /* since zone accounts for these, take them out of stolen */ VM_PAGE_MOVE_STOLEN(vm_page_zone_pages); }); } /* * Create the vm_pages zone. This is used for the vm_page structures for the pages * that are scavanged from other boot time usages by ml_static_mfree(). As such, * this needs to happen in early VM bootstrap. */ __startup_func static void vm_page_module_init(void) { vm_size_t vm_page_with_ppnum_size; /* * Since the pointers to elements in this zone will be packed, they * must have appropriate size. Not strictly what sizeof() reports. */ vm_page_with_ppnum_size = (sizeof(struct vm_page_with_ppnum) + (VM_PAGE_PACKED_PTR_ALIGNMENT - 1)) & ~(VM_PAGE_PACKED_PTR_ALIGNMENT - 1); vm_page_zone = zone_create_ext("vm pages", vm_page_with_ppnum_size, ZC_ALIGNMENT_REQUIRED | ZC_VM, ZONE_ID_ANY, ^(zone_t z) { /* * The number "10" is a small number that is larger than the number * of fictitious pages that any single caller will attempt to allocate * without blocking. * * The largest such number at the moment is kmem_alloc() * when 2 guard pages are asked. 10 is simply a somewhat larger number, * taking into account the 50% hysteresis the zone allocator uses. * * Note: this works at all because the zone allocator * doesn't ever allocate fictitious pages. */ zone_raise_reserve(z, 10); }); } STARTUP(ZALLOC, STARTUP_RANK_SECOND, vm_page_module_init); #if XNU_VM_HAS_LINEAR_PAGES_ARRAY /* * Radix tree of pages within the [pmap_first_pnum, vm_pages_first_pnum) range, * in order to support page lookup by pnum (@see vm_page_find_canonical()), * which corresponds to pages returned to the VM via @c ml_static_mfree(). * * Kernel vm pages are never freed, which means that this data structure * is insert only. * * Empirically we have about 4-5k such pages, typically in only few rather dense * contiguous spans, inside a range of roughly 32k pnums. * * A radix tree works well with the distribution of keys, but also allows for * a straightforward lockless lookup path. */ #define VM_PAGE_RADIX_FANOUT_SHIFT 8 #define VM_PAGE_RADIX_FANOUT (1u << VM_PAGE_RADIX_FANOUT_SHIFT) typedef uint32_t vm_page_radix_ptr_t; typedef struct vm_page_radix_node { vm_page_radix_ptr_t vmpr_array[VM_PAGE_RADIX_FANOUT]; } *vm_page_radix_node_t; static LCK_GRP_DECLARE(vm_pages_radix_lock_grp, "VM pages radix"); static LCK_MTX_DECLARE(vm_pages_radix_lock, &vm_pages_radix_lock_grp); static SECURITY_READ_ONLY_LATE(uintptr_t) vm_pages_radix_root; static uint32_t vm_pages_radix_count; static vm_page_radix_node_t vm_page_radix_node_unpack(vm_page_radix_ptr_t ptr) { return (vm_page_radix_node_t)VM_UNPACK_POINTER(ptr, VM_PAGE_PACKED_PTR); } static vm_page_radix_ptr_t vm_page_radix_node_pack(vm_page_radix_node_t node) { vm_offset_t ptr = (vm_offset_t)node; VM_ASSERT_POINTER_PACKABLE(ptr, VM_PAGE_PACKED_PTR); return (vm_page_radix_ptr_t)VM_PACK_POINTER(ptr, VM_PAGE_PACKED_PTR); } static uint32_t vm_page_radix_key(uint32_t level, uint32_t index) { uint32_t key = index >> (VM_PAGE_RADIX_FANOUT_SHIFT * level); return key & (VM_PAGE_RADIX_FANOUT - 1); } static vm_page_radix_ptr_t * vm_page_radix_slot(vm_page_radix_node_t node, uint32_t level, uint32_t index) { return node->vmpr_array + vm_page_radix_key(level, index); } __startup_func __attribute__((noinline)) static vm_page_radix_node_t vm_pages_radix_init_root(uint32_t *levelp) { uint32_t max_index = vm_pages_first_pnum - pmap_first_pnum - 1; vm_page_radix_node_t root; uint32_t level; vm_size_t size; /* * Init a top-level node right away, to cover any index within * [0, vm_pages_first_pnum - pmap_first_pnum) */ level = (fls(max_index | 1) - 1) / VM_PAGE_RADIX_FANOUT_SHIFT; size = (vm_page_radix_key(level, max_index) + 1) * sizeof(vm_page_radix_ptr_t); root = zalloc_permanent(size, ZALIGN_64); /* * Pack the level into the root pointer low bits, * so that pointer and level can be read atomically. * * See vm_pages_radix_load_root(). */ os_atomic_store(&vm_pages_radix_root, (uintptr_t)root | level, release); *levelp = level; return root; } static vm_page_radix_node_t vm_pages_radix_node_alloc(vm_page_radix_ptr_t *slot) { vm_page_radix_node_t node; node = zalloc_permanent(sizeof(struct vm_page_radix_node), VM_PAGE_PACKED_PTR_ALIGNMENT - 1); os_atomic_store(slot, vm_page_radix_node_pack(node), release); return node; } static vm_page_radix_node_t vm_pages_radix_load_root(uint32_t *level) { const uintptr_t VM_PAGE_RADIX_LEVEL_MASK = 0x7ul; uintptr_t root = os_atomic_load(&vm_pages_radix_root, dependency); *level = root & VM_PAGE_RADIX_LEVEL_MASK; root &= ~VM_PAGE_RADIX_LEVEL_MASK; return (vm_page_radix_node_t)root; } vm_page_t vm_pages_radix_next(uint32_t *cursor, ppnum_t *pnum) { const uint32_t max_index = vm_pages_first_pnum - pmap_first_pnum; vm_page_radix_node_t node; uint32_t level, index; index = *cursor; node = vm_pages_radix_load_root(&level); if (node == NULL) { return VM_PAGE_NULL; } while (index < max_index) { vm_page_radix_ptr_t *slot = vm_page_radix_slot(node, level, index); vm_page_radix_ptr_t ptr = os_atomic_load(slot, dependency); if (ptr == 0) { uint32_t stride = 1 << (VM_PAGE_RADIX_FANOUT_SHIFT * level); index = (index + stride) & -stride; if (vm_page_radix_key(level, index) == 0) { /* restart lookup at the top */ node = vm_pages_radix_load_root(&level); } } else if (level > 0) { node = vm_page_radix_node_unpack(ptr); level -= 1; } else { *cursor = index + 1; if (pnum) { *pnum = pmap_first_pnum + index; } return (vm_page_t)VM_PAGE_UNPACK_PTR(ptr); } } if (pnum) { *pnum = 0; } return VM_PAGE_NULL; } #if DEBUG || DEVELOPMENT static int vm_page_radix_verify_test(int64_t in __unused, int64_t *out) { uint32_t count = 0; vm_page_t mem; lck_mtx_lock(&vm_pages_radix_lock); vm_pages_radix_for_each(mem) { count++; assert(mem == vm_page_find_canonical(VM_PAGE_GET_PHYS_PAGE(mem))); } assert(count == vm_pages_radix_count); lck_mtx_unlock(&vm_pages_radix_lock); *out = 1; return 0; } SYSCTL_TEST_REGISTER(vm_page_radix_verify, vm_page_radix_verify_test); #endif /* DEBUG || DEVELOPMENT */ __attribute__((noinline)) static void vm_pages_radix_insert(ppnum_t pnum, vm_page_t page) { vm_page_radix_ptr_t *slot; vm_page_radix_node_t node; uint32_t level, index; assert(!vm_page_in_array(page)); index = pnum - pmap_first_pnum; lck_mtx_lock(&vm_pages_radix_lock); node = vm_pages_radix_load_root(&level); if (node == NULL) { node = vm_pages_radix_init_root(&level); } for (; level > 0; level--) { slot = vm_page_radix_slot(node, level, index); if (*slot == 0) { node = vm_pages_radix_node_alloc(slot); } else { node = vm_page_radix_node_unpack(*slot); } } slot = vm_page_radix_slot(node, 0, index); assert(*slot == 0); os_atomic_store(slot, VM_PAGE_PACK_PTR(page), release); vm_pages_radix_count++; lck_mtx_unlock(&vm_pages_radix_lock); } __abortlike static void vm_page_for_ppnum_panic(ppnum_t pnum) { if (pnum < pmap_first_pnum) { panic("physical page is before the start of DRAM: %#x < %#x)", pnum, pmap_first_pnum); } panic("physical page is beyond the end of managed DRAM: %#x >= %#x)", pnum, vm_pages_first_pnum + vm_pages_count); } __mockable vm_page_t vm_page_find_canonical(ppnum_t pnum) { vm_page_radix_ptr_t *slot; vm_page_radix_node_t node; vm_page_radix_ptr_t ptr; uint32_t level, index; if (pnum < pmap_first_pnum) { vm_page_for_ppnum_panic(pnum); } if (pnum >= vm_pages_first_pnum + vm_pages_count) { /* * We could receive requests for pages which are beyond the xnu's managed space. (eg: ECC errors) * These need to be handled gracefully, so we return VM_PAGE_NULL here. */ return VM_PAGE_NULL; } if (__probable(pnum >= vm_pages_first_pnum)) { return vm_page_get(pnum - vm_pages_first_pnum); } index = pnum - pmap_first_pnum; node = vm_pages_radix_load_root(&level); for (; node && level > 0; level--) { slot = vm_page_radix_slot(node, level, index); ptr = os_atomic_load(slot, dependency); node = vm_page_radix_node_unpack(ptr); } if (__probable(node)) { slot = vm_page_radix_slot(node, 0, index); ptr = os_atomic_load(slot, dependency); return (vm_page_t)VM_PAGE_UNPACK_PTR(ptr); } return VM_PAGE_NULL; } #endif /* XNU_VM_HAS_LINEAR_PAGES_ARRAY */ /*! * @function vm_page_create() * * @brief * Common helper for all vm_page_create* functions. */ vm_page_t vm_page_create(ppnum_t phys_page, bool canonical, zalloc_flags_t flags) { vm_page_t m; m = zalloc_flags(vm_page_zone, flags); if (m) { vm_page_init(m, phys_page); if (phys_page == vm_page_guard_addr) { counter_inc(&vm_guard_count); } } if (canonical) { assert((flags & (Z_NOWAIT | Z_NOPAGEWAIT)) == 0); m->vmp_canonical = true; #if HAS_MTE m->vmp_using_mte = pmap_is_tagged_page(phys_page); #endif /* HAS_MTE */ #if XNU_VM_HAS_LINEAR_PAGES_ARRAY vm_pages_radix_insert(phys_page, m); #endif /* XNU_VM_HAS_LINEAR_PAGES_ARRAY */ vm_free_page_lock(); vm_page_pages++; vm_free_page_unlock(); } return m; } /* * Routine: vm_page_create_canonical * Purpose: * After the VM system is up, machine-dependent code * may stumble across more physical memory. For example, * memory that it was reserving for a frame buffer. * vm_page_create_canonical turns this memory into available pages. */ void vm_page_create_canonical(ppnum_t phys_page) { vm_page_t m; m = vm_page_create(phys_page, true, Z_WAITOK); vm_page_release(m, VMP_RELEASE_NONE); } /* * vm_page_hash: * * Distributes the object/offset key pair among hash buckets. * * NOTE: The bucket count must be a power of 2 */ #define vm_page_hash(object, offset) (\ ( (natural_t)((uintptr_t)object * vm_page_bucket_hash) + ((uint32_t)atop_64(offset) ^ vm_page_bucket_hash))\ & vm_page_hash_mask) static void vm_page_hash_insert_locked(vm_page_bucket_t *bucket, vm_page_t mem) { mem->vmp_next_m = bucket->page_list; mem->vmp_hashed = true; bucket->page_list = VM_PAGE_PACK_PTR(mem); } static void vm_page_hash_remove_locked(vm_page_packed_t *prev, vm_page_t mem) { *prev = mem->vmp_next_m; mem->vmp_next_m = VM_PAGE_PACK_PTR(NULL); mem->vmp_hashed = false; } /* * Lookup a page in a given bucket. * * This function is called under extremely unusual locking behavior. * Specifically, hw_lck_ticket_unlock_after_lookup is used with the return value * of this function. That means that any loads in this function expecting to be * protected by the bucket locks must be directly necessary to get the `mem` * returned by this function. * We can't do writes protected by the lock. * * If we remove the data dependent locking, we can probably merge this with * @c vm_page_hash_lookup_and_remove_locked as they are very similar code. */ static vm_page_t vm_page_hash_lookup_data_dependent_locked( vm_page_bucket_t *bucket, vm_object_t object, vm_object_offset_t offset) { vm_page_object_t packed = VM_PAGE_PACK_OBJECT(object); vm_page_packed_t *prev = &bucket->page_list; while (*prev) { vm_page_t mem = (vm_page_t)(VM_PAGE_UNPACK_PTR(*prev)); if (mem->vmp_object == packed && mem->vmp_offset == offset) { return mem; } prev = &mem->vmp_next_m; } return VM_PAGE_NULL; } /* * Lookup a page in a given bucket and remove it from that bucket. */ static vm_page_t vm_page_hash_lookup_and_remove_locked( vm_page_bucket_t *bucket, vm_object_t object, vm_object_offset_t offset) { vm_page_object_t packed = VM_PAGE_PACK_OBJECT(object); vm_page_packed_t *prev = &bucket->page_list; while (*prev) { vm_page_t mem = (vm_page_t)(VM_PAGE_UNPACK_PTR(*prev)); if (mem->vmp_object == packed && mem->vmp_offset == offset) { vm_page_hash_remove_locked(prev, mem); return mem; } prev = &mem->vmp_next_m; } return VM_PAGE_NULL; } static void vm_page_hash_remove(vm_page_t mem, vm_object_t object) { vm_page_packed_t packed = VM_PAGE_PACK_PTR(mem); uint32_t hash_id = vm_page_hash(object, mem->vmp_offset); vm_page_bucket_t *bucket = &vm_page_buckets[hash_id]; hw_lck_ticket_t *lock = &vm_page_bucket_locks[hash_id / BUCKETS_PER_LOCK]; vm_page_packed_t *prev = &bucket->page_list; /* * Remove from the object_object/offset hash table */ hw_lck_ticket_lock(lock, &vm_page_lck_grp_bucket); while (*prev != packed) { prev = &((vm_page_t)VM_PAGE_UNPACK_PTR(*prev))->vmp_next_m; } vm_page_hash_remove_locked(prev, mem); #if MACH_PAGE_HASH_STATS bucket->cur_count--; #endif /* MACH_PAGE_HASH_STATS */ hw_lck_ticket_unlock(lock); } void vm_page_hash_insert(vm_page_t mem, vm_object_t object, vm_object_offset_t offset) { uint32_t hash_id = vm_page_hash(object, offset); vm_page_bucket_t *bucket = &vm_page_buckets[hash_id]; hw_lck_ticket_t *lock = &vm_page_bucket_locks[hash_id / BUCKETS_PER_LOCK]; if (object->internal && (offset >= object->vo_size)) { panic("(page=%p,obj=%p,off=0x%llx,size=0x%llx) inserted at offset past object bounds", mem, object, offset, object->vo_size); } assert(mem->vmp_object == VM_PAGE_PACK_OBJECT(object) && mem->vmp_offset == offset && !mem->vmp_hashed); #if CONFIG_SECLUDED_MEMORY if (object->eligible_for_secluded) { vm_page_secluded.eligible_for_secluded++; } #endif /* CONFIG_SECLUDED_MEMORY */ /* * Insert it into the object_object/offset hash table */ hw_lck_ticket_lock(lock, &vm_page_lck_grp_bucket); assert(!vm_page_hash_lookup_data_dependent_locked(bucket, object, offset)); vm_page_hash_insert_locked(bucket, mem); #if MACH_PAGE_HASH_STATS if (++bucket->cur_count > bucket->hi_count) { bucket->hi_count = bucket->cur_count; } #endif /* MACH_PAGE_HASH_STATS */ hw_lck_ticket_unlock(lock); } static void vm_page_hash_replace(vm_page_t mem, vm_object_t object, vm_object_offset_t offset) { uint32_t hash_id = vm_page_hash(object, offset); vm_page_bucket_t *bucket = &vm_page_buckets[hash_id]; hw_lck_ticket_t *lock = &vm_page_bucket_locks[hash_id / BUCKETS_PER_LOCK]; vm_page_t found_m; hw_lck_ticket_lock(lock, &vm_page_lck_grp_bucket); found_m = vm_page_hash_lookup_and_remove_locked(bucket, object, offset); vm_page_hash_insert_locked(bucket, mem); hw_lck_ticket_unlock(lock); if (found_m) { VM_PAGE_FREE(found_m); } } /* * vm_page_insert: [ internal use only ] * * Inserts the given mem entry into the object/object-page * table and object list. * * The object must be locked. */ void vm_page_insert( vm_page_t mem, vm_object_t object, vm_object_offset_t offset) { vm_page_insert_internal(mem, object, offset, VM_KERN_MEMORY_NONE, VMPI_NONE, NULL); } void vm_page_insert_wired( vm_page_t mem, vm_object_t object, vm_object_offset_t offset, vm_tag_t tag) { vm_page_insert_internal(mem, object, offset, tag, VMPI_NONE, NULL); } void vm_page_insert_internal( vm_page_t mem, vm_object_t object, vm_object_offset_t offset, vm_tag_t tag, vmpi_flags_t flags, struct vmpi_acct *delayed_acct) { ledger_t ledger; vmo_ledgers_t lidx; #if 0 /* * we may not hold the page queue lock * so this check isn't safe to make */ VM_PAGE_CHECK(mem); #endif assertf(page_aligned(offset), "0x%llx\n", offset); assert(!VM_PAGE_WIRED(mem) || !vm_page_is_canonical(mem) || (tag != VM_KERN_MEMORY_NONE)); #if HAS_MTE assert_mte_vmo_matches_vmp(object, mem); #endif /* HAS_MTE */ vm_object_lock_assert_exclusive(object); if (flags & VMPI_Q_LOCKED) { LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); } else { LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_NOTOWNED); assert(!VM_PAGE_PAGEABLE(mem)); } /* * Record the object/offset pair in this page */ mem->vmp_object = VM_PAGE_PACK_OBJECT(object); mem->vmp_offset = offset; if (flags & VMPI_REPLACE) { assert((flags & VMPI_DELAY_HASH) == 0); vm_page_hash_replace(mem, object, offset); } else if (flags & VMPI_DELAY_HASH) { #if MACH_ASSERT assert(!object->delayed_page_insert); object->delayed_page_insert = true; #endif /* MACH_ASSERT */ } else { vm_page_hash_insert(mem, object, offset); } { unsigned int cache_attr; cache_attr = object->wimg_bits & VM_WIMG_MASK; #if HAS_MTE /* * Set the cache attributes if it's neither the default atttributes * nor it's WIMG_MTE because we would have already set it before * inserting the page into this object. There is no need to take * the set hit. * * */ if (cache_attr == VM_WIMG_MTE) { if (vm_object_is_mte_mappable_with_page(object, mem)) { /* * By now, we expect non-fictitious pages to have been made * tagged. This should happen in mteinfo_page_list_fix_tagging() * when the page is inserted onto the per-CPU free tagged queue. */ assert(mem->vmp_using_mte); assert(pmap_cache_attributes(VM_PAGE_GET_PHYS_PAGE(mem)) == VM_WIMG_MTE); } else { /* * We don't want the object for fictitious pages to have its * cache attributes set if the object is MTE. */ } } else #endif /* HAS_MTE */ if (cache_attr != VM_WIMG_USE_DEFAULT) { PMAP_SET_CACHE_ATTR(mem, object, cache_attr, (flags & VMPI_BATCH_PMAP_OP)); } } /* * Now link into the object's list of backed pages. */ vm_page_queue_enter(&object->memq, mem, vmp_listq); object->memq_hint = mem; mem->vmp_tabled = TRUE; /* * Show that the object has one more resident page. */ object->resident_page_count++; if (VM_PAGE_WIRED(mem)) { assert(mem->vmp_wire_count > 0); VM_OBJECT_WIRED_PAGE_UPDATE_START(object); VM_OBJECT_WIRED_PAGE_ADD(object, mem); VM_OBJECT_WIRED_PAGE_UPDATE_END(object, tag); } assert(object->resident_page_count >= object->wired_page_count); #if COMPRESSOR_PAGEOUT_CHEADS_MAX_COUNT > 1 vm_object_set_chead_hint(object); #endif if (object->object_is_shared_cache && object->pager != NULL && object->pager->mo_pager_ops == &shared_region_pager_ops) { assert(!object->internal); VM_COUNTER_ATOMIC_INC(&vm_page_shared_region_count); } if (delayed_acct) { delayed_acct->vmpi_inserted++; } else if (object->internal) { counter_inc(&vm_page_internal_count); } else { counter_inc(&vm_page_external_count); } /* * It wouldn't make sense to insert a "reusable" page in * an object (the page would have been marked "reusable" only * at the time of a madvise(MADV_FREE_REUSABLE) if it was already * in the object at that time). * But a page could be inserted in a "all_reusable" object, if * something faults it in (a vm_read() from another task or a * "use-after-free" issue in user space, for example). It can * also happen if we're relocating a page from that object to * a different physical page during a physically-contiguous * allocation. */ assert(!mem->vmp_reusable); if (delayed_acct == NULL && object->all_reusable) { os_atomic_inc(&vm_page_stats_reusable.reusable_count, relaxed); } ledger = VM_OBJECT_LEDGER(object); if (ledger && delayed_acct == NULL) { lidx = vm_object_ledger_tag_ledgers(object); disable_preemption(); } if (ledger && object->internal && (object->purgable == VM_PURGABLE_NONVOLATILE || object->purgable == VM_PURGABLE_DENY || VM_PAGE_WIRED(mem))) { if (delayed_acct) { delayed_acct->vmpi_nonvolatile++; } else { /* more non-volatile bytes */ ledger_credit_nopreempt(ledger, lidx.vmo_nonvolatile, PAGE_SIZE); ledger_credit_nopreempt(ledger, lidx.vmo_footprint, PAGE_SIZE); } } else if (ledger && object->internal && (object->purgable == VM_PURGABLE_VOLATILE || object->purgable == VM_PURGABLE_EMPTY)) { assert(!VM_PAGE_WIRED(mem)); if (delayed_acct) { delayed_acct->vmpi_volatile++; } else { /* more volatile bytes */ ledger_credit_nopreempt(ledger, lidx.vmo_volatile, PAGE_SIZE); } } else if (ledger && !object->internal && object->vo_ledger_tag && VM_PAGE_WIRED(mem)) { if (delayed_acct) { delayed_acct->vmpi_external_wired++; } else { ledger_credit_nopreempt(ledger, lidx.vmo_external_wired, PAGE_SIZE); ledger_credit_nopreempt(ledger, lidx.vmo_footprint, PAGE_SIZE); } } if (ledger && delayed_acct == NULL) { enable_preemption(); } if (object->purgable == VM_PURGABLE_VOLATILE) { if (VM_PAGE_WIRED(mem)) { counter_inc(&vm_page_purgeable_wired_count); } else { counter_inc(&vm_page_purgeable_count); } } else if (object->purgable == VM_PURGABLE_EMPTY && mem->vmp_q_state == VM_PAGE_ON_THROTTLED_Q) { /* * This page belongs to a purged VM object but hasn't * been purged (because it was "busy"). * It's in the "throttled" queue and hence not * visible to vm_pageout_scan(). Move it to a pageable * queue, so that it can eventually be reclaimed, instead * of lingering in the "empty" object. */ if ((flags & VMPI_Q_LOCKED) == 0) { vm_page_lockspin_queues(); } vm_page_deactivate(mem); if ((flags & VMPI_Q_LOCKED) == 0) { vm_page_unlock_queues(); } } #if HAS_MTE /* * If adding pages to the compressor object, account for whether it's * tag storage or not. */ if (object == compressor_object) { if (vm_page_is_tag_storage(mem)) { counter_inc(&compressor_tag_storage_pages_in_pool); } else { counter_inc(&compressor_non_tag_storage_pages_in_pool); } } #endif /* HAS_MTE */ #if VM_OBJECT_TRACKING_OP_MODIFIED if (vm_object_tracking_btlog && object->internal && object->resident_page_count == 0 && object->pager == NULL && object->shadow != NULL && object->shadow->vo_copy == object) { btlog_record(vm_object_tracking_btlog, object, VM_OBJECT_TRACKING_OP_MODIFIED, btref_get(__builtin_frame_address(0), 0)); } #endif /* VM_OBJECT_TRACKING_OP_MODIFIED */ } void vm_page_insert_flush_accounting(vm_object_t object, struct vmpi_acct *acct) { if (acct->vmpi_inserted) { disable_preemption(); if (object->internal) { counter_add_preemption_disabled(&vm_page_internal_count, acct->vmpi_inserted); } else { counter_add_preemption_disabled(&vm_page_external_count, acct->vmpi_inserted); } if (object->all_reusable) { os_atomic_add(&vm_page_stats_reusable.reusable_count, acct->vmpi_inserted, relaxed); } if (acct->vmpi_nonvolatile || acct->vmpi_volatile || acct->vmpi_external_wired) { ledger_t ledger; vmo_ledgers_t lidx; ledger = VM_OBJECT_LEDGER(object); lidx = vm_object_ledger_tag_ledgers(object); assert(ledger && object->internal); if (acct->vmpi_nonvolatile) { /* more non-volatile bytes */ ledger_credit_nopreempt(ledger, lidx.vmo_nonvolatile, ptoa(acct->vmpi_nonvolatile)); ledger_credit_nopreempt(ledger, lidx.vmo_footprint, ptoa(acct->vmpi_nonvolatile)); } if (acct->vmpi_volatile) { ledger_credit_nopreempt(ledger, lidx.vmo_volatile, ptoa(acct->vmpi_volatile)); } if (acct->vmpi_external_wired) { ledger_credit_nopreempt(ledger, lidx.vmo_external_wired, ptoa(acct->vmpi_external_wired)); ledger_credit_nopreempt(ledger, lidx.vmo_footprint, ptoa(acct->vmpi_external_wired)); } } enable_preemption(); } } /* * vm_page_remove: [ internal use only ] * * Removes the given mem entry from the object/offset-page * table and the object page list. * * The object must be locked. */ void vm_page_remove(vm_page_t mem) { vm_object_t m_object; ledger_t ledger; vmo_ledgers_t lidx; m_object = VM_PAGE_OBJECT(mem); vm_object_lock_assert_exclusive(m_object); assert(mem->vmp_tabled); assert(!mem->vmp_cleaning); assert(!mem->vmp_laundry); if (VM_PAGE_PAGEABLE(mem)) { LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); } #if 0 /* * we don't hold the page queue lock * so this check isn't safe to make */ VM_PAGE_CHECK(mem); #endif /* * Now remove from the object's list of backed pages. */ if (mem->vmp_hashed) { vm_page_hash_remove(mem, m_object); } vm_page_remove_internal(mem); /* * And show that the object has one fewer resident * page. */ assert(m_object->resident_page_count > 0); m_object->resident_page_count--; if (m_object->object_is_shared_cache && m_object->pager != NULL && m_object->pager->mo_pager_ops == &shared_region_pager_ops) { assert(!m_object->internal); VM_COUNTER_ATOMIC_DEC(&vm_page_shared_region_count); } if (m_object->internal) { counter_dec(&vm_page_internal_count); } else { counter_dec(&vm_page_external_count); if (mem->vmp_xpmapped) { assert(vm_page_xpmapped_external_count); OSAddAtomic(-1, &vm_page_xpmapped_external_count); } } if (!m_object->internal && m_object->cached_list.next && m_object->cached_list.prev) { if (m_object->resident_page_count == 0) { vm_object_cache_remove(m_object); } } if (VM_PAGE_WIRED(mem)) { assert(mem->vmp_wire_count > 0); VM_OBJECT_WIRED_PAGE_UPDATE_START(m_object); VM_OBJECT_WIRED_PAGE_REMOVE(m_object, mem); VM_OBJECT_WIRED_PAGE_UPDATE_END(m_object, m_object->wire_tag); } assert(m_object->resident_page_count >= m_object->wired_page_count); if (mem->vmp_reusable) { assert(m_object->reusable_page_count > 0); m_object->reusable_page_count--; assert(m_object->reusable_page_count <= m_object->resident_page_count); mem->vmp_reusable = FALSE; OSAddAtomic(-1, &vm_page_stats_reusable.reusable_count); vm_page_stats_reusable.reused_remove++; } else if (m_object->all_reusable) { OSAddAtomic(-1, &vm_page_stats_reusable.reusable_count); vm_page_stats_reusable.reused_remove++; } ledger = VM_OBJECT_LEDGER(m_object); if (ledger) { lidx = vm_object_ledger_tag_ledgers(m_object); disable_preemption(); } if (ledger && m_object->internal && (m_object->purgable == VM_PURGABLE_NONVOLATILE || m_object->purgable == VM_PURGABLE_DENY || VM_PAGE_WIRED(mem))) { /* less non-volatile bytes */ ledger_debit_nopreempt(ledger, lidx.vmo_nonvolatile, PAGE_SIZE); ledger_debit_nopreempt(ledger, lidx.vmo_footprint, PAGE_SIZE); } else if (ledger && m_object->internal && (m_object->purgable == VM_PURGABLE_VOLATILE || m_object->purgable == VM_PURGABLE_EMPTY)) { assert(!VM_PAGE_WIRED(mem)); /* less volatile bytes */ ledger_debit_nopreempt(ledger, lidx.vmo_volatile, PAGE_SIZE); } else if (ledger && !m_object->internal && m_object->vo_ledger_tag && VM_PAGE_WIRED(mem)) { ledger_credit_nopreempt(ledger, lidx.vmo_external_wired, PAGE_SIZE); ledger_credit_nopreempt(ledger, lidx.vmo_footprint, PAGE_SIZE); } if (ledger) { enable_preemption(); } if (m_object->purgable == VM_PURGABLE_VOLATILE) { if (VM_PAGE_WIRED(mem)) { counter_dec(&vm_page_purgeable_wired_count); } else { counter_dec(&vm_page_purgeable_count); } } #if HAS_MTE /* * If removing pages from the compressor object, account for whether it's * tag storage or not. */ if (m_object == compressor_object) { if (vm_page_is_tag_storage(mem)) { counter_dec(&compressor_tag_storage_pages_in_pool); } else { counter_dec(&compressor_non_tag_storage_pages_in_pool); } } assert_mte_vmo_matches_vmp(m_object, mem); if (!vm_object_is_mte_mappable(m_object)) { #endif /* HAS_MTE */ if (m_object->set_cache_attr == TRUE) { pmap_set_cache_attributes(VM_PAGE_GET_PHYS_PAGE(mem), 0); } #if HAS_MTE } #endif /* HAS_MTE */ mem->vmp_tabled = FALSE; mem->vmp_object = 0; mem->vmp_offset = (vm_object_offset_t) -1; } /* * vm_page_lookup: * * Returns the page associated with the object/offset * pair specified; if none is found, VM_PAGE_NULL is returned. * * The object must be locked. No side effects. */ #define VM_PAGE_HASH_LOOKUP_THRESHOLD 10 #if DEBUG_VM_PAGE_LOOKUP struct { uint64_t vpl_total; uint64_t vpl_empty_obj; uint64_t vpl_bucket_NULL; uint64_t vpl_hit_hint; uint64_t vpl_hit_hint_next; uint64_t vpl_hit_hint_prev; uint64_t vpl_fast; uint64_t vpl_slow; uint64_t vpl_hit; uint64_t vpl_miss; uint64_t vpl_fast_elapsed; uint64_t vpl_slow_elapsed; } vm_page_lookup_stats __attribute__((aligned(8))); #endif #define KDP_VM_PAGE_WALK_MAX 1000 vm_page_t kdp_vm_page_lookup( vm_object_t object, vm_object_offset_t offset) { vm_page_t cur_page; int num_traversed = 0; if (not_in_kdp) { panic("panic: kdp_vm_page_lookup done outside of kernel debugger"); } vm_page_queue_iterate(&object->memq, cur_page, vmp_listq) { if (cur_page->vmp_offset == offset) { return cur_page; } num_traversed++; if (num_traversed >= KDP_VM_PAGE_WALK_MAX) { return VM_PAGE_NULL; } } return VM_PAGE_NULL; } vm_page_t vm_page_lookup(vm_object_t object, vm_object_offset_t offset) { vm_page_t mem; vm_page_bucket_t *bucket; vm_page_queue_entry_t qe; hw_lck_ticket_t *bucket_lock = NULL; uint32_t hash_id; #if DEBUG_VM_PAGE_LOOKUP uint64_t start, elapsed; OSAddAtomic64(1, &vm_page_lookup_stats.vpl_total); #endif vm_object_lock_assert_held(object); assertf(page_aligned(offset), "offset 0x%llx\n", offset); if (object->resident_page_count == 0) { #if DEBUG_VM_PAGE_LOOKUP OSAddAtomic64(1, &vm_page_lookup_stats.vpl_empty_obj); #endif return VM_PAGE_NULL; } mem = object->memq_hint; if (mem != VM_PAGE_NULL) { assert(VM_PAGE_OBJECT(mem) == object); if (mem->vmp_offset == offset) { #if DEBUG_VM_PAGE_LOOKUP OSAddAtomic64(1, &vm_page_lookup_stats.vpl_hit_hint); #endif return mem; } qe = (vm_page_queue_entry_t)vm_page_queue_next(&mem->vmp_listq); if (!vm_page_queue_end(&object->memq, qe)) { vm_page_t next_page; next_page = (vm_page_t)((uintptr_t)qe); assert(VM_PAGE_OBJECT(next_page) == object); if (next_page->vmp_offset == offset) { object->memq_hint = next_page; /* new hint */ #if DEBUG_VM_PAGE_LOOKUP OSAddAtomic64(1, &vm_page_lookup_stats.vpl_hit_hint_next); #endif return next_page; } } qe = (vm_page_queue_entry_t)vm_page_queue_prev(&mem->vmp_listq); if (!vm_page_queue_end(&object->memq, qe)) { vm_page_t prev_page; prev_page = (vm_page_t)((uintptr_t)qe); assert(VM_PAGE_OBJECT(prev_page) == object); if (prev_page->vmp_offset == offset) { object->memq_hint = prev_page; /* new hint */ #if DEBUG_VM_PAGE_LOOKUP OSAddAtomic64(1, &vm_page_lookup_stats.vpl_hit_hint_prev); #endif return prev_page; } } } /* * Search the hash table for this object/offset pair */ hash_id = vm_page_hash(object, offset); bucket = &vm_page_buckets[hash_id]; /* * since we hold the object lock, we are guaranteed that no * new pages can be inserted into this object... this in turn * guarantess that the page we're looking for can't exist * if the bucket it hashes to is currently NULL even when looked * at outside the scope of the hash bucket lock... this is a * really cheap optimiztion to avoid taking the lock */ if (!bucket->page_list) { #if DEBUG_VM_PAGE_LOOKUP OSAddAtomic64(1, &vm_page_lookup_stats.vpl_bucket_NULL); #endif return VM_PAGE_NULL; } #if DEBUG_VM_PAGE_LOOKUP start = mach_absolute_time(); #endif if (object->resident_page_count <= VM_PAGE_HASH_LOOKUP_THRESHOLD) { /* * on average, it's roughly 3 times faster to run a short memq list * than to take the spin lock and go through the hash list */ mem = (vm_page_t)vm_page_queue_first(&object->memq); while (!vm_page_queue_end(&object->memq, (vm_page_queue_entry_t)mem)) { if (mem->vmp_offset == offset) { break; } mem = (vm_page_t)vm_page_queue_next(&mem->vmp_listq); } if (vm_page_queue_end(&object->memq, (vm_page_queue_entry_t)mem)) { mem = NULL; } } else { bucket_lock = &vm_page_bucket_locks[hash_id / BUCKETS_PER_LOCK]; /* * This lookup is extremely performance sensitive: in the * zerofill path, the release barrier in the regular call to * hw_lck_ticket_unlock() can stall when there is an in flight * vm_page_zero_fill(). * * To avoid having to synchronize with these in flight stores, * given that the only thing we do is a read-only lookup of * a page (mem), we can use hw_lck_ticket_unlock_after_lookup() * which only orders "mem" with unlock but doesn't have an * actual release barrier and allows for the vm_page_zero_fill() * stores to bleed past this code. * * On arm64 devices this is a crucial optimization on the * zerofill path that can yield 10-20% wins on a zerofill * benchmark (and significant wins on macro benchmarks that * happen to zerofill a lot). */ hw_lck_ticket_lock(bucket_lock, &vm_page_lck_grp_bucket); mem = vm_page_hash_lookup_data_dependent_locked(bucket, object, offset); hw_lck_ticket_unlock_after_lookup(bucket_lock, mem); } #if DEBUG_VM_PAGE_LOOKUP elapsed = mach_absolute_time() - start; if (bucket_lock) { OSAddAtomic64(1, &vm_page_lookup_stats.vpl_slow); OSAddAtomic64(elapsed, &vm_page_lookup_stats.vpl_slow_elapsed); } else { OSAddAtomic64(1, &vm_page_lookup_stats.vpl_fast); OSAddAtomic64(elapsed, &vm_page_lookup_stats.vpl_fast_elapsed); } if (mem != VM_PAGE_NULL) { OSAddAtomic64(1, &vm_page_lookup_stats.vpl_hit); } else { OSAddAtomic64(1, &vm_page_lookup_stats.vpl_miss); } #endif if (mem != VM_PAGE_NULL) { assert(VM_PAGE_OBJECT(mem) == object); object->memq_hint = mem; } return mem; } /* * vm_page_rename: * * Move the given memory entry from its * current object to the specified target object/offset. * * The object must be locked. */ void vm_page_rename( vm_page_t mem, vm_object_t new_object, vm_object_offset_t new_offset) { boolean_t internal_to_external, external_to_internal; vm_tag_t tag; vm_object_t m_object; m_object = VM_PAGE_OBJECT(mem); assert(m_object != new_object); assert(m_object); /* * Changes to mem->vmp_object require the page lock because * the pageout daemon uses that lock to get the object. */ vm_page_lockspin_queues(); internal_to_external = FALSE; external_to_internal = FALSE; if (mem->vmp_q_state == VM_PAGE_ON_ACTIVE_LOCAL_Q) { /* * it's much easier to get the vm_page_pageable_xxx accounting correct * if we first move the page to the active queue... it's going to end * up there anyway, and we don't do vm_page_rename's frequently enough * for this to matter. */ vm_page_queues_remove(mem, FALSE); vm_page_activate(mem); } if (VM_PAGE_PAGEABLE(mem)) { if (m_object->internal && !new_object->internal) { internal_to_external = TRUE; } if (!m_object->internal && new_object->internal) { external_to_internal = TRUE; } } tag = m_object->wire_tag; vm_page_remove(mem); vm_page_insert_internal(mem, new_object, new_offset, tag, VMPI_Q_LOCKED, NULL); if (internal_to_external) { vm_page_pageable_internal_count--; vm_page_pageable_external_count++; } else if (external_to_internal) { vm_page_pageable_external_count--; vm_page_pageable_internal_count++; } vm_page_unlock_queues(); } /* * vm_page_init: * * Initialize the fields in a new page. * This takes a structure with random values and initializes it * so that it can be given to vm_page_release or vm_page_insert. */ void vm_page_init(vm_page_t mem, ppnum_t phys_page) { assert(phys_page); #if DEBUG if ((phys_page != vm_page_fictitious_addr) && (phys_page != vm_page_guard_addr)) { if (!(pmap_valid_page(phys_page))) { panic("vm_page_init: non-DRAM phys_page 0x%x", phys_page); } } #endif /* DEBUG */ /* * Initialize the fields of the vm_page. If adding any new fields to vm_page, * try to use initial values which match 0. This minimizes the number of writes * needed for boot-time initialization. */ assert(VM_PAGE_NOT_ON_Q == 0); assert(sizeof(*mem) % sizeof(uintptr_t) == 0); *mem = (struct vm_page) { .vmp_offset = (vm_object_offset_t)-1, .vmp_q_state = VM_PAGE_NOT_ON_Q, .vmp_on_specialq = VM_PAGE_SPECIAL_Q_EMPTY, .vmp_canonical = vm_page_in_array(mem), .vmp_busy = true, }; VM_PAGE_INIT_PHYS_PAGE(mem, phys_page); #if 0 /* * we're leaving this turned off for now... currently pages * come off the free list and are either immediately dirtied/referenced * due to zero-fill or COW faults, or are used to read or write files... * in the file I/O case, the UPL mechanism takes care of clearing * the state of the HW ref/mod bits in a somewhat fragile way. * Since we may change the way this works in the future (to toughen it up), * I'm leaving this as a reminder of where these bits could get cleared */ /* * make sure both the h/w referenced and modified bits are * clear at this point... we are especially dependent on * not finding a 'stale' h/w modified in a number of spots * once this page goes back into use */ pmap_clear_refmod(phys_page, VM_MEM_MODIFIED | VM_MEM_REFERENCED); #endif } vm_page_t vm_page_create_fictitious(void) { return vm_page_create(vm_page_fictitious_addr, false, Z_WAITOK); } vm_page_t vm_page_create_guard(bool canwait) { return vm_page_create(vm_page_guard_addr, false, canwait ? Z_WAITOK : Z_NOWAIT); } vm_page_t vm_page_create_private(ppnum_t base_page) { assert(base_page != vm_page_fictitious_addr && base_page != vm_page_guard_addr); return vm_page_create(base_page, false, Z_WAITOK); } bool vm_page_is_canonical(const struct vm_page *m) { return m->vmp_canonical; } bool vm_page_is_fictitious(const struct vm_page *m) { #if XNU_VM_HAS_LINEAR_PAGES_ARRAY if (vm_page_in_array(m)) { return false; } #endif /* XNU_VM_HAS_LINEAR_PAGES_ARRAY */ switch (VM_PAGE_GET_PHYS_PAGE(m)) { case vm_page_guard_addr: case vm_page_fictitious_addr: return true; default: return false; } } bool vm_page_is_guard(const struct vm_page *m) { #if XNU_VM_HAS_LINEAR_PAGES_ARRAY if (vm_page_in_array(m)) { return false; } #endif /* XNU_VM_HAS_LINEAR_PAGES_ARRAY */ return VM_PAGE_GET_PHYS_PAGE(m) == vm_page_guard_addr; } bool vm_page_is_private(const struct vm_page *m) { return !vm_page_is_canonical(m) && !vm_page_is_fictitious(m); } void vm_page_make_private(vm_page_t m, ppnum_t base_page) { LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); assert(VM_PAGE_GET_PHYS_PAGE(m) == vm_page_fictitious_addr); VM_PAGE_SET_PHYS_PAGE(m, base_page); } void vm_page_reset_private(vm_page_t m) { assert(vm_page_is_private(m)); VM_PAGE_SET_PHYS_PAGE(m, vm_page_fictitious_addr); } /* * vm_page_release_fictitious: * * Release a fictitious page to the zone pool */ static void vm_page_release_fictitious(vm_page_t m) { assert((m->vmp_q_state == VM_PAGE_NOT_ON_Q) || VM_PAGE_WIRED(m)); assert(vm_page_is_fictitious(m)); assert(!m->vmp_realtime); if (vm_page_is_guard(m)) { counter_dec(&vm_guard_count); } zfree(vm_page_zone, m); } /* * vm_pool_low(): * * Return true if it is not likely that a non-vm_privileged thread * can get memory without blocking. Advisory only, since the * situation may change under us. */ bool vm_pool_low(void) { /* No locking, at worst we will fib. */ return vm_page_free_count <= vm_page_free_reserved; } boolean_t vm_darkwake_mode = FALSE; /* * vm_update_darkwake_mode(): * * Tells the VM that the system is in / out of darkwake. * * Today, the VM only lowers/raises the background queue target * so as to favor consuming more/less background pages when * darwake is ON/OFF. * * We might need to do more things in the future. */ void vm_update_darkwake_mode(boolean_t darkwake_mode) { #if XNU_TARGET_OS_OSX && defined(__arm64__) #pragma unused(darkwake_mode) assert(vm_darkwake_mode == FALSE); /* * Darkwake mode isn't supported for AS macOS. */ return; #else /* XNU_TARGET_OS_OSX && __arm64__ */ LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_NOTOWNED); vm_page_lockspin_queues(); if (vm_darkwake_mode == darkwake_mode) { /* * No change. */ vm_page_unlock_queues(); return; } vm_darkwake_mode = darkwake_mode; if (vm_darkwake_mode == TRUE) { /* save background target to restore later */ vm_page_background_target_snapshot = vm_page_background_target; /* target is set to 0...no protection for background pages */ vm_page_background_target = 0; } else if (vm_darkwake_mode == FALSE) { if (vm_page_background_target_snapshot) { vm_page_background_target = vm_page_background_target_snapshot; } } vm_page_unlock_queues(); #endif } void vm_page_update_special_state(vm_page_t mem) { if (mem->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR || mem->vmp_on_specialq == VM_PAGE_SPECIAL_Q_EMPTY) { return; } switch (mem->vmp_on_specialq) { case VM_PAGE_SPECIAL_Q_BG: { task_t my_task = current_task_early(); if (vm_page_background_mode == VM_PAGE_BG_DISABLED) { return; } if (my_task) { if (task_get_darkwake_mode(my_task)) { return; } } if (my_task) { if (proc_get_effective_task_policy(my_task, TASK_POLICY_DARWIN_BG)) { return; } } vm_page_lockspin_queues(); vm_page_background_promoted_count++; vm_page_remove_from_specialq(mem); mem->vmp_on_specialq = VM_PAGE_SPECIAL_Q_EMPTY; vm_page_unlock_queues(); break; } case VM_PAGE_SPECIAL_Q_DONATE: { task_t my_task = current_task_early(); if (vm_page_donate_mode == VM_PAGE_DONATE_DISABLED) { return; } if (my_task->donates_own_pages == false) { vm_page_lockspin_queues(); vm_page_remove_from_specialq(mem); mem->vmp_on_specialq = VM_PAGE_SPECIAL_Q_EMPTY; vm_page_unlock_queues(); } break; } default: { assert(VM_PAGE_UNPACK_PTR(mem->vmp_specialq.next) == (uintptr_t)NULL && VM_PAGE_UNPACK_PTR(mem->vmp_specialq.prev) == (uintptr_t)NULL); break; } } } void vm_page_assign_special_state(vm_page_t mem, vm_page_specialq_t mode) { if (mem->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) { return; } switch (mode) { case VM_PAGE_SPECIAL_Q_BG: { if (vm_page_background_mode == VM_PAGE_BG_DISABLED) { return; } task_t my_task = current_task_early(); if (my_task) { if (task_get_darkwake_mode(my_task)) { mem->vmp_on_specialq = VM_PAGE_SPECIAL_Q_BG; return; } } if (my_task) { mem->vmp_on_specialq = (proc_get_effective_task_policy(my_task, TASK_POLICY_DARWIN_BG) ? VM_PAGE_SPECIAL_Q_BG : VM_PAGE_SPECIAL_Q_EMPTY); } break; } case VM_PAGE_SPECIAL_Q_DONATE: { if (vm_page_donate_mode == VM_PAGE_DONATE_DISABLED) { return; } mem->vmp_on_specialq = VM_PAGE_SPECIAL_Q_DONATE; break; } default: break; } } void vm_page_remove_from_specialq(vm_page_t mem) { vm_object_t m_object; LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); switch (mem->vmp_on_specialq) { case VM_PAGE_SPECIAL_Q_BG: { if (mem->vmp_specialq.next && mem->vmp_specialq.prev) { vm_page_queue_remove(&vm_page_queue_background, mem, vmp_specialq); mem->vmp_specialq.next = 0; mem->vmp_specialq.prev = 0; vm_page_background_count--; m_object = VM_PAGE_OBJECT(mem); if (m_object->internal) { vm_page_background_internal_count--; } else { vm_page_background_external_count--; } } break; } case VM_PAGE_SPECIAL_Q_DONATE: { if (mem->vmp_specialq.next && mem->vmp_specialq.prev) { vm_page_queue_remove((vm_page_queue_head_t*)&vm_page_queue_donate, mem, vmp_specialq); mem->vmp_specialq.next = 0; mem->vmp_specialq.prev = 0; vm_page_donate_count--; if (vm_page_donate_queue_ripe && (vm_page_donate_count < vm_page_donate_target)) { assert(vm_page_donate_target == vm_page_donate_target_low); vm_page_donate_target = vm_page_donate_target_high; vm_page_donate_queue_ripe = false; } } break; } default: { assert(VM_PAGE_UNPACK_PTR(mem->vmp_specialq.next) == (uintptr_t)NULL && VM_PAGE_UNPACK_PTR(mem->vmp_specialq.prev) == (uintptr_t)NULL); break; } } } void vm_page_add_to_specialq(vm_page_t mem, boolean_t first) { vm_object_t m_object; LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); if (mem->vmp_specialq.next && mem->vmp_specialq.prev) { return; } switch (mem->vmp_on_specialq) { case VM_PAGE_SPECIAL_Q_BG: { if (vm_page_background_mode == VM_PAGE_BG_DISABLED) { return; } m_object = VM_PAGE_OBJECT(mem); if (vm_page_background_exclude_external && !m_object->internal) { return; } if (first == TRUE) { vm_page_queue_enter_first(&vm_page_queue_background, mem, vmp_specialq); } else { vm_page_queue_enter(&vm_page_queue_background, mem, vmp_specialq); } mem->vmp_on_specialq = VM_PAGE_SPECIAL_Q_BG; vm_page_background_count++; if (m_object->internal) { vm_page_background_internal_count++; } else { vm_page_background_external_count++; } break; } case VM_PAGE_SPECIAL_Q_DONATE: { if (first == TRUE) { vm_page_queue_enter_first((vm_page_queue_head_t*)&vm_page_queue_donate, mem, vmp_specialq); } else { vm_page_queue_enter((vm_page_queue_head_t*)&vm_page_queue_donate, mem, vmp_specialq); } vm_page_donate_count++; if (!vm_page_donate_queue_ripe && (vm_page_donate_count > vm_page_donate_target)) { assert(vm_page_donate_target == vm_page_donate_target_high); vm_page_donate_target = vm_page_donate_target_low; vm_page_donate_queue_ripe = true; } mem->vmp_on_specialq = VM_PAGE_SPECIAL_Q_DONATE; break; } default: break; } } /*! * @brief * Prepares a page that has been successfully grabbed for the caller. * * @discussion * This function will update accounting, emit tracements, ... */ __static_testable vm_page_t vm_page_grab_finalize(vm_grab_options_t grab_options __kdebug_only, vm_page_t mem) { task_t task; #if MACH_ASSERT /* * For all free pages, no matter their provenance... * ensure they are not referenced anywhere, * and their state is clean. */ if (vm_check_refs_on_alloc) { pmap_recycle_page(VM_PAGE_GET_PHYS_PAGE(mem)); } assert(!pmap_is_noencrypt(VM_PAGE_GET_PHYS_PAGE(mem))); assert(mem->vmp_pageq.next == 0 && mem->vmp_pageq.prev == 0 && mem->vmp_listq.next == 0 && mem->vmp_listq.prev == 0 && mem->vmp_specialq.next == 0 && mem->vmp_specialq.prev == 0 && mem->vmp_next_m == 0 && mem->vmp_object == 0 && mem->vmp_wire_count == 0 && mem->vmp_busy && !mem->vmp_tabled && !mem->vmp_laundry && !mem->vmp_pmapped && !mem->vmp_wpmapped && !mem->vmp_realtime); #endif /* MACH_ASSERT */ mem->vmp_q_state = VM_PAGE_NOT_ON_Q; VM_PAGE_ZERO_PAGEQ_ENTRY(mem); #if HAS_MTE if (!(grab_options & VM_PAGE_GRAB_ALLOW_TAG_STORAGE)) { assert(!vm_page_is_tag_storage(mem)); } if (grab_options & VM_PAGE_GRAB_MTE) { assert(mem->vmp_using_mte); counter_inc(&vm_mte_tagged_pages_grabbed); VM_DEBUG_EVENT(vm_page_grab, DBG_VM_PAGE_GRAB_MTE, DBG_FUNC_NONE, grab_options, 0, 0, 0); } else #endif /* HAS_MTE */ { #if HAS_MTE if (mem->vmp_using_mte) { counter_inc(&vm_mte_tagged_pages_grabbed_for_untagged); } #endif /* HAS_MTE */ VM_DEBUG_EVENT(vm_page_grab, DBG_VM_PAGE_GRAB, DBG_FUNC_NONE, grab_options, 0, 0, 0); } ledger_credit(current_thread()->t_ledger, task_ledgers.pages_grabbed, 1); counter_inc(&vm_page_grab_count); task = current_task_early(); if (task != TASK_NULL && task != kernel_task) { /* * tag:DONATE this is where the donate state of the page * is decided according to what task grabs it */ if (task->donates_own_pages) { vm_page_assign_special_state(mem, VM_PAGE_SPECIAL_Q_DONATE); } else { vm_page_assign_special_state(mem, VM_PAGE_SPECIAL_Q_BG); } } if (grab_options & VM_PAGE_GRAB_ZERO_FILL) { vm_page_zero_fill(mem); } return mem; } #if __x86_64__ /* * This can be switched to FALSE to help debug drivers * that are having problems with memory > 4G. */ boolean_t vm_himemory_mode = TRUE; #endif /* __x86_64__ */ #if XNU_VM_HAS_LOPAGE vm_page_t vm_page_grablo(vm_grab_options_t options) { vm_page_t mem = VM_PAGE_NULL; if (!vm_lopage_needed) { return vm_page_grab_options(options); } vm_free_page_lock_spin(); if (vm_lopage_free_count) { #if LCK_MTX_USE_ARCH /* * Intel locks do not really always disable preemption * for lck_mtx_lock_spin(), and vm_page_free_queue_grab() * really want that. */ disable_preemption(); #endif mem = vm_page_free_queue_grab(PERCPU_GET(vm_page_pcpu), options, VM_MEMORY_CLASS_LOPAGE, 1, VM_PAGE_NOT_ON_Q).vmpl_head; #if LCK_MTX_USE_ARCH enable_preemption(); #endif } vm_free_page_unlock(); if (mem == VM_PAGE_NULL) { if (cpm_allocate(PAGE_SIZE, &mem, atop(PPNUM_MAX), 0, FALSE, KMA_LOMEM) != KERN_SUCCESS) { vm_free_page_lock_spin(); vm_lopages_allocated_cpm_failed++; vm_free_page_unlock(); return VM_PAGE_NULL; } assert(mem->vmp_q_state == VM_PAGE_NOT_ON_Q); mem->vmp_busy = TRUE; vm_page_lockspin_queues(); mem->vmp_gobbled = FALSE; vm_page_gobble_count--; vm_page_wire_count--; vm_lopages_allocated_cpm_success++; vm_page_unlock_queues(); } return vm_page_grab_finalize(options, mem); } #endif /* XNU_VM_HAS_LOPAGE */ #if CONFIG_SECLUDED_MEMORY /*! * @brief * Attempt to allocate a page from the secluded queue * * @discussion * This function will check that the caller is eligible * for the secluded pool, and if not, return VM_PAGE_NULL. */ __attribute__((noinline)) static vm_page_t vm_page_grab_secluded(vm_grab_options_t grab_options) { vm_page_t mem; vm_object_t object; int refmod_state; #if HAS_MTE if (grab_options & VM_PAGE_GRAB_MTE) { return VM_PAGE_NULL; } #endif /* HAS_MTE */ if (vm_page_secluded_count == 0) { return VM_PAGE_NULL; } if (grab_options & VM_PAGE_GRAB_SECLUDED) { vm_page_secluded.grab_for_iokit++; } else if (!task_can_use_secluded_mem(current_task(), TRUE)) { return VM_PAGE_NULL; } /* secluded queue is protected by the VM page queue lock */ vm_page_lock_queues(); if (vm_page_secluded_count == 0) { /* no secluded pages to grab... */ vm_page_unlock_queues(); return VM_PAGE_NULL; } #if 00 /* can we grab from the secluded queue? */ if (vm_page_secluded_count > vm_page_secluded_target || (vm_page_secluded_count > 0 && task_can_use_secluded_mem(current_task(), TRUE))) { /* OK */ } else { /* can't grab from secluded queue... */ vm_page_unlock_queues(); return VM_PAGE_NULL; } #endif /* we can grab a page from secluded queue! */ assert((vm_page_secluded_count_free + vm_page_secluded_count_inuse) == vm_page_secluded_count); if (current_task()->task_can_use_secluded_mem) { assert(num_tasks_can_use_secluded_mem > 0); } assert(!vm_page_queue_empty(&vm_page_queue_secluded)); LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); mem = (vm_page_t)vm_page_queue_first(&vm_page_queue_secluded); assert(mem->vmp_q_state == VM_PAGE_ON_SECLUDED_Q); vm_page_queues_remove(mem, TRUE); object = VM_PAGE_OBJECT(mem); assert(!vm_page_is_fictitious(mem)); assert(!VM_PAGE_WIRED(mem)); if (object == VM_OBJECT_NULL) { /* free for grab! */ vm_page_unlock_queues(); vm_page_secluded.grab_success_free++; goto out_success; } assert(!object->internal); // vm_page_pageable_external_count--; if (!vm_object_lock_try(object)) { // printf("SECLUDED: page %p: object %p locked\n", mem, object); vm_page_secluded.grab_failure_locked++; reactivate_secluded_page: vm_page_activate(mem); vm_page_unlock_queues(); return VM_PAGE_NULL; } if (mem->vmp_busy || mem->vmp_cleaning || mem->vmp_laundry) { /* can't steal page in this state... */ vm_object_unlock(object); vm_page_secluded.grab_failure_state++; goto reactivate_secluded_page; } if (mem->vmp_realtime) { /* don't steal pages used by realtime threads... */ vm_object_unlock(object); vm_page_secluded.grab_failure_realtime++; goto reactivate_secluded_page; } mem->vmp_busy = TRUE; refmod_state = pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(mem)); if (refmod_state & VM_MEM_REFERENCED) { mem->vmp_reference = TRUE; } if (refmod_state & VM_MEM_MODIFIED) { SET_PAGE_DIRTY(mem, FALSE); } if (mem->vmp_dirty || mem->vmp_precious) { /* can't grab a dirty page; re-activate */ // printf("SECLUDED: dirty page %p\n", mem); vm_page_wakeup_done(object, mem); vm_page_secluded.grab_failure_dirty++; vm_object_unlock(object); goto reactivate_secluded_page; } if (mem->vmp_reference) { /* it's been used but we do need to grab a page... */ } vm_page_unlock_queues(); /* finish what vm_page_free() would have done... */ vm_page_free_prepare_object(mem); vm_object_unlock(object); object = VM_OBJECT_NULL; pmap_clear_noencrypt(VM_PAGE_GET_PHYS_PAGE(mem)); vm_page_secluded.grab_success_other++; out_success: if (grab_options & VM_PAGE_GRAB_SECLUDED) { vm_page_secluded.grab_for_iokit_success++; } return mem; } uint64_t vm_page_secluded_drain(void) { vm_page_t local_freeq; int local_freed; uint64_t num_reclaimed; unsigned int saved_secluded_count, saved_secluded_target; num_reclaimed = 0; local_freeq = NULL; local_freed = 0; vm_page_lock_queues(); saved_secluded_count = vm_page_secluded_count; saved_secluded_target = vm_page_secluded_target; vm_page_secluded_target = 0; VM_PAGE_SECLUDED_COUNT_OVER_TARGET_UPDATE(); while (vm_page_secluded_count) { vm_page_t secluded_page; assert((vm_page_secluded_count_free + vm_page_secluded_count_inuse) == vm_page_secluded_count); secluded_page = (vm_page_t)vm_page_queue_first(&vm_page_queue_secluded); assert(secluded_page->vmp_q_state == VM_PAGE_ON_SECLUDED_Q); vm_page_queues_remove(secluded_page, FALSE); assert(!vm_page_is_fictitious(secluded_page)); assert(!VM_PAGE_WIRED(secluded_page)); if (secluded_page->vmp_object == 0) { /* transfer to free queue */ assert(secluded_page->vmp_busy); secluded_page->vmp_snext = local_freeq; local_freeq = secluded_page; local_freed += 1; } else { /* transfer to head of active queue */ vm_page_enqueue_active(secluded_page, FALSE); secluded_page = VM_PAGE_NULL; } num_reclaimed++; } vm_page_secluded_target = saved_secluded_target; VM_PAGE_SECLUDED_COUNT_OVER_TARGET_UPDATE(); // printf("FBDP %s:%d secluded_count %d->%d, target %d, reclaimed %lld\n", __FUNCTION__, __LINE__, saved_secluded_count, vm_page_secluded_count, vm_page_secluded_target, num_reclaimed); vm_page_unlock_queues(); if (local_freed) { vm_page_free_list(local_freeq, TRUE); local_freeq = NULL; local_freed = 0; } return num_reclaimed; } #endif /* CONFIG_SECLUDED_MEMORY */ /*! * @brief * Attempts to allocate a page from the specified per-cpu page queue. */ static vm_page_t vm_page_grab_from_cpu( vm_grab_options_t *options, vm_page_t *zf_page, vm_page_t *cpu_list, scalable_counter_t *counter) { vm_page_t mem = VM_PAGE_NULL; if ((*options & VM_PAGE_GRAB_ZERO_FILL) && (mem = *zf_page)) { *zf_page = VM_PAGE_NULL; *options &= ~VM_PAGE_GRAB_ZERO_FILL; } else if ((mem = _vm_page_list_pop(cpu_list)) == VM_PAGE_NULL) { return VM_PAGE_NULL; } #if HIBERNATION if (hibernate_rebuild_needed) { panic("should not modify cpu->free_pages while hibernating"); } #endif /* HIBERNATION */ counter_dec_preemption_disabled(counter); return mem; } #if HAS_MTE /*! * @brief * Attempts to allocate pages from free tag storage percpu queue. */ static vm_page_t vm_page_grab_claimed_from_cpu(vm_page_pcpu_t pcpu, vm_grab_options_t options) { vm_page_t mem = VM_PAGE_NULL; if (!(options & VM_PAGE_GRAB_ALLOW_TAG_STORAGE)) { return VM_PAGE_NULL; } if (vm_page_queue_empty(&pcpu->free_claimed_pages)) { return VM_PAGE_NULL; } lck_ticket_lock(&pcpu->free_claimed_lock, &vm_page_lck_grp_bucket); if (!vm_page_queue_empty(&pcpu->free_claimed_pages)) { vm_page_queue_remove_first(&pcpu->free_claimed_pages, mem, vmp_pageq); counter_dec_preemption_disabled(&vm_cpu_free_claimed_count); counter_inc(&vm_cpu_claimed_count); /* must be done immediately to synchronize with stealing */ mem->vmp_q_state = VM_PAGE_NOT_ON_Q; mem->vmp_local_id = 0; } lck_ticket_unlock(&pcpu->free_claimed_lock); return mem; } #endif /* HAS_MTE */ /*! * @brief * Attempts to allocate pages from free queues, and to populate the per-cpu * queue as a side effect. * * @discussion * This function will take the properties of the allocating thread into account * to decide how many pages it can allocate. * * If the free queues are depleted, then it will return VM_PAGE_NULL. */ __attribute__((noinline)) static vm_page_t vm_page_grab_slow(vm_grab_options_t grab_options) { #if HAS_MTE unsigned int mte_draw = 0; unsigned int mte_slop = 0; #endif /* HAS_MTE */ unsigned int target = vm_free_magazine_refill_limit; vm_memory_class_t class = VM_MEMORY_CLASS_REGULAR; vm_page_t mem = VM_PAGE_NULL; vm_page_list_t list = { }; vm_page_pcpu_t vmp_pcpu = NULL; vm_page_t *zf_page = NULL; vm_page_t *cpu_list = NULL; scalable_counter_t *counter = NULL; vm_free_page_lock_spin(); #if LCK_MTX_USE_ARCH /* Intel does't disable preemption with vm_free_page_lock_spin() */ disable_preemption(); #endif /* LCK_MTX_USE_ARCH */ vmp_pcpu = PERCPU_GET(vm_page_pcpu); zf_page = &vmp_pcpu->free_zero_page; cpu_list = &vmp_pcpu->free_pages; counter = &vm_cpu_free_count; #if HAS_MTE if (grab_options & VM_PAGE_GRAB_MTE) { again: zf_page = &vmp_pcpu->free_tagged_zero_page; cpu_list = &vmp_pcpu->free_tagged_pages; counter = &vm_cpu_free_tagged_count; target = vm_free_magazine_refill_limit / 2; class = VM_MEMORY_CLASS_TAGGED; mte_slop = 0; } else if (grab_options & VM_PAGE_GRAB_ALLOW_TAG_STORAGE) { /* * Note that this is the last time we'll explicitly try to grab * free, claimable pages. If it comes down to it, we'll grab either * normal or dead tag storage pages in vm_page_free_queue_grab() * and hopefully refill the per-CPU free claimable queue. */ mem = vm_page_grab_claimed_from_cpu(vmp_pcpu, grab_options); if (mem != VM_PAGE_NULL) { vm_free_page_unlock(); return mem; } } #endif /* HAS_MTE */ if (grab_options & VM_PAGE_GRAB_PRIME) { mem = *cpu_list ? VM_PAGE_PRIMED : VM_PAGE_NULL; } else { mem = vm_page_grab_from_cpu(&grab_options, zf_page, cpu_list, counter); } if (mem != VM_PAGE_NULL) { #if LCK_MTX_USE_ARCH enable_preemption(); #endif /* LCK_MTX_USE_ARCH */ vm_free_page_unlock(); return mem; } if (vm_page_free_count <= vm_page_free_reserved) { if ((grab_options & VM_PAGE_GRAB_VM_PRIV) == 0) { target = 0; } else if (vm_page_free_count == 0) { target = 0; } else { target = 1; } } else { target = MIN(target, vm_page_free_count - vm_page_free_reserved); } #if HAS_MTE if (grab_options & VM_PAGE_GRAB_MTE) { mte_draw = target; target = 0; if (vm_page_free_taggable_count < mte_draw + vm_page_free_min && vm_page_free_count >= mte_draw + vm_page_free_min && !(grab_options & VM_PAGE_GRAB_Q_LOCK_HELD)) { /* * If the mte draw is such that we deplete our reserves, * but there are enough free untaggable pages available, * attempt to activate pages in order to rebalance * toward the taggable pool. * * If the operation succeeds, the free page queue lock * was dropped and we need to re-take it from the top. */ if (mteinfo_tag_storage_try_activate(mte_draw + vm_page_free_min - vm_page_free_taggable_count, /* lock_spin */ true)) { vmp_pcpu = PERCPU_GET(vm_page_pcpu); goto again; } } } else if (target > vm_page_free_count - vm_page_free_taggable_count) { mte_draw = target - (vm_page_free_count - vm_page_free_taggable_count); target = (vm_page_free_count - vm_page_free_taggable_count); } else { mte_draw = 0; } if (vm_page_free_taggable_count <= vm_page_free_reserved) { if ((grab_options & VM_PAGE_GRAB_VM_PRIV) == 0) { mte_draw = 0; } else if (vm_page_free_taggable_count == 0) { mte_draw = 0; } else if (target) { mte_draw = 0; } else { mte_draw = 1; } } else { mte_draw = MIN(mte_draw, vm_page_free_taggable_count - vm_page_free_reserved); } target += mte_draw; #endif /* HAS_MTE */ #if HIBERNATION if (target > 0 && hibernate_rebuild_needed) { panic("should not modify CPU free_pages while hibernating"); } #endif /* HIBERNATION */ /* * Convert the lock hold into a mutex, to signal to waiters that the * lock may be held for longer. */ #if !LCK_MTX_USE_ARCH disable_preemption(); #endif /* !LCK_MTX_USE_ARCH */ vm_free_page_lock_convert(); if (target != 0) { list = vm_page_free_queue_grab(vmp_pcpu, grab_options, class, target, VM_PAGE_ON_FREE_LOCAL_Q); } #if VM_PAGE_WIRE_COUNT_WARNING if (vm_page_wire_count >= VM_PAGE_WIRE_COUNT_WARNING) { printf("mk: vm_page_grab(): high wired page count of %d\n", vm_page_wire_count); } #endif #if VM_PAGE_GOBBLE_COUNT_WARNING if (vm_page_gobble_count >= VM_PAGE_GOBBLE_COUNT_WARNING) { printf("mk: vm_page_grab(): high gobbled page count of %d\n", vm_page_gobble_count); } #endif if (vm_page_free_count < vm_page_free_min && !vm_pageout_running) { thread_wakeup(&vm_page_free_wanted); } vm_free_page_unlock(); VM_CHECK_MEMORYSTATUS; if (list.vmpl_head) { #if HAS_MTE mteinfo_page_list_fix_tagging(class, &list); #endif /* HAS_MTE */ /* Steal a page off the list for the caller. */ if (grab_options & VM_PAGE_GRAB_PRIME) { mem = VM_PAGE_PRIMED; } else { mem = vm_page_list_pop(&list); } /* Add the remaining pages to the CPU's free list. */ assert(*cpu_list == VM_PAGE_NULL); counter_add_preemption_disabled(counter, list.vmpl_count); if ((grab_options & VM_PAGE_GRAB_PRIME) && !*zf_page && (*zf_page = vm_page_list_pop(&list))) { vm_page_zero_fill(*zf_page); } *cpu_list = list.vmpl_head; counter_add_preemption_disabled(counter, list.vmpl_count); } enable_preemption(); return mem; } __mockable vm_page_t vm_page_grab_options(vm_grab_options_t options) { vm_page_pcpu_t vmp_pcpu = NULL; vm_page_t *zf_page = NULL; vm_page_t *cpu_list = NULL; scalable_counter_t *counter = &vm_cpu_free_count; vm_page_t mem = VM_PAGE_NULL; if (current_thread()->options & TH_OPT_VMPRIV) { options |= VM_PAGE_GRAB_VM_PRIV; } restart: /* * Step 1: look at the CPU magazines. */ disable_preemption(); vmp_pcpu = PERCPU_GET(vm_page_pcpu); zf_page = &vmp_pcpu->free_zero_page; cpu_list = &vmp_pcpu->free_pages; #if HAS_MTE if (options & VM_PAGE_GRAB_MTE) { counter = &vm_cpu_free_tagged_count; zf_page = &vmp_pcpu->free_tagged_zero_page; cpu_list = &vmp_pcpu->free_tagged_pages; } if (options & VM_PAGE_GRAB_ALLOW_TAG_STORAGE) { mem = vm_page_grab_claimed_from_cpu(vmp_pcpu, options); } if (mem == VM_PAGE_NULL) { mem = vm_page_grab_from_cpu(&options, zf_page, cpu_list, counter); } #else mem = vm_page_grab_from_cpu(&options, zf_page, cpu_list, counter); #endif /* HAS_MTE */ enable_preemption(); if (mem != VM_PAGE_NULL) { return vm_page_grab_finalize(options, mem); } #if XNU_VM_HAS_DELAYED_PAGES /* * If free count is low and we have delayed pages from early boot, * get one of those instead. */ if (__improbable(vm_delayed_count > 0 && vm_page_free_count <= vm_page_free_target)) { mem = vm_get_delayed_page(options); if (mem != VM_PAGE_NULL) { return vm_page_grab_finalize(options, mem); } } #endif /* XNU_VM_HAS_DELAYED_PAGES */ /* * Step 2: Try to promote pages from the free queues, * or the secluded queue if appropriate. */ mem = vm_page_grab_slow(options); if (mem != VM_PAGE_NULL) { return vm_page_grab_finalize(options, mem); } #if CONFIG_SECLUDED_MEMORY mem = vm_page_grab_secluded(options); if (mem != VM_PAGE_NULL) { return vm_page_grab_finalize(options, mem); } #endif /* CONFIG_SECLUDED_MEMORY */ /* * Step 3: Privileged threads block and retry, others fail. */ #if HAS_MTE if (options & VM_PAGE_GRAB_MTE) { current_thread()->page_wait_class = VM_MEMORY_CLASS_TAGGED; } else { current_thread()->page_wait_class = VM_MEMORY_CLASS_REGULAR; } #endif /* HAS_MTE */ if ((options & (VM_PAGE_GRAB_NOPAGEWAIT | VM_PAGE_GRAB_VM_PRIV)) == VM_PAGE_GRAB_VM_PRIV) { VM_PAGE_WAIT(); goto restart; } return VM_PAGE_NULL; } vm_grab_options_t vm_page_grab_options_for_object(vm_object_t object __unused) { vm_grab_options_t options = VM_PAGE_GRAB_OPTIONS_NONE; #if CONFIG_SECLUDED_MEMORY if (object->can_grab_secluded) { options |= VM_PAGE_GRAB_SECLUDED; } #endif /* CONFIG_SECLUDED_MEMORY */ #if HAS_MTE if (vm_object_is_mte_mappable(object)) { options |= VM_PAGE_GRAB_MTE; } #endif /* HAS_MTE */ return options; } __attribute__((always_inline)) void vm_page_grab_prime(void) { vm_page_pcpu_t vmp_pcpu; vm_page_t *zfp; vm_page_t mem; #if HAS_MTE vm_page_t tmem; #endif /* HAS_MTE */ disable_preemption(); vmp_pcpu = PERCPU_GET(vm_page_pcpu); zfp = &vmp_pcpu->free_zero_page; if (!*zfp && (*zfp = _vm_page_list_pop(&vmp_pcpu->free_pages))) { vm_page_zero_fill(*zfp); } mem = vmp_pcpu->free_pages; #if HAS_MTE zfp = &vmp_pcpu->free_tagged_zero_page; if (!*zfp && (*zfp = _vm_page_list_pop(&vmp_pcpu->free_tagged_pages))) { vm_page_zero_fill(*zfp); } tmem = vmp_pcpu->free_tagged_pages; #endif /* HAS_MTE */ enable_preemption(); if (mem == VM_PAGE_NULL) { (void)vm_page_grab_slow(VM_PAGE_GRAB_NOPAGEWAIT | VM_PAGE_GRAB_PRIME); } #if HAS_MTE if (tmem == VM_PAGE_NULL) { (void)vm_page_grab_slow(VM_PAGE_GRAB_NOPAGEWAIT | VM_PAGE_GRAB_PRIME | VM_PAGE_GRAB_MTE); } #endif } /*! * @function vm_page_free_queue_steal() * * @abstract * Steal a given page from the free queues. * * @discussion * The given page must be in the given free queue, or state may be corrupted. * * Internally, the free queue is not synchronized, so any locking must be done * outside of this function. * * This function, like vm_page_grab(), takes care of waking up * page out scan as needed. */ static void vm_page_free_queue_steal(vm_grab_options_t options, vm_page_t mem) { ppnum_t pnum = VM_PAGE_GET_PHYS_PAGE(mem); vm_memory_class_t class = vm_page_get_memory_class(mem, pnum); assert(mem->vmp_q_state == VM_PAGE_ON_FREE_Q); assert(!mem->vmp_lopage && mem->vmp_busy); vm_page_free_queue_remove(class, mem, pnum, VM_PAGE_NOT_ON_Q); vm_page_grab_finalize(options, mem); if (vm_page_free_count < vm_page_free_min && !vm_pageout_running) { thread_wakeup(&vm_page_free_wanted); } } #if HAS_MTE /*! * @function _vm_page_wait_wakeup_fill_thread() * * @abstract * Given the number of waiters, return whether the MTE fill thread should * wake up. * * @discussion * The idea is to wake up the MTE fill thread without explicitly triggering * pageout_scan(), which means @c vm_page_free_count must be at least * @c vm_page_free_min. On top of that, it's possible that tag storage pages * may get relocated, which means that some free untagged pages will be needed * to activate a tag storage page. This function uses the naive, pessimistic * heuristic that a given tag storage page does not have many free covered * pages, and some number of those tag storage pages will need to be relocated. * * The free queue lock should be held during this function. * * @param n_waiters The number of waiters for tagged memory. * * @returns Whether the system has enough free pages to * wake up the MTE fill thread. */ static bool _vm_page_wait_wakeup_fill_thread(uint32_t n_waiters) { LCK_MTX_ASSERT(&vm_page_queue_free_lock, LCK_MTX_ASSERT_OWNED); return vm_page_free_count > vm_page_free_min + (3 * n_waiters) / 2; } #endif /* HAS_MTE */ /* * vm_page_wait: * * Wait for a page to become available. * If there are plenty of free pages, then we don't sleep. * * Returns: * TRUE: There may be another page, try again * FALSE: We were interrupted out of our wait, don't try again */ boolean_t vm_page_wait(int interruptible) { /* * We can't use vm_page_free_reserved to make this * determination. Consider: some thread might * need to allocate two pages. The first allocation * succeeds, the second fails. After the first page is freed, * a call to vm_page_wait must really block. */ kern_return_t wait_result = THREAD_NOT_WAITING; thread_t cur_thread = current_thread(); bool is_privileged = cur_thread->options & TH_OPT_VMPRIV; bool need_wakeup = false; event_t wait_event = NULL; #if HAS_MTE bool wakeup_refill_thread = false; #endif /* HAS_MTE */ vm_free_page_lock_spin(); #if HAS_MTE if (cur_thread->page_wait_class == VM_MEMORY_CLASS_TAGGED) { if (is_privileged) { if (vm_page_free_taggable_count) { vm_free_page_unlock(); goto out; } if (vm_page_free_wanted_tagged_privileged++ == 0) { need_wakeup = true; } wait_event = (event_t)&vm_page_free_wanted_tagged_privileged; } else if (vm_page_free_taggable_count >= vm_page_free_target) { vm_free_page_unlock(); goto out; } else { if (vm_page_free_wanted_tagged++ == 0) { wakeup_refill_thread = true; } wait_event = (event_t)&vm_page_free_wanted_tagged; } } else #endif /* !HAS_MTE */ if (is_privileged) { if (vm_page_free_count) { vm_free_page_unlock(); goto out; } if (vm_page_free_wanted_privileged++ == 0) { need_wakeup = true; } wait_event = (event_t)&vm_page_free_wanted_privileged; } else if (vm_page_free_count >= vm_page_free_target) { vm_free_page_unlock(); goto out; #if CONFIG_SECLUDED_MEMORY } else if (secluded_for_apps && task_can_use_secluded_mem(current_task(), FALSE)) { #if 00 /* XXX FBDP: need pageq lock for this... */ /* XXX FBDP: might wait even if pages available, */ /* XXX FBDP: hopefully not for too long... */ if (vm_page_secluded_count > 0) { vm_free_page_unlock(); goto out; } #endif if (vm_page_free_wanted_secluded++ == 0) { need_wakeup = true; } wait_event = (event_t)&vm_page_free_wanted_secluded; #endif /* CONFIG_SECLUDED_MEMORY */ } else { if (vm_page_free_wanted++ == 0) { need_wakeup = true; } wait_event = (event_t)&vm_page_free_count; } #if HAS_MTE /* * If we're here, it means that the free taggable count is low. * If there are enough free pages in the system, we can ask the * fill thread to convert some free untagged pages to free tagged * pages. Otherwise, we will wake up pageout_scan(), which will * free pages, and on the free path, the fill thread will get woken up * (see vm_page_free_queue_handle_wakeups_and_unlock()). * * The fill thread will run or not run under a variety of conditions * (see mteinfo_tag_storage_active_should_refill() for more details), * but what's relevant here is that the fill thread will run so long * as there are tagged waiters. We should at least ensure that the * system has enough free untagged memory to service the existing * tagged waiters. */ if (wakeup_refill_thread) { uint32_t total_tagged_waiters = vm_page_free_wanted_tagged + +vm_page_free_wanted_tagged_privileged; if (_vm_page_wait_wakeup_fill_thread(total_tagged_waiters)) { /* If there are enough pages for all tagged waiters. */ } else { /* * Otherwise, wake up pageout_scan(), and the fill thread will * run later. */ wakeup_refill_thread = false; need_wakeup = true; } } #endif /* HAS_MTE */ if (vm_pageout_running) { need_wakeup = false; } /* * We don't do a vm_pageout_scan wakeup if we already have * some waiters because vm_pageout_scan checks for waiters * before it returns and does so behind the vm_page_queue_free_lock, * which we own when we bump the waiter counts. */ if (vps_dynamic_priority_enabled) { /* * We are waking up vm_pageout_scan here. If it needs * the vm_page_queue_free_lock before we unlock it * we'll end up just blocking and incur an extra * context switch. Could be a perf. issue. */ #if HAS_MTE if (cur_thread->page_wait_class != VM_MEMORY_CLASS_REGULAR) { panic("vm_page_wait does not support MTE+vps_dynamic_priority_enabled"); } #endif /* HAS_MTE */ if (need_wakeup) { thread_wakeup((event_t)&vm_page_free_wanted); } /* * LD: This event is going to get recorded every time because * we don't get back THREAD_WAITING from lck_mtx_sleep_with_inheritor. * We just block in that routine. */ VM_DEBUG_CONSTANT_EVENT(vm_page_wait_block, DBG_VM_PAGE_WAIT_BLOCK, DBG_FUNC_START, vm_page_free_wanted_privileged, vm_page_free_wanted, #if CONFIG_SECLUDED_MEMORY vm_page_free_wanted_secluded, #else /* CONFIG_SECLUDED_MEMORY */ 0, #endif /* CONFIG_SECLUDED_MEMORY */ 0); wait_result = lck_mtx_sleep_with_inheritor(&vm_page_queue_free_lock, LCK_SLEEP_UNLOCK, wait_event, vm_pageout_scan_thread, interruptible, 0); } else { wait_result = assert_wait(wait_event, interruptible); vm_free_page_unlock(); if (need_wakeup) { thread_wakeup((event_t)&vm_page_free_wanted); } #if HAS_MTE if (wakeup_refill_thread) { assert(!need_wakeup); mteinfo_wake_fill_thread(); } #endif /* HAS_MTE */ if (wait_result != THREAD_WAITING) { goto out; } #if HAS_MTE if (cur_thread->page_wait_class == VM_MEMORY_CLASS_TAGGED) { VM_DEBUG_CONSTANT_EVENT(vm_page_wait_block, DBG_VM_PAGE_MTE_WAIT_BLOCK, DBG_FUNC_START, vm_page_free_wanted_tagged_privileged, vm_page_free_wanted_tagged, 0, 0); wait_result = thread_block(THREAD_CONTINUE_NULL); VM_DEBUG_CONSTANT_EVENT(vm_page_wait_block, DBG_VM_PAGE_MTE_WAIT_BLOCK, DBG_FUNC_END, 0, 0, 0, 0); goto out; } #endif /* HAS_MTE */ VM_DEBUG_CONSTANT_EVENT(vm_page_wait_block, DBG_VM_PAGE_WAIT_BLOCK, DBG_FUNC_START, vm_page_free_wanted_privileged, vm_page_free_wanted, #if CONFIG_SECLUDED_MEMORY vm_page_free_wanted_secluded, #else /* CONFIG_SECLUDED_MEMORY */ 0, #endif /* CONFIG_SECLUDED_MEMORY */ 0); wait_result = thread_block(THREAD_CONTINUE_NULL); VM_DEBUG_CONSTANT_EVENT(vm_page_wait_block, DBG_VM_PAGE_WAIT_BLOCK, DBG_FUNC_END, 0, 0, 0, 0); } out: #if HAS_MTE cur_thread->page_wait_class = VM_MEMORY_CLASS_REGULAR; #endif /* HAS_MTE */ return (wait_result == THREAD_AWAKENED) || (wait_result == THREAD_NOT_WAITING); } /* * vm_page_free_prepare: * * Removes page from any queue it may be on * and disassociates it from its VM object. * * Object and page queues must be locked prior to entry. */ static void vm_page_free_prepare( vm_page_t mem) { vm_page_free_prepare_queues(mem); vm_page_free_prepare_object(mem); #if CONFIG_SPTM /** * The pmap should retype frames as necessary when pmap_recycle_page() * is called. In order to catch potential cases where this does not * happen, add an appropriate assert here. This code should be * executed on every frame that is about to be released to the VM. */ const sptm_paddr_t paddr = ((uint64_t)VM_PAGE_GET_PHYS_PAGE(mem)) << PAGE_SHIFT; __unused const sptm_frame_type_t frame_type = sptm_get_frame_type(paddr); assert(frame_type == XNU_DEFAULT); #endif /* CONFIG_SPTM */ #if HAS_MTE /* * At this point, any busy bit on `mem` has been cleared. If the refill * thread wanted this page, update the cell state from PINNED to CLAIMED. * * We only expect to come through here when swap-ins/outs have erred. */ if (mem->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR && mem->vmp_ts_wanted) { mteinfo_tag_storage_wakeup(mem, false); } #endif /* HAS_MTE */ } void vm_page_free_prepare_queues( vm_page_t mem) { vm_object_t m_object; VM_PAGE_CHECK(mem); assert(mem->vmp_q_state != VM_PAGE_ON_FREE_Q); assert(!mem->vmp_cleaning); m_object = VM_PAGE_OBJECT(mem); LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); if (m_object) { vm_object_lock_assert_exclusive(m_object); } if (mem->vmp_laundry) { /* * We may have to free a page while it's being laundered * if we lost its pager (due to a forced unmount, for example). * We need to call vm_pageout_steal_laundry() before removing * the page from its VM object, so that we can remove it * from its pageout queue and adjust the laundry accounting */ vm_pageout_steal_laundry(mem, TRUE); } vm_page_queues_remove(mem, TRUE); if (mem->vmp_realtime) { mem->vmp_realtime = false; VM_COUNTER_DEC(&vm_page_realtime_count); } if (VM_PAGE_WIRED(mem)) { assert(mem->vmp_wire_count > 0); if (m_object) { ledger_t ledger; vmo_ledgers_t lidx; VM_OBJECT_WIRED_PAGE_UPDATE_START(m_object); VM_OBJECT_WIRED_PAGE_REMOVE(m_object, mem); VM_OBJECT_WIRED_PAGE_UPDATE_END(m_object, m_object->wire_tag); assert(m_object->resident_page_count >= m_object->wired_page_count); if (m_object->purgable == VM_PURGABLE_VOLATILE) { counter_inc(&vm_page_purgeable_count); counter_dec(&vm_page_purgeable_wired_count); } if (m_object->internal && (m_object->purgable == VM_PURGABLE_VOLATILE || m_object->purgable == VM_PURGABLE_EMPTY) && (ledger = VM_OBJECT_LEDGER(m_object))) { lidx = vm_object_ledger_tag_ledgers(m_object); disable_preemption(); /* * While wired, this page was accounted * as "non-volatile" but it should now * be accounted as "volatile". */ /* one less "non-volatile"... */ ledger_debit_nopreempt(ledger, lidx.vmo_nonvolatile, PAGE_SIZE); ledger_debit_nopreempt(ledger, lidx.vmo_footprint, PAGE_SIZE); /* one more "volatile" */ ledger_credit_nopreempt(ledger, lidx.vmo_volatile, PAGE_SIZE); enable_preemption(); } } if (vm_page_is_canonical(mem)) { vm_page_wire_count--; } #if HAS_MTE mteinfo_decrement_wire_count(mem, true); #endif /* HAS_MTE */ mem->vmp_q_state = VM_PAGE_NOT_ON_Q; mem->vmp_wire_count = 0; assert(!mem->vmp_gobbled); } else if (mem->vmp_gobbled) { if (vm_page_is_canonical(mem)) { vm_page_wire_count--; } vm_page_gobble_count--; } } /* * like vm_page_init, but we have to preserve fields related to phys page */ inline static void vm_page_reset_canonical(vm_page_t mem) { *mem = (struct vm_page){ .vmp_offset = (vm_object_offset_t)-1, .vmp_q_state = VM_PAGE_NOT_ON_Q, .vmp_on_specialq = VM_PAGE_SPECIAL_Q_EMPTY, #if XNU_VM_HAS_LOPAGE .vmp_lopage = mem->vmp_lopage, #endif /* XNU_VM_HAS_LOPAGE */ .vmp_canonical = true, .vmp_busy = true, .vmp_realtime = mem->vmp_realtime, #if HAS_MTE .vmp_using_mte = mem->vmp_using_mte, #endif #if !XNU_VM_HAS_LINEAR_PAGES_ARRAY .vmp_phys_page = mem->vmp_phys_page, #endif /* !XNU_VM_HAS_LINEAR_PAGES_ARRAY */ }; /* ECC information is out of `struct vm_page` and preserved */ } void vm_page_free_prepare_object(vm_page_t mem) { if (mem->vmp_tabled) { vm_page_remove(mem); /* clears tabled, object, offset */ } vm_page_wakeup(VM_OBJECT_NULL, mem); /* clears wanted */ if (vm_page_is_private(mem)) { vm_page_reset_private(mem); } if (vm_page_is_canonical(mem)) { assert(mem->vmp_pageq.next == 0 && mem->vmp_pageq.prev == 0 && mem->vmp_listq.next == 0 && mem->vmp_listq.prev == 0 && mem->vmp_specialq.next == 0 && mem->vmp_specialq.prev == 0 && mem->vmp_next_m == 0); pmap_recycle_page(VM_PAGE_GET_PHYS_PAGE(mem)); vm_page_reset_canonical(mem); } } /* * vm_page_release: * * Return a page to the free list. * * Keep in sync with vm_page_free_list(). */ void vm_page_release(vm_page_t mem, vmp_release_options_t options) { if (options & VMP_RELEASE_Q_LOCKED) { LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); } else { LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_NOTOWNED); } assert(vm_page_is_canonical(mem)); assert(mem->vmp_q_state == VM_PAGE_NOT_ON_Q); if ((options & VMP_RELEASE_SKIP_FREE_CHECK) == 0) { pmap_recycle_page(VM_PAGE_GET_PHYS_PAGE(mem)); } pmap_clear_noencrypt(VM_PAGE_GET_PHYS_PAGE(mem)); vm_page_free_queue_enter_list(vm_page_list_for_page(mem), options); } /* * This version of vm_page_release() is used only at startup * when we are single-threaded and pages are being released * for the first time. Hence, no locking or unnecessary checks are made. * Note: VM_CHECK_MEMORYSTATUS invoked by the caller. */ void vm_page_release_startup(vm_page_t mem) { #if HAS_MTE if (pmap_in_tag_storage_range(VM_PAGE_GET_PHYS_PAGE(mem)) && mte_enabled()) { /* * Add the MTE tag page to the FREE_MTE_TAG queue. These pages * can be used/claimed for other purposes (other than tag pages) * provided that they can be reclaimed quickly without waiting * on I/O, e.g. readonly/clean file pages. */ mteinfo_tag_storage_release_startup(mem); return; } #endif /* HAS_MTE */ vm_page_free_queue_enter_list(vm_page_list_for_page(mem), VMP_RELEASE_STARTUP); } /* * vm_page_free: * * Returns the given page to the free list, * disassociating it with any VM object. * * Object and page queues must be locked prior to entry. */ void vm_page_free(vm_page_t mem) { vm_page_free_prepare(mem); if (vm_page_is_canonical(mem)) { /* page queues are locked */ vm_page_release(mem, VMP_RELEASE_Q_LOCKED | VMP_RELEASE_SKIP_FREE_CHECK); } else { vm_page_release_fictitious(mem); } } void vm_page_free_unlocked(vm_page_t mem) { vm_page_lockspin_queues(); vm_page_free_prepare_queues(mem); vm_page_unlock_queues(); vm_page_free_prepare_object(mem); if (vm_page_is_canonical(mem)) { /* page queues are not locked */ vm_page_release(mem, VMP_RELEASE_SKIP_FREE_CHECK); } else { vm_page_release_fictitious(mem); } } /* * Free a list of pages. The list can be up to several hundred pages, * as blocked up by vm_pageout_scan(). * The big win is not having to take the free list lock once * per page. * * The VM page queues lock (vm_page_queue_lock) should NOT be held. * The VM page free queues lock (vm_page_queue_free_lock) should NOT be held. * * Keep in sync with vm_page_release(). */ void vm_page_free_list(vm_page_t freeq, bool prepare_object) { LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_NOTOWNED); LCK_MTX_ASSERT(&vm_page_queue_free_lock, LCK_MTX_ASSERT_NOTOWNED); while (freeq) { vm_page_list_t list = { }; while (list.vmpl_count < VMP_FREE_BATCH_SIZE && freeq) { vm_page_t mem = _vm_page_list_pop(&freeq); assert((mem->vmp_q_state == VM_PAGE_NOT_ON_Q) || VM_PAGE_WIRED(mem)); if (prepare_object) { vm_page_free_prepare_object(mem); } if (vm_page_is_fictitious(mem)) { vm_page_release_fictitious(mem); continue; } if (!prepare_object) { /* vm_page_free_prepare_object() checked it */ pmap_recycle_page(VM_PAGE_GET_PHYS_PAGE(mem)); } pmap_clear_noencrypt(VM_PAGE_GET_PHYS_PAGE(mem)); /* * IMPORTANT: we can't set the page "free" here * because that would make the page eligible for * a physically-contiguous allocation (see * vm_page_find_contiguous()) right away (we don't * hold the vm_page_queue_free lock). That would * cause trouble because the page is not actually * in the free queue yet... */ vm_page_list_push(&list, mem); } if (list.vmpl_count) { vm_page_free_queue_enter_list(list, VMP_RELEASE_NONE); } } } /* * vm_page_wire: * * Mark this page as wired down by yet * another map, removing it from paging queues * as necessary. * * The page's object and the page queues must be locked. */ void vm_page_wire( vm_page_t mem, vm_tag_t tag, boolean_t check_memorystatus) { vm_object_t m_object; m_object = VM_PAGE_OBJECT(mem); // dbgLog(current_thread(), mem->vmp_offset, m_object, 1); /* (TEST/DEBUG) */ VM_PAGE_CHECK(mem); if (m_object) { vm_object_lock_assert_exclusive(m_object); } else { /* * In theory, the page should be in an object before it * gets wired, since we need to hold the object lock * to update some fields in the page structure. * However, some code (i386 pmap, for example) might want * to wire a page before it gets inserted into an object. * That's somewhat OK, as long as nobody else can get to * that page and update it at the same time. */ } LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); if (!VM_PAGE_WIRED(mem)) { if (mem->vmp_laundry) { vm_pageout_steal_laundry(mem, TRUE); } vm_page_queues_remove(mem, TRUE); assert(mem->vmp_wire_count == 0); mem->vmp_q_state = VM_PAGE_IS_WIRED; #if CONFIG_TRACK_UNMODIFIED_ANON_PAGES if (mem->vmp_unmodified_ro == true) { /* Object and PageQ locks are held*/ mem->vmp_unmodified_ro = false; os_atomic_dec(&compressor_ro_uncompressed, relaxed); vm_object_compressor_pager_state_clr(VM_PAGE_OBJECT(mem), mem->vmp_offset); } #endif /* CONFIG_TRACK_UNMODIFIED_ANON_PAGES */ if (m_object) { ledger_t ledger; vmo_ledgers_t lidx; VM_OBJECT_WIRED_PAGE_UPDATE_START(m_object); VM_OBJECT_WIRED_PAGE_ADD(m_object, mem); VM_OBJECT_WIRED_PAGE_UPDATE_END(m_object, tag); assert(m_object->resident_page_count >= m_object->wired_page_count); if (m_object->purgable == VM_PURGABLE_VOLATILE) { counter_dec(&vm_page_purgeable_count); counter_inc(&vm_page_purgeable_wired_count); } if (m_object->internal && (m_object->purgable == VM_PURGABLE_VOLATILE || m_object->purgable == VM_PURGABLE_EMPTY) && (ledger = VM_OBJECT_LEDGER(m_object))) { lidx = vm_object_ledger_tag_ledgers(m_object); disable_preemption(); /* less volatile bytes */ ledger_debit_nopreempt(ledger, lidx.vmo_volatile, PAGE_SIZE); /* more not-quite-volatile bytes */ ledger_credit_nopreempt(ledger, lidx.vmo_nonvolatile, PAGE_SIZE); ledger_credit_nopreempt(ledger, lidx.vmo_footprint, PAGE_SIZE); enable_preemption(); } if (m_object->all_reusable) { /* * Wired pages are not counted as "re-usable" * in "all_reusable" VM objects, so nothing * to do here. */ } else if (mem->vmp_reusable) { /* * This page is not "re-usable" when it's * wired, so adjust its state and the * accounting. */ vm_page_lockconvert_queues(); vm_object_reuse_pages(m_object, mem->vmp_offset, mem->vmp_offset + PAGE_SIZE_64, FALSE); } } assert(!mem->vmp_reusable); if (vm_page_is_canonical(mem) && !mem->vmp_gobbled) { vm_page_wire_count++; } if (mem->vmp_gobbled) { vm_page_gobble_count--; } mem->vmp_gobbled = FALSE; if (check_memorystatus == TRUE) { VM_CHECK_MEMORYSTATUS; } } assert(!mem->vmp_gobbled); assert(VM_PAGE_WIRED(mem)); mem->vmp_wire_count++; #if HAS_MTE if (mem->vmp_wire_count == 1 && tag != VM_KERN_MEMORY_MTAG) { /* * Only notify Mte Info if the caller isn't * mteinfo_tag_storage_wire_locked(). */ mteinfo_increment_wire_count(mem); } #endif /* HAS_MTE */ if (__improbable(mem->vmp_wire_count == 0)) { panic("vm_page_wire(%p): wire_count overflow", mem); } VM_PAGE_CHECK(mem); } /* * vm_page_unwire: * * Release one wiring of this page, potentially * enabling it to be paged again. * * The page's object and the page queues must be locked. */ void vm_page_unwire( vm_page_t mem, boolean_t queueit) { vm_object_t m_object; m_object = VM_PAGE_OBJECT(mem); // dbgLog(current_thread(), mem->vmp_offset, m_object, 0); /* (TEST/DEBUG) */ VM_PAGE_CHECK(mem); assert(VM_PAGE_WIRED(mem)); assert(mem->vmp_wire_count > 0); assert(!mem->vmp_gobbled); assert(m_object != VM_OBJECT_NULL); vm_object_lock_assert_exclusive(m_object); LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); if (--mem->vmp_wire_count == 0) { ledger_t ledger; vmo_ledgers_t lidx; mem->vmp_q_state = VM_PAGE_NOT_ON_Q; VM_OBJECT_WIRED_PAGE_UPDATE_START(m_object); VM_OBJECT_WIRED_PAGE_REMOVE(m_object, mem); VM_OBJECT_WIRED_PAGE_UPDATE_END(m_object, m_object->wire_tag); if (vm_page_is_canonical(mem)) { vm_page_wire_count--; } #if HAS_MTE mteinfo_decrement_wire_count(mem, true); #endif /* HAS_MTE */ assert(m_object->resident_page_count >= m_object->wired_page_count); if (m_object->purgable == VM_PURGABLE_VOLATILE) { counter_inc(&vm_page_purgeable_count); counter_dec(&vm_page_purgeable_wired_count); } if (m_object->internal && (m_object->purgable == VM_PURGABLE_VOLATILE || m_object->purgable == VM_PURGABLE_EMPTY) && (ledger = VM_OBJECT_LEDGER(m_object))) { lidx = vm_object_ledger_tag_ledgers(m_object); disable_preemption(); /* more volatile bytes */ ledger_credit_nopreempt(ledger, lidx.vmo_volatile, PAGE_SIZE); /* less not-quite-volatile bytes */ ledger_debit_nopreempt(ledger, lidx.vmo_nonvolatile, PAGE_SIZE); ledger_debit_nopreempt(ledger, lidx.vmo_footprint, PAGE_SIZE); enable_preemption(); } assert(!is_kernel_object(m_object)); assert(mem->vmp_pageq.next == 0 && mem->vmp_pageq.prev == 0); if (queueit == TRUE) { if (m_object->purgable == VM_PURGABLE_EMPTY) { vm_page_deactivate(mem); } else { vm_page_activate(mem); } } VM_CHECK_MEMORYSTATUS; } VM_PAGE_CHECK(mem); } /* * vm_page_deactivate: * * Returns the given page to the inactive list, * indicating that no physical maps have access * to this page. [Used by the physical mapping system.] * * The page queues must be locked. */ void vm_page_deactivate( vm_page_t m) { vm_page_deactivate_internal(m, TRUE); } void vm_page_deactivate_internal( vm_page_t m, boolean_t clear_hw_reference) { vm_object_t m_object; m_object = VM_PAGE_OBJECT(m); VM_PAGE_CHECK(m); assert(!is_kernel_object(m_object)); assert(!vm_page_is_guard(m)); // dbgLog(VM_PAGE_GET_PHYS_PAGE(m), vm_page_free_count, vm_page_wire_count, 6); /* (TEST/DEBUG) */ LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); /* * This page is no longer very interesting. If it was * interesting (active or inactive/referenced), then we * clear the reference bit and (re)enter it in the * inactive queue. Note wired pages should not have * their reference bit cleared. */ assert( !(m->vmp_absent && !m->vmp_unusual)); if (m->vmp_gobbled) { /* can this happen? */ assert( !VM_PAGE_WIRED(m)); if (vm_page_is_canonical(m)) { vm_page_wire_count--; } vm_page_gobble_count--; m->vmp_gobbled = FALSE; } /* * if this page is currently on the pageout queue, we can't do the * vm_page_queues_remove (which doesn't handle the pageout queue case) * and we can't remove it manually since we would need the object lock * (which is not required here) to decrement the activity_in_progress * reference which is held on the object while the page is in the pageout queue... * just let the normal laundry processing proceed */ if (m->vmp_laundry || !vm_page_is_canonical(m) || (m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) || (m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q) || VM_PAGE_WIRED(m)) { return; } if (!m->vmp_absent && clear_hw_reference == TRUE) { vm_page_lockconvert_queues(); pmap_clear_reference(VM_PAGE_GET_PHYS_PAGE(m)); } m->vmp_reference = FALSE; m->vmp_no_cache = FALSE; if (!VM_PAGE_INACTIVE(m)) { vm_page_queues_remove(m, FALSE); if (!VM_DYNAMIC_PAGING_ENABLED() && m->vmp_dirty && m_object->internal && (m_object->purgable == VM_PURGABLE_DENY || m_object->purgable == VM_PURGABLE_NONVOLATILE || m_object->purgable == VM_PURGABLE_VOLATILE)) { vm_page_check_pageable_safe(m); vm_page_queue_enter(&vm_page_queue_throttled, m, vmp_pageq); m->vmp_q_state = VM_PAGE_ON_THROTTLED_Q; vm_page_throttled_count++; } else { if (m_object->named && os_ref_get_count_raw(&m_object->ref_count) == 1) { vm_page_speculate(m, FALSE); #if DEVELOPMENT || DEBUG vm_page_speculative_recreated++; #endif } else { vm_page_enqueue_inactive(m, FALSE); } } } } /* * vm_page_enqueue_cleaned * * Put the page on the cleaned queue, mark it cleaned, etc. * Being on the cleaned queue (and having m->clean_queue set) * does ** NOT ** guarantee that the page is clean! * * Call with the queues lock held. */ void vm_page_enqueue_cleaned(vm_page_t m) { vm_object_t m_object; m_object = VM_PAGE_OBJECT(m); assert(!vm_page_is_guard(m)); LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); assert(!(m->vmp_absent && !m->vmp_unusual)); if (VM_PAGE_WIRED(m)) { return; } if (m->vmp_gobbled) { if (vm_page_is_canonical(m)) { vm_page_wire_count--; } vm_page_gobble_count--; m->vmp_gobbled = FALSE; } /* * if this page is currently on the pageout queue, we can't do the * vm_page_queues_remove (which doesn't handle the pageout queue case) * and we can't remove it manually since we would need the object lock * (which is not required here) to decrement the activity_in_progress * reference which is held on the object while the page is in the pageout queue... * just let the normal laundry processing proceed */ if (m->vmp_laundry || !vm_page_is_canonical(m) || (m->vmp_q_state == VM_PAGE_ON_INACTIVE_CLEANED_Q) || (m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q)) { return; } vm_page_queues_remove(m, FALSE); vm_page_check_pageable_safe(m); vm_page_queue_enter(&vm_page_queue_cleaned, m, vmp_pageq); m->vmp_q_state = VM_PAGE_ON_INACTIVE_CLEANED_Q; vm_page_cleaned_count++; vm_page_inactive_count++; if (m_object->internal) { vm_page_pageable_internal_count++; } else { vm_page_pageable_external_count++; } vm_page_add_to_specialq(m, TRUE); VM_PAGEOUT_DEBUG(vm_pageout_enqueued_cleaned, 1); } /* * vm_page_activate: * * Put the specified page on the active list (if appropriate). * * The page queues must be locked. */ void vm_page_activate( vm_page_t m) { vm_object_t m_object; m_object = VM_PAGE_OBJECT(m); VM_PAGE_CHECK(m); #ifdef FIXME_4778297 assert(!is_kernel_object(m_object)); #endif assert(!vm_page_is_guard(m)); LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); assert( !(m->vmp_absent && !m->vmp_unusual)); if (m->vmp_gobbled) { assert( !VM_PAGE_WIRED(m)); if (vm_page_is_canonical(m)) { vm_page_wire_count--; } vm_page_gobble_count--; m->vmp_gobbled = FALSE; } /* * if this page is currently on the pageout queue, we can't do the * vm_page_queues_remove (which doesn't handle the pageout queue case) * and we can't remove it manually since we would need the object lock * (which is not required here) to decrement the activity_in_progress * reference which is held on the object while the page is in the pageout queue... * just let the normal laundry processing proceed */ if (m->vmp_laundry || !vm_page_is_canonical(m) || (m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) || (m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q)) { return; } #if DEBUG if (m->vmp_q_state == VM_PAGE_ON_ACTIVE_Q) { panic("vm_page_activate: already active"); } #endif if (m->vmp_q_state == VM_PAGE_ON_SPECULATIVE_Q) { DTRACE_VM2(pgrec, int, 1, (uint64_t *), NULL); DTRACE_VM2(pgfrec, int, 1, (uint64_t *), NULL); } /* * A freshly activated page should be promoted in the donation queue. * So we remove it here while preserving its hint and we will enqueue * it again in vm_page_enqueue_active. */ vm_page_queues_remove(m, ((m->vmp_on_specialq == VM_PAGE_SPECIAL_Q_DONATE) ? TRUE : FALSE)); if (!VM_PAGE_WIRED(m)) { vm_page_check_pageable_safe(m); if (!VM_DYNAMIC_PAGING_ENABLED() && m->vmp_dirty && m_object->internal && (m_object->purgable == VM_PURGABLE_DENY || m_object->purgable == VM_PURGABLE_NONVOLATILE || m_object->purgable == VM_PURGABLE_VOLATILE)) { vm_page_queue_enter(&vm_page_queue_throttled, m, vmp_pageq); m->vmp_q_state = VM_PAGE_ON_THROTTLED_Q; vm_page_throttled_count++; } else { #if CONFIG_SECLUDED_MEMORY if (secluded_for_filecache && vm_page_secluded_target != 0 && num_tasks_can_use_secluded_mem == 0 && m_object->eligible_for_secluded && !m->vmp_realtime) { vm_page_queue_enter(&vm_page_queue_secluded, m, vmp_pageq); m->vmp_q_state = VM_PAGE_ON_SECLUDED_Q; vm_page_secluded_count++; VM_PAGE_SECLUDED_COUNT_OVER_TARGET_UPDATE(); vm_page_secluded_count_inuse++; assert(!m_object->internal); // vm_page_pageable_external_count++; } else #endif /* CONFIG_SECLUDED_MEMORY */ vm_page_enqueue_active(m, FALSE); } m->vmp_reference = TRUE; m->vmp_no_cache = FALSE; } VM_PAGE_CHECK(m); } /* * vm_page_speculate: * * Put the specified page on the speculative list (if appropriate). * * The page queues must be locked. */ void vm_page_speculate( vm_page_t m, boolean_t new) { struct vm_speculative_age_q *aq; vm_object_t m_object; m_object = VM_PAGE_OBJECT(m); VM_PAGE_CHECK(m); vm_page_check_pageable_safe(m); assert(!vm_page_is_guard(m)); LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); assert(!(m->vmp_absent && !m->vmp_unusual)); assert(m_object->internal == FALSE); /* * if this page is currently on the pageout queue, we can't do the * vm_page_queues_remove (which doesn't handle the pageout queue case) * and we can't remove it manually since we would need the object lock * (which is not required here) to decrement the activity_in_progress * reference which is held on the object while the page is in the pageout queue... * just let the normal laundry processing proceed */ if (m->vmp_laundry || !vm_page_is_canonical(m) || (m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) || (m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q)) { return; } vm_page_queues_remove(m, FALSE); if (!VM_PAGE_WIRED(m)) { mach_timespec_t ts; clock_sec_t sec; clock_nsec_t nsec; clock_get_system_nanotime(&sec, &nsec); ts.tv_sec = (unsigned int) sec; ts.tv_nsec = nsec; if (vm_page_speculative_count == 0) { speculative_age_index = VM_PAGE_MIN_SPECULATIVE_AGE_Q; speculative_steal_index = VM_PAGE_MIN_SPECULATIVE_AGE_Q; aq = &vm_page_queue_speculative[speculative_age_index]; /* * set the timer to begin a new group */ aq->age_ts.tv_sec = vm_pageout_state.vm_page_speculative_q_age_ms / 1000; aq->age_ts.tv_nsec = (vm_pageout_state.vm_page_speculative_q_age_ms % 1000) * 1000 * NSEC_PER_USEC; ADD_MACH_TIMESPEC(&aq->age_ts, &ts); } else { aq = &vm_page_queue_speculative[speculative_age_index]; if (CMP_MACH_TIMESPEC(&ts, &aq->age_ts) >= 0) { speculative_age_index++; if (speculative_age_index > vm_page_max_speculative_age_q) { speculative_age_index = VM_PAGE_MIN_SPECULATIVE_AGE_Q; } if (speculative_age_index == speculative_steal_index) { speculative_steal_index = speculative_age_index + 1; if (speculative_steal_index > vm_page_max_speculative_age_q) { speculative_steal_index = VM_PAGE_MIN_SPECULATIVE_AGE_Q; } } aq = &vm_page_queue_speculative[speculative_age_index]; if (!vm_page_queue_empty(&aq->age_q)) { vm_page_speculate_ageit(aq); } aq->age_ts.tv_sec = vm_pageout_state.vm_page_speculative_q_age_ms / 1000; aq->age_ts.tv_nsec = (vm_pageout_state.vm_page_speculative_q_age_ms % 1000) * 1000 * NSEC_PER_USEC; ADD_MACH_TIMESPEC(&aq->age_ts, &ts); } } vm_page_enqueue_tail(&aq->age_q, &m->vmp_pageq); m->vmp_q_state = VM_PAGE_ON_SPECULATIVE_Q; vm_page_speculative_count++; vm_page_pageable_external_count++; if (new == TRUE) { vm_object_lock_assert_exclusive(m_object); m_object->pages_created++; #if DEVELOPMENT || DEBUG vm_page_speculative_created++; #endif } } VM_PAGE_CHECK(m); } /* * move pages from the specified aging bin to * the speculative bin that pageout_scan claims from * * The page queues must be locked. */ void vm_page_speculate_ageit(struct vm_speculative_age_q *aq) { struct vm_speculative_age_q *sq; vm_page_t t; sq = &vm_page_queue_speculative[VM_PAGE_SPECULATIVE_AGED_Q]; if (vm_page_queue_empty(&sq->age_q)) { sq->age_q.next = aq->age_q.next; sq->age_q.prev = aq->age_q.prev; t = (vm_page_t)VM_PAGE_UNPACK_PTR(sq->age_q.next); t->vmp_pageq.prev = VM_PAGE_PACK_PTR(&sq->age_q); t = (vm_page_t)VM_PAGE_UNPACK_PTR(sq->age_q.prev); t->vmp_pageq.next = VM_PAGE_PACK_PTR(&sq->age_q); } else { t = (vm_page_t)VM_PAGE_UNPACK_PTR(sq->age_q.prev); t->vmp_pageq.next = aq->age_q.next; t = (vm_page_t)VM_PAGE_UNPACK_PTR(aq->age_q.next); t->vmp_pageq.prev = sq->age_q.prev; t = (vm_page_t)VM_PAGE_UNPACK_PTR(aq->age_q.prev); t->vmp_pageq.next = VM_PAGE_PACK_PTR(&sq->age_q); sq->age_q.prev = aq->age_q.prev; } vm_page_queue_init(&aq->age_q); } void vm_page_lru( vm_page_t m) { VM_PAGE_CHECK(m); assert(!is_kernel_object(VM_PAGE_OBJECT(m))); assert(!vm_page_is_guard(m)); LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); if (m->vmp_q_state == VM_PAGE_ON_INACTIVE_EXTERNAL_Q) { /* * we don't need to do all the other work that * vm_page_queues_remove and vm_page_enqueue_inactive * bring along for the ride */ assert(!m->vmp_laundry); assert(!vm_page_is_private(m)); m->vmp_no_cache = FALSE; vm_page_queue_remove(&vm_page_queue_inactive, m, vmp_pageq); vm_page_queue_enter(&vm_page_queue_inactive, m, vmp_pageq); return; } /* * if this page is currently on the pageout queue, we can't do the * vm_page_queues_remove (which doesn't handle the pageout queue case) * and we can't remove it manually since we would need the object lock * (which is not required here) to decrement the activity_in_progress * reference which is held on the object while the page is in the pageout queue... * just let the normal laundry processing proceed */ if (m->vmp_laundry || vm_page_is_private(m) || (m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) || (m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q) || VM_PAGE_WIRED(m)) { return; } m->vmp_no_cache = FALSE; vm_page_queues_remove(m, FALSE); vm_page_enqueue_inactive(m, FALSE); } void vm_page_reactivate_all_throttled(void) { vm_page_t first_throttled, last_throttled; vm_page_t first_active; vm_page_t m; int extra_active_count; int extra_internal_count, extra_external_count; vm_object_t m_object; if (!VM_DYNAMIC_PAGING_ENABLED()) { return; } extra_active_count = 0; extra_internal_count = 0; extra_external_count = 0; vm_page_lock_queues(); if (!vm_page_queue_empty(&vm_page_queue_throttled)) { /* * Switch "throttled" pages to "active". */ vm_page_queue_iterate(&vm_page_queue_throttled, m, vmp_pageq) { VM_PAGE_CHECK(m); assert(m->vmp_q_state == VM_PAGE_ON_THROTTLED_Q); m_object = VM_PAGE_OBJECT(m); extra_active_count++; if (m_object->internal) { extra_internal_count++; } else { extra_external_count++; } m->vmp_q_state = VM_PAGE_ON_ACTIVE_Q; VM_PAGE_CHECK(m); vm_page_add_to_specialq(m, FALSE); } /* * Transfer the entire throttled queue to a regular LRU page queues. * We insert it at the head of the active queue, so that these pages * get re-evaluated by the LRU algorithm first, since they've been * completely out of it until now. */ first_throttled = (vm_page_t) vm_page_queue_first(&vm_page_queue_throttled); last_throttled = (vm_page_t) vm_page_queue_last(&vm_page_queue_throttled); first_active = (vm_page_t) vm_page_queue_first(&vm_page_queue_active); if (vm_page_queue_empty(&vm_page_queue_active)) { vm_page_queue_active.prev = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(last_throttled); } else { first_active->vmp_pageq.prev = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(last_throttled); } vm_page_queue_active.next = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(first_throttled); first_throttled->vmp_pageq.prev = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(&vm_page_queue_active); last_throttled->vmp_pageq.next = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(first_active); #if DEBUG printf("reactivated %d throttled pages\n", vm_page_throttled_count); #endif vm_page_queue_init(&vm_page_queue_throttled); /* * Adjust the global page counts. */ vm_page_active_count += extra_active_count; vm_page_pageable_internal_count += extra_internal_count; vm_page_pageable_external_count += extra_external_count; vm_page_throttled_count = 0; } assert(vm_page_throttled_count == 0); assert(vm_page_queue_empty(&vm_page_queue_throttled)); vm_page_unlock_queues(); } /* * move pages from the indicated local queue to the global active queue * its ok to fail if we're below the hard limit and force == FALSE * the nolocks == TRUE case is to allow this function to be run on * the hibernate path */ void vm_page_reactivate_local(uint32_t lid, boolean_t force, boolean_t nolocks) { struct vpl *lq; vm_page_t first_local, last_local; vm_page_t first_active; vm_page_t m; uint32_t count = 0; uint32_t internal_count __kdebug_only; uint32_t external_count __kdebug_only; bool hit_hard_limit; if (vm_page_local_q == NULL) { return; } lq = zpercpu_get_cpu(vm_page_local_q, lid); if (nolocks == FALSE) { hit_hard_limit = lq->vpl_count >= vm_page_local_q_hard_limit; if (!hit_hard_limit && !force) { if (!vm_page_trylockspin_queues()) { return; } } else { vm_page_lockspin_queues(); } VPL_LOCK(&lq->vpl_lock); } KDBG(VMDBG_CODE(DBG_VM_PAGE_LOCAL_TO_GLOBAL_ACTIVE) | DBG_FUNC_START, lid, hit_hard_limit, force); if (lq->vpl_count) { /* * Switch "local" pages to "active". */ assert(!vm_page_queue_empty(&lq->vpl_queue)); vm_page_queue_iterate(&lq->vpl_queue, m, vmp_pageq) { VM_PAGE_CHECK(m); vm_page_check_pageable_safe(m); assert(m->vmp_q_state == VM_PAGE_ON_ACTIVE_LOCAL_Q); assert(!vm_page_is_fictitious(m)); if (m->vmp_local_id != lid) { panic("vm_page_reactivate_local: found vm_page_t(%p) with wrong cpuid", m); } m->vmp_local_id = 0; m->vmp_q_state = VM_PAGE_ON_ACTIVE_Q; VM_PAGE_CHECK(m); vm_page_add_to_specialq(m, FALSE); count++; } if (count != lq->vpl_count) { panic("vm_page_reactivate_local: count = %d, vm_page_local_count = %d", count, lq->vpl_count); } /* * Transfer the entire local queue to a regular LRU page queues. */ first_local = (vm_page_t) vm_page_queue_first(&lq->vpl_queue); last_local = (vm_page_t) vm_page_queue_last(&lq->vpl_queue); first_active = (vm_page_t) vm_page_queue_first(&vm_page_queue_active); if (vm_page_queue_empty(&vm_page_queue_active)) { vm_page_queue_active.prev = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(last_local); } else { first_active->vmp_pageq.prev = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(last_local); } vm_page_queue_active.next = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(first_local); first_local->vmp_pageq.prev = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(&vm_page_queue_active); last_local->vmp_pageq.next = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(first_active); vm_page_queue_init(&lq->vpl_queue); /* * Adjust the global page counts. */ vm_page_active_count += lq->vpl_count; vm_page_pageable_internal_count += lq->vpl_internal_count; vm_page_pageable_external_count += lq->vpl_external_count; internal_count = lq->vpl_internal_count; external_count = lq->vpl_external_count; lq->vpl_count = 0; lq->vpl_internal_count = 0; lq->vpl_external_count = 0; } assert(vm_page_queue_empty(&lq->vpl_queue)); if (nolocks == FALSE) { VPL_UNLOCK(&lq->vpl_lock); vm_page_balance_inactive(count / 4); vm_page_unlock_queues(); } KDBG(VMDBG_CODE(DBG_VM_PAGE_LOCAL_TO_GLOBAL_ACTIVE) | DBG_FUNC_END, count, internal_count, external_count); } /* * vm_page_part_zero_fill: * * Zero-fill a part of the page. */ #define PMAP_ZERO_PART_PAGE_IMPLEMENTED void vm_page_part_zero_fill( vm_page_t m, vm_offset_t m_pa, vm_size_t len) { #if 0 /* * we don't hold the page queue lock * so this check isn't safe to make */ VM_PAGE_CHECK(m); #endif #ifdef PMAP_ZERO_PART_PAGE_IMPLEMENTED pmap_zero_part_page(VM_PAGE_GET_PHYS_PAGE(m), m_pa, len); #else vm_page_t tmp; while (1) { tmp = vm_page_grab(); if (tmp == VM_PAGE_NULL) { vm_page_wait(THREAD_UNINT); continue; } break; } pmap_zero_page(VM_PAGE_GET_PHYS_PAGE(tmp)); if (m_pa != 0) { vm_page_part_copy(m, 0, tmp, 0, m_pa); } if ((m_pa + len) < PAGE_SIZE) { vm_page_part_copy(m, m_pa + len, tmp, m_pa + len, PAGE_SIZE - (m_pa + len)); } vm_page_copy(tmp, m); VM_PAGE_FREE(tmp); #endif } /*! * @function vm_page_zero_fill * * @abstract * Zero-fill the specified page. * * @param m The page to zero. */ void vm_page_zero_fill(vm_page_t m) { pmap_zero_page_with_options(VM_PAGE_GET_PHYS_PAGE(m), #if HAS_MTE m->vmp_using_mte ? cppvZeroPageTags : #endif /* HAS_MTE */ 0); #if HAS_MTE if (m->vmp_using_mte) { KDBG(VMDBG_CODE(DBG_VM_PAGE_MTE_ZFOD) | DBG_FUNC_NONE); } #endif /* HAS_MTE */ counter_inc(&vm_statistics_zero_fill_count); DTRACE_VM2(zfod, int, 1, (uint64_t *), NULL); } /* * vm_page_part_copy: * * copy part of one page to another * * This function is currently only consumed downstream of a * vm_map_copy_overwrite(). The implementation has a simpler contract * than vm_page_copy() as there's a restricted set of cases that * are allowed to be overwriteable. If vm_map_entry_is_overwriteable() * is expanded, this function may have to be adjusted. */ void vm_page_part_copy( vm_page_t src_m, vm_offset_t src_pa, vm_page_t dst_m, vm_offset_t dst_pa, vm_size_t len) { #if 0 /* * we don't hold the page queue lock * so this check isn't safe to make */ VM_PAGE_CHECK(src_m); VM_PAGE_CHECK(dst_m); #endif /* * Copying from/into restricted pages is a security issue, * as it allows for restricted pages' policies bypass. */ if (vm_page_is_restricted(src_m)) { panic("%s: cannot copy from a restricted page", __func__); } if (vm_page_is_restricted(dst_m)) { panic("%s: cannot copy into a restricted page", __func__); } #if HAS_MTE /* * As an example of a necessary expansion for vm_page_part_copy(), * MTE objects are currently not overwriteable, but whenever * rdar://134375521 ([VM MTE] Handle overwriting of MTE objects) * gets dealt with, we'll have to update the call down here to pass * the right flags to bcopy_phys(). */ #endif /* HAS_MTE */ pmap_copy_part_page(VM_PAGE_GET_PHYS_PAGE(src_m), src_pa, VM_PAGE_GET_PHYS_PAGE(dst_m), dst_pa, len); } /* * vm_page_copy: * * Copy one page to another */ int vm_page_copy_cs_validations = 0; int vm_page_copy_cs_tainted = 0; void vm_page_copy( vm_page_t src_m, vm_page_t dest_m) { vm_object_t src_m_object; int options = 0; src_m_object = VM_PAGE_OBJECT(src_m); #if 0 /* * we don't hold the page queue lock * so this check isn't safe to make */ VM_PAGE_CHECK(src_m); VM_PAGE_CHECK(dest_m); #endif vm_object_lock_assert_held(src_m_object); /* * Copying from/into restricted pages is a security issue, * as it allows for restricted pages' policies bypass. */ if (vm_page_is_restricted(src_m)) { panic("%s: cannot copy from a restricted page", __func__); } if (vm_page_is_restricted(dest_m)) { panic("%s: cannot copy into a restricted page", __func__); } if (src_m_object != VM_OBJECT_NULL && src_m_object->code_signed) { /* * We're copying a page from a code-signed object. * Whoever ends up mapping the copy page might care about * the original page's integrity, so let's validate the * source page now. */ vm_page_copy_cs_validations++; vm_page_validate_cs(src_m, PAGE_SIZE, 0); #if DEVELOPMENT || DEBUG DTRACE_VM4(codesigned_copy, vm_object_t, src_m_object, vm_object_offset_t, src_m->vmp_offset, int, src_m->vmp_cs_validated, int, src_m->vmp_cs_tainted); #endif /* DEVELOPMENT || DEBUG */ } /* * Propagate the cs_tainted bit to the copy page. Do not propagate * the cs_validated bit. */ dest_m->vmp_cs_tainted = src_m->vmp_cs_tainted; dest_m->vmp_cs_nx = src_m->vmp_cs_nx; if (dest_m->vmp_cs_tainted) { vm_page_copy_cs_tainted++; } #if HAS_MTE /* * vm_page_copy-ing from an untagged page into a tagged page * would happen with tag checking disabled and actually potentially be * an MTE violation. */ if (!src_m->vmp_using_mte && dest_m->vmp_using_mte) { panic("Attempt to write to an MTE tagged page through the physical aperture"); } if (src_m->vmp_using_mte) { /* If we are copying from an MTE-enabled page, disable tag checking */ options |= cppvDisableTagCheck; if (dest_m->vmp_using_mte) { /* * If both source and destination are tagged, this means that we are * either CoWing or relocating a page. Tags need to follow along. */ options |= cppvCopyTags; } } #endif /* HAS_MTE */ dest_m->vmp_error = VMP_ERROR_GET(src_m); /* sliding src_m might have failed... */ pmap_copy_page(VM_PAGE_GET_PHYS_PAGE(src_m), VM_PAGE_GET_PHYS_PAGE(dest_m), options); } #if MACH_ASSERT static void _vm_page_print( vm_page_t p) { printf("vm_page %p: \n", p); printf(" pageq: next=%p prev=%p\n", (vm_page_t)VM_PAGE_UNPACK_PTR(p->vmp_pageq.next), (vm_page_t)VM_PAGE_UNPACK_PTR(p->vmp_pageq.prev)); printf(" listq: next=%p prev=%p\n", (vm_page_t)(VM_PAGE_UNPACK_PTR(p->vmp_listq.next)), (vm_page_t)(VM_PAGE_UNPACK_PTR(p->vmp_listq.prev))); printf(" next=%p\n", (vm_page_t)(VM_PAGE_UNPACK_PTR(p->vmp_next_m))); printf(" object=%p offset=0x%llx\n", VM_PAGE_OBJECT(p), p->vmp_offset); printf(" wire_count=%u\n", p->vmp_wire_count); printf(" q_state=%u\n", p->vmp_q_state); printf(" %slaundry, %sref, %sgobbled, %sprivate\n", (p->vmp_laundry ? "" : "!"), (p->vmp_reference ? "" : "!"), (p->vmp_gobbled ? "" : "!"), (vm_page_is_private(p) ? "" : "!")); printf(" %sbusy, %swanted, %stabled, %sfictitious, %spmapped, %swpmapped\n", (p->vmp_busy ? "" : "!"), (p->vmp_wanted ? "" : "!"), (p->vmp_tabled ? "" : "!"), (vm_page_is_fictitious(p) ? "" : "!"), (p->vmp_pmapped ? "" : "!"), (p->vmp_wpmapped ? "" : "!")); printf(" %sfree_when_done, %sabsent, %serror, %sdirty, %scleaning, %sprecious, %sclustered\n", (p->vmp_free_when_done ? "" : "!"), (p->vmp_absent ? "" : "!"), (VMP_ERROR_GET(p) ? "" : "!"), (p->vmp_dirty ? "" : "!"), (p->vmp_cleaning ? "" : "!"), (p->vmp_precious ? "" : "!"), (p->vmp_clustered ? "" : "!")); printf(" %soverwriting, %srestart, %sunusual\n", (p->vmp_overwriting ? "" : "!"), (p->vmp_restart ? "" : "!"), (p->vmp_unusual ? "" : "!")); printf(" cs_validated=%d, cs_tainted=%d, cs_nx=%d, %sno_cache\n", p->vmp_cs_validated, p->vmp_cs_tainted, p->vmp_cs_nx, (p->vmp_no_cache ? "" : "!")); printf("phys_page=0x%x\n", VM_PAGE_GET_PHYS_PAGE(p)); } /* * Check that the list of pages is ordered by * ascending physical address and has no holes. */ static int vm_page_verify_contiguous( vm_page_t pages, unsigned int npages) { vm_page_t m; unsigned int page_count; vm_offset_t prev_addr; prev_addr = VM_PAGE_GET_PHYS_PAGE(pages); page_count = 1; for (m = NEXT_PAGE(pages); m != VM_PAGE_NULL; m = NEXT_PAGE(m)) { if (VM_PAGE_GET_PHYS_PAGE(m) != prev_addr + 1) { printf("m %p prev_addr 0x%lx, current addr 0x%x\n", m, (long)prev_addr, VM_PAGE_GET_PHYS_PAGE(m)); printf("pages %p page_count %d npages %d\n", pages, page_count, npages); panic("vm_page_verify_contiguous: not contiguous!"); } prev_addr = VM_PAGE_GET_PHYS_PAGE(m); ++page_count; } if (page_count != npages) { printf("pages %p actual count 0x%x but requested 0x%x\n", pages, page_count, npages); panic("vm_page_verify_contiguous: count error"); } return 1; } /* * Check the free lists for proper length etc. */ static boolean_t vm_page_verify_this_free_list_enabled = FALSE; static unsigned int vm_page_verify_free_list( vm_page_queue_head_t *vm_page_queue, unsigned int color, vm_page_t look_for_page, boolean_t expect_page) { unsigned int npages; vm_page_t m; vm_page_t prev_m; boolean_t found_page; if (!vm_page_verify_this_free_list_enabled) { return 0; } found_page = FALSE; npages = 0; prev_m = (vm_page_t)((uintptr_t)vm_page_queue); vm_page_queue_iterate(vm_page_queue, m, vmp_pageq) { if (m == look_for_page) { found_page = TRUE; } if ((vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.prev) != prev_m) { panic("vm_page_verify_free_list(color=%u, npages=%u): page %p corrupted prev ptr %p instead of %p", color, npages, m, (vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.prev), prev_m); } if (!m->vmp_busy) { panic("vm_page_verify_free_list(color=%u, npages=%u): page %p not busy", color, npages, m); } if (color != (unsigned int) -1) { if (VM_PAGE_GET_COLOR(m) != color) { panic("vm_page_verify_free_list(color=%u, npages=%u): page %p wrong color %u instead of %u", color, npages, m, VM_PAGE_GET_COLOR(m), color); } if (m->vmp_q_state != VM_PAGE_ON_FREE_Q) { panic("vm_page_verify_free_list(color=%u, npages=%u): page %p - expecting q_state == VM_PAGE_ON_FREE_Q, found %d", color, npages, m, m->vmp_q_state); } } else { if (m->vmp_q_state != VM_PAGE_ON_FREE_LOCAL_Q) { panic("vm_page_verify_free_list(npages=%u): local page %p - expecting q_state == VM_PAGE_ON_FREE_LOCAL_Q, found %d", npages, m, m->vmp_q_state); } } ++npages; prev_m = m; } if (look_for_page != VM_PAGE_NULL) { unsigned int other_color; if (expect_page && !found_page) { printf("vm_page_verify_free_list(color=%u, npages=%u): page %p not found phys=%u\n", color, npages, look_for_page, VM_PAGE_GET_PHYS_PAGE(look_for_page)); _vm_page_print(look_for_page); for (other_color = 0; other_color < vm_colors; other_color++) { if (other_color == color) { continue; } vm_page_verify_free_list(&vm_page_queue_free.vmpfq_queues[other_color].qhead, other_color, look_for_page, FALSE); } #if XNU_VM_HAS_LOPAGE if (color == (unsigned int) -1) { vm_page_verify_free_list(&vm_lopage_queue_free, (unsigned int) -1, look_for_page, FALSE); } #endif /* XNU_VM_HAS_LOPAGE */ panic("vm_page_verify_free_list(color=%u)", color); } if (!expect_page && found_page) { printf("vm_page_verify_free_list(color=%u, npages=%u): page %p found phys=%u\n", color, npages, look_for_page, VM_PAGE_GET_PHYS_PAGE(look_for_page)); } } return npages; } static boolean_t vm_page_verify_all_free_lists_enabled = FALSE; static void vm_page_verify_free_lists( void ) { unsigned int color, npages, nlopages; boolean_t toggle = TRUE; if (!vm_page_verify_all_free_lists_enabled) { return; } npages = 0; nlopages = 0; vm_free_page_lock(); if (vm_page_verify_this_free_list_enabled == TRUE) { /* * This variable has been set globally for extra checking of * each free list Q. Since we didn't set it, we don't own it * and we shouldn't toggle it. */ toggle = FALSE; } if (toggle == TRUE) { vm_page_verify_this_free_list_enabled = TRUE; } for (color = 0; color < vm_colors; color++) { npages += vm_page_verify_free_list(&vm_page_queue_free.vmpfq_queues[color].qhead, color, VM_PAGE_NULL, FALSE); } #if XNU_VM_HAS_LOPAGE nlopages = vm_page_verify_free_list(&vm_lopage_queue_free, (unsigned int) -1, VM_PAGE_NULL, FALSE); #endif /* XNU_VM_HAS_LOPAGE */ if (npages != vm_page_free_count || nlopages != vm_lopage_free_count) { panic("vm_page_verify_free_lists: " "npages %u free_count %d nlopages %u lo_free_count %u", npages, vm_page_free_count, nlopages, vm_lopage_free_count); } if (toggle == TRUE) { vm_page_verify_this_free_list_enabled = FALSE; } vm_free_page_unlock(); } #endif /* MACH_ASSERT */ extern boolean_t(*volatile consider_buffer_cache_collect)(int); /* * CONTIGUOUS PAGE ALLOCATION AND HELPER FUNCTIONS */ /* * Helper function used to determine if a page can be relocated * A page is relocatable if it is in a stable non-transient state * and if the page being relocated is compatible with the reason for reloc * The page queue lock must be held, and the object lock too, if the page * is in an object. */ boolean_t vm_page_is_relocatable(vm_page_t m, vm_relocate_reason_t reloc_reason) { if (VM_PAGE_WIRED(m) || m->vmp_gobbled || m->vmp_laundry || m->vmp_wanted || m->vmp_cleaning || m->vmp_overwriting || m->vmp_free_when_done) { /* * Page is in a transient state * or a state we don't want to deal with. */ return FALSE; } else if ((m->vmp_q_state == VM_PAGE_NOT_ON_Q) || (m->vmp_q_state == VM_PAGE_ON_FREE_LOCAL_Q) || #if XNU_VM_HAS_LOPAGE (m->vmp_q_state == VM_PAGE_ON_FREE_LOPAGE_Q) || #endif /* XNU_VM_HAS_LOPAGE */ (m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q)) { /* * Page needs to be on one of our queues (other then the pageout or special * free queues) or it needs to belong to the compressor pool (which is now * indicated by vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR and falls out from * the check for VM_PAGE_NOT_ON_Q) in order for it to be stable behind the * locks we hold at this point... */ return FALSE; } else if ((m->vmp_q_state != VM_PAGE_ON_FREE_Q) && (!m->vmp_tabled || m->vmp_busy)) { /* * pages on the free list are always 'busy' * so we couldn't test for 'busy' in the check * for the transient states... pages that are * 'free' are never 'tabled', so we also couldn't * test for 'tabled'. So we check here to make * sure that a non-free page is not busy and is * tabled on an object... */ return FALSE; } /* * Lastly, check the page against the relocation reason; the page may * be in a relocatable state, but not be a page we WANT to relocate for * the caller's use case. */ switch (reloc_reason) { #if HAS_MTE case VM_RELOCATE_REASON_TAG_STORAGE_RECLAIM: { /* * Relocating the content of tag storage pages so the * fill thread can reclaim a page is perfectly valid, * unless the page is busy. */ if (m->vmp_busy) { return FALSE; } break; } case VM_RELOCATE_REASON_TAG_STORAGE_WIRE: #endif /* HAS_MTE */ case VM_RELOCATE_REASON_CONTIGUOUS: { #if HAS_MTE /* * Tag storage pages may be needed for tag storage. Because * the contiguous allocator is likely being used for wired * allocations, this page is not eligible to be relocated in * this case. */ if (vm_page_is_tag_storage(m)) { return FALSE; } #endif /* HAS_MTE */ break; } default: { panic("Invalid relocation reason %u", reloc_reason); __builtin_unreachable(); } } return TRUE; } /* * Free up the given page by possibily relocating its contents to a new page * If the page is on an object the object lock must be held. * * Whether or not the page is considered relocatable is contingent on the * reason it is being relocated. * * Return the new page back to the caller if requested, as done in * vm_object_iopl_wire_full(). * * The VM page queues lock must also be held. * * @returns * - KERN_SUCCESS if the relocation was successful. * - KERN_INVALID_OBJECT if @c m1's object is VM_OBJECT_NULL. * - KERN_FAILURE if the reolcation failed due to @c m1's state. * - KERN_RESOURCE_SHORTAGE if no page could be allocated to relocate @c m1. */ kern_return_t vm_page_relocate( vm_page_t m1, int *compressed_pages, vm_relocate_reason_t reloc_reason, vm_page_t* new_page) { int refmod = 0; vm_object_t object = VM_PAGE_OBJECT(m1); kern_return_t kr; switch (reloc_reason) { case VM_RELOCATE_REASON_CONTIGUOUS: { #if HAS_MTE /* * The contiguous allocator should not be considering tag * storage pages. */ assert(!vm_page_is_tag_storage(m1)); #endif /* HAS_MTE */ break; } #if HAS_MTE case VM_RELOCATE_REASON_TAG_STORAGE_RECLAIM: { /* * If we are trying to reclaim tag storage, we should be * relocating a tag storage page. */ assert(vm_page_is_tag_storage(m1)); if (m1->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) { vm_page_tag_storage_compressor_relocation_count++; } break; } case VM_RELOCATE_REASON_TAG_STORAGE_WIRE: { assert(vm_page_is_tag_storage(m1) && m1->vmp_q_state != VM_PAGE_USED_BY_COMPRESSOR); vm_page_tag_storage_wire_relocation_count++; break; } #endif /* HAS_MTE */ default: { panic("Unrecognized relocation reason %u\n", reloc_reason); break; } } if (object == VM_OBJECT_NULL) { return KERN_INVALID_OBJECT; } vm_object_lock_assert_held(object); if (VM_PAGE_WIRED(m1) || m1->vmp_gobbled || m1->vmp_laundry || m1->vmp_wanted || m1->vmp_cleaning || m1->vmp_overwriting || m1->vmp_free_when_done || m1->vmp_busy || m1->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q) { return KERN_FAILURE; } boolean_t disconnected = FALSE; boolean_t reusable = FALSE; /* * Pages from reusable objects can be reclaimed directly. */ if ((m1->vmp_reusable || object->all_reusable) && m1->vmp_q_state == VM_PAGE_ON_INACTIVE_INTERNAL_Q && !m1->vmp_dirty && !m1->vmp_reference) { /* * reusable page... */ refmod = pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(m1)); disconnected = TRUE; if (refmod == 0) { /* * ... not reused: can steal without relocating contents. */ reusable = TRUE; } } if ((m1->vmp_pmapped && !reusable) || m1->vmp_dirty || m1->vmp_precious) { vm_grab_options_t grab_options = VM_PAGE_GRAB_Q_LOCK_HELD; vm_object_offset_t offset; int copy_page_options = 0; #if HAS_MTE if (m1->vmp_using_mte) { grab_options |= VM_PAGE_GRAB_MTE; copy_page_options |= cppvCopyTags; } #endif /* HAS_MTE */ /* page is not reusable, we need to allocate a new page * and move its contents there. */ vm_page_t m2 = vm_page_grab_options(grab_options); if (m2 == VM_PAGE_NULL) { return KERN_RESOURCE_SHORTAGE; } if (!disconnected) { if (m1->vmp_pmapped) { refmod = pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(m1)); } else { refmod = 0; } } #if HAS_MTE assert(m1->vmp_using_mte == m2->vmp_using_mte); if (m1->vmp_using_mte) { assert(pmap_is_tagged_page(VM_PAGE_GET_PHYS_PAGE(m2))); copy_page_options |= (cppvCopyTags | cppvDisableTagCheck); } #endif /* HAS_MTE */ /* copy the page's contents */ pmap_copy_page(VM_PAGE_GET_PHYS_PAGE(m1), VM_PAGE_GET_PHYS_PAGE(m2), copy_page_options); /* copy the page's state */ assert(!VM_PAGE_WIRED(m1)); assert(m1->vmp_q_state != VM_PAGE_ON_FREE_Q); assert(m1->vmp_q_state != VM_PAGE_ON_PAGEOUT_Q); assert(!m1->vmp_laundry); m2->vmp_reference = m1->vmp_reference; assert(!m1->vmp_gobbled); m2->vmp_no_cache = m1->vmp_no_cache; m2->vmp_xpmapped = 0; assert(!m1->vmp_busy); assert(!m1->vmp_wanted); assert(vm_page_is_canonical(m1)); m2->vmp_pmapped = m1->vmp_pmapped; /* should flush cache ? */ m2->vmp_wpmapped = m1->vmp_wpmapped; assert(!m1->vmp_free_when_done); m2->vmp_absent = m1->vmp_absent; m2->vmp_error = VMP_ERROR_GET(m1); m2->vmp_dirty = m1->vmp_dirty; assert(!m1->vmp_cleaning); m2->vmp_precious = m1->vmp_precious; m2->vmp_clustered = m1->vmp_clustered; assert(!m1->vmp_overwriting); m2->vmp_restart = m1->vmp_restart; m2->vmp_unusual = m1->vmp_unusual; m2->vmp_cs_validated = m1->vmp_cs_validated; m2->vmp_cs_tainted = m1->vmp_cs_tainted; m2->vmp_cs_nx = m1->vmp_cs_nx; m2->vmp_realtime = m1->vmp_realtime; m1->vmp_realtime = false; /* * If m1 had really been reusable, * we would have just stolen it, so * let's not propagate its "reusable" * bit and assert that m2 is not * marked as "reusable". */ // m2->vmp_reusable = m1->vmp_reusable; assert(!m2->vmp_reusable); // assert(!m1->vmp_lopage); if (m1->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) { m2->vmp_q_state = VM_PAGE_USED_BY_COMPRESSOR; /* * We just grabbed m2 up above and so it isn't * going to be on any special Q as yet and so * we don't need to 'remove' it from the special * queues. Just resetting the state should be enough. */ m2->vmp_on_specialq = VM_PAGE_SPECIAL_Q_EMPTY; } /* * page may need to be flushed if * it is marshalled into a UPL * that is going to be used by a device * that doesn't support coherency */ m2->vmp_written_by_kernel = TRUE; /* * make sure we clear the ref/mod state * from the pmap layer... else we risk * inheriting state from the last time * this page was used... */ pmap_clear_refmod(VM_PAGE_GET_PHYS_PAGE(m2), VM_MEM_MODIFIED | VM_MEM_REFERENCED); if (refmod & VM_MEM_REFERENCED) { m2->vmp_reference = TRUE; } if (refmod & VM_MEM_MODIFIED) { SET_PAGE_DIRTY(m2, TRUE); } offset = m1->vmp_offset; /* * completely cleans up the state * of the page so that it is ready * to be put onto the free list, or * for this purpose it looks like it * just came off of the free list */ vm_page_free_prepare(m1); /* * now put the substitute page on the object */ vm_page_insert_internal(m2, object, offset, VM_KERN_MEMORY_NONE, VMPI_Q_LOCKED, NULL); /* * Return the relocated vm_page_t if the caller wants to know. */ if (new_page) { *new_page = m2; } if (m2->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) { m2->vmp_pmapped = TRUE; m2->vmp_wpmapped = TRUE; kr = pmap_enter_check(kernel_pmap, (vm_map_offset_t)m2->vmp_offset, m2, VM_PROT_READ | VM_PROT_WRITE, VM_PROT_NONE, TRUE); assert(kr == KERN_SUCCESS); if (compressed_pages) { ++*compressed_pages; } } else { /* relocated page was not used by the compressor * put it on either the active or inactive lists */ if (m2->vmp_reference) { vm_page_activate(m2); } else { vm_page_deactivate(m2); } } /* unset the busy flag (pages on the free queue are busy) and notify if wanted */ vm_page_wakeup_done(object, m2); } else { assert(m1->vmp_q_state != VM_PAGE_USED_BY_COMPRESSOR); /* * completely cleans up the state * of the page so that it is ready * to be put onto the free list, or * for this purpose it looks like it * just came off of the free list */ vm_page_free_prepare(m1); if (new_page) { vm_page_t m2; vm_object_offset_t offset; vm_grab_options_t grab_options = VM_PAGE_GRAB_Q_LOCK_HELD; /* The caller still wanted a page, so let's give them a new one. */ offset = m1->vmp_offset; #if HAS_MTE if (m1->vmp_using_mte) { grab_options |= VM_PAGE_GRAB_MTE; } #endif /* HAS_MTE */ m2 = vm_page_grab_options(grab_options); if (m2 == VM_PAGE_NULL) { return KERN_RESOURCE_SHORTAGE; } /* * make sure we clear the ref/mod state * from the pmap layer... else we risk * inheriting state from the last time * this page was used... */ pmap_clear_refmod(VM_PAGE_GET_PHYS_PAGE(m2), VM_MEM_MODIFIED | VM_MEM_REFERENCED); offset = m1->vmp_offset; /* * now put the substitute page on the object */ vm_page_insert_internal(m2, object, offset, VM_KERN_MEMORY_NONE, VMPI_Q_LOCKED, NULL); *new_page = m2; } } /* we're done here */ return KERN_SUCCESS; } /* * CONTIGUOUS PAGE ALLOCATION * * Find a region large enough to contain at least n pages * of contiguous physical memory. * * This is done by traversing the vm_page_t array in a linear fashion * we assume that the vm_page_t array has the avaiable physical pages in an * ordered, ascending list... this is currently true of all our implementations * and must remain so... there can be 'holes' in the array... we also can * no longer tolerate the vm_page_t's in the list being 'freed' and reclaimed * which use to happen via 'vm_page_convert'... that function was no longer * being called and was removed... * * The basic flow consists of stabilizing some of the interesting state of * a vm_page_t behind the vm_page_queue and vm_page_free locks... we start our * sweep at the beginning of the array looking for pages that meet our criterea * for a 'stealable' page... currently we are pretty conservative... if the page * meets this criterea and is physically contiguous to the previous page in the 'run' * we keep developing it. If we hit a page that doesn't fit, we reset our state * and start to develop a new run... if at this point we've already considered * at least MAX_CONSIDERED_BEFORE_YIELD pages, we'll drop the 2 locks we hold, * and mutex_pause (which will yield the processor), to keep the latency low w/r * to other threads trying to acquire free pages (or move pages from q to q), * and then continue from the spot we left off... we only make 1 pass through the * array. Once we have a 'run' that is long enough, we'll go into the loop which * which steals the pages from the queues they're currently on... pages on the free * queue can be stolen directly... pages that are on any of the other queues * must be removed from the object they are tabled on... this requires taking the * object lock... we do this as a 'try' to prevent deadlocks... if the 'try' fails * or if the state of the page behind the vm_object lock is no longer viable, we'll * dump the pages we've currently stolen back to the free list, and pick up our * scan from the point where we aborted the 'current' run. * * * Requirements: * - neither vm_page_queue nor vm_free_list lock can be held on entry * * Returns a pointer to a list of gobbled/wired pages or VM_PAGE_NULL. * * Algorithm: */ #define MAX_CONSIDERED_BEFORE_YIELD 1000 #define RESET_STATE_OF_RUN() \ MACRO_BEGIN \ prevcontaddr = -2; \ start_pnum = -1; \ free_considered = 0; \ substitute_needed = 0; \ npages = 0; \ MACRO_END /* * Can we steal in-use (i.e. not free) pages when searching for * physically-contiguous pages ? */ #define VM_PAGE_FIND_CONTIGUOUS_CAN_STEAL 1 static unsigned int vm_page_find_contiguous_last_idx = 0, vm_page_lomem_find_contiguous_last_idx = 0; #if DEBUG int vm_page_find_contig_debug = 0; #endif static vm_page_t vm_page_find_contiguous( unsigned int contig_pages, ppnum_t max_pnum, ppnum_t pnum_mask, boolean_t wire, int flags) { vm_page_list_t list = { }; ppnum_t prevcontaddr = 0; ppnum_t start_pnum = 0; unsigned int npages = 0, considered = 0, scanned = 0; unsigned int page_idx = 0, start_idx = 0, last_idx = 0, orig_last_idx = 0; unsigned int idx_last_contig_page_found = 0; int free_considered = 0, free_available = 0; int substitute_needed = 0; int zone_gc_called = 0; boolean_t wrapped; kern_return_t kr; #if DEBUG clock_sec_t tv_start_sec = 0, tv_end_sec = 0; clock_usec_t tv_start_usec = 0, tv_end_usec = 0; #endif int yielded = 0; int dumped_run = 0; int stolen_pages = 0; int compressed_pages = 0; if (contig_pages == 0) { return VM_PAGE_NULL; } full_scan_again: #if MACH_ASSERT vm_page_verify_free_lists(); #endif #if DEBUG clock_get_system_microtime(&tv_start_sec, &tv_start_usec); #endif c_page_replacement_allowed_start(); #if XNU_VM_HAS_DELAYED_PAGES /* * If there are still delayed pages, try to free up some that match. */ if (__improbable(vm_delayed_count != 0 && contig_pages != 0)) { vm_free_delayed_pages_contig(contig_pages, max_pnum, pnum_mask); } #endif /* XNU_VM_HAS_DELAYED_PAGES */ vm_page_lock_queues(); vm_free_page_lock(); RESET_STATE_OF_RUN(); scanned = 0; considered = 0; free_available = vm_page_free_count - vm_page_free_reserved; wrapped = FALSE; if (flags & KMA_LOMEM) { idx_last_contig_page_found = vm_page_lomem_find_contiguous_last_idx; } else { idx_last_contig_page_found = vm_page_find_contiguous_last_idx; } orig_last_idx = idx_last_contig_page_found; last_idx = orig_last_idx; for (page_idx = last_idx, start_idx = last_idx; npages < contig_pages && page_idx < vm_pages_count; page_idx++) { vm_page_t m = NULL; retry: if (wrapped && npages == 0 && page_idx >= orig_last_idx) { /* * We're back where we started and we haven't * found any suitable contiguous range. Let's * give up. */ break; } scanned++; m = vm_page_get(page_idx); assert(vm_page_is_canonical(m)); if (max_pnum && VM_PAGE_GET_PHYS_PAGE(m) > max_pnum) { /* no more low pages... */ break; } if (!npages & ((VM_PAGE_GET_PHYS_PAGE(m) & pnum_mask) != 0)) { /* * not aligned */ RESET_STATE_OF_RUN(); } else if (!vm_page_is_relocatable(m, VM_RELOCATE_REASON_CONTIGUOUS)) { /* * page is not relocatable */ RESET_STATE_OF_RUN(); } else { if (VM_PAGE_GET_PHYS_PAGE(m) != prevcontaddr + 1) { if ((VM_PAGE_GET_PHYS_PAGE(m) & pnum_mask) != 0) { RESET_STATE_OF_RUN(); goto did_consider; } else { npages = 1; start_idx = page_idx; start_pnum = VM_PAGE_GET_PHYS_PAGE(m); } } else { npages++; } prevcontaddr = VM_PAGE_GET_PHYS_PAGE(m); VM_PAGE_CHECK(m); if (m->vmp_q_state == VM_PAGE_ON_FREE_Q) { free_considered++; } else { /* * This page is not free. * If we can't steal used pages, * we have to give up this run * and keep looking. * Otherwise, we might need to * move the contents of this page * into a substitute page. */ #if VM_PAGE_FIND_CONTIGUOUS_CAN_STEAL if (m->vmp_pmapped || m->vmp_dirty || m->vmp_precious) { substitute_needed++; } #else RESET_STATE_OF_RUN(); #endif } if ((free_considered + substitute_needed) > free_available) { /* * if we let this run continue * we will end up dropping the vm_page_free_count * below the reserve limit... we need to abort * this run, but we can at least re-consider this * page... thus the jump back to 'retry' */ RESET_STATE_OF_RUN(); if (free_available && considered <= MAX_CONSIDERED_BEFORE_YIELD) { considered++; goto retry; } /* * free_available == 0 * so can't consider any free pages... if * we went to retry in this case, we'd * get stuck looking at the same page * w/o making any forward progress * we also want to take this path if we've already * reached our limit that controls the lock latency */ } } did_consider: if (considered > MAX_CONSIDERED_BEFORE_YIELD && npages <= 1) { c_page_replacement_allowed_end(); vm_free_page_unlock(); vm_page_unlock_queues(); mutex_pause(0); c_page_replacement_allowed_start(); vm_page_lock_queues(); vm_free_page_lock(); RESET_STATE_OF_RUN(); /* * reset our free page limit since we * dropped the lock protecting the vm_page_free_queue */ free_available = vm_page_free_count - vm_page_free_reserved; considered = 0; yielded++; goto retry; } considered++; } /* main for-loop end */ if (npages != contig_pages) { if (!wrapped) { /* * We didn't find a contiguous range but we didn't * start from the very first page. * Start again from the very first page. */ RESET_STATE_OF_RUN(); if (flags & KMA_LOMEM) { idx_last_contig_page_found = vm_page_lomem_find_contiguous_last_idx = 0; } else { idx_last_contig_page_found = vm_page_find_contiguous_last_idx = 0; } last_idx = 0; page_idx = last_idx; wrapped = TRUE; goto retry; } vm_free_page_unlock(); } else { vm_page_t m1; unsigned int cur_idx; unsigned int tmp_start_idx; vm_object_t locked_object = VM_OBJECT_NULL; bool abort_run = false; assert(page_idx - start_idx == contig_pages); tmp_start_idx = start_idx; /* * first pass through to pull the free pages * off of the free queue so that in case we * need substitute pages, we won't grab any * of the free pages in the run... we'll clear * the 'free' bit in the 2nd pass, and even in * an abort_run case, we'll collect all of the * free pages in this run and return them to the free list */ while (start_idx < page_idx) { vm_grab_options_t options = VM_PAGE_GRAB_OPTIONS_NONE; m1 = vm_page_get(start_idx++); #if !VM_PAGE_FIND_CONTIGUOUS_CAN_STEAL assert(m1->vmp_q_state == VM_PAGE_ON_FREE_Q); #endif if (m1->vmp_q_state == VM_PAGE_ON_FREE_Q) { vm_page_free_queue_steal(options, m1); } } if (flags & KMA_LOMEM) { vm_page_lomem_find_contiguous_last_idx = page_idx; } else { vm_page_find_contiguous_last_idx = page_idx; } /* * we can drop the free queue lock at this point since * we've pulled any 'free' candidates off of the list * we need it dropped so that we can do a vm_page_grab * when substituing for pmapped/dirty pages */ vm_free_page_unlock(); start_idx = tmp_start_idx; cur_idx = page_idx - 1; while (start_idx++ < page_idx) { /* * must go through the list from back to front * so that the page list is created in the * correct order - low -> high phys addresses */ m1 = vm_page_get(cur_idx--); if (m1->vmp_object == 0) { /* * page has already been removed from * the free list in the 1st pass */ assert(m1->vmp_q_state == VM_PAGE_NOT_ON_Q); assert(m1->vmp_offset == (vm_object_offset_t) -1); assert(m1->vmp_busy); assert(!m1->vmp_wanted); assert(!m1->vmp_laundry); } else { /* * try to relocate/steal the page */ if (abort_run) { continue; } assert(m1->vmp_q_state != VM_PAGE_NOT_ON_Q); vm_object_t object = VM_PAGE_OBJECT(m1); if (object != locked_object) { if (locked_object) { vm_object_unlock(locked_object); locked_object = VM_OBJECT_NULL; } if (vm_object_lock_try(object)) { locked_object = object; } else { /* object must be locked to relocate its pages */ tmp_start_idx = cur_idx; abort_run = true; continue; } } kr = vm_page_relocate(m1, &compressed_pages, VM_RELOCATE_REASON_CONTIGUOUS, NULL); if (kr != KERN_SUCCESS) { if (locked_object) { vm_object_unlock(locked_object); locked_object = VM_OBJECT_NULL; } tmp_start_idx = cur_idx; abort_run = true; continue; } stolen_pages++; } /* m1 is ours at this point ... */ if (m1->vmp_q_state != VM_PAGE_USED_BY_COMPRESSOR) { /* * The Q state is preserved on m1 because vm_page_queues_remove doesn't * change it for pages marked as used-by-compressor. */ vm_page_assign_special_state(m1, VM_PAGE_SPECIAL_Q_BG); } VM_PAGE_ZERO_PAGEQ_ENTRY(m1); vm_page_list_push(&list, m1); } if (locked_object) { vm_object_unlock(locked_object); locked_object = VM_OBJECT_NULL; } if (abort_run) { /* * want the index of the last * page in this run that was * successfully 'stolen', so back * it up 1 for the auto-decrement on use * and 1 more to bump back over this page */ page_idx = tmp_start_idx + 2; if (page_idx >= vm_pages_count) { if (wrapped) { if (list.vmpl_count) { vm_page_unlock_queues(); vm_page_free_list(list.vmpl_head, FALSE); vm_page_lock_queues(); list = (vm_page_list_t){ }; } dumped_run++; goto done_scanning; } page_idx = last_idx = 0; wrapped = TRUE; } abort_run = false; /* * We didn't find a contiguous range but we didn't * start from the very first page. * Start again from the very first page. */ RESET_STATE_OF_RUN(); if (flags & KMA_LOMEM) { idx_last_contig_page_found = vm_page_lomem_find_contiguous_last_idx = page_idx; } else { idx_last_contig_page_found = vm_page_find_contiguous_last_idx = page_idx; } last_idx = page_idx; if (list.vmpl_count) { vm_page_unlock_queues(); vm_page_free_list(list.vmpl_head, FALSE); vm_page_lock_queues(); list = (vm_page_list_t){ }; } dumped_run++; vm_free_page_lock(); /* * reset our free page limit since we * dropped the lock protecting the vm_page_free_queue */ free_available = vm_page_free_count - vm_page_free_reserved; goto retry; } #if HAS_MTE else if (list.vmpl_has_tagged) { const unified_page_list_t pmap_batch_list = { .page_slist = list.vmpl_head, .type = UNIFIED_PAGE_LIST_TYPE_VM_PAGE_LIST, }; /* * We successfully found a contiguous range we could * steal all the pages from. As a last step, make * certain all pages are regular pages, or convert * any non-regular pages to regular pages. */ vm_page_unlock_queues(); /* Make any tagged pages we stole non-tagged. */ pmap_unmake_tagged_pages(&pmap_batch_list); vm_free_page_lock(); /* Mark any tagged pages we stole as non-tagged. */ vm_page_list_foreach(m1, list) { if (m1->vmp_using_mte) { ppnum_t pnum = VM_PAGE_GET_PHYS_PAGE(m1); m1->vmp_using_mte = false; mteinfo_covered_page_clear_tagged(pnum); } } list.vmpl_has_tagged = false; list.vmpl_has_untagged = true; vm_free_page_unlock(); vm_page_lock_queues(); } #endif /* HAS_MTE */ vm_page_list_foreach(m1, list) { assert(m1->vmp_q_state == VM_PAGE_NOT_ON_Q); assert(m1->vmp_wire_count == 0); if (wire == TRUE) { m1->vmp_wire_count++; m1->vmp_q_state = VM_PAGE_IS_WIRED; #if HAS_MTE if (m1->vmp_wire_count == 1) { mteinfo_increment_wire_count(m1); } #endif /* HAS_MTE */ } else { m1->vmp_gobbled = TRUE; } } if (wire == FALSE) { vm_page_gobble_count += npages; } /* * gobbled pages are also counted as wired pages */ vm_page_wire_count += npages; assert(vm_page_verify_contiguous(list.vmpl_head, npages)); } done_scanning: c_page_replacement_allowed_end(); vm_page_unlock_queues(); #if DEBUG clock_get_system_microtime(&tv_end_sec, &tv_end_usec); tv_end_sec -= tv_start_sec; if (tv_end_usec < tv_start_usec) { tv_end_sec--; tv_end_usec += 1000000; } tv_end_usec -= tv_start_usec; if (tv_end_usec >= 1000000) { tv_end_sec++; tv_end_sec -= 1000000; } if (vm_page_find_contig_debug) { printf("%s(num=%d,low=%d): found %d pages at 0x%llx in %ld.%06ds... started at %d... scanned %d pages... yielded %d times... dumped run %d times... stole %d pages... stole %d compressed pages\n", __func__, contig_pages, max_pnum, npages, (vm_object_offset_t)start_pnum << PAGE_SHIFT, (long)tv_end_sec, tv_end_usec, orig_last_idx, scanned, yielded, dumped_run, stolen_pages, compressed_pages); } #endif #if MACH_ASSERT vm_page_verify_free_lists(); #endif if (list.vmpl_count == 0 && zone_gc_called < 2) { printf("%s(num=%d,low=%d): found %d pages at 0x%llx...scanned %d pages... yielded %d times... dumped run %d times... stole %d pages... stole %d compressed pages... wired count is %d\n", __func__, contig_pages, max_pnum, npages, (vm_object_offset_t)start_pnum << PAGE_SHIFT, scanned, yielded, dumped_run, stolen_pages, compressed_pages, vm_page_wire_count); if (consider_buffer_cache_collect != NULL) { (void)(*consider_buffer_cache_collect)(1); } zone_gc(zone_gc_called ? ZONE_GC_DRAIN : ZONE_GC_TRIM); zone_gc_called++; printf("vm_page_find_contiguous: zone_gc called... wired count is %d\n", vm_page_wire_count); goto full_scan_again; } return list.vmpl_head; } /* * Allocate a list of contiguous, wired pages. */ __mockable kern_return_t cpm_allocate( vm_size_t size, vm_page_t *list, ppnum_t max_pnum, ppnum_t pnum_mask, boolean_t wire, int flags) { vm_page_t pages; unsigned int npages; if (size % PAGE_SIZE != 0) { return KERN_INVALID_ARGUMENT; } npages = (unsigned int) (size / PAGE_SIZE); if (npages != size / PAGE_SIZE) { /* 32-bit overflow */ return KERN_INVALID_ARGUMENT; } /* * Obtain a pointer to a subset of the free * list large enough to satisfy the request; * the region will be physically contiguous. */ pages = vm_page_find_contiguous(npages, max_pnum, pnum_mask, wire, flags); if (pages == VM_PAGE_NULL) { return KERN_NO_SPACE; } /* * determine need for wakeups */ if (vm_page_free_count < vm_page_free_min) { vm_free_page_lock(); if (vm_pageout_running == FALSE) { vm_free_page_unlock(); thread_wakeup((event_t) &vm_page_free_wanted); } else { vm_free_page_unlock(); } } VM_CHECK_MEMORYSTATUS; /* * The CPM pages should now be available and * ordered by ascending physical address. */ assert(vm_page_verify_contiguous(pages, npages)); if (flags & KMA_ZERO) { for (vm_page_t m = pages; m; m = NEXT_PAGE(m)) { pmap_zero_page(VM_PAGE_GET_PHYS_PAGE(m)); } } *list = pages; return KERN_SUCCESS; } unsigned int vm_max_delayed_work_limit = DEFAULT_DELAYED_WORK_LIMIT; /* * when working on a 'run' of pages, it is necessary to hold * the vm_page_queue_lock (a hot global lock) for certain operations * on the page... however, the majority of the work can be done * while merely holding the object lock... in fact there are certain * collections of pages that don't require any work brokered by the * vm_page_queue_lock... to mitigate the time spent behind the global * lock, go to a 2 pass algorithm... collect pages up to DELAYED_WORK_LIMIT * while doing all of the work that doesn't require the vm_page_queue_lock... * then call vm_page_do_delayed_work to acquire the vm_page_queue_lock and do the * necessary work for each page... we will grab the busy bit on the page * if it's not already held so that vm_page_do_delayed_work can drop the object lock * if it can't immediately take the vm_page_queue_lock in order to compete * for the locks in the same order that vm_pageout_scan takes them. * the operation names are modeled after the names of the routines that * need to be called in order to make the changes very obvious in the * original loop * * On certain configurations, this function may return failure if any of * the pages in the run has a mapping state that doesn't allow the specified * operation. In that case, it will still fully process the run of pages * in order to avoid requiring the caller to partially undo the work done * here. */ kern_return_t vm_page_do_delayed_work( vm_object_t object, vm_tag_t tag, struct vm_page_delayed_work *dwp, int dw_count) { kern_return_t kr = KERN_SUCCESS; int j; vm_page_t m; vm_page_t local_free_q = VM_PAGE_NULL; /* * pageout_scan takes the vm_page_lock_queues first * then tries for the object lock... to avoid what * is effectively a lock inversion, we'll go to the * trouble of taking them in that same order... otherwise * if this object contains the majority of the pages resident * in the UBC (or a small set of large objects actively being * worked on contain the majority of the pages), we could * cause the pageout_scan thread to 'starve' in its attempt * to find pages to move to the free queue, since it has to * successfully acquire the object lock of any candidate page * before it can steal/clean it. */ if (!vm_page_trylock_queues()) { vm_object_unlock(object); /* * "Turnstile enabled vm_pageout_scan" can be runnable * for a very long time without getting on a core. * If this is a higher priority thread it could be * waiting here for a very long time respecting the fact * that pageout_scan would like its object after VPS does * a mutex_pause(0). * So we cap the number of yields in the vm_object_lock_avoid() * case to a single mutex_pause(0) which will give vm_pageout_scan * 10us to run and grab the object if needed. */ vm_page_lock_queues(); for (j = 0;; j++) { if ((!vm_object_lock_avoid(object) || (vps_dynamic_priority_enabled && (j > 0))) && _vm_object_lock_try(object)) { break; } vm_page_unlock_queues(); mutex_pause(j); vm_page_lock_queues(); } } for (j = 0; j < dw_count; j++, dwp++) { m = dwp->dw_m; if (dwp->dw_mask & DW_vm_pageout_throttle_up) { vm_pageout_throttle_up(m); } #if CONFIG_PHANTOM_CACHE if (dwp->dw_mask & DW_vm_phantom_cache_update) { vm_phantom_cache_update(m); } #endif if (dwp->dw_mask & DW_vm_page_wire) { vm_page_wire(m, tag, FALSE); if (dwp->dw_mask & DW_vm_page_iopl_wire) { #if CONFIG_SPTM /* * The SPTM's security model prevents us from allowing writable I/O * mappings of executable pages. We need to check that here, * in the same place that we set VM_PAGE_IS_IOPL_WIRED, because this * function may have transiently dropped the VM object lock * before reaching this point, which means that frontloading * this check in the caller may not work in all cases. */ if ((dwp->dw_mask & DW_vm_page_iopl_wire_write) && PMAP_PAGE_IS_USER_EXECUTABLE(m)) { if (kr == KERN_SUCCESS) { kr = KERN_PROTECTION_FAILURE; vm_map_guard_exception(current_map(), VM_PAGE_GET_PHYS_PAGE(m), kGUARD_EXC_SEC_IOPL_ON_EXEC_PAGE); ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_VM, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_VM_IOPL_ON_EXEC_PAGE), (uintptr_t)(VM_PAGE_GET_PHYS_PAGE(m))); } } else { m->vmp_q_state = VM_PAGE_IS_IOPL_WIRED; } #else m->vmp_q_state = VM_PAGE_IS_IOPL_WIRED; #endif /* CONFIG_SPTM */ } } else if (dwp->dw_mask & DW_vm_page_unwire) { boolean_t queueit; queueit = (dwp->dw_mask & (DW_vm_page_free | DW_vm_page_deactivate_internal)) ? FALSE : TRUE; vm_page_unwire(m, queueit); } if (dwp->dw_mask & DW_vm_page_free) { vm_page_free_prepare_queues(m); assert(m->vmp_pageq.next == 0 && m->vmp_pageq.prev == 0); /* * Add this page to our list of reclaimed pages, * to be freed later. */ m->vmp_snext = local_free_q; local_free_q = m; } else { if (dwp->dw_mask & DW_vm_page_deactivate_internal) { vm_page_deactivate_internal(m, FALSE); } else if (dwp->dw_mask & DW_vm_page_activate) { if (m->vmp_q_state != VM_PAGE_ON_ACTIVE_Q) { vm_page_activate(m); } } else if (dwp->dw_mask & DW_vm_page_speculate) { vm_page_speculate(m, TRUE); } else if (dwp->dw_mask & DW_enqueue_cleaned) { /* * if we didn't hold the object lock and did this, * we might disconnect the page, then someone might * soft fault it back in, then we would put it on the * cleaned queue, and so we would have a referenced (maybe even dirty) * page on that queue, which we don't want */ int refmod_state = pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(m)); if ((refmod_state & VM_MEM_REFERENCED)) { /* * this page has been touched since it got cleaned; let's activate it * if it hasn't already been */ VM_PAGEOUT_DEBUG(vm_pageout_enqueued_cleaned, 1); VM_PAGEOUT_DEBUG(vm_pageout_cleaned_reactivated, 1); if (m->vmp_q_state != VM_PAGE_ON_ACTIVE_Q) { vm_page_activate(m); } } else { m->vmp_reference = FALSE; vm_page_enqueue_cleaned(m); } } else if (dwp->dw_mask & DW_vm_page_lru) { vm_page_lru(m); } else if (dwp->dw_mask & DW_VM_PAGE_QUEUES_REMOVE) { if (m->vmp_q_state != VM_PAGE_ON_PAGEOUT_Q) { vm_page_queues_remove(m, TRUE); } } if (dwp->dw_mask & DW_set_reference) { m->vmp_reference = TRUE; } else if (dwp->dw_mask & DW_clear_reference) { m->vmp_reference = FALSE; } if (dwp->dw_mask & DW_move_page) { if (m->vmp_q_state != VM_PAGE_ON_PAGEOUT_Q) { vm_page_queues_remove(m, FALSE); assert(!is_kernel_object(VM_PAGE_OBJECT(m))); vm_page_enqueue_inactive(m, FALSE); } } if (dwp->dw_mask & DW_clear_busy) { m->vmp_busy = FALSE; } if (dwp->dw_mask & DW_PAGE_WAKEUP) { vm_page_wakeup(object, m); } #if HAS_MTE if (dwp->dw_mask & DW_vm_page_wakeup_tag_storage) { assert(m->vmp_ts_wanted); mteinfo_tag_storage_wakeup(m, false); } #endif /* HAS_MTE */ } } vm_page_unlock_queues(); if (local_free_q) { vm_page_free_list(local_free_q, TRUE); } VM_CHECK_MEMORYSTATUS; return kr; } __abortlike static void __vm_page_alloc_list_failed_panic( vm_size_t page_count, kma_flags_t flags, kern_return_t kr) { panic("vm_page_alloc_list(%zd, 0x%x) failed unexpectedly with %d", (size_t)page_count, flags, kr); } kern_return_t vm_page_alloc_list(vm_size_t page_count, kma_flags_t flags, vm_page_t *list) { vm_page_t page_list = VM_PAGE_NULL; vm_page_t mem; kern_return_t kr = KERN_SUCCESS; int page_grab_count = 0; for (vm_size_t i = 0; i < page_count; i++) { for (;;) { vm_grab_options_t options = VM_PAGE_GRAB_OPTIONS_NONE; #if HAS_MTE if (flags & KMA_TAG) { options |= VM_PAGE_GRAB_MTE; } if (vm_mte_tag_storage_for_compressor && (flags & KMA_COMPRESSOR)) { /* * These pages will be used in the compressor pool. * Prefer tag storage pages for these allocations. */ options |= VM_PAGE_GRAB_ALLOW_TAG_STORAGE; } #endif /* HAS_MTE */ if (flags & KMA_NOPAGEWAIT) { options |= VM_PAGE_GRAB_NOPAGEWAIT; } if (flags & KMA_LOMEM) { mem = vm_page_grablo(options); } else { mem = vm_page_grab_options(options); } if (mem != VM_PAGE_NULL) { break; } if (flags & KMA_NOPAGEWAIT) { kr = KERN_RESOURCE_SHORTAGE; goto out; } if ((flags & KMA_LOMEM) && vm_lopage_needed) { kr = KERN_RESOURCE_SHORTAGE; goto out; } /* VM privileged threads should have waited in vm_page_grab() and not get here. */ assert(!(current_thread()->options & TH_OPT_VMPRIV)); if ((flags & KMA_NOFAIL) == 0 && ptoa_64(page_count) > max_mem / 4) { uint64_t unavailable = ptoa_64(vm_page_wire_count + vm_page_free_target); if (unavailable > max_mem || ptoa_64(page_count) > (max_mem - unavailable)) { kr = KERN_RESOURCE_SHORTAGE; goto out; } } VM_PAGE_WAIT(); } page_grab_count++; mem->vmp_snext = page_list; page_list = mem; } if ((KMA_ZERO | KMA_NOENCRYPT) & flags) { for (mem = page_list; mem; mem = mem->vmp_snext) { pmap_zero_page(VM_PAGE_GET_PHYS_PAGE(mem)); } } out: ledger_credit(current_thread()->t_ledger, task_ledgers.pages_grabbed_kern, page_grab_count); counter_inc(&vm_page_grab_count_kern); if (kr == KERN_SUCCESS) { *list = page_list; } else if (flags & KMA_NOFAIL) { __vm_page_alloc_list_failed_panic(page_count, flags, kr); } else { vm_page_free_list(page_list, FALSE); } return kr; } void vm_page_set_offset(vm_page_t page, vm_object_offset_t offset) { page->vmp_offset = offset; } vm_page_t vm_page_get_next(vm_page_t page) { return page->vmp_snext; } vm_object_offset_t vm_page_get_offset(vm_page_t page) { return page->vmp_offset; } ppnum_t vm_page_get_phys_page(vm_page_t page) { return VM_PAGE_GET_PHYS_PAGE(page); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #if HIBERNATION static uint32_t hibernate_teardown_vm_structs(hibernate_page_list_t *, hibernate_page_list_t *); struct hibernate_statistics { int hibernate_considered; int hibernate_reentered_on_q; int hibernate_found_dirty; int hibernate_skipped_cleaning; int hibernate_skipped_transient; int hibernate_skipped_precious; int hibernate_skipped_external; int hibernate_queue_nolock; int hibernate_queue_paused; int hibernate_throttled; int hibernate_throttle_timeout; int hibernate_drained; int hibernate_drain_timeout; int cd_lock_failed; int cd_found_precious; int cd_found_wired; int cd_found_busy; int cd_found_unusual; int cd_found_cleaning; int cd_found_laundry; int cd_found_dirty; int cd_found_xpmapped; int cd_skipped_xpmapped; int cd_local_free; int cd_total_free; int cd_vm_page_wire_count; int cd_vm_struct_pages_unneeded; int cd_pages; int cd_discarded; int cd_count_wire; } hibernate_stats; #if CONFIG_SPTM /** * On SPTM-based systems don't save any executable pages into the hibernation * image. The SPTM has stronger guarantees around not allowing write access to * the executable pages than on older systems, which prevents XNU from being * able to restore any pages mapped as executable. */ #define HIBERNATE_XPMAPPED_LIMIT 0ULL #else /* CONFIG_SPTM */ /* * clamp the number of 'xpmapped' pages we'll sweep into the hibernation image * so that we don't overrun the estimated image size, which would * result in a hibernation failure. * * We use a size value instead of pages because we don't want to take up more space * on disk if the system has a 16K page size vs 4K. Also, we are not guaranteed * to have that additional space available. * * Since this was set at 40000 pages on X86 we are going to use 160MB as our * xpmapped size. */ #define HIBERNATE_XPMAPPED_LIMIT ((160 * 1024 * 1024ULL) / PAGE_SIZE) #endif /* CONFIG_SPTM */ static int hibernate_drain_pageout_queue(struct vm_pageout_queue *q) { wait_result_t wait_result; vm_page_lock_queues(); while (!vm_page_queue_empty(&q->pgo_pending)) { q->pgo_draining = TRUE; assert_wait_timeout((event_t) (&q->pgo_laundry + 1), THREAD_INTERRUPTIBLE, 5000, 1000 * NSEC_PER_USEC); vm_page_unlock_queues(); wait_result = thread_block(THREAD_CONTINUE_NULL); if (wait_result == THREAD_TIMED_OUT && !vm_page_queue_empty(&q->pgo_pending)) { hibernate_stats.hibernate_drain_timeout++; if (q == &vm_pageout_queue_external) { return 0; } return 1; } vm_page_lock_queues(); hibernate_stats.hibernate_drained++; } vm_page_unlock_queues(); return 0; } boolean_t hibernate_skip_external = FALSE; static int hibernate_flush_queue(vm_page_queue_head_t *q, int qcount) { vm_page_t m; vm_object_t l_object = NULL; vm_object_t m_object = NULL; int refmod_state = 0; int try_failed_count = 0; int retval = 0; int current_run = 0; struct vm_pageout_queue *iq; struct vm_pageout_queue *eq; struct vm_pageout_queue *tq; KDBG(IOKDBG_CODE(DBG_HIBERNATE, 4) | DBG_FUNC_START, VM_KERNEL_UNSLIDE_OR_PERM(q), qcount); iq = &vm_pageout_queue_internal; eq = &vm_pageout_queue_external; vm_page_lock_queues(); while (qcount && !vm_page_queue_empty(q)) { if (current_run++ == 1000) { if (hibernate_should_abort()) { retval = 1; break; } current_run = 0; } m = (vm_page_t) vm_page_queue_first(q); m_object = VM_PAGE_OBJECT(m); /* * check to see if we currently are working * with the same object... if so, we've * already got the lock */ if (m_object != l_object) { /* * the object associated with candidate page is * different from the one we were just working * with... dump the lock if we still own it */ if (l_object != NULL) { vm_object_unlock(l_object); l_object = NULL; } /* * Try to lock object; since we've alread got the * page queues lock, we can only 'try' for this one. * if the 'try' fails, we need to do a mutex_pause * to allow the owner of the object lock a chance to * run... */ if (!vm_object_lock_try_scan(m_object)) { if (try_failed_count > 20) { hibernate_stats.hibernate_queue_nolock++; goto reenter_pg_on_q; } vm_page_unlock_queues(); mutex_pause(try_failed_count++); vm_page_lock_queues(); hibernate_stats.hibernate_queue_paused++; continue; } else { l_object = m_object; } } if (!m_object->alive || m->vmp_cleaning || m->vmp_laundry || m->vmp_busy || m->vmp_absent || VMP_ERROR_GET(m)) { /* * page is not to be cleaned * put it back on the head of its queue */ if (m->vmp_cleaning) { hibernate_stats.hibernate_skipped_cleaning++; } else { hibernate_stats.hibernate_skipped_transient++; } goto reenter_pg_on_q; } if (m_object->vo_copy == VM_OBJECT_NULL) { if (m_object->purgable == VM_PURGABLE_VOLATILE || m_object->purgable == VM_PURGABLE_EMPTY) { /* * let the normal hibernate image path * deal with these */ goto reenter_pg_on_q; } } if (!m->vmp_dirty && m->vmp_pmapped) { refmod_state = pmap_get_refmod(VM_PAGE_GET_PHYS_PAGE(m)); if ((refmod_state & VM_MEM_MODIFIED)) { SET_PAGE_DIRTY(m, FALSE); } } else { refmod_state = 0; } if (!m->vmp_dirty) { /* * page is not to be cleaned * put it back on the head of its queue */ if (m->vmp_precious) { hibernate_stats.hibernate_skipped_precious++; } goto reenter_pg_on_q; } if (hibernate_skip_external == TRUE && !m_object->internal) { hibernate_stats.hibernate_skipped_external++; goto reenter_pg_on_q; } tq = NULL; if (m_object->internal) { if (VM_PAGE_Q_THROTTLED(iq)) { tq = iq; } } else if (VM_PAGE_Q_THROTTLED(eq)) { tq = eq; } if (tq != NULL) { wait_result_t wait_result; int wait_count = 5; if (l_object != NULL) { vm_object_unlock(l_object); l_object = NULL; } while (retval == 0) { tq->pgo_throttled = TRUE; assert_wait_timeout((event_t) &tq->pgo_laundry, THREAD_INTERRUPTIBLE, 1000, 1000 * NSEC_PER_USEC); vm_page_unlock_queues(); wait_result = thread_block(THREAD_CONTINUE_NULL); vm_page_lock_queues(); if (wait_result != THREAD_TIMED_OUT) { break; } if (!VM_PAGE_Q_THROTTLED(tq)) { break; } if (hibernate_should_abort()) { retval = 1; } if (--wait_count == 0) { hibernate_stats.hibernate_throttle_timeout++; if (tq == eq) { hibernate_skip_external = TRUE; break; } retval = 1; } } if (retval) { break; } hibernate_stats.hibernate_throttled++; continue; } /* * we've already factored out pages in the laundry which * means this page can't be on the pageout queue so it's * safe to do the vm_page_queues_remove */ vm_page_queues_remove(m, TRUE); if (m_object->internal == TRUE) { pmap_disconnect_options(VM_PAGE_GET_PHYS_PAGE(m), PMAP_OPTIONS_COMPRESSOR, NULL); } vm_pageout_cluster(m); hibernate_stats.hibernate_found_dirty++; goto next_pg; reenter_pg_on_q: vm_page_queue_remove(q, m, vmp_pageq); vm_page_queue_enter(q, m, vmp_pageq); hibernate_stats.hibernate_reentered_on_q++; next_pg: hibernate_stats.hibernate_considered++; qcount--; try_failed_count = 0; } if (l_object != NULL) { vm_object_unlock(l_object); l_object = NULL; } vm_page_unlock_queues(); KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 4) | DBG_FUNC_END, hibernate_stats.hibernate_found_dirty, retval, 0, 0, 0); return retval; } static int hibernate_flush_dirty_pages(int pass) { struct vm_speculative_age_q *aq; uint32_t i; if (vm_page_local_q) { zpercpu_foreach_cpu(lid) { vm_page_reactivate_local(lid, TRUE, FALSE); } } for (i = 0; i <= vm_page_max_speculative_age_q; i++) { int qcount; vm_page_t m; aq = &vm_page_queue_speculative[i]; if (vm_page_queue_empty(&aq->age_q)) { continue; } qcount = 0; vm_page_lockspin_queues(); vm_page_queue_iterate(&aq->age_q, m, vmp_pageq) { qcount++; } vm_page_unlock_queues(); if (qcount) { if (hibernate_flush_queue(&aq->age_q, qcount)) { return 1; } } } if (hibernate_flush_queue(&vm_page_queue_inactive, vm_page_inactive_count - vm_page_anonymous_count - vm_page_cleaned_count)) { return 1; } /* XXX FBDP TODO: flush secluded queue */ if (hibernate_flush_queue(&vm_page_queue_anonymous, vm_page_anonymous_count)) { return 1; } if (hibernate_flush_queue(&vm_page_queue_cleaned, vm_page_cleaned_count)) { return 1; } if (hibernate_drain_pageout_queue(&vm_pageout_queue_internal)) { return 1; } if (pass == 1) { vm_compressor_record_warmup_start(); } if (hibernate_flush_queue(&vm_page_queue_active, vm_page_active_count)) { if (pass == 1) { vm_compressor_record_warmup_end(); } return 1; } if (hibernate_drain_pageout_queue(&vm_pageout_queue_internal)) { if (pass == 1) { vm_compressor_record_warmup_end(); } return 1; } if (pass == 1) { vm_compressor_record_warmup_end(); } if (hibernate_skip_external == FALSE && hibernate_drain_pageout_queue(&vm_pageout_queue_external)) { return 1; } return 0; } void hibernate_reset_stats(void) { bzero(&hibernate_stats, sizeof(struct hibernate_statistics)); } int hibernate_flush_memory(void) { int retval; assert(VM_CONFIG_COMPRESSOR_IS_PRESENT); KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 3) | DBG_FUNC_START, vm_page_free_count, 0, 0, 0, 0); hibernate_cleaning_in_progress = TRUE; hibernate_skip_external = FALSE; if ((retval = hibernate_flush_dirty_pages(1)) == 0) { KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 10) | DBG_FUNC_START, VM_PAGE_COMPRESSOR_COUNT, 0, 0, 0, 0); vm_compressor_flush(); KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 10) | DBG_FUNC_END, VM_PAGE_COMPRESSOR_COUNT, 0, 0, 0, 0); if (consider_buffer_cache_collect != NULL) { unsigned int orig_wire_count; KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 7) | DBG_FUNC_START, 0, 0, 0, 0, 0); orig_wire_count = vm_page_wire_count; (void)(*consider_buffer_cache_collect)(1); zone_gc(ZONE_GC_DRAIN); HIBLOG("hibernate_flush_memory: buffer_cache_gc freed up %d wired pages\n", orig_wire_count - vm_page_wire_count); KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 7) | DBG_FUNC_END, orig_wire_count - vm_page_wire_count, 0, 0, 0, 0); } } hibernate_cleaning_in_progress = FALSE; KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 3) | DBG_FUNC_END, vm_page_free_count, hibernate_stats.hibernate_found_dirty, retval, 0, 0); if (retval) { HIBLOG("hibernate_flush_memory() failed to finish - vm_page_compressor_count(%d)\n", VM_PAGE_COMPRESSOR_COUNT); } HIBPRINT("hibernate_flush_memory() considered(%d) reentered_on_q(%d) found_dirty(%d)\n", hibernate_stats.hibernate_considered, hibernate_stats.hibernate_reentered_on_q, hibernate_stats.hibernate_found_dirty); HIBPRINT(" skipped_cleaning(%d) skipped_transient(%d) skipped_precious(%d) skipped_external(%d) queue_nolock(%d)\n", hibernate_stats.hibernate_skipped_cleaning, hibernate_stats.hibernate_skipped_transient, hibernate_stats.hibernate_skipped_precious, hibernate_stats.hibernate_skipped_external, hibernate_stats.hibernate_queue_nolock); HIBPRINT(" queue_paused(%d) throttled(%d) throttle_timeout(%d) drained(%d) drain_timeout(%d)\n", hibernate_stats.hibernate_queue_paused, hibernate_stats.hibernate_throttled, hibernate_stats.hibernate_throttle_timeout, hibernate_stats.hibernate_drained, hibernate_stats.hibernate_drain_timeout); return retval; } static void hibernate_page_list_zero(hibernate_page_list_t *list) { uint32_t bank; hibernate_bitmap_t * bitmap; bitmap = &list->bank_bitmap[0]; for (bank = 0; bank < list->bank_count; bank++) { uint32_t last_bit; bzero((void *) &bitmap->bitmap[0], bitmap->bitmapwords << 2); // set out-of-bound bits at end of bitmap. last_bit = ((bitmap->last_page - bitmap->first_page + 1) & 31); if (last_bit) { bitmap->bitmap[bitmap->bitmapwords - 1] = (0xFFFFFFFF >> last_bit); } bitmap = (hibernate_bitmap_t *) &bitmap->bitmap[bitmap->bitmapwords]; } } static boolean_t hibernate_consider_discard(vm_page_t m, boolean_t preflight) { vm_object_t object = NULL; int refmod_state; boolean_t discard = FALSE; do{ if (vm_page_is_private(m)) { panic("hibernate_consider_discard: private"); } object = VM_PAGE_OBJECT(m); if (!vm_object_lock_try(object)) { object = NULL; if (!preflight) { hibernate_stats.cd_lock_failed++; } break; } if (VM_PAGE_WIRED(m)) { if (!preflight) { hibernate_stats.cd_found_wired++; } break; } if (m->vmp_precious) { if (!preflight) { hibernate_stats.cd_found_precious++; } break; } if (m->vmp_busy || !object->alive) { /* * Somebody is playing with this page. */ if (!preflight) { hibernate_stats.cd_found_busy++; } break; } if (m->vmp_absent || m->vmp_unusual || VMP_ERROR_GET(m)) { /* * If it's unusual in anyway, ignore it */ if (!preflight) { hibernate_stats.cd_found_unusual++; } break; } if (m->vmp_cleaning) { if (!preflight) { hibernate_stats.cd_found_cleaning++; } break; } if (m->vmp_laundry) { if (!preflight) { hibernate_stats.cd_found_laundry++; } break; } if (!m->vmp_dirty) { refmod_state = pmap_get_refmod(VM_PAGE_GET_PHYS_PAGE(m)); if (refmod_state & VM_MEM_REFERENCED) { m->vmp_reference = TRUE; } if (refmod_state & VM_MEM_MODIFIED) { SET_PAGE_DIRTY(m, FALSE); } } /* * If it's clean or purgeable we can discard the page on wakeup. */ discard = (!m->vmp_dirty) || (VM_PURGABLE_VOLATILE == object->purgable) || (VM_PURGABLE_EMPTY == object->purgable); if (discard == FALSE) { if (!preflight) { hibernate_stats.cd_found_dirty++; } } else if (m->vmp_xpmapped && m->vmp_reference && !object->internal) { if (hibernate_stats.cd_found_xpmapped < HIBERNATE_XPMAPPED_LIMIT) { if (!preflight) { hibernate_stats.cd_found_xpmapped++; } discard = FALSE; } else { if (!preflight) { hibernate_stats.cd_skipped_xpmapped++; } } } }while (FALSE); if (object) { vm_object_unlock(object); } return discard; } static void hibernate_discard_page(vm_page_t m) { vm_object_t m_object; if (m->vmp_absent || m->vmp_unusual || VMP_ERROR_GET(m)) { /* * If it's unusual in anyway, ignore */ return; } m_object = VM_PAGE_OBJECT(m); #if MACH_ASSERT || DEBUG if (!vm_object_lock_try(m_object)) { panic("hibernate_discard_page(%p) !vm_object_lock_try", m); } #else /* No need to lock page queue for token delete, hibernate_vm_unlock() * makes sure these locks are uncontended before sleep */ #endif /* MACH_ASSERT || DEBUG */ if (m->vmp_pmapped == TRUE) { __unused int refmod_state = pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(m)); } if (m->vmp_laundry) { panic("hibernate_discard_page(%p) laundry", m); } if (vm_page_is_private(m)) { panic("hibernate_discard_page(%p) private", m); } if (vm_page_is_fictitious(m)) { panic("hibernate_discard_page(%p) fictitious", m); } if (VM_PURGABLE_VOLATILE == m_object->purgable) { /* object should be on a queue */ assert((m_object->objq.next != NULL) && (m_object->objq.prev != NULL)); purgeable_q_t old_queue = vm_purgeable_object_remove(m_object); assert(old_queue); if (m_object->purgeable_when_ripe) { vm_purgeable_token_delete_first(old_queue); } vm_object_lock_assert_exclusive(m_object); VM_OBJECT_SET_PURGABLE(m_object, VM_PURGABLE_EMPTY); /* * Purgeable ledgers: pages of VOLATILE and EMPTY objects are * accounted in the "volatile" ledger, so no change here. * We have to update vm_page_purgeable_count, though, since we're * effectively purging this object. */ unsigned int delta; assert(m_object->resident_page_count >= m_object->wired_page_count); delta = (m_object->resident_page_count - m_object->wired_page_count); assert(delta > 0); counter_add(&vm_page_purgeable_count, -(int64_t)delta); } vm_page_free(m); #if MACH_ASSERT || DEBUG vm_object_unlock(m_object); #endif /* MACH_ASSERT || DEBUG */ } /* * Grab locks for hibernate_page_list_setall() */ void hibernate_vm_lock_queues(void) { vm_object_lock(compressor_object); vm_page_lock_queues(); vm_free_page_lock(); lck_mtx_lock(&vm_purgeable_queue_lock); if (vm_page_local_q) { zpercpu_foreach(lq, vm_page_local_q) { VPL_LOCK(&lq->vpl_lock); } } } void hibernate_vm_unlock_queues(void) { if (vm_page_local_q) { zpercpu_foreach(lq, vm_page_local_q) { VPL_UNLOCK(&lq->vpl_lock); } } lck_mtx_unlock(&vm_purgeable_queue_lock); vm_free_page_unlock(); vm_page_unlock_queues(); vm_object_unlock(compressor_object); } #if CONFIG_SPTM static bool hibernate_sptm_should_force_page_to_wired_pagelist(vm_page_t vmp) { const sptm_paddr_t paddr = ptoa_64(VM_PAGE_GET_PHYS_PAGE(vmp)); const sptm_frame_type_t frame_type = sptm_get_frame_type(paddr); const vm_object_t vmp_objp = VM_PAGE_OBJECT(vmp); return frame_type == XNU_USER_JIT || frame_type == XNU_USER_DEBUG || (frame_type == XNU_USER_EXEC && vmp_objp->internal == TRUE); } #endif /* * Bits zero in the bitmaps => page needs to be saved. All pages default to be saved, * pages known to VM to not need saving are subtracted. * Wired pages to be saved are present in page_list_wired, pageable in page_list. */ void hibernate_page_list_setall(hibernate_page_list_t * page_list, hibernate_page_list_t * page_list_wired, hibernate_page_list_t * page_list_pal, boolean_t preflight, boolean_t will_discard, uint32_t * pagesOut) { uint64_t start, end, nsec; vm_page_t m; vm_page_t next; __block uint32_t pages = page_list->page_count; __block uint32_t count_wire = pages; uint32_t count_anonymous = 0, count_throttled = 0, count_compressor = 0; uint32_t count_inactive = 0, count_active = 0, count_speculative = 0, count_cleaned = 0; uint32_t count_discard_active = 0; uint32_t count_discard_inactive = 0; uint32_t count_retired = 0; uint32_t count_discard_cleaned = 0; uint32_t count_discard_purgeable = 0; uint32_t count_discard_speculative = 0; uint32_t count_discard_vm_struct_pages = 0; uint32_t bank; hibernate_bitmap_t * bitmap; hibernate_bitmap_t * bitmap_wired; boolean_t discard_all; boolean_t discard = FALSE; HIBLOG("hibernate_page_list_setall(preflight %d) start\n", preflight); if (preflight) { page_list = NULL; page_list_wired = NULL; page_list_pal = NULL; discard_all = FALSE; } else { discard_all = will_discard; } #if MACH_ASSERT || DEBUG if (!preflight) { assert(hibernate_vm_locks_are_safe()); vm_page_lock_queues(); if (vm_page_local_q) { zpercpu_foreach(lq, vm_page_local_q) { VPL_LOCK(&lq->vpl_lock); } } } #endif /* MACH_ASSERT || DEBUG */ KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 8) | DBG_FUNC_START, count_wire, 0, 0, 0, 0); clock_get_uptime(&start); if (!preflight) { hibernate_page_list_zero(page_list); hibernate_page_list_zero(page_list_wired); hibernate_page_list_zero(page_list_pal); hibernate_stats.cd_vm_page_wire_count = vm_page_wire_count; hibernate_stats.cd_pages = pages; } if (vm_page_local_q) { zpercpu_foreach_cpu(lid) { vm_page_reactivate_local(lid, TRUE, !preflight); } } if (preflight) { vm_object_lock(compressor_object); vm_page_lock_queues(); vm_free_page_lock(); } LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); hibernation_vmqueues_inspection = TRUE; __auto_type hib_free_boilerplate = ^(vm_page_t page) { assert((page->vmp_q_state == VM_PAGE_ON_FREE_Q) || #if XNU_VM_HAS_LOPAGE (page->vmp_q_state == VM_PAGE_ON_FREE_LOPAGE_Q) || #endif /* XNU_VM_HAS_LOPAGE */ (page->vmp_q_state == VM_PAGE_ON_FREE_LOCAL_Q)); pages--; count_wire--; if (!preflight) { hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(page)); hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(page)); hibernate_stats.cd_total_free++; if (page->vmp_q_state == VM_PAGE_ON_FREE_LOCAL_Q) { hibernate_stats.cd_local_free++; } } }; if (!preflight) { percpu_foreach(vmp_pcpu, vm_page_pcpu) { _vm_page_list_foreach(m, vmp_pcpu->free_pages) { assert(m->vmp_q_state == VM_PAGE_ON_FREE_LOCAL_Q); hib_free_boilerplate(m); } #if HAS_MTE _vm_page_list_foreach(m, vmp_pcpu->free_tagged_pages) { assert(m->vmp_q_state == VM_PAGE_ON_FREE_LOCAL_Q); hib_free_boilerplate(m); } vm_page_queue_iterate(&vmp_pcpu->free_claimed_pages, m, vmp_pageq) { assert(m->vmp_q_state == VM_PAGE_ON_FREE_LOCAL_Q); hib_free_boilerplate(m); } #endif /* HAS_MTE */ } } #if CONFIG_SPTM if (vm_pages_free_masks()) { uint32_t bits = vm_pages_free_mask_len() * MAX_COLORS; bitmap_t *map = vm_pages_free_masks_as_bitmap(0); for (int bit = bitmap_first(map, bits); bit >= 0; bit = bitmap_next(map, bit)) { ppnum_t pnum = pmap_first_pnum + bit; vm_page_t mem = vm_page_find_canonical(pnum); hib_free_boilerplate(mem); } } else #endif /* CONFIG_SPTM */ { vm_page_free_queue_foreach(&vm_page_queue_free, hib_free_boilerplate); } #if HAS_MTE mteinfo_free_queue_foreach(hib_free_boilerplate); #endif /* HAS_MTE */ #if XNU_VM_HAS_LOPAGE vm_page_free_queue_foreach(&vm_lopage_queue_free, hib_free_boilerplate); #endif /* XNU_VM_HAS_LOPAGE */ m = (vm_page_t) vm_page_queue_first(&vm_page_queue_throttled); while (m && !vm_page_queue_end(&vm_page_queue_throttled, (vm_page_queue_entry_t)m)) { assert(m->vmp_q_state == VM_PAGE_ON_THROTTLED_Q); next = (vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.next); discard = FALSE; if ((kIOHibernateModeDiscardCleanInactive & gIOHibernateMode) && hibernate_consider_discard(m, preflight)) { if (!preflight) { hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } count_discard_inactive++; discard = discard_all; } else { count_throttled++; } count_wire--; if (!preflight) { hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } if (discard) { hibernate_discard_page(m); } m = next; } m = (vm_page_t)vm_page_queue_first(&vm_page_queue_anonymous); while (m && !vm_page_queue_end(&vm_page_queue_anonymous, (vm_page_queue_entry_t)m)) { assert(m->vmp_q_state == VM_PAGE_ON_INACTIVE_INTERNAL_Q); bool force_to_wired_list = false; /* Default to NOT forcing page into the wired page list */ #if CONFIG_SPTM force_to_wired_list = hibernate_sptm_should_force_page_to_wired_pagelist(m); #endif next = (vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.next); discard = FALSE; if ((kIOHibernateModeDiscardCleanInactive & gIOHibernateMode) && hibernate_consider_discard(m, preflight)) { if (!preflight) { hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } if (m->vmp_dirty) { count_discard_purgeable++; } else { count_discard_inactive++; } discard = discard_all; } else { /* * If the page must be force-added to the wired page list, prevent it from appearing * in the unwired page list. */ if (force_to_wired_list) { if (!preflight) { hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } } else { count_anonymous++; } } /* * If the page is NOT being forced into the wired page list, remove it from the * wired page list here. */ if (!force_to_wired_list) { count_wire--; if (!preflight) { hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } } if (discard) { hibernate_discard_page(m); } m = next; } m = (vm_page_t) vm_page_queue_first(&vm_page_queue_cleaned); while (m && !vm_page_queue_end(&vm_page_queue_cleaned, (vm_page_queue_entry_t)m)) { assert(m->vmp_q_state == VM_PAGE_ON_INACTIVE_CLEANED_Q); next = (vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.next); discard = FALSE; if ((kIOHibernateModeDiscardCleanInactive & gIOHibernateMode) && hibernate_consider_discard(m, preflight)) { if (!preflight) { hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } if (m->vmp_dirty) { count_discard_purgeable++; } else { count_discard_cleaned++; } discard = discard_all; } else { count_cleaned++; } count_wire--; if (!preflight) { hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } if (discard) { hibernate_discard_page(m); } m = next; } m = (vm_page_t) vm_page_queue_first(&vm_page_queue_active); while (m && !vm_page_queue_end(&vm_page_queue_active, (vm_page_queue_entry_t)m)) { assert(m->vmp_q_state == VM_PAGE_ON_ACTIVE_Q); bool force_to_wired_list = false; /* Default to NOT forcing page into the wired page list */ #if CONFIG_SPTM force_to_wired_list = hibernate_sptm_should_force_page_to_wired_pagelist(m); #endif next = (vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.next); discard = FALSE; if ((kIOHibernateModeDiscardCleanActive & gIOHibernateMode) && hibernate_consider_discard(m, preflight)) { if (!preflight) { hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } if (m->vmp_dirty) { count_discard_purgeable++; } else { count_discard_active++; } discard = discard_all; } else { /* * If the page must be force-added to the wired page list, prevent it from appearing * in the unwired page list. */ if (force_to_wired_list) { if (!preflight) { hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } } else { count_active++; } } /* * If the page is NOT being forced into the wired page list, remove it from the * wired page list here. */ if (!force_to_wired_list) { count_wire--; if (!preflight) { hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } } if (discard) { hibernate_discard_page(m); } m = next; } m = (vm_page_t) vm_page_queue_first(&vm_page_queue_inactive); while (m && !vm_page_queue_end(&vm_page_queue_inactive, (vm_page_queue_entry_t)m)) { assert(m->vmp_q_state == VM_PAGE_ON_INACTIVE_EXTERNAL_Q); bool force_to_wired_list = false; /* Default to NOT forcing page into the wired page list */ #if CONFIG_SPTM force_to_wired_list = hibernate_sptm_should_force_page_to_wired_pagelist(m); #endif next = (vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.next); discard = FALSE; if ((kIOHibernateModeDiscardCleanInactive & gIOHibernateMode) && hibernate_consider_discard(m, preflight)) { if (!preflight) { hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } if (m->vmp_dirty) { count_discard_purgeable++; } else { count_discard_inactive++; } discard = discard_all; } else { /* * If the page must be force-added to the wired page list, prevent it from appearing * in the unwired page list. */ if (force_to_wired_list) { if (!preflight) { hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } } else { count_inactive++; } } /* * If the page is NOT being forced into the wired page list, remove it from the * wired page list here. */ if (!force_to_wired_list) { count_wire--; if (!preflight) { hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } } if (discard) { hibernate_discard_page(m); } m = next; } /* XXX FBDP TODO: secluded queue */ for (uint32_t i = 0; i <= vm_page_max_speculative_age_q; i++) { m = (vm_page_t) vm_page_queue_first(&vm_page_queue_speculative[i].age_q); while (m && !vm_page_queue_end(&vm_page_queue_speculative[i].age_q, (vm_page_queue_entry_t)m)) { assertf(m->vmp_q_state == VM_PAGE_ON_SPECULATIVE_Q, "Bad page: %p (0x%x:0x%x) on queue %d has state: %d (Discard: %d, Preflight: %d)", m, m->vmp_pageq.next, m->vmp_pageq.prev, i, m->vmp_q_state, discard, preflight); next = (vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.next); discard = FALSE; if ((kIOHibernateModeDiscardCleanInactive & gIOHibernateMode) && hibernate_consider_discard(m, preflight)) { if (!preflight) { hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } count_discard_speculative++; discard = discard_all; } else { count_speculative++; } count_wire--; if (!preflight) { hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } if (discard) { hibernate_discard_page(m); } m = next; } } vm_page_queue_iterate(&compressor_object->memq, m, vmp_listq) { assert(m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR); count_compressor++; count_wire--; if (!preflight) { hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m)); } } if (preflight == FALSE && discard_all == TRUE) { KDBG(IOKDBG_CODE(DBG_HIBERNATE, 12) | DBG_FUNC_START); HIBLOG("hibernate_teardown started\n"); count_discard_vm_struct_pages = hibernate_teardown_vm_structs(page_list, page_list_wired); HIBLOG("hibernate_teardown completed - discarded %d\n", count_discard_vm_struct_pages); pages -= count_discard_vm_struct_pages; count_wire -= count_discard_vm_struct_pages; hibernate_stats.cd_vm_struct_pages_unneeded = count_discard_vm_struct_pages; KDBG(IOKDBG_CODE(DBG_HIBERNATE, 12) | DBG_FUNC_END); } if (!preflight) { // pull wired from hibernate_bitmap bitmap = &page_list->bank_bitmap[0]; bitmap_wired = &page_list_wired->bank_bitmap[0]; for (bank = 0; bank < page_list->bank_count; bank++) { for (uint32_t i = 0; i < bitmap->bitmapwords; i++) { bitmap->bitmap[i] = bitmap->bitmap[i] | ~bitmap_wired->bitmap[i]; } bitmap = (hibernate_bitmap_t *)&bitmap->bitmap[bitmap->bitmapwords]; bitmap_wired = (hibernate_bitmap_t *) &bitmap_wired->bitmap[bitmap_wired->bitmapwords]; } } // machine dependent adjustments hibernate_page_list_setall_machine(page_list, page_list_wired, preflight, &pages); if (!preflight) { hibernate_stats.cd_count_wire = count_wire; hibernate_stats.cd_discarded = count_discard_active + count_discard_inactive + count_discard_purgeable + count_discard_speculative + count_discard_cleaned + count_discard_vm_struct_pages; } clock_get_uptime(&end); absolutetime_to_nanoseconds(end - start, &nsec); HIBLOG("hibernate_page_list_setall time: %qd ms\n", nsec / 1000000ULL); HIBLOG("pages %d, wire %d, act %d, inact %d, cleaned %d spec %d, " "zf %d, throt %d, compr %d, xpmapped %d\n" " %s discard act %d inact %d purgeable %d " "spec %d cleaned %d retired %d\n", pages, count_wire, count_active, count_inactive, count_cleaned, count_speculative, count_anonymous, count_throttled, count_compressor, hibernate_stats.cd_found_xpmapped, discard_all ? "did" : "could", count_discard_active, count_discard_inactive, count_discard_purgeable, count_discard_speculative, count_discard_cleaned, count_retired); if (hibernate_stats.cd_skipped_xpmapped) { HIBLOG("WARNING: hibernate_page_list_setall skipped %d xpmapped pages\n", hibernate_stats.cd_skipped_xpmapped); } *pagesOut = pages - count_discard_active - count_discard_inactive - count_discard_purgeable - count_discard_speculative - count_discard_cleaned - count_retired; if (preflight && will_discard) { *pagesOut -= count_compressor + count_throttled + count_anonymous + count_inactive + count_cleaned + count_speculative + count_active; /* * We try to keep max HIBERNATE_XPMAPPED_LIMIT pages around in the hibernation image * even if these are clean and so we need to size the hibernation image accordingly. * * NB: We have to assume all HIBERNATE_XPMAPPED_LIMIT pages might show up because 'dirty' * xpmapped pages aren't distinguishable from other 'dirty' pages in preflight. So we might * only see part of the xpmapped pages if we look at 'cd_found_xpmapped' which solely tracks * clean xpmapped pages. * * Since these pages are all cleaned by the time we are in the post-preflight phase, we might * see a much larger number in 'cd_found_xpmapped' now than we did in the preflight phase */ *pagesOut += HIBERNATE_XPMAPPED_LIMIT; } hibernation_vmqueues_inspection = FALSE; #if MACH_ASSERT || DEBUG if (!preflight) { if (vm_page_local_q) { zpercpu_foreach(lq, vm_page_local_q) { VPL_UNLOCK(&lq->vpl_lock); } } vm_page_unlock_queues(); } #endif /* MACH_ASSERT || DEBUG */ if (preflight) { vm_free_page_unlock(); vm_page_unlock_queues(); vm_object_unlock(compressor_object); } KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 8) | DBG_FUNC_END, count_wire, *pagesOut, 0, 0, 0); } void hibernate_page_list_discard(hibernate_page_list_t * page_list) { uint64_t start, end, nsec; vm_page_t m; vm_page_t next; uint32_t i; uint32_t count_discard_active = 0; uint32_t count_discard_inactive = 0; uint32_t count_discard_purgeable = 0; uint32_t count_discard_cleaned = 0; uint32_t count_discard_speculative = 0; #if MACH_ASSERT || DEBUG vm_page_lock_queues(); if (vm_page_local_q) { zpercpu_foreach(lq, vm_page_local_q) { VPL_LOCK(&lq->vpl_lock); } } #endif /* MACH_ASSERT || DEBUG */ clock_get_uptime(&start); m = (vm_page_t) vm_page_queue_first(&vm_page_queue_anonymous); while (m && !vm_page_queue_end(&vm_page_queue_anonymous, (vm_page_queue_entry_t)m)) { assert(m->vmp_q_state == VM_PAGE_ON_INACTIVE_INTERNAL_Q); next = (vm_page_t) VM_PAGE_UNPACK_PTR(m->vmp_pageq.next); if (hibernate_page_bittst(page_list, VM_PAGE_GET_PHYS_PAGE(m))) { if (m->vmp_dirty) { count_discard_purgeable++; } else { count_discard_inactive++; } hibernate_discard_page(m); } m = next; } for (i = 0; i <= vm_page_max_speculative_age_q; i++) { m = (vm_page_t) vm_page_queue_first(&vm_page_queue_speculative[i].age_q); while (m && !vm_page_queue_end(&vm_page_queue_speculative[i].age_q, (vm_page_queue_entry_t)m)) { assert(m->vmp_q_state == VM_PAGE_ON_SPECULATIVE_Q); next = (vm_page_t) VM_PAGE_UNPACK_PTR(m->vmp_pageq.next); if (hibernate_page_bittst(page_list, VM_PAGE_GET_PHYS_PAGE(m))) { count_discard_speculative++; hibernate_discard_page(m); } m = next; } } m = (vm_page_t) vm_page_queue_first(&vm_page_queue_inactive); while (m && !vm_page_queue_end(&vm_page_queue_inactive, (vm_page_queue_entry_t)m)) { assert(m->vmp_q_state == VM_PAGE_ON_INACTIVE_EXTERNAL_Q); next = (vm_page_t) VM_PAGE_UNPACK_PTR(m->vmp_pageq.next); if (hibernate_page_bittst(page_list, VM_PAGE_GET_PHYS_PAGE(m))) { if (m->vmp_dirty) { count_discard_purgeable++; } else { count_discard_inactive++; } hibernate_discard_page(m); } m = next; } /* XXX FBDP TODO: secluded queue */ m = (vm_page_t) vm_page_queue_first(&vm_page_queue_active); while (m && !vm_page_queue_end(&vm_page_queue_active, (vm_page_queue_entry_t)m)) { assert(m->vmp_q_state == VM_PAGE_ON_ACTIVE_Q); next = (vm_page_t) VM_PAGE_UNPACK_PTR(m->vmp_pageq.next); if (hibernate_page_bittst(page_list, VM_PAGE_GET_PHYS_PAGE(m))) { if (m->vmp_dirty) { count_discard_purgeable++; } else { count_discard_active++; } hibernate_discard_page(m); } m = next; } m = (vm_page_t) vm_page_queue_first(&vm_page_queue_cleaned); while (m && !vm_page_queue_end(&vm_page_queue_cleaned, (vm_page_queue_entry_t)m)) { assert(m->vmp_q_state == VM_PAGE_ON_INACTIVE_CLEANED_Q); next = (vm_page_t) VM_PAGE_UNPACK_PTR(m->vmp_pageq.next); if (hibernate_page_bittst(page_list, VM_PAGE_GET_PHYS_PAGE(m))) { if (m->vmp_dirty) { count_discard_purgeable++; } else { count_discard_cleaned++; } hibernate_discard_page(m); } m = next; } #if MACH_ASSERT || DEBUG if (vm_page_local_q) { zpercpu_foreach(lq, vm_page_local_q) { VPL_UNLOCK(&lq->vpl_lock); } } vm_page_unlock_queues(); #endif /* MACH_ASSERT || DEBUG */ clock_get_uptime(&end); absolutetime_to_nanoseconds(end - start, &nsec); HIBLOG("hibernate_page_list_discard time: %qd ms, discarded act %d inact %d purgeable %d spec %d cleaned %d\n", nsec / 1000000ULL, count_discard_active, count_discard_inactive, count_discard_purgeable, count_discard_speculative, count_discard_cleaned); } boolean_t hibernate_paddr_map_inited = FALSE; unsigned int hibernate_teardown_last_valid_compact_indx = -1; vm_page_t hibernate_rebuild_hash_list = NULL; unsigned int hibernate_teardown_found_tabled_pages = 0; unsigned int hibernate_teardown_found_created_pages = 0; unsigned int hibernate_teardown_found_free_pages = 0; unsigned int hibernate_teardown_vm_page_free_count; struct ppnum_mapping { struct ppnum_mapping *ppnm_next; ppnum_t ppnm_base_paddr; unsigned int ppnm_sindx; unsigned int ppnm_eindx; }; struct ppnum_mapping *ppnm_head; struct ppnum_mapping *ppnm_last_found = NULL; void hibernate_create_paddr_map(void) { unsigned int i; ppnum_t next_ppnum_in_run = 0; struct ppnum_mapping *ppnm = NULL; if (hibernate_paddr_map_inited == FALSE) { for (i = 0; i < vm_pages_count; i++) { if (ppnm) { ppnm->ppnm_eindx = i; } if (ppnm == NULL || VM_PAGE_GET_PHYS_PAGE(vm_page_get(i)) != next_ppnum_in_run) { ppnm = zalloc_permanent_type(struct ppnum_mapping); ppnm->ppnm_next = ppnm_head; ppnm_head = ppnm; ppnm->ppnm_sindx = i; ppnm->ppnm_base_paddr = VM_PAGE_GET_PHYS_PAGE(vm_page_get(i)); } next_ppnum_in_run = VM_PAGE_GET_PHYS_PAGE(vm_page_get(i)) + 1; } ppnm->ppnm_eindx = vm_pages_count; hibernate_paddr_map_inited = TRUE; } } static ppnum_t hibernate_lookup_paddr(unsigned int indx) { struct ppnum_mapping *ppnm = NULL; ppnm = ppnm_last_found; if (ppnm) { if (indx >= ppnm->ppnm_sindx && indx < ppnm->ppnm_eindx) { goto done; } } for (ppnm = ppnm_head; ppnm; ppnm = ppnm->ppnm_next) { if (indx >= ppnm->ppnm_sindx && indx < ppnm->ppnm_eindx) { ppnm_last_found = ppnm; break; } } if (ppnm == NULL) { panic("hibernate_lookup_paddr of %d failed", indx); } done: return ppnm->ppnm_base_paddr + (indx - ppnm->ppnm_sindx); } static uint32_t hibernate_mark_as_unneeded(addr64_t saddr, addr64_t eaddr, hibernate_page_list_t *page_list, hibernate_page_list_t *page_list_wired) { addr64_t saddr_aligned; addr64_t eaddr_aligned; addr64_t addr; ppnum_t paddr; unsigned int mark_as_unneeded_pages = 0; saddr_aligned = (saddr + PAGE_MASK_64) & ~PAGE_MASK_64; eaddr_aligned = eaddr & ~PAGE_MASK_64; for (addr = saddr_aligned; addr < eaddr_aligned; addr += PAGE_SIZE_64) { paddr = pmap_find_phys(kernel_pmap, addr); assert(paddr); hibernate_page_bitset(page_list, TRUE, paddr); hibernate_page_bitset(page_list_wired, TRUE, paddr); mark_as_unneeded_pages++; } return mark_as_unneeded_pages; } static void hibernate_hash_insert_page(vm_page_t mem) { uint32_t hash_id; vm_object_t m_object; m_object = VM_PAGE_OBJECT(mem); assert(mem->vmp_hashed); assert(m_object); assert(mem->vmp_offset != (vm_object_offset_t) -1); /* * Insert it into the object_object/offset hash table */ hash_id = vm_page_hash(m_object, mem->vmp_offset); vm_page_hash_insert_locked(&vm_page_buckets[hash_id], mem); } static void hibernate_free_range_flush(vm_page_list_t *list) { vm_page_free_queue_enter_list(*list, VMP_RELEASE_HIBERNATE); *list = (vm_page_list_t){ }; } static void hibernate_free_range(vm_page_list_t *list, int sindx, int eindx) { for (; sindx < eindx; sindx++) { vm_page_t mem = vm_page_get(sindx); ppnum_t pnum = hibernate_lookup_paddr(sindx); vm_page_init(mem, pnum); #if HAS_MTE mem->vmp_using_mte = pmap_is_tagged_page(pnum); #endif /* HAS_MTE */ vm_page_list_push(list, mem); /* Max batch size of these lists is 255 due to vmp_free_list_result_t */ if (list->vmpl_count >= UINT8_MAX) { hibernate_free_range_flush(list); } } } void hibernate_rebuild_vm_structs(void) { int cindx, sindx, eindx; vm_page_list_t list = { }; vm_page_t mem, tmem, mem_next; AbsoluteTime startTime, endTime; uint64_t nsec; if (!hibernate_rebuild_needed) { return; } KDBG(IOKDBG_CODE(DBG_HIBERNATE, 13) | DBG_FUNC_START); HIBLOG("hibernate_rebuild started\n"); clock_get_uptime(&startTime); pal_hib_rebuild_pmap_structs(); bzero(&vm_page_buckets[0], vm_page_bucket_count * sizeof(vm_page_bucket_t)); eindx = vm_pages_count; /* * Mark all the vm_pages[] that have not been initialized yet as being * transient. This is needed to ensure that buddy page search is corrrect. * Without this random data in these vm_pages[] can trip the buddy search */ for (int i = hibernate_teardown_last_valid_compact_indx + 1; i < eindx; ++i) { vm_page_get(i)->vmp_q_state = VM_PAGE_NOT_ON_Q; } for (cindx = hibernate_teardown_last_valid_compact_indx; cindx >= 0; cindx--) { mem = vm_page_get(cindx); assert(mem->vmp_q_state != VM_PAGE_ON_FREE_Q); /* * hibernate_teardown_vm_structs leaves the location where * this vm_page_t must be located in "next". */ tmem = (vm_page_t)(VM_PAGE_UNPACK_PTR(mem->vmp_next_m)); mem->vmp_next_m = VM_PAGE_PACK_PTR(NULL); assert(tmem >= mem); sindx = (int)(tmem - vm_page_get(0)); if (mem != tmem) { /* * this vm_page_t was moved by hibernate_teardown_vm_structs, * so move it back to its real location */ *tmem = *mem; mem = tmem; } if (mem->vmp_hashed) { hibernate_hash_insert_page(mem); } /* * the 'hole' between this vm_page_t and the previous * vm_page_t we moved needs to be initialized as * a range of free vm_page_t's */ hibernate_free_range(&list, sindx + 1, eindx); eindx = sindx; } hibernate_free_range(&list, 0, sindx); hibernate_free_range_flush(&list); VM_CHECK_MEMORYSTATUS; assert(vm_page_free_count == hibernate_teardown_vm_page_free_count); /* * process the list of vm_page_t's that were entered in the hash, * but were not located in the vm_pages arrary... these are * vm_page_t's that were created on the fly (i.e. fictitious) */ for (mem = hibernate_rebuild_hash_list; mem; mem = mem_next) { mem_next = (vm_page_t)(VM_PAGE_UNPACK_PTR(mem->vmp_next_m)); mem->vmp_next_m = 0; hibernate_hash_insert_page(mem); } hibernate_rebuild_hash_list = NULL; clock_get_uptime(&endTime); SUB_ABSOLUTETIME(&endTime, &startTime); absolutetime_to_nanoseconds(endTime, &nsec); HIBLOG("hibernate_rebuild completed - took %qd msecs\n", nsec / 1000000ULL); hibernate_rebuild_needed = false; KDBG(IOKDBG_CODE(DBG_HIBERNATE, 13) | DBG_FUNC_END); } static uint32_t hibernate_teardown_vm_structs(hibernate_page_list_t *page_list, hibernate_page_list_t *page_list_wired) { unsigned int compact_target_indx; unsigned int mark_as_unneeded_pages = 0; unsigned int unneeded_vm_page_bucket_pages = 0; unsigned int unneeded_vm_pages_pages = 0; unsigned int unneeded_pmap_pages = 0; addr64_t start_of_unneeded = 0; addr64_t end_of_unneeded = 0; if (hibernate_should_abort()) { return 0; } hibernate_rebuild_needed = true; HIBLOG("hibernate_teardown: wired_pages %d, free_pages %d, " "active_pages %d, inactive_pages %d, speculative_pages %d, " "cleaned_pages %d, compressor_pages %d\n", vm_page_wire_count, vm_page_free_count, vm_page_active_count, vm_page_inactive_count, vm_page_speculative_count, vm_page_cleaned_count, compressor_object->resident_page_count); for (uint32_t i = 0; i < vm_page_bucket_count; i++) { vm_page_bucket_t *bucket = &vm_page_buckets[i]; vm_page_t mem, mem_next; for (mem = (vm_page_t)(VM_PAGE_UNPACK_PTR(bucket->page_list)); mem != VM_PAGE_NULL; mem = mem_next) { assert(mem->vmp_hashed); mem_next = (vm_page_t)(VM_PAGE_UNPACK_PTR(mem->vmp_next_m)); if (!vm_page_in_array(mem)) { mem->vmp_next_m = VM_PAGE_PACK_PTR(hibernate_rebuild_hash_list); hibernate_rebuild_hash_list = mem; } } } unneeded_vm_page_bucket_pages = hibernate_mark_as_unneeded((addr64_t)&vm_page_buckets[0], (addr64_t)&vm_page_buckets[vm_page_bucket_count], page_list, page_list_wired); mark_as_unneeded_pages += unneeded_vm_page_bucket_pages; hibernate_teardown_vm_page_free_count = vm_page_free_count; compact_target_indx = 0; vm_free_page_lock(); for (uint32_t i = 0; i < vm_pages_count; i++) { vm_page_t mem = vm_page_get(i); ppnum_t pnum = VM_PAGE_GET_PHYS_PAGE(mem); vm_memory_class_t class = vm_page_get_memory_class(mem, pnum); if (mem->vmp_q_state == VM_PAGE_ON_FREE_Q) { vm_page_free_queue_remove(class, mem, pnum, VM_PAGE_ON_FREE_Q); hibernate_teardown_found_free_pages++; if (vm_page_get(compact_target_indx)->vmp_q_state != VM_PAGE_ON_FREE_Q) { compact_target_indx = i; } } else { /* * record this vm_page_t's original location * we need this even if it doesn't get moved * as an indicator to the rebuild function that * we don't have to move it */ mem->vmp_next_m = VM_PAGE_PACK_PTR(mem); if (vm_page_get(compact_target_indx)->vmp_q_state == VM_PAGE_ON_FREE_Q) { /* * we've got a hole to fill, so * move this vm_page_t to it's new home */ *vm_page_get(compact_target_indx) = *mem; mem->vmp_q_state = VM_PAGE_ON_FREE_Q; hibernate_teardown_last_valid_compact_indx = compact_target_indx; compact_target_indx++; } else { hibernate_teardown_last_valid_compact_indx = i; } } } vm_free_page_unlock(); unneeded_vm_pages_pages = hibernate_mark_as_unneeded( (addr64_t)vm_page_get(hibernate_teardown_last_valid_compact_indx + 1), (addr64_t)vm_page_get(vm_pages_count - 1), page_list, page_list_wired); mark_as_unneeded_pages += unneeded_vm_pages_pages; pal_hib_teardown_pmap_structs(&start_of_unneeded, &end_of_unneeded); if (start_of_unneeded) { unneeded_pmap_pages = hibernate_mark_as_unneeded(start_of_unneeded, end_of_unneeded, page_list, page_list_wired); mark_as_unneeded_pages += unneeded_pmap_pages; } HIBLOG("hibernate_teardown: mark_as_unneeded_pages %d, %d, %d\n", unneeded_vm_page_bucket_pages, unneeded_vm_pages_pages, unneeded_pmap_pages); return mark_as_unneeded_pages; } #endif /* HIBERNATION */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #if VM_PAGE_BUCKETS_CHECK void vm_page_buckets_check(void) { unsigned int i; vm_page_t p; unsigned int p_hash; vm_page_bucket_t *bucket; hw_lck_ticket_t *bucket_lock; if (!vm_page_buckets_check_ready) { return; } #if HIBERNATION if (hibernate_rebuild_needed || hibernate_rebuild_hash_list) { panic("BUCKET_CHECK: hibernation in progress: " "rebuild_needed=%d rebuild_hash_list=%p\n", hibernate_rebuild_needed, hibernate_rebuild_hash_list); } #endif /* HIBERNATION */ #if VM_PAGE_FAKE_BUCKETS char *cp; for (cp = (char *) vm_page_fake_buckets_start; cp < (char *) vm_page_fake_buckets_end; cp++) { if (*cp != 0x5a) { panic("BUCKET_CHECK: corruption at %p in fake buckets " "[0x%llx:0x%llx]\n", cp, (uint64_t) vm_page_fake_buckets_start, (uint64_t) vm_page_fake_buckets_end); } } #endif /* VM_PAGE_FAKE_BUCKETS */ for (i = 0; i < vm_page_bucket_count; i++) { vm_object_t p_object; bucket = &vm_page_buckets[i]; if (!bucket->page_list) { continue; } bucket_lock = &vm_page_bucket_locks[i / BUCKETS_PER_LOCK]; hw_lck_ticket_lock(bucket_lock, &vm_page_lck_grp_bucket); p = (vm_page_t)(VM_PAGE_UNPACK_PTR(bucket->page_list)); while (p != VM_PAGE_NULL) { p_object = VM_PAGE_OBJECT(p); if (!p->vmp_hashed) { panic("BUCKET_CHECK: page %p (%p,0x%llx) " "hash %d in bucket %d at %p " "is not hashed\n", p, p_object, p->vmp_offset, p_hash, i, bucket); } p_hash = vm_page_hash(p_object, p->vmp_offset); if (p_hash != i) { panic("BUCKET_CHECK: corruption in bucket %d " "at %p: page %p object %p offset 0x%llx " "hash %d\n", i, bucket, p, p_object, p->vmp_offset, p_hash); } p = (vm_page_t)(VM_PAGE_UNPACK_PTR(p->vmp_next_m)); } hw_lck_ticket_unlock(bucket_lock); } // printf("BUCKET_CHECK: checked buckets\n"); } #endif /* VM_PAGE_BUCKETS_CHECK */ /* * 'vm_fault_enter' will place newly created pages (zero-fill and COW) onto the * local queues if they exist... its the only spot in the system where we add pages * to those queues... once on those queues, those pages can only move to one of the * global page queues or the free queues... they NEVER move from local q to local q. * the 'local' state is stable when vm_page_queues_remove is called since we're behind * the global vm_page_queue_lock at this point... we still need to take the local lock * in case this operation is being run on a different CPU then the local queue's identity, * but we don't have to worry about the page moving to a global queue or becoming wired * while we're grabbing the local lock since those operations would require the global * vm_page_queue_lock to be held, and we already own it. * * this is why its safe to utilze the wire_count field in the vm_page_t as the local_id... * 'wired' and local are ALWAYS mutually exclusive conditions. */ void vm_page_queues_remove(vm_page_t mem, boolean_t remove_from_specialq) { boolean_t was_pageable = TRUE; vm_object_t m_object; m_object = VM_PAGE_OBJECT(mem); LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); if (mem->vmp_q_state == VM_PAGE_NOT_ON_Q) { assert(mem->vmp_pageq.next == 0 && mem->vmp_pageq.prev == 0); if (remove_from_specialq == TRUE) { vm_page_remove_from_specialq(mem); } /*if (mem->vmp_on_specialq != VM_PAGE_SPECIAL_Q_EMPTY) { * assert(mem->vmp_specialq.next != 0); * assert(mem->vmp_specialq.prev != 0); * } else {*/ if (mem->vmp_on_specialq == VM_PAGE_SPECIAL_Q_EMPTY) { assert(mem->vmp_specialq.next == 0); assert(mem->vmp_specialq.prev == 0); } return; } if (mem->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) { assert(mem->vmp_pageq.next == 0 && mem->vmp_pageq.prev == 0); assert(mem->vmp_specialq.next == 0 && mem->vmp_specialq.prev == 0 && mem->vmp_on_specialq == VM_PAGE_SPECIAL_Q_EMPTY); return; } if (VM_PAGE_WIRED(mem)) { /* * might put these guys on a list for debugging purposes * if we do, we'll need to remove this assert */ assert(mem->vmp_pageq.next == 0 && mem->vmp_pageq.prev == 0); assert(mem->vmp_specialq.next == 0 && mem->vmp_specialq.prev == 0); /* * Recall that vmp_on_specialq also means a request to put * it on the special Q. So we don't want to reset that bit * just because a wiring request came in. We might want to * put it on the special queue post-unwiring. * * && * mem->vmp_on_specialq == VM_PAGE_SPECIAL_Q_EMPTY); */ return; } assert(m_object != compressor_object); assert(!is_kernel_object(m_object)); assert(!vm_page_is_fictitious(mem)); switch (mem->vmp_q_state) { case VM_PAGE_ON_ACTIVE_LOCAL_Q: { struct vpl *lq; lq = zpercpu_get_cpu(vm_page_local_q, mem->vmp_local_id); VPL_LOCK(&lq->vpl_lock); vm_page_queue_remove(&lq->vpl_queue, mem, vmp_pageq); mem->vmp_local_id = 0; lq->vpl_count--; if (m_object->internal) { lq->vpl_internal_count--; } else { lq->vpl_external_count--; } VPL_UNLOCK(&lq->vpl_lock); was_pageable = FALSE; break; } case VM_PAGE_ON_ACTIVE_Q: { vm_page_queue_remove(&vm_page_queue_active, mem, vmp_pageq); vm_page_active_count--; break; } case VM_PAGE_ON_INACTIVE_INTERNAL_Q: { assert(m_object->internal == TRUE); vm_page_inactive_count--; vm_page_queue_remove(&vm_page_queue_anonymous, mem, vmp_pageq); vm_page_anonymous_count--; vm_purgeable_q_advance_all(); vm_page_balance_inactive(3); break; } case VM_PAGE_ON_INACTIVE_EXTERNAL_Q: { assert(m_object->internal == FALSE); vm_page_inactive_count--; vm_page_queue_remove(&vm_page_queue_inactive, mem, vmp_pageq); vm_purgeable_q_advance_all(); vm_page_balance_inactive(3); break; } case VM_PAGE_ON_INACTIVE_CLEANED_Q: { assert(m_object->internal == FALSE); vm_page_inactive_count--; vm_page_queue_remove(&vm_page_queue_cleaned, mem, vmp_pageq); vm_page_cleaned_count--; vm_page_balance_inactive(3); break; } case VM_PAGE_ON_THROTTLED_Q: { assert(m_object->internal == TRUE); vm_page_queue_remove(&vm_page_queue_throttled, mem, vmp_pageq); vm_page_throttled_count--; was_pageable = FALSE; break; } case VM_PAGE_ON_SPECULATIVE_Q: { assert(m_object->internal == FALSE); vm_page_remque(&mem->vmp_pageq); vm_page_speculative_count--; vm_page_balance_inactive(3); break; } #if CONFIG_SECLUDED_MEMORY case VM_PAGE_ON_SECLUDED_Q: { vm_page_queue_remove(&vm_page_queue_secluded, mem, vmp_pageq); vm_page_secluded_count--; VM_PAGE_SECLUDED_COUNT_OVER_TARGET_UPDATE(); if (m_object == VM_OBJECT_NULL) { vm_page_secluded_count_free--; was_pageable = FALSE; } else { assert(!m_object->internal); vm_page_secluded_count_inuse--; was_pageable = FALSE; // was_pageable = TRUE; } break; } #endif /* CONFIG_SECLUDED_MEMORY */ default: { /* * if (mem->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q) * NOTE: vm_page_queues_remove does not deal with removing pages from the pageout queue... * the caller is responsible for determing if the page is on that queue, and if so, must * either first remove it (it needs both the page queues lock and the object lock to do * this via vm_pageout_steal_laundry), or avoid the call to vm_page_queues_remove * * we also don't expect to encounter VM_PAGE_ON_FREE_Q, VM_PAGE_ON_FREE_LOCAL_Q, VM_PAGE_ON_FREE_LOPAGE_Q * or any of the undefined states */ panic("vm_page_queues_remove - bad page q_state (%p, %d)", mem, mem->vmp_q_state); break; } } VM_PAGE_ZERO_PAGEQ_ENTRY(mem); mem->vmp_q_state = VM_PAGE_NOT_ON_Q; if (remove_from_specialq == TRUE) { vm_page_remove_from_specialq(mem); } if (was_pageable) { if (m_object->internal) { vm_page_pageable_internal_count--; } else { vm_page_pageable_external_count--; } } } void vm_page_remove_internal(vm_page_t page) { vm_object_t __object = VM_PAGE_OBJECT(page); if (page == __object->memq_hint) { vm_page_t __new_hint; vm_page_queue_entry_t __qe; __qe = (vm_page_queue_entry_t)vm_page_queue_next(&page->vmp_listq); if (vm_page_queue_end(&__object->memq, __qe)) { __qe = (vm_page_queue_entry_t)vm_page_queue_prev(&page->vmp_listq); if (vm_page_queue_end(&__object->memq, __qe)) { __qe = NULL; } } __new_hint = (vm_page_t)((uintptr_t) __qe); __object->memq_hint = __new_hint; } vm_page_queue_remove(&__object->memq, page, vmp_listq); #if CONFIG_SECLUDED_MEMORY if (__object->eligible_for_secluded) { vm_page_secluded.eligible_for_secluded--; } #endif /* CONFIG_SECLUDED_MEMORY */ #if HAS_MTE assert_mte_vmo_matches_vmp(__object, page); #endif /* HAS_MTE */ } void vm_page_enqueue_inactive(vm_page_t mem, boolean_t first) { vm_object_t m_object; m_object = VM_PAGE_OBJECT(mem); LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); assert(!vm_page_is_fictitious(mem)); assert(!mem->vmp_laundry); assert(mem->vmp_q_state == VM_PAGE_NOT_ON_Q); vm_page_check_pageable_safe(mem); if (m_object->internal) { mem->vmp_q_state = VM_PAGE_ON_INACTIVE_INTERNAL_Q; if (first == TRUE) { vm_page_queue_enter_first(&vm_page_queue_anonymous, mem, vmp_pageq); } else { vm_page_queue_enter(&vm_page_queue_anonymous, mem, vmp_pageq); } vm_page_anonymous_count++; vm_page_pageable_internal_count++; } else { mem->vmp_q_state = VM_PAGE_ON_INACTIVE_EXTERNAL_Q; if (first == TRUE) { vm_page_queue_enter_first(&vm_page_queue_inactive, mem, vmp_pageq); } else { vm_page_queue_enter(&vm_page_queue_inactive, mem, vmp_pageq); } vm_page_pageable_external_count++; } vm_page_inactive_count++; token_new_pagecount++; vm_page_add_to_specialq(mem, FALSE); } void vm_page_enqueue_active(vm_page_t mem, boolean_t first) { vm_object_t m_object; m_object = VM_PAGE_OBJECT(mem); LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED); assert(!vm_page_is_fictitious(mem)); assert(!mem->vmp_laundry); assert(mem->vmp_q_state == VM_PAGE_NOT_ON_Q); vm_page_check_pageable_safe(mem); mem->vmp_q_state = VM_PAGE_ON_ACTIVE_Q; if (first == TRUE) { vm_page_queue_enter_first(&vm_page_queue_active, mem, vmp_pageq); } else { vm_page_queue_enter(&vm_page_queue_active, mem, vmp_pageq); } vm_page_active_count++; if (m_object->internal) { vm_page_pageable_internal_count++; } else { vm_page_pageable_external_count++; } vm_page_add_to_specialq(mem, FALSE); vm_page_balance_inactive(3); } /* * Pages from special kernel objects shouldn't * be placed on pageable queues. */ void vm_page_check_pageable_safe(vm_page_t page) { vm_object_t page_object; page_object = VM_PAGE_OBJECT(page); if (is_kernel_object(page_object)) { panic("vm_page_check_pageable_safe: trying to add page" "from a kernel object to pageable queue"); } if (page_object == compressor_object) { panic("vm_page_check_pageable_safe: trying to add page" "from compressor object (%p) to pageable queue", compressor_object); } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * wired page diagnose * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <libkern/OSKextLibPrivate.h> #define KA_SIZE(namelen, subtotalscount) \ (sizeof(struct vm_allocation_site) + (namelen) + 1 + ((subtotalscount) * sizeof(struct vm_allocation_total))) #define KA_NAME(alloc) \ ((char *)(&(alloc)->subtotals[(alloc->subtotalscount)])) #define KA_NAME_LEN(alloc) \ (VM_TAG_NAME_LEN_MAX & (alloc->flags >> VM_TAG_NAME_LEN_SHIFT)) vm_tag_t vm_tag_bt(void) { uintptr_t* frameptr; uintptr_t* frameptr_next; uintptr_t retaddr; uintptr_t kstackb, kstackt; const vm_allocation_site_t * site; thread_t cthread; kern_allocation_name_t name; cthread = current_thread(); if (__improbable(cthread == NULL)) { return VM_KERN_MEMORY_OSFMK; } if ((name = thread_get_kernel_state(cthread)->allocation_name)) { if (!name->tag) { vm_tag_alloc(name); } return name->tag; } kstackb = cthread->kernel_stack; kstackt = kstackb + kernel_stack_size; /* Load stack frame pointer (EBP on x86) into frameptr */ frameptr = __builtin_frame_address(0); site = NULL; while (frameptr != NULL) { /* Verify thread stack bounds */ if (((uintptr_t)(frameptr + 2) > kstackt) || ((uintptr_t)frameptr < kstackb)) { break; } /* Next frame pointer is pointed to by the previous one */ frameptr_next = (uintptr_t*) *frameptr; #if defined(HAS_APPLE_PAC) frameptr_next = ptrauth_strip(frameptr_next, ptrauth_key_frame_pointer); #endif /* Pull return address from one spot above the frame pointer */ retaddr = *(frameptr + 1); #if defined(HAS_APPLE_PAC) retaddr = (uintptr_t) ptrauth_strip((void *)retaddr, ptrauth_key_return_address); #endif if (((retaddr < vm_kernel_builtinkmod_text_end) && (retaddr >= vm_kernel_builtinkmod_text)) || !kernel_text_contains(retaddr)) { site = OSKextGetAllocationSiteForCaller(retaddr); break; } frameptr = frameptr_next; } if (site) { return site->tag; } #if MACH_ASSERT /* * Kernel tests appear here as unrecognized call sites and would get * no memory tag. Give them a default tag to prevent panics later. */ if (thread_get_test_option(test_option_vm_prevent_wire_tag_panic)) { return VM_KERN_MEMORY_OSFMK; } #endif return VM_KERN_MEMORY_NONE; } static uint64_t free_tag_bits[VM_MAX_TAG_VALUE / 64]; void vm_tag_alloc_locked(vm_allocation_site_t * site, vm_allocation_site_t ** releasesiteP) { vm_tag_t tag; uint64_t avail; uint32_t idx; vm_allocation_site_t * prev; if (site->tag) { return; } idx = 0; while (TRUE) { avail = free_tag_bits[idx]; if (avail) { tag = (vm_tag_t)__builtin_clzll(avail); avail &= ~(1ULL << (63 - tag)); free_tag_bits[idx] = avail; tag += (idx << 6); break; } idx++; if (idx >= ARRAY_COUNT(free_tag_bits)) { for (idx = 0; idx < ARRAY_COUNT(vm_allocation_sites); idx++) { prev = vm_allocation_sites[idx]; if (!prev) { continue; } if (!KA_NAME_LEN(prev)) { continue; } if (!prev->tag) { continue; } if (prev->total) { continue; } if (1 != prev->refcount) { continue; } assert(idx == prev->tag); tag = (vm_tag_t)idx; prev->tag = VM_KERN_MEMORY_NONE; *releasesiteP = prev; break; } if (idx >= ARRAY_COUNT(vm_allocation_sites)) { tag = VM_KERN_MEMORY_ANY; } break; } } site->tag = tag; OSAddAtomic16(1, &site->refcount); if (VM_KERN_MEMORY_ANY != tag) { vm_allocation_sites[tag] = site; } if (tag > vm_allocation_tag_highest) { vm_allocation_tag_highest = tag; } } static void vm_tag_free_locked(vm_tag_t tag) { uint64_t avail; uint32_t idx; uint64_t bit; if (VM_KERN_MEMORY_ANY == tag) { return; } idx = (tag >> 6); avail = free_tag_bits[idx]; tag &= 63; bit = (1ULL << (63 - tag)); assert(!(avail & bit)); free_tag_bits[idx] = (avail | bit); } static void vm_tag_init(void) { vm_tag_t tag; for (tag = VM_KERN_MEMORY_FIRST_DYNAMIC; tag < VM_KERN_MEMORY_ANY; tag++) { vm_tag_free_locked(tag); } for (tag = VM_KERN_MEMORY_ANY + 1; tag < VM_MAX_TAG_VALUE; tag++) { vm_tag_free_locked(tag); } } vm_tag_t vm_tag_alloc(vm_allocation_site_t * site) { vm_allocation_site_t * releasesite; if (!site->tag) { releasesite = NULL; lck_ticket_lock(&vm_allocation_sites_lock, &vm_page_lck_grp_bucket); vm_tag_alloc_locked(site, &releasesite); lck_ticket_unlock(&vm_allocation_sites_lock); if (releasesite) { kern_allocation_name_release(releasesite); } } return site->tag; } #ifndef ARRAY_SIZE #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) #endif /* ARRAY_SIZE */ #define VM_KERN_MEMORY_ELEM(name) [VM_KERN_MEMORY_##name] = "VM_KERN_MEMORY_" #name const char *vm_kern_memory_names[] = { VM_KERN_MEMORY_ELEM(NONE), VM_KERN_MEMORY_ELEM(OSFMK), VM_KERN_MEMORY_ELEM(BSD), VM_KERN_MEMORY_ELEM(IOKIT), VM_KERN_MEMORY_ELEM(LIBKERN), VM_KERN_MEMORY_ELEM(OSKEXT), VM_KERN_MEMORY_ELEM(KEXT), VM_KERN_MEMORY_ELEM(IPC), VM_KERN_MEMORY_ELEM(STACK), VM_KERN_MEMORY_ELEM(CPU), VM_KERN_MEMORY_ELEM(PMAP), VM_KERN_MEMORY_ELEM(PTE), VM_KERN_MEMORY_ELEM(ZONE), VM_KERN_MEMORY_ELEM(KALLOC), VM_KERN_MEMORY_ELEM(COMPRESSOR), VM_KERN_MEMORY_ELEM(COMPRESSED_DATA), VM_KERN_MEMORY_ELEM(PHANTOM_CACHE), VM_KERN_MEMORY_ELEM(WAITQ), VM_KERN_MEMORY_ELEM(DIAG), VM_KERN_MEMORY_ELEM(LOG), VM_KERN_MEMORY_ELEM(FILE), VM_KERN_MEMORY_ELEM(MBUF), VM_KERN_MEMORY_ELEM(UBC), VM_KERN_MEMORY_ELEM(SECURITY), VM_KERN_MEMORY_ELEM(MLOCK), VM_KERN_MEMORY_ELEM(REASON), VM_KERN_MEMORY_ELEM(SKYWALK), VM_KERN_MEMORY_ELEM(LTABLE), VM_KERN_MEMORY_ELEM(HV), VM_KERN_MEMORY_ELEM(KALLOC_DATA), VM_KERN_MEMORY_ELEM(RETIRED), VM_KERN_MEMORY_ELEM(KALLOC_TYPE), VM_KERN_MEMORY_ELEM(TRIAGE), VM_KERN_MEMORY_ELEM(RECOUNT), VM_KERN_MEMORY_ELEM(MTAG), VM_KERN_MEMORY_ELEM(EXCLAVES), VM_KERN_MEMORY_ELEM(EXCLAVES_SHARED), VM_KERN_MEMORY_ELEM(KALLOC_SHARED), VM_KERN_MEMORY_ELEM(CPUTRACE), }; _Static_assert(ARRAY_SIZE(vm_kern_memory_names) == VM_KERN_MEMORY_FIRST_DYNAMIC, "vm_kern_memory_names must map all counter tags"); #define VM_KERN_COUNT_ELEM(name) [VM_KERN_COUNT_##name] = "VM_KERN_COUNT_" #name const char *vm_kern_count_names[] = { VM_KERN_COUNT_ELEM(MANAGED), VM_KERN_COUNT_ELEM(RESERVED), VM_KERN_COUNT_ELEM(WIRED), VM_KERN_COUNT_ELEM(WIRED_MANAGED), VM_KERN_COUNT_ELEM(STOLEN), VM_KERN_COUNT_ELEM(LOPAGE), VM_KERN_COUNT_ELEM(MAP_KERNEL), VM_KERN_COUNT_ELEM(MAP_ZONE), VM_KERN_COUNT_ELEM(MAP_KALLOC_LARGE), VM_KERN_COUNT_ELEM(WIRED_BOOT), VM_KERN_COUNT_ELEM(BOOT_STOLEN), VM_KERN_COUNT_ELEM(WIRED_STATIC_KERNELCACHE), VM_KERN_COUNT_ELEM(MAP_KALLOC_LARGE_DATA), VM_KERN_COUNT_ELEM(MAP_KERNEL_DATA), VM_KERN_COUNT_ELEM(EXCLAVES_CARVEOUT), }; #if VM_BTLOG_TAGS #define VM_KERN_MEMORY_STR_MAX_LEN (32) TUNABLE_STR(vmtaglog, VM_KERN_MEMORY_STR_MAX_LEN, "vmtaglog", ""); #define VM_TAG_BTLOG_SIZE (16u << 10) btlog_t vmtaglog_btlog; vm_tag_t vmtaglog_tag; static void vm_tag_log(vm_object_t object, int64_t delta, void *fp) { if (is_kernel_object(object)) { /* kernel object backtraces are tracked in vm entries */ return; } if (delta > 0) { btref_t ref = btref_get(fp, BTREF_GET_NOWAIT); btlog_record(vmtaglog_btlog, object, 0, ref); } else if (object->wired_page_count == 0) { btlog_erase(vmtaglog_btlog, object); } } _Static_assert(ARRAY_SIZE(vm_kern_count_names) == VM_KERN_COUNTER_COUNT, "vm_kern_count_names must map all counter tags"); static vm_tag_t vm_tag_str_to_idx(char tagstr[VM_KERN_MEMORY_STR_MAX_LEN]) { for (vm_tag_t i = VM_KERN_MEMORY_OSFMK; i < ARRAY_SIZE(vm_kern_memory_names); i++) { if (!strncmp(vm_kern_memory_names[i], tagstr, VM_KERN_MEMORY_STR_MAX_LEN)) { return i; } } if (!strncmp("dynamic", tagstr, VM_KERN_MEMORY_STR_MAX_LEN)) { return VM_KERN_MEMORY_FIRST_DYNAMIC; } if (!strncmp("any", tagstr, VM_KERN_MEMORY_STR_MAX_LEN)) { return VM_KERN_MEMORY_ANY; } printf("Unable to find vm tag %s for btlog\n", tagstr); return VM_KERN_MEMORY_NONE; } __startup_func static void vm_btlog_init(void) { vmtaglog_tag = vm_tag_str_to_idx(vmtaglog); if (vmtaglog_tag != VM_KERN_MEMORY_NONE) { vmtaglog_btlog = btlog_create(BTLOG_HASH, VM_TAG_BTLOG_SIZE, 0); } } STARTUP(ZALLOC, STARTUP_RANK_FIRST, vm_btlog_init); #endif /* VM_BTLOG_TAGS */ void vm_tag_update_size(vm_tag_t tag, int64_t delta, vm_object_t object) { assert(VM_KERN_MEMORY_NONE != tag && tag < VM_MAX_TAG_VALUE); kern_allocation_update_size(vm_allocation_sites[tag], delta, object); } uint64_t vm_tag_get_size(vm_tag_t tag) { vm_allocation_site_t *allocation; assert(VM_KERN_MEMORY_NONE != tag && tag < VM_MAX_TAG_VALUE); allocation = vm_allocation_sites[tag]; return allocation ? os_atomic_load(&allocation->total, relaxed) : 0; } void kern_allocation_update_size(kern_allocation_name_t allocation, int64_t delta, __unused vm_object_t object) { uint64_t value; value = os_atomic_add(&allocation->total, delta, relaxed); if (delta < 0) { assertf(value + (uint64_t)-delta > value, "tag %d, site %p", allocation->tag, allocation); } #if DEBUG || DEVELOPMENT /* release to publish the new total */ os_atomic_max(&allocation->peak, value, release); #endif /* DEBUG || DEVELOPMENT */ if (value == (uint64_t)delta && !allocation->tag) { vm_tag_alloc(allocation); } #if VM_BTLOG_TAGS if (vmtaglog_matches(allocation->tag) && object) { vm_tag_log(object, delta, __builtin_frame_address(0)); } #endif /* VM_BTLOG_TAGS */ } #if DEBUG || DEVELOPMENT void vm_tag_reset_all_peaks(void) { vm_log("resetting peak size for all kernel tags\n"); for (vm_tag_t tag = 0; tag <= vm_allocation_tag_highest; tag++) { vm_tag_reset_peak(tag); } } kern_return_t vm_tag_reset_peak(vm_tag_t tag) { if (tag > vm_allocation_tag_highest) { return KERN_INVALID_ARGUMENT; } vm_allocation_site_t *site = vm_allocation_sites[tag]; vm_log_info("resetting peak size for kernel tag %s\n", KA_NAME(site)); uint64_t new_peak = os_atomic_load(&site->total, relaxed); /* acquire updates to the total */ os_atomic_min(&site->peak, new_peak, acquire); return KERN_SUCCESS; } #endif /* DEBUG || DEVELOPMENT */ #if VM_TAG_SIZECLASSES void vm_allocation_zones_init(void) { vm_offset_t addr; vm_size_t size; const vm_tag_t early_tags[] = { VM_KERN_MEMORY_DIAG, VM_KERN_MEMORY_KALLOC, VM_KERN_MEMORY_KALLOC_DATA, VM_KERN_MEMORY_KALLOC_SHARED, VM_KERN_MEMORY_KALLOC_TYPE, VM_KERN_MEMORY_LIBKERN, VM_KERN_MEMORY_OSFMK, VM_KERN_MEMORY_RECOUNT, }; size = VM_MAX_TAG_VALUE * sizeof(vm_allocation_zone_total_t * *) + ARRAY_COUNT(early_tags) * VM_TAG_SIZECLASSES * sizeof(vm_allocation_zone_total_t); kmem_alloc(kernel_map, &addr, round_page(size), KMA_NOFAIL | KMA_KOBJECT | KMA_ZERO | KMA_PERMANENT, VM_KERN_MEMORY_DIAG); vm_allocation_zone_totals = (vm_allocation_zone_total_t **) addr; addr += VM_MAX_TAG_VALUE * sizeof(vm_allocation_zone_total_t * *); // prepopulate early tag ranges so allocations // in vm_tag_update_zone_size() and early boot won't recurse for (size_t i = 0; i < ARRAY_COUNT(early_tags); i++) { vm_allocation_zone_totals[early_tags[i]] = (vm_allocation_zone_total_t *)addr; addr += VM_TAG_SIZECLASSES * sizeof(vm_allocation_zone_total_t); } } __attribute__((noinline)) static vm_tag_t vm_tag_zone_stats_alloc(vm_tag_t tag, zalloc_flags_t flags) { vm_allocation_zone_total_t *stats; vm_size_t size = sizeof(*stats) * VM_TAG_SIZECLASSES; flags = Z_VM_TAG(Z_ZERO | flags, VM_KERN_MEMORY_DIAG); stats = kalloc_data(size, flags); if (!stats) { return VM_KERN_MEMORY_NONE; } if (!os_atomic_cmpxchg(&vm_allocation_zone_totals[tag], NULL, stats, release)) { kfree_data(stats, size); } return tag; } vm_tag_t vm_tag_will_update_zone(vm_tag_t tag, uint32_t zflags) { assert(VM_KERN_MEMORY_NONE != tag); assert(tag < VM_MAX_TAG_VALUE); if (__probable(vm_allocation_zone_totals[tag])) { return tag; } return vm_tag_zone_stats_alloc(tag, zflags); } void vm_tag_update_zone_size(vm_tag_t tag, uint32_t zidx, long delta) { vm_allocation_zone_total_t *stats; vm_size_t value; assert(VM_KERN_MEMORY_NONE != tag); assert(tag < VM_MAX_TAG_VALUE); if (zidx >= VM_TAG_SIZECLASSES) { return; } stats = vm_allocation_zone_totals[tag]; assert(stats); stats += zidx; value = os_atomic_add(&stats->vazt_total, delta, relaxed); if (delta < 0) { assertf((long)value >= 0, "zidx %d, tag %d, %p", zidx, tag, stats); return; } else if (os_atomic_load(&stats->vazt_peak, relaxed) < value) { os_atomic_max(&stats->vazt_peak, value, relaxed); } } #endif /* VM_TAG_SIZECLASSES */ void kern_allocation_update_subtotal(kern_allocation_name_t allocation, vm_tag_t subtag, int64_t delta) { kern_allocation_name_t other; struct vm_allocation_total * total; uint32_t subidx; assert(VM_KERN_MEMORY_NONE != subtag); lck_ticket_lock(&vm_allocation_sites_lock, &vm_page_lck_grp_bucket); for (subidx = 0; subidx < allocation->subtotalscount; subidx++) { total = &allocation->subtotals[subidx]; if (subtag == total->tag) { break; } } if (subidx >= allocation->subtotalscount) { for (subidx = 0; subidx < allocation->subtotalscount; subidx++) { total = &allocation->subtotals[subidx]; if ((VM_KERN_MEMORY_NONE == total->tag) || !total->total) { total->tag = (vm_tag_t)subtag; break; } } } assert(subidx < allocation->subtotalscount); if (subidx >= allocation->subtotalscount) { lck_ticket_unlock(&vm_allocation_sites_lock); return; } if (delta < 0) { assertf(total->total >= ((uint64_t)-delta), "name %p", allocation); } OSAddAtomic64(delta, &total->total); lck_ticket_unlock(&vm_allocation_sites_lock); other = vm_allocation_sites[subtag]; assert(other); if (delta < 0) { assertf(other->mapped >= ((uint64_t)-delta), "other %p", other); } OSAddAtomic64(delta, &other->mapped); } const char * kern_allocation_get_name(kern_allocation_name_t allocation) { return KA_NAME(allocation); } kern_allocation_name_t kern_allocation_name_allocate(const char * name, uint16_t subtotalscount) { kern_allocation_name_t allocation; uint16_t namelen; namelen = (uint16_t)strnlen(name, MACH_MEMORY_INFO_NAME_MAX_LEN - 1); allocation = kalloc_data(KA_SIZE(namelen, subtotalscount), Z_WAITOK | Z_ZERO); allocation->refcount = 1; allocation->subtotalscount = subtotalscount; allocation->flags = (uint16_t)(namelen << VM_TAG_NAME_LEN_SHIFT); strlcpy(KA_NAME(allocation), name, namelen + 1); vm_tag_alloc(allocation); return allocation; } void kern_allocation_name_release(kern_allocation_name_t allocation) { assert(allocation->refcount > 0); if (1 == OSAddAtomic16(-1, &allocation->refcount)) { kfree_data(allocation, KA_SIZE(KA_NAME_LEN(allocation), allocation->subtotalscount)); } } #if !VM_TAG_ACTIVE_UPDATE static void vm_page_count_object(mach_memory_info_t * info, unsigned int __unused num_info, vm_object_t object) { if (!object->wired_page_count) { return; } if (!is_kernel_object(object)) { assert(object->wire_tag < num_info); info[object->wire_tag].size += ptoa_64(object->wired_page_count); } } typedef void (*vm_page_iterate_proc)(mach_memory_info_t * info, unsigned int num_info, vm_object_t object); static void vm_page_iterate_purgeable_objects(mach_memory_info_t * info, unsigned int num_info, vm_page_iterate_proc proc, purgeable_q_t queue, int group) { vm_object_t object; for (object = (vm_object_t) queue_first(&queue->objq[group]); !queue_end(&queue->objq[group], (queue_entry_t) object); object = (vm_object_t) queue_next(&object->objq)) { proc(info, num_info, object); } } static void vm_page_iterate_objects(mach_memory_info_t * info, unsigned int num_info, vm_page_iterate_proc proc) { vm_object_t object; lck_spin_lock_grp(&vm_objects_wired_lock, &vm_page_lck_grp_bucket); queue_iterate(&vm_objects_wired, object, vm_object_t, wired_objq) { proc(info, num_info, object); } lck_spin_unlock(&vm_objects_wired_lock); } #endif /* ! VM_TAG_ACTIVE_UPDATE */ static uint64_t process_account(mach_memory_info_t * info, unsigned int num_info, uint64_t zones_collectable_bytes, bool redact_info __unused) { size_t namelen; unsigned int idx, count, nextinfo; vm_allocation_site_t * site; lck_ticket_lock(&vm_allocation_sites_lock, &vm_page_lck_grp_bucket); for (idx = 0; idx <= vm_allocation_tag_highest; idx++) { site = vm_allocation_sites[idx]; if (!site) { continue; } info[idx].mapped = site->mapped; info[idx].tag = site->tag; info[idx].size = site->total; #if DEBUG || DEVELOPMENT info[idx].peak = site->peak; #endif /* DEBUG || DEVELOPMENT */ info[idx].flags |= VM_KERN_SITE_WIRED; if (idx < VM_KERN_MEMORY_FIRST_DYNAMIC) { info[idx].site = idx; info[idx].flags |= VM_KERN_SITE_TAG; if (VM_KERN_MEMORY_ZONE == idx) { info[idx].flags |= VM_KERN_SITE_HIDE; info[idx].flags &= ~VM_KERN_SITE_WIRED; info[idx].collectable_bytes = zones_collectable_bytes; } info[idx].flags |= VM_KERN_SITE_NAMED; strlcpy(info[idx].name, vm_kern_memory_names[idx], MACH_MEMORY_INFO_NAME_MAX_LEN); } else if ((namelen = (VM_TAG_NAME_LEN_MAX & (site->flags >> VM_TAG_NAME_LEN_SHIFT)))) { info[idx].site = 0; info[idx].flags |= VM_KERN_SITE_NAMED; if (namelen > sizeof(info[idx].name)) { namelen = sizeof(info[idx].name); } strncpy(&info[idx].name[0], KA_NAME(site), namelen); } else if (VM_TAG_KMOD & site->flags) { info[idx].site = OSKextGetKmodIDForSite(site, NULL, 0); info[idx].flags |= VM_KERN_SITE_KMOD; } else { info[idx].site = VM_KERNEL_UNSLIDE(site); info[idx].flags |= VM_KERN_SITE_KERNEL; } } nextinfo = (vm_allocation_tag_highest + 1); count = nextinfo; if (count >= num_info) { count = num_info; } for (idx = 0; idx < count; idx++) { site = vm_allocation_sites[idx]; if (!site) { continue; } #if VM_TAG_SIZECLASSES vm_allocation_zone_total_t * zone; unsigned int zidx; if (!redact_info && vm_allocation_zone_totals && (zone = vm_allocation_zone_totals[idx]) && (nextinfo < num_info)) { for (zidx = 0; zidx < VM_TAG_SIZECLASSES; zidx++) { if (!zone[zidx].vazt_peak) { continue; } info[nextinfo] = info[idx]; info[nextinfo].zone = zone_index_from_tag_index(zidx); info[nextinfo].flags &= ~VM_KERN_SITE_WIRED; info[nextinfo].flags |= VM_KERN_SITE_ZONE; info[nextinfo].flags |= VM_KERN_SITE_KALLOC; info[nextinfo].size = zone[zidx].vazt_total; info[nextinfo].peak = zone[zidx].vazt_peak; info[nextinfo].mapped = 0; nextinfo++; } } #endif /* VM_TAG_SIZECLASSES */ if (site->subtotalscount) { uint64_t mapped, mapcost, take; uint32_t sub; vm_tag_t alloctag; info[idx].size = site->total; mapped = info[idx].size; info[idx].mapped = mapped; mapcost = 0; for (sub = 0; sub < site->subtotalscount; sub++) { alloctag = site->subtotals[sub].tag; assert(alloctag < num_info); if (info[alloctag].name[0] && alloctag >= VM_KERN_MEMORY_FIRST_DYNAMIC) { continue; } take = site->subtotals[sub].total; if (take > info[alloctag].size) { take = info[alloctag].size; } if (take > mapped) { take = mapped; } info[alloctag].mapped -= take; info[alloctag].size -= take; mapped -= take; mapcost += take; } info[idx].size = mapcost; } } lck_ticket_unlock(&vm_allocation_sites_lock); return 0; } uint32_t vm_page_diagnose_estimate(void) { vm_allocation_site_t * site; uint32_t count = zone_view_count; uint32_t idx; lck_ticket_lock(&vm_allocation_sites_lock, &vm_page_lck_grp_bucket); for (idx = 0; idx < VM_MAX_TAG_VALUE; idx++) { site = vm_allocation_sites[idx]; if (!site) { continue; } count++; #if VM_TAG_SIZECLASSES if (vm_allocation_zone_totals) { vm_allocation_zone_total_t * zone; zone = vm_allocation_zone_totals[idx]; if (!zone) { continue; } for (uint32_t zidx = 0; zidx < VM_TAG_SIZECLASSES; zidx++) { count += (zone[zidx].vazt_peak != 0); } } #endif } lck_ticket_unlock(&vm_allocation_sites_lock); /* some slop for new tags created */ count += 8; count += VM_KERN_COUNTER_COUNT; return count; } static void vm_page_diagnose_zone_stats(mach_memory_info_t *info, zone_stats_t zstats, bool percpu) { zpercpu_foreach(zs, zstats) { info->size += zs->zs_mem_allocated - zs->zs_mem_freed; } if (percpu) { info->size *= zpercpu_count(); } info->flags |= VM_KERN_SITE_NAMED | VM_KERN_SITE_ZONE_VIEW; } static void vm_page_add_info( mach_memory_info_t *info, zone_stats_t stats, bool per_cpu, const char *parent_heap_name, const char *parent_zone_name, const char *view_name) { vm_page_diagnose_zone_stats(info, stats, per_cpu); snprintf(info->name, sizeof(info->name), "%s%s[%s]", parent_heap_name, parent_zone_name, view_name); } static void vm_page_diagnose_zone(mach_memory_info_t *info, zone_t z) { vm_page_add_info(info, z->z_stats, z->z_percpu, zone_heap_name(z), z->z_name, "raw"); } static void vm_page_add_view( mach_memory_info_t *info, zone_stats_t stats, const char *parent_heap_name, const char *parent_zone_name, const char *view_name) { vm_page_add_info(info, stats, false, parent_heap_name, parent_zone_name, view_name); } static uint32_t vm_page_diagnose_heap_views( mach_memory_info_t *info, kalloc_heap_t kh, const char *parent_heap_name, const char *parent_zone_name) { uint32_t i = 0; while (kh) { vm_page_add_view(info + i, kh->kh_stats, parent_heap_name, parent_zone_name, kh->kh_name); kh = kh->kh_views; i++; } return i; } static uint32_t vm_page_diagnose_heap(mach_memory_info_t *info, kalloc_heap_t kheap) { uint32_t i = 0; for (; i < KHEAP_NUM_ZONES; i++) { vm_page_diagnose_zone(info + i, zone_by_id(kheap->kh_zstart + i)); } i += vm_page_diagnose_heap_views(info + i, kheap->kh_views, kheap->kh_name, NULL); return i; } static int vm_page_diagnose_kt_heaps(mach_memory_info_t *info) { uint32_t idx = 0; vm_page_add_view(info + idx, KHEAP_KT_VAR->kh_stats, KHEAP_KT_VAR->kh_name, "", "raw"); idx++; for (uint32_t i = 0; i < KT_VAR_MAX_HEAPS; i++) { struct kheap_info heap = kalloc_type_heap_array[i]; char heap_num_tmp[MAX_ZONE_NAME] = ""; const char *heap_num; snprintf(&heap_num_tmp[0], MAX_ZONE_NAME, "%u", i); heap_num = &heap_num_tmp[0]; for (kalloc_type_var_view_t ktv = heap.kt_views; ktv; ktv = (kalloc_type_var_view_t) ktv->kt_next) { if (ktv->kt_stats && ktv->kt_stats != KHEAP_KT_VAR->kh_stats) { vm_page_add_view(info + idx, ktv->kt_stats, KHEAP_KT_VAR->kh_name, heap_num, ktv->kt_name); idx++; } } idx += vm_page_diagnose_heap_views(info + idx, heap.kh_views, KHEAP_KT_VAR->kh_name, heap_num); } return idx; } kern_return_t vm_page_diagnose(mach_memory_info_t * info, unsigned int num_info, uint64_t zones_collectable_bytes, bool redact_info) { uint64_t wired_size; uint64_t wired_managed_size; uint64_t wired_reserved_size; mach_memory_info_t * counts; uint32_t i; bzero(info, num_info * sizeof(mach_memory_info_t)); if (!vm_page_wire_count_initial) { return KERN_ABORTED; } wired_size = ptoa_64(vm_page_wire_count); wired_reserved_size = ptoa_64(vm_page_wire_count_initial - vm_page_stolen_count); #if XNU_TARGET_OS_OSX wired_size += ptoa_64(vm_lopage_free_count + vm_page_throttled_count); wired_reserved_size += ptoa_64(vm_page_throttled_count); #endif /* XNU_TARGET_OS_OSX */ #if CONFIG_EXCLAVES wired_reserved_size -= exclaves_carveout_size + exclaves_bundle_size; #endif /* CONFIG_EXCLAVES */ wired_managed_size = ptoa_64(vm_page_wire_count - vm_page_wire_count_initial); wired_size += booter_size; assert(num_info >= VM_KERN_COUNTER_COUNT); num_info -= VM_KERN_COUNTER_COUNT; counts = &info[num_info]; #define SET_COUNT(xcount, xsize, xflags) MACRO_BEGIN \ counts[xcount].tag = VM_MAX_TAG_VALUE + xcount; \ counts[xcount].site = (xcount); \ counts[xcount].size = (xsize); \ counts[xcount].mapped = (xsize); \ counts[xcount].flags = VM_KERN_SITE_COUNTER | VM_KERN_SITE_NAMED | xflags; \ strlcpy(counts[xcount].name, vm_kern_count_names[xcount], MACH_MEMORY_INFO_NAME_MAX_LEN); \ MACRO_END; SET_COUNT(VM_KERN_COUNT_MANAGED, ptoa_64(vm_page_pages), 0); SET_COUNT(VM_KERN_COUNT_WIRED, wired_size, 0); SET_COUNT(VM_KERN_COUNT_WIRED_MANAGED, wired_managed_size, 0); SET_COUNT(VM_KERN_COUNT_RESERVED, wired_reserved_size, VM_KERN_SITE_WIRED); SET_COUNT(VM_KERN_COUNT_STOLEN, ptoa_64(vm_page_stolen_count), VM_KERN_SITE_WIRED); SET_COUNT(VM_KERN_COUNT_LOPAGE, ptoa_64(vm_lopage_free_count), VM_KERN_SITE_WIRED); SET_COUNT(VM_KERN_COUNT_WIRED_BOOT, ptoa_64(vm_page_wire_count_on_boot), 0); SET_COUNT(VM_KERN_COUNT_BOOT_STOLEN, booter_size, VM_KERN_SITE_WIRED); SET_COUNT(VM_KERN_COUNT_WIRED_STATIC_KERNELCACHE, ptoa_64(vm_page_kernelcache_count), 0); #if CONFIG_EXCLAVES SET_COUNT(VM_KERN_COUNT_EXCLAVES_CARVEOUT, exclaves_carveout_size + exclaves_bundle_size, VM_KERN_SITE_WIRED); #endif /* CONFIG_EXCLAVES */ #define SET_MAP(xcount, xsize, xfree, xlargest) MACRO_BEGIN \ counts[xcount].site = (xcount); \ counts[xcount].size = (xsize); \ counts[xcount].mapped = (xsize); \ counts[xcount].free = (xfree); \ counts[xcount].largest = (xlargest); \ counts[xcount].flags = VM_KERN_SITE_COUNTER | VM_KERN_SITE_NAMED; \ strlcpy(counts[xcount].name, vm_kern_count_names[xcount], MACH_MEMORY_INFO_NAME_MAX_LEN); \ MACRO_END; vm_map_size_t map_size, map_free, map_largest; vm_map_sizes(kernel_map, &map_size, &map_free, &map_largest); SET_MAP(VM_KERN_COUNT_MAP_KERNEL, map_size, map_free, map_largest); zone_map_sizes(&map_size, &map_free, &map_largest); SET_MAP(VM_KERN_COUNT_MAP_ZONE, map_size, map_free, map_largest); assert(num_info >= zone_view_count); num_info -= zone_view_count; counts = &info[num_info]; i = 0; if (!redact_info) { if (zone_is_data_buffers_kheap(KHEAP_DATA_PRIVATE->kh_heap_id)) { i += vm_page_diagnose_heap(counts + i, KHEAP_DATA_PRIVATE); } if (zone_is_data_shared_kheap(KHEAP_DATA_SHARED->kh_heap_id)) { i += vm_page_diagnose_heap(counts + i, KHEAP_DATA_SHARED); } if (KHEAP_KT_VAR->kh_heap_id == KHEAP_ID_KT_VAR) { i += vm_page_diagnose_kt_heaps(counts + i); } assert(i <= zone_view_count); zone_index_foreach(zidx) { zone_t z = &zone_array[zidx]; zone_security_flags_t zsflags = zone_security_array[zidx]; zone_view_t zv = z->z_views; if (zv == NULL) { continue; } zone_stats_t zv_stats_head = z->z_stats; bool has_raw_view = false; for (; zv; zv = zv->zv_next) { /* * kalloc_types that allocate from the same zone are linked * as views. Only print the ones that have their own stats. */ if (zv->zv_stats == zv_stats_head) { continue; } has_raw_view = true; vm_page_diagnose_zone_stats(counts + i, zv->zv_stats, z->z_percpu); snprintf(counts[i].name, sizeof(counts[i].name), "%s%s[%s]", zone_heap_name(z), z->z_name, zv->zv_name); i++; assert(i <= zone_view_count); } /* * Print raw views for non kalloc or kalloc_type zones */ bool kalloc_type = zsflags.z_kalloc_type; if ((zsflags.z_kheap_id == KHEAP_ID_NONE && !kalloc_type) || (kalloc_type && has_raw_view)) { vm_page_diagnose_zone(counts + i, z); i++; assert(i <= zone_view_count); } } } process_account(info, num_info, zones_collectable_bytes, redact_info); return KERN_SUCCESS; } #if DEBUG || DEVELOPMENT kern_return_t vm_kern_allocation_info(uintptr_t addr, vm_size_t * size, vm_tag_t * tag, vm_size_t * zone_size) { kern_return_t ret; vm_size_t zsize; vm_map_entry_t entry; vm_map_t map = kernel_map; vmlp_api_start(VM_KERN_ALLOCATION_INFO); zsize = zone_element_info((void *) addr, tag); if (zsize) { *zone_size = *size = zsize; vmlp_api_end(VM_KERN_ALLOCATION_INFO, KERN_SUCCESS); return KERN_SUCCESS; } *zone_size = 0; VM_MAP_FIND_LOCK_CTX_DECLARE(ctx); vm_map_lock_ctx_set_preflight( ctx, ^kern_return_t (vm_map_lock_ctx_t vctx __unused, vm_map_entry_t vme) { /* * Because this function only works on kernel maps, we will run the * preflight even in child entries in submaps, since those submaps * are transparent. And we don't need to translate the address in * transparent submaps, so we can use `addr` directly. */ if (vme->vme_start != addr) { return KERN_INVALID_ADDRESS; } return KERN_SUCCESS; }); ret = vm_map_find_entry_sh_locked(ctx, &map, addr, VMRL_FIND_SH_NO_MIN_MAX_CHECK); if (ret != KERN_SUCCESS) { vmlp_api_end(VM_KERN_ALLOCATION_INFO, ret); return ret; } entry = vm_map_found_entry_get_entry(ctx); *tag = (vm_tag_t)VME_ALIAS(entry); *size = (entry->vme_end - addr); ret = KERN_SUCCESS; vm_map_found_entry_sh_unlock(ctx, &map); vmlp_api_end(VM_KERN_ALLOCATION_INFO, ret); return ret; } // some DEBUG/DEVELOPMENT code to get a process to page out its shared cache TEXT pages, // only used for DK driver in LPW testing uint64_t vm_task_evict_shared_cache(task_t task) { VM_MAP_LOCK_CTX_DECLARE(ctx); kern_return_t kr; vm_map_t map; vm_object_t textObject, shadow; vm_map_entry_t entry; vm_object_offset_t textOffset, textSize; uint64_t count; count = counter_load(&task->pageins); map = get_task_map(task); kr = vm_map_range_sh_lock(ctx, &map, VMRL_WHOLE_MAP_START, VMRL_WHOLE_MAP_END, VMRL_SH_STREAM | VMRL_SH_WHOLE_MAP | VMRL_SH_DESCEND_INTO_CONSTANT); if (kr != KERN_SUCCESS) { assert(kr == KERN_INVALID_ADDRESS); /* No entries in map */ return count; } while ((entry = vm_map_range_stream_next(ctx))) { if ((ctx->__vmlc_descended != VMLC_NOT_DESCENDED) && ((VM_PROT_EXECUTE | VM_PROT_READ) == entry->protection)) { break; /* we found the entry we wanted */ } } if (entry == VM_MAP_ENTRY_NULL) { /* didn't find a single entry we're interested in */ vm_map_range_sh_unlock(ctx, &map); return count; } textObject = VME_OBJECT(entry); vm_object_lock(textObject); while ((shadow = textObject->shadow)) { vm_object_lock(shadow); vm_object_unlock(textObject); textObject = shadow; } vm_object_reference_locked(textObject); vm_object_unlock(textObject); textOffset = VME_OFFSET(entry); textSize = entry->vme_end - entry->vme_start; vm_map_range_sh_unlock(ctx, &map); vm_object_sync(textObject, textOffset, textSize, true, false, false); vm_object_deallocate(textObject); return count; } uint64_t vm_task_pageins(task_t task) { return counter_load(&task->pageins); } #endif /* DEBUG || DEVELOPMENT */ uint32_t vm_tag_get_kext(vm_tag_t tag, char * name, vm_size_t namelen) { vm_allocation_site_t * site; uint32_t kmodId; kmodId = 0; lck_ticket_lock(&vm_allocation_sites_lock, &vm_page_lck_grp_bucket); if ((site = vm_allocation_sites[tag])) { if (VM_TAG_KMOD & site->flags) { kmodId = OSKextGetKmodIDForSite(site, name, namelen); } } lck_ticket_unlock(&vm_allocation_sites_lock); return kmodId; } #if CONFIG_SECLUDED_MEMORY /* * Note that there's no locking around other accesses to vm_page_secluded_target. * That should be OK, since these are the only place where it can be changed after * initialization. Other users (like vm_pageout) may see the wrong value briefly, * but will eventually get the correct value. This brief mismatch is OK as pageout * and page freeing will auto-adjust the vm_page_secluded_count to match the target * over time. */ unsigned int vm_page_secluded_suppress_cnt = 0; unsigned int vm_page_secluded_save_target; LCK_GRP_DECLARE(secluded_suppress_slock_grp, "secluded_suppress_slock"); LCK_SPIN_DECLARE(secluded_suppress_slock, &secluded_suppress_slock_grp); void start_secluded_suppression(task_t task) { if (task->task_suppressed_secluded) { return; } lck_spin_lock(&secluded_suppress_slock); if (!task->task_suppressed_secluded && vm_page_secluded_suppress_cnt++ == 0) { task->task_suppressed_secluded = TRUE; vm_page_secluded_save_target = vm_page_secluded_target; vm_page_secluded_target = 0; VM_PAGE_SECLUDED_COUNT_OVER_TARGET_UPDATE(); } lck_spin_unlock(&secluded_suppress_slock); } void stop_secluded_suppression(task_t task) { lck_spin_lock(&secluded_suppress_slock); if (task->task_suppressed_secluded && --vm_page_secluded_suppress_cnt == 0) { task->task_suppressed_secluded = FALSE; vm_page_secluded_target = vm_page_secluded_save_target; VM_PAGE_SECLUDED_COUNT_OVER_TARGET_UPDATE(); } lck_spin_unlock(&secluded_suppress_slock); } #endif /* CONFIG_SECLUDED_MEMORY */ /* * Move the list of retired pages on the vm_page_queue_retired to * their final resting place on retired_pages_object. */ void vm_retire_boot_pages(void) { } /* * This holds the reported physical address if an ECC error leads to a panic. * SMC will store it in PMU SRAM under the 'sECC' key. */ uint64_t ecc_panic_physical_address = 0; |