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 | /* * Copyright (c) 2000-2021 Apple Inc. All rights reserved. * * @Apple_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This 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 OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ #include <sys/errno.h> #include <sys/kdebug_private.h> #include <sys/proc_internal.h> #include <sys/vm.h> #include <sys/sysctl.h> #include <sys/kdebug_common.h> #include <sys/kdebug.h> #include <sys/kdebug_triage.h> #include <sys/kauth.h> #include <sys/ktrace.h> #include <sys/sysproto.h> #include <sys/bsdtask_info.h> #include <sys/random.h> #include <mach/mach_vm.h> #include <machine/atomic.h> #include <mach/machine.h> #include <mach/vm_map.h> #include <kern/clock.h> #include <kern/task.h> #include <kern/debug.h> #include <kern/kalloc.h> #include <kern/telemetry.h> #include <kern/sched_prim.h> #include <sys/lock.h> #include <pexpert/device_tree.h> #include <os/atomic.h> #include <sys/malloc.h> #include <sys/vnode.h> #include <sys/vnode_internal.h> #include <sys/fcntl.h> #include <sys/file_internal.h> #include <sys/ubc.h> #include <sys/param.h> /* for isset() */ #include <vm/vm_kern_xnu.h> #include <vm/vm_map_xnu.h> #include <libkern/OSAtomic.h> #include <machine/pal_routines.h> #include <machine/atomic.h> extern unsigned int wake_nkdbufs; extern unsigned int trace_wrap; // Coprocessors (or "IOP"s) // // Coprocessors are auxiliary cores that want to participate in kdebug event // logging. They are registered dynamically, as devices match hardware, and are // each assigned an ID at registration. // // Once registered, a coprocessor is permanent; it cannot be unregistered. // The current implementation depends on this for thread safety. // // The `kd_coprocs` list may be safely walked at any time, without holding // locks. // // When starting a trace session, the current `kd_coprocs` head is captured. Any // operations that depend on the buffer state (such as flushing IOP traces on // reads, etc.) should use the captured list head. This will allow registrations // to take place while trace is in use, though their events will be rejected // until the next time a trace session is started. struct kd_coproc { char full_name[32]; kdebug_coproc_flags_t flags; kd_callback_t callback; uint32_t cpu_id; struct kd_coproc *next; struct mpsc_queue_chain chain; }; static struct kd_coproc *kd_coprocs = NULL; // Use an MPSC queue to notify coprocessors of the current trace state during // registration, if space is available for them in the current trace session. static struct mpsc_daemon_queue _coproc_notify_queue; // Typefilter(s) // // A typefilter is a 8KB bitmap that is used to selectively filter events // being recorded. It is able to individually address every class & subclass. // // There is a shared typefilter in the kernel which is lazily allocated. Once // allocated, the shared typefilter is never deallocated. The shared typefilter // is also mapped on demand into userspace processes that invoke kdebug_trace // API from Libsyscall. When mapped into a userspace process, the memory is // read only, and does not have a fixed address. // // It is a requirement that the kernel's shared typefilter always pass DBG_TRACE // events. This is enforced automatically, by having the needed bits set any // time the shared typefilter is mutated. typedef uint8_t *typefilter_t; static typefilter_t kdbg_typefilter; static mach_port_t kdbg_typefilter_memory_entry; /* * There are 3 combinations of page sizes: * * 4KB / 4KB * 4KB / 16KB * 16KB / 16KB * * The typefilter is exactly 8KB. In the first two scenarios, we would like * to use 2 pages exactly; in the third scenario we must make certain that * a full page is allocated so we do not inadvertantly share 8KB of random * data to userspace. The round_page_32 macro rounds to kernel page size. */ #define TYPEFILTER_ALLOC_SIZE MAX(round_page_32(KDBG_TYPEFILTER_BITMAP_SIZE), KDBG_TYPEFILTER_BITMAP_SIZE) static typefilter_t typefilter_create(void) { typefilter_t tf; if (KERN_SUCCESS == kmem_alloc(kernel_map, (vm_offset_t*)&tf, TYPEFILTER_ALLOC_SIZE, KMA_DATA_SHARED | KMA_ZERO, VM_KERN_MEMORY_DIAG)) { return tf; } return NULL; } static void typefilter_deallocate(typefilter_t tf) { assert(tf != NULL); assert(tf != kdbg_typefilter); kmem_free(kernel_map, (vm_offset_t)tf, TYPEFILTER_ALLOC_SIZE); } static void typefilter_copy(typefilter_t dst, typefilter_t src) { assert(src != NULL); assert(dst != NULL); memcpy(dst, src, KDBG_TYPEFILTER_BITMAP_SIZE); } static void typefilter_reject_all(typefilter_t tf) { assert(tf != NULL); memset(tf, 0, KDBG_TYPEFILTER_BITMAP_SIZE); } static void typefilter_allow_all(typefilter_t tf) { assert(tf != NULL); memset(tf, ~0, KDBG_TYPEFILTER_BITMAP_SIZE); } static void typefilter_allow_class(typefilter_t tf, uint8_t class) { assert(tf != NULL); const uint32_t BYTES_PER_CLASS = 256 / 8; // 256 subclasses, 1 bit each memset(&tf[class * BYTES_PER_CLASS], 0xFF, BYTES_PER_CLASS); } static void typefilter_allow_csc(typefilter_t tf, uint16_t csc) { assert(tf != NULL); setbit(tf, csc); } static bool typefilter_is_debugid_allowed(typefilter_t tf, uint32_t id) { assert(tf != NULL); return isset(tf, KDBG_EXTRACT_CSC(id)); } static mach_port_t typefilter_create_memory_entry(typefilter_t tf) { assert(tf != NULL); mach_port_t memory_entry = MACH_PORT_NULL; memory_object_size_t size = TYPEFILTER_ALLOC_SIZE; kern_return_t kr = mach_make_memory_entry_64(kernel_map, &size, (memory_object_offset_t)tf, VM_PROT_READ, &memory_entry, MACH_PORT_NULL); if (kr != KERN_SUCCESS) { return MACH_PORT_NULL; } return memory_entry; } static int kdbg_copyin_typefilter(user_addr_t addr, size_t size); static void kdbg_enable_typefilter(void); static void kdbg_disable_typefilter(void); // External prototypes void commpage_update_kdebug_state(void); static int kdbg_readcurthrmap(user_addr_t, size_t *); static int kdbg_setpidex(kd_regtype *); static int kdbg_setpid(kd_regtype *); static int kdbg_reinit(unsigned int extra_cpus); #if DEVELOPMENT || DEBUG static int kdbg_test(size_t flavor); #endif /* DEVELOPMENT || DEBUG */ static int kdbg_copyout_thread_map(user_addr_t buffer, size_t *buffer_size); static void _clear_thread_map(void); static bool kdbg_wait(uint64_t timeout_ms); static void _try_wakeup_waiter(void); static void _wakeup_waiter(void); static int _copy_cpu_map(int version, void **dst, size_t *size); static kd_threadmap *_thread_map_create_live(size_t max_count, vm_size_t *map_size, vm_size_t *map_count); static bool kdebug_current_proc_enabled(uint32_t debugid); static errno_t kdebug_check_trace_string(uint32_t debugid, uint64_t str_id); #define RAW_FLUSH_SIZE (2 * 1024 * 1024) __enum_closed_decl(kd_dest_kind_t, uint32_t, { KD_DEST_COPYOUT = 0x1, KD_DEST_VFS = 0x2, }); struct kd_dest { kd_dest_kind_t kdd_kind; bool kdd_chunk_format; off_t kdd_cur_offset; union { struct { user_addr_t kdd_user_buffer; size_t kdd_user_size; }; struct { struct vfs_context kdd_vfs_ctx; vnode_t kdd_vnode; off_t kdd_file_written_since_flush; }; }; }; static inline struct kd_dest kd_dest_copyout(user_addr_t buf, size_t size) { return (struct kd_dest){ .kdd_kind = KD_DEST_COPYOUT, .kdd_user_buffer = buf, .kdd_user_size = size, }; } static inline int kd_dest_init_write(struct kd_dest *dest, int fd, struct fileproc **fp_out) { dest->kdd_kind = KD_DEST_VFS; proc_t p = current_proc(); struct fileproc *fp = NULL; if (fp_get_ftype(p, fd, DTYPE_VNODE, EBADF, &fp)) { return EBADF; } dest->kdd_vnode = fp_get_data(fp); int error = vnode_getwithref(dest->kdd_vnode); if (error != 0) { fp_drop(p, fd, fp, 0); return error; } dest->kdd_vfs_ctx.vc_thread = current_thread(); dest->kdd_vfs_ctx.vc_ucred = fp->fp_glob->fg_cred; dest->kdd_cur_offset = fp->fp_glob->fg_offset; *fp_out = fp; return 0; } static inline void kd_dest_finish_write(struct kd_dest *dest, struct fileproc *fp, int fd) { fp->fp_glob->fg_offset = dest->kdd_cur_offset; vnode_put(dest->kdd_vnode); fp_drop(current_proc(), fd, fp, 0); } static int _send_events(struct kd_dest *dest, const void *src, size_t event_count); static int kdbg_write_thread_map(struct kd_dest *dest); static int _write_legacy_header(bool write_thread_map, struct kd_dest *dest); extern void IOSleep(int); unsigned int kdebug_enable = 0; // A static buffer to record events prior to the start of regular logging. #define KD_EARLY_BUFFER_SIZE (16 * 1024) #define KD_EARLY_EVENT_COUNT (KD_EARLY_BUFFER_SIZE / sizeof(kd_buf)) #if defined(__x86_64__) __attribute__((aligned(KD_EARLY_BUFFER_SIZE))) static kd_buf kd_early_buffer[KD_EARLY_EVENT_COUNT]; #else /* defined(__x86_64__) */ // On ARM, the space for this is carved out by osfmk/arm/data.s -- clang // has problems aligning to greater than 4K. extern kd_buf kd_early_buffer[KD_EARLY_EVENT_COUNT]; #endif /* !defined(__x86_64__) */ static __security_const_late unsigned int kd_early_index = 0; static __security_const_late bool kd_early_overflow = false; static __security_const_late bool kd_early_done = false; static bool kd_waiter = false; static LCK_SPIN_DECLARE(kd_wait_lock, &kdebug_lck_grp); // Synchronize access to coprocessor list for kdebug trace. static LCK_SPIN_DECLARE(kd_coproc_spinlock, &kdebug_lck_grp); #define TRACE_KDCOPYBUF_COUNT 8192 #define TRACE_KDCOPYBUF_SIZE (TRACE_KDCOPYBUF_COUNT * sizeof(kd_buf)) struct kd_control kd_control_trace = { .kds_free_list = {.raw = KDS_PTR_NULL}, .enabled = 0, .mode = KDEBUG_MODE_TRACE, .kdebug_events_per_storage_unit = TRACE_EVENTS_PER_STORAGE_UNIT, .kdebug_min_storage_units_per_cpu = TRACE_MIN_STORAGE_UNITS_PER_CPU, .kdebug_kdcopybuf_count = TRACE_KDCOPYBUF_COUNT, .kdebug_kdcopybuf_size = TRACE_KDCOPYBUF_SIZE, .kdc_flags = 0, .kdc_emit = KDEMIT_DISABLE, .kdc_oldest_time = 0 }; struct kd_buffer kd_buffer_trace = { .kdb_event_count = 0, .kdb_storage_count = 0, .kdb_storage_threshold = 0, .kdb_region_count = 0, .kdb_info = NULL, .kd_bufs = NULL, .kdcopybuf = NULL }; unsigned int kdlog_beg = 0; unsigned int kdlog_end = 0; unsigned int kdlog_value1 = 0; unsigned int kdlog_value2 = 0; unsigned int kdlog_value3 = 0; unsigned int kdlog_value4 = 0; kd_threadmap *kd_mapptr = 0; vm_size_t kd_mapsize = 0; vm_size_t kd_mapcount = 0; /* * A globally increasing counter for identifying strings in trace. Starts at * 1 because 0 is a reserved return value. */ __attribute__((aligned(MAX_CPU_CACHE_LINE_SIZE))) static uint64_t g_curr_str_id = 1; #define STR_ID_SIG_OFFSET (48) #define STR_ID_MASK ((1ULL << STR_ID_SIG_OFFSET) - 1) #define STR_ID_SIG_MASK (~STR_ID_MASK) /* * A bit pattern for identifying string IDs generated by * kdebug_trace_string(2). */ static uint64_t g_str_id_signature = (0x70acULL << STR_ID_SIG_OFFSET); #define RAW_VERSION3 0x00001000 #define V3_RAW_EVENTS 0x00001e00 static void _coproc_lock(void) { lck_spin_lock_grp(&kd_coproc_spinlock, &kdebug_lck_grp); } static void _coproc_unlock(void) { lck_spin_unlock(&kd_coproc_spinlock); } static void _coproc_list_check(void) { #if MACH_ASSERT _coproc_lock(); struct kd_coproc *coproc = kd_control_trace.kdc_coprocs; if (coproc) { /* Is list sorted by cpu_id? */ struct kd_coproc* temp = coproc; do { assert(!temp->next || temp->next->cpu_id == temp->cpu_id - 1); assert(temp->next || (temp->cpu_id == kdbg_cpu_count())); } while ((temp = temp->next)); /* Does each entry have a function and a name? */ temp = coproc; do { assert(temp->callback.func); assert(strlen(temp->callback.iop_name) < sizeof(temp->callback.iop_name)); } while ((temp = temp->next)); } _coproc_unlock(); #endif // MACH_ASSERT } static void _coproc_list_callback(kd_callback_type type, void *arg) { if (kd_control_trace.kdc_flags & KDBG_DISABLE_COPROCS) { return; } _coproc_lock(); // Coprocessor list is only ever prepended to. struct kd_coproc *head = kd_control_trace.kdc_coprocs; _coproc_unlock(); while (head) { head->callback.func(head->callback.context, type, arg); head = head->next; } } // Leave some extra space for coprocessors to register while tracing is active. #define EXTRA_COPROC_COUNT (16) // There are more coprocessors registering during boot tracing. #define EXTRA_COPROC_COUNT_BOOT (32) static kdebug_emit_filter_t _trace_emit_filter(void) { if (!kdebug_enable) { return KDEMIT_DISABLE; } else if (kd_control_trace.kdc_flags & KDBG_TYPEFILTER_CHECK) { return KDEMIT_TYPEFILTER; } else if (kd_control_trace.kdc_flags & KDBG_RANGECHECK) { return KDEMIT_RANGE; } else if (kd_control_trace.kdc_flags & KDBG_VALCHECK) { return KDEMIT_EXACT; } else { return KDEMIT_ALL; } } static void kdbg_set_tracing_enabled(bool enabled, uint32_t trace_type) { // Drain any events from coprocessors before making the state change. On // enabling, this removes any stale events from before tracing. On // disabling, this saves any events up to the point tracing is disabled. _coproc_list_callback(KD_CALLBACK_SYNC_FLUSH, NULL); if (!enabled) { // Give coprocessors a chance to log any events before tracing is // disabled, outside the lock. _coproc_list_callback(KD_CALLBACK_KDEBUG_DISABLED, NULL); } int intrs_en = kdebug_storage_lock(&kd_control_trace); if (enabled) { // Latch the status of the user-controlled flags for wrapping. kd_control_trace.kdc_live_flags = kd_control_trace.kdc_flags & KDBG_NOWRAP; // The oldest valid time is now; reject past events from coprocessors. kd_control_trace.kdc_oldest_time = kdebug_timestamp(); kdebug_enable |= trace_type; kd_control_trace.kdc_emit = _trace_emit_filter(); kd_control_trace.enabled = 1; commpage_update_kdebug_state(); } else { kdebug_enable = 0; kd_control_trace.kdc_emit = KDEMIT_DISABLE; kd_control_trace.enabled = 0; commpage_update_kdebug_state(); } kdebug_storage_unlock(&kd_control_trace, intrs_en); if (enabled) { _coproc_list_callback(KD_CALLBACK_KDEBUG_ENABLED, NULL); } } static int create_buffers_trace(unsigned int extra_cpus) { int events_per_storage_unit = kd_control_trace.kdebug_events_per_storage_unit; int min_storage_units_per_cpu = kd_control_trace.kdebug_min_storage_units_per_cpu; // For the duration of this allocation, trace code will only reference // kdc_coprocs. kd_control_trace.kdc_coprocs = kd_coprocs; _coproc_list_check(); // If the list is valid, it is sorted from newest to oldest. Each entry is // prepended, so the CPU IDs are sorted in descending order. kd_control_trace.kdebug_cpus = kd_control_trace.kdc_coprocs ? kd_control_trace.kdc_coprocs->cpu_id + 1 : kdbg_cpu_count(); kd_control_trace.alloc_cpus = kd_control_trace.kdebug_cpus + extra_cpus; size_t min_event_count = kd_control_trace.alloc_cpus * events_per_storage_unit * min_storage_units_per_cpu; if (kd_buffer_trace.kdb_event_count < min_event_count) { kd_buffer_trace.kdb_storage_count = kd_control_trace.alloc_cpus * min_storage_units_per_cpu; } else { kd_buffer_trace.kdb_storage_count = kd_buffer_trace.kdb_event_count / events_per_storage_unit; } kd_buffer_trace.kdb_event_count = kd_buffer_trace.kdb_storage_count * events_per_storage_unit; kd_buffer_trace.kd_bufs = NULL; int error = create_buffers(&kd_control_trace, &kd_buffer_trace, VM_KERN_MEMORY_DIAG); if (!error) { struct kd_bufinfo *info = kd_buffer_trace.kdb_info; struct kd_coproc *cur_iop = kd_control_trace.kdc_coprocs; while (cur_iop != NULL) { info[cur_iop->cpu_id].continuous_timestamps = ISSET(cur_iop->flags, KDCP_CONTINUOUS_TIME); cur_iop = cur_iop->next; } kd_buffer_trace.kdb_storage_threshold = kd_buffer_trace.kdb_storage_count / 2; } return error; } static void delete_buffers_trace(void) { delete_buffers(&kd_control_trace, &kd_buffer_trace); } static int _register_coproc_internal(const char *name, kdebug_coproc_flags_t flags, kd_callback_fn callback, void *context) { struct kd_coproc *coproc = NULL; coproc = zalloc_permanent_type(struct kd_coproc); coproc->callback.func = callback; coproc->callback.context = context; coproc->flags = flags; strlcpy(coproc->full_name, name, sizeof(coproc->full_name)); _coproc_lock(); coproc->next = kd_coprocs; coproc->cpu_id = kd_coprocs == NULL ? kdbg_cpu_count() : kd_coprocs->cpu_id + 1; kd_coprocs = coproc; if (coproc->cpu_id < kd_control_trace.alloc_cpus) { kd_control_trace.kdc_coprocs = kd_coprocs; kd_control_trace.kdebug_cpus += 1; if (kdebug_enable) { mpsc_daemon_enqueue(&_coproc_notify_queue, &coproc->chain, MPSC_QUEUE_NONE); } } _coproc_unlock(); return coproc->cpu_id; } int kernel_debug_register_callback(kd_callback_t callback) { // Be paranoid about using the provided name, but it's too late to reject // it. bool is_valid_name = false; for (uint32_t length = 0; length < sizeof(callback.iop_name); ++length) { if (callback.iop_name[length] > 0x20 && callback.iop_name[length] < 0x7F) { continue; } if (callback.iop_name[length] == 0) { if (length) { is_valid_name = true; } break; } } kd_callback_t sane_cb = callback; if (!is_valid_name) { strlcpy(sane_cb.iop_name, "IOP-???", sizeof(sane_cb.iop_name)); } return _register_coproc_internal(sane_cb.iop_name, 0, sane_cb.func, sane_cb.context); } int kdebug_register_coproc(const char *name, kdebug_coproc_flags_t flags, kd_callback_fn callback, void *context) { size_t name_len = strlen(name); if (!name || name_len == 0) { panic("kdebug: invalid name for coprocessor: %p", name); } for (size_t i = 0; i < name_len; i++) { if (name[i] <= 0x20 || name[i] >= 0x7F) { panic("kdebug: invalid name for coprocessor: %s", name); } } if (!callback) { panic("kdebug: no callback for coprocessor `%s'", name); } return _register_coproc_internal(name, flags, callback, context); } static inline bool _should_emit_debugid(kdebug_emit_filter_t emit, uint32_t debugid) { switch (emit) { case KDEMIT_DISABLE: return false; case KDEMIT_TYPEFILTER: return typefilter_is_debugid_allowed(kdbg_typefilter, debugid); case KDEMIT_RANGE: return debugid >= kdlog_beg && debugid <= kdlog_end; case KDEMIT_EXACT:; uint32_t eventid = debugid & KDBG_EVENTID_MASK; return eventid == kdlog_value1 || eventid == kdlog_value2 || eventid == kdlog_value3 || eventid == kdlog_value4; case KDEMIT_ALL: return true; } } static void _try_wakeup_above_threshold(uint32_t debugid) { bool over_threshold = kd_control_trace.kdc_storage_used >= kd_buffer_trace.kdb_storage_threshold; if (kd_waiter && over_threshold) { // Wakeup any waiters if called from a safe context. const uint32_t INTERRUPT_EVENT = 0x01050000; const uint32_t VMFAULT_EVENT = 0x01300008; const uint32_t BSD_SYSCALL_CSC = 0x040c0000; const uint32_t MACH_SYSCALL_CSC = 0x010c0000; uint32_t eventid = debugid & KDBG_EVENTID_MASK; uint32_t csc = debugid & KDBG_CSC_MASK; if (eventid == INTERRUPT_EVENT || eventid == VMFAULT_EVENT || csc == BSD_SYSCALL_CSC || csc == MACH_SYSCALL_CSC) { _try_wakeup_waiter(); } } } __attribute__((always_inline)) static struct kd_storage * _next_storage_unit(struct kd_bufinfo *info, unsigned int cpu) { struct kd_storage *store = NULL; do { bool needs_new_store = true; union kds_ptr kds_raw = info->kd_list_tail; if (kds_raw.raw != KDS_PTR_NULL) { store = POINTER_FROM_KDS_PTR(kd_buffer_trace.kd_bufs, kds_raw); if (store->kds_bufindx < kd_control_trace.kdebug_events_per_storage_unit) { needs_new_store = false; } } if (!needs_new_store) { return store; } bool allocated = kdebug_storage_alloc(&kd_control_trace, &kd_buffer_trace, cpu); if (!allocated) { // Failed to allocate while wrapping is disabled. return NULL; } } while (true); } __attribute__((always_inline)) static kd_buf * _next_timestamped_coproc_record(unsigned int cpu, uint64_t timestamp) { struct kd_bufinfo *info = &kd_buffer_trace.kdb_info[cpu]; bool timestamp_is_continuous = info->continuous_timestamps; if (kdebug_using_continuous_time()) { if (!timestamp_is_continuous) { timestamp = absolutetime_to_continuoustime(timestamp); } } else { if (timestamp_is_continuous) { timestamp = continuoustime_to_absolutetime(timestamp); } } if (timestamp < kd_control_trace.kdc_oldest_time) { if (info->latest_past_event_timestamp < timestamp) { info->latest_past_event_timestamp = timestamp; } return NULL; } struct kd_storage *store = NULL; uint32_t store_index = 0; do { store = _next_storage_unit(info, cpu); if (!store) { return NULL; } store_index = store->kds_bufindx; // Prevent an interrupt from stealing this slot in the storage unit, // retrying if necessary. No barriers are needed because this only // concerns visibility on this same CPU. if (os_atomic_cmpxchg(&store->kds_bufindx, store_index, store_index + 1, relaxed)) { break; } } while (true); // Make sure kds_timestamp is less than any event in this buffer. This can // only happen for coprocessors because this field is initialized to the // current time when a storage unit is allocated by a CPU. if (timestamp < store->kds_timestamp) { store->kds_timestamp = timestamp; } os_atomic_inc(&store->kds_bufcnt, relaxed); kd_buf *kd = &store->kds_records[store_index]; kd->timestamp = timestamp; return kd; } __attribute__((always_inline)) static void _write_trace_record_coproc_nopreempt( uint64_t timestamp, uint32_t debugid, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3, uintptr_t arg4, uintptr_t arg5, unsigned int cpu) { if (kd_control_trace.enabled == 0) { return; } kd_buf *kd = _next_timestamped_coproc_record(cpu, timestamp); if (kd) { kd->debugid = debugid; kd->arg1 = arg1; kd->arg2 = arg2; kd->arg3 = arg3; kd->arg4 = arg4; kd->arg5 = arg5; kd->cpuid = cpu; } } __attribute__((always_inline)) static kd_buf * _next_timestamped_record(unsigned int cpu) { struct kd_bufinfo *info = &kd_buffer_trace.kdb_info[cpu]; struct kd_storage *store = NULL; uint64_t now = 0; uint32_t store_index = 0; do { store = _next_storage_unit(info, cpu); if (!store) { return NULL; } store_index = store->kds_bufindx; // Re-capture the timestamp to ensure time is monotonically-increasing // within storage units. now = kdebug_timestamp(); if (os_atomic_cmpxchg(&store->kds_bufindx, store_index, store_index + 1, relaxed)) { break; } } while (true); os_atomic_inc(&store->kds_bufcnt, relaxed); kd_buf *kd = &store->kds_records[store_index]; kd->timestamp = now; return kd; } static bool kdebug_debugid_procfilt_allowed(uint32_t debugid); static void _write_trace_record( uint32_t debugid, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3, uintptr_t arg4, uintptr_t arg5, kdebug_emit_flags_t flags) { kdebug_emit_filter_t emit = kd_control_trace.kdc_emit; if (!emit || !kdebug_enable) { return; } bool only_filter = flags & KDBG_FILTER_ONLY; bool observe_procfilt = !(flags & KDBG_NON_PROCESS); if (!_should_emit_debugid(emit, debugid)) { return; } if (emit == KDEMIT_ALL && only_filter) { return; } if (!ml_at_interrupt_context() && observe_procfilt && !kdebug_debugid_procfilt_allowed(debugid)) { return; } disable_preemption(); if (kd_control_trace.enabled == 0) { enable_preemption(); return; } unsigned int cpu = cpu_number(); kd_buf *kd = _next_timestamped_record(cpu); if (kd) { kd->debugid = debugid; kd->arg1 = arg1; kd->arg2 = arg2; kd->arg3 = arg3; kd->arg4 = arg4; kd->arg5 = arg5; kd->cpuid = cpu; } enable_preemption(); #if KPERF kperf_kdebug_callback(debugid, __builtin_frame_address(0)); #endif // KPERF } static void kernel_debug_internal( uint32_t debugid, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3, uintptr_t arg4, uintptr_t arg5, kdebug_emit_flags_t flags) { _write_trace_record(debugid, arg1, arg2, arg3, arg4, arg5, flags); _try_wakeup_above_threshold(debugid); } __attribute__((noinline)) void kernel_debug(uint32_t debugid, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3, uintptr_t arg4, __unused uintptr_t arg5) { uintptr_t tid = (uintptr_t)thread_tid(current_thread()); kernel_debug_internal(debugid, arg1, arg2, arg3, arg4, tid, 0); } __attribute__((noinline)) void kernel_debug1(uint32_t debugid, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3, uintptr_t arg4, uintptr_t arg5) { kernel_debug_internal(debugid, arg1, arg2, arg3, arg4, arg5, 0); } __attribute__((noinline)) void kernel_debug_flags( uint32_t debugid, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3, uintptr_t arg4, kdebug_emit_flags_t flags) { uintptr_t tid = (uintptr_t)thread_tid(current_thread()); kernel_debug_internal(debugid, arg1, arg2, arg3, arg4, tid, flags); } __attribute__((noinline)) void kernel_debug_filtered( uint32_t debugid, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3, uintptr_t arg4) { kernel_debug_flags(debugid, arg1, arg2, arg3, arg4, KDBG_FILTER_ONLY); } void kernel_debug_string_early(const char *message) { uintptr_t a[4] = { 0 }; strncpy((char *)a, message, sizeof(a)); KERNEL_DEBUG_EARLY(TRACE_INFO_STRING, a[0], a[1], a[2], a[3]); } // Emit events from coprocessors. void kernel_debug_enter( uint32_t coreid, uint32_t debugid, uint64_t timestamp, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3, uintptr_t arg4, uintptr_t threadid ) { if (kd_control_trace.kdc_flags & KDBG_DISABLE_COPROCS) { return; } if (coreid >= kd_control_trace.kdebug_cpus) { return; } kdebug_emit_filter_t emit = kd_control_trace.kdc_emit; if (!emit || !kdebug_enable) { return; } if (!_should_emit_debugid(emit, debugid)) { return; } disable_preemption(); _write_trace_record_coproc_nopreempt(timestamp, debugid, arg1, arg2, arg3, arg4, threadid, coreid); enable_preemption(); } __pure2 static inline proc_t kdebug_current_proc_unsafe(void) { return get_thread_ro_unchecked(current_thread())->tro_proc; } // Return true iff the debug ID should be traced by the current process. __attribute__((always_inline)) static bool kdebug_debugid_procfilt_allowed(uint32_t debugid) { uint32_t procfilt_flags = kd_control_trace.kdc_flags & (KDBG_PIDCHECK | KDBG_PIDEXCLUDE); if (!procfilt_flags) { return true; } // DBG_TRACE and MACH_SCHED tracepoints ignore the process filter. if ((debugid & KDBG_CSC_MASK) == MACHDBG_CODE(DBG_MACH_SCHED, 0) || (KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE)) { return true; } struct proc *curproc = kdebug_current_proc_unsafe(); // If the process is missing (early in boot), allow it. if (!curproc) { return true; } switch (procfilt_flags) { case KDBG_PIDCHECK: return curproc->p_kdebug; case KDBG_PIDEXCLUDE: return !curproc->p_kdebug; default: panic("kdebug: invalid procfilt flags %x", kd_control_trace.kdc_flags); } } #define SIMPLE_STR_LEN (64) static_assert(SIMPLE_STR_LEN % sizeof(uintptr_t) == 0); void kernel_debug_string_simple(uint32_t eventid, const char *str) { if (!kdebug_enable) { return; } /* array of uintptr_ts simplifies emitting the string as arguments */ uintptr_t str_buf[(SIMPLE_STR_LEN / sizeof(uintptr_t)) + 1] = { 0 }; size_t len = strlcpy((char *)str_buf, str, SIMPLE_STR_LEN + 1); len = MIN(len, SIMPLE_STR_LEN); uintptr_t thread_id = (uintptr_t)thread_tid(current_thread()); uint32_t debugid = eventid | DBG_FUNC_START; /* string can fit in a single tracepoint */ if (len <= (4 * sizeof(uintptr_t))) { debugid |= DBG_FUNC_END; } kernel_debug_internal(debugid, str_buf[0], str_buf[1], str_buf[2], str_buf[3], thread_id, 0); debugid &= KDBG_EVENTID_MASK; int i = 4; size_t written = 4 * sizeof(uintptr_t); for (; written < len; i += 4, written += 4 * sizeof(uintptr_t)) { /* if this is the last tracepoint to be emitted */ if ((written + (4 * sizeof(uintptr_t))) >= len) { debugid |= DBG_FUNC_END; } kernel_debug_internal(debugid, str_buf[i], str_buf[i + 1], str_buf[i + 2], str_buf[i + 3], thread_id, 0); } } extern int master_cpu; /* MACH_KERNEL_PRIVATE */ /* * Used prior to start_kern_tracing() being called. * Log temporarily into a static buffer. */ void kernel_debug_early( uint32_t debugid, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3, uintptr_t arg4) { #if defined(__x86_64__) extern int early_boot; /* * Note that "early" isn't early enough in some cases where * we're invoked before gsbase is set on x86, hence the * check of "early_boot". */ if (early_boot) { return; } #endif /* If early tracing is over, use the normal path. */ if (kd_early_done) { KDBG_RELEASE(debugid, arg1, arg2, arg3, arg4); return; } /* Do nothing if the buffer is full or we're not on the boot cpu. */ kd_early_overflow = kd_early_index >= KD_EARLY_EVENT_COUNT; if (kd_early_overflow || cpu_number() != master_cpu) { return; } kd_early_buffer[kd_early_index].debugid = debugid; kd_early_buffer[kd_early_index].timestamp = mach_absolute_time(); kd_early_buffer[kd_early_index].arg1 = arg1; kd_early_buffer[kd_early_index].arg2 = arg2; kd_early_buffer[kd_early_index].arg3 = arg3; kd_early_buffer[kd_early_index].arg4 = arg4; kd_early_buffer[kd_early_index].arg5 = 0; kd_early_index++; } /* * Transfer the contents of the temporary buffer into the trace buffers. * Precede that by logging the rebase time (offset) - the TSC-based time (in ns) * when mach_absolute_time is set to 0. */ static void kernel_debug_early_end(void) { if (cpu_number() != master_cpu) { panic("kernel_debug_early_end() not call on boot processor"); } /* reset the current oldest time to allow early events */ kd_control_trace.kdc_oldest_time = 0; #if defined(__x86_64__) /* Fake sentinel marking the start of kernel time relative to TSC */ kernel_debug_enter(0, TRACE_TIMESTAMPS, 0, (uint32_t)(tsc_rebase_abs_time >> 32), (uint32_t)tsc_rebase_abs_time, tsc_at_boot, 0, 0); #endif /* defined(__x86_64__) */ for (unsigned int i = 0; i < kd_early_index; i++) { kernel_debug_enter(0, kd_early_buffer[i].debugid, kd_early_buffer[i].timestamp, kd_early_buffer[i].arg1, kd_early_buffer[i].arg2, kd_early_buffer[i].arg3, kd_early_buffer[i].arg4, 0); } /* Cut events-lost event on overflow */ if (kd_early_overflow) { KDBG_RELEASE(TRACE_LOST_EVENTS, 1); } kd_early_done = true; /* This trace marks the start of kernel tracing */ kernel_debug_string_early("early trace done"); } void kernel_debug_disable(void) { kdbg_set_tracing_enabled(false, 0); _wakeup_waiter(); } // Returns true if debugid should only be traced from the kernel. static int _kernel_only_event(uint32_t debugid) { return KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE; } /* * Support syscall SYS_kdebug_typefilter. */ int kdebug_typefilter(__unused struct proc* p, struct kdebug_typefilter_args* uap, __unused int *retval) { if (uap->addr == USER_ADDR_NULL || uap->size == USER_ADDR_NULL) { return EINVAL; } mach_vm_offset_t user_addr = 0; vm_map_t user_map = current_map(); const bool copy = false; kern_return_t kr = mach_vm_map_kernel(user_map, &user_addr, TYPEFILTER_ALLOC_SIZE, 0, VM_MAP_KERNEL_FLAGS_ANYWHERE(), kdbg_typefilter_memory_entry, 0, copy, VM_PROT_READ, VM_PROT_READ, VM_INHERIT_SHARE); if (kr != KERN_SUCCESS) { return mach_to_bsd_errno(kr); } vm_size_t user_ptr_size = vm_map_is_64bit(user_map) ? 8 : 4; int error = copyout((void *)&user_addr, uap->addr, user_ptr_size); if (error != 0) { mach_vm_deallocate(user_map, user_addr, TYPEFILTER_ALLOC_SIZE); } return error; } // Support SYS_kdebug_trace. int kdebug_trace(struct proc *p, struct kdebug_trace_args *uap, int32_t *retval) { struct kdebug_trace64_args uap64 = { .code = uap->code, .arg1 = uap->arg1, .arg2 = uap->arg2, .arg3 = uap->arg3, .arg4 = uap->arg4, }; return kdebug_trace64(p, &uap64, retval); } // Support kdebug_trace(2). 64-bit arguments on K32 will get truncated // to fit in the 32-bit record format. // // It is intentional that error conditions are not checked until kdebug is // enabled. This is to match the userspace wrapper behavior, which is optimizing // for non-error case performance. int kdebug_trace64(__unused struct proc *p, struct kdebug_trace64_args *uap, __unused int32_t *retval) { if (__probable(kdebug_enable == 0)) { return 0; } if (_kernel_only_event(uap->code)) { return EPERM; } kernel_debug_internal(uap->code, (uintptr_t)uap->arg1, (uintptr_t)uap->arg2, (uintptr_t)uap->arg3, (uintptr_t)uap->arg4, (uintptr_t)thread_tid(current_thread()), 0); return 0; } /* * Adding enough padding to contain a full tracepoint for the last * portion of the string greatly simplifies the logic of splitting the * string between tracepoints. Full tracepoints can be generated using * the buffer itself, without having to manually add zeros to pad the * arguments. */ /* 2 string args in first tracepoint and 9 string data tracepoints */ #define STR_BUF_ARGS (2 + (32 * 4)) /* times the size of each arg on K64 */ #define MAX_STR_LEN (STR_BUF_ARGS * sizeof(uint64_t)) /* on K32, ending straddles a tracepoint, so reserve blanks */ #define STR_BUF_SIZE (MAX_STR_LEN + (2 * sizeof(uint32_t))) /* * This function does no error checking and assumes that it is called with * the correct arguments, including that the buffer pointed to by str is at * least STR_BUF_SIZE bytes. However, str must be aligned to word-size and * be NUL-terminated. In cases where a string can fit evenly into a final * tracepoint without its NUL-terminator, this function will not end those * strings with a NUL in trace. It's up to clients to look at the function * qualifier for DBG_FUNC_END in this case, to end the string. */ static uint64_t kernel_debug_string_internal(uint32_t debugid, uint64_t str_id, void *vstr, size_t str_len) { /* str must be word-aligned */ uintptr_t *str = vstr; size_t written = 0; uintptr_t thread_id; int i; uint32_t trace_debugid = TRACEDBG_CODE(DBG_TRACE_STRING, TRACE_STRING_GLOBAL); thread_id = (uintptr_t)thread_tid(current_thread()); /* if the ID is being invalidated, just emit that */ if (str_id != 0 && str_len == 0) { kernel_debug_internal(trace_debugid | DBG_FUNC_START | DBG_FUNC_END, (uintptr_t)debugid, (uintptr_t)str_id, 0, 0, thread_id, 0); return str_id; } /* generate an ID, if necessary */ if (str_id == 0) { str_id = OSIncrementAtomic64((SInt64 *)&g_curr_str_id); str_id = (str_id & STR_ID_MASK) | g_str_id_signature; } trace_debugid |= DBG_FUNC_START; /* string can fit in a single tracepoint */ if (str_len <= (2 * sizeof(uintptr_t))) { trace_debugid |= DBG_FUNC_END; } kernel_debug_internal(trace_debugid, (uintptr_t)debugid, (uintptr_t)str_id, str[0], str[1], thread_id, 0); trace_debugid &= KDBG_EVENTID_MASK; i = 2; written += 2 * sizeof(uintptr_t); for (; written < str_len; i += 4, written += 4 * sizeof(uintptr_t)) { if ((written + (4 * sizeof(uintptr_t))) >= str_len) { trace_debugid |= DBG_FUNC_END; } kernel_debug_internal(trace_debugid, str[i], str[i + 1], str[i + 2], str[i + 3], thread_id, 0); } return str_id; } /* * Returns true if the current process can emit events, and false otherwise. * Trace system and scheduling events circumvent this check, as do events * emitted in interrupt context. */ static bool kdebug_current_proc_enabled(uint32_t debugid) { /* can't determine current process in interrupt context */ if (ml_at_interrupt_context()) { return true; } /* always emit trace system and scheduling events */ if ((KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE || (debugid & KDBG_CSC_MASK) == MACHDBG_CODE(DBG_MACH_SCHED, 0))) { return true; } if (kd_control_trace.kdc_flags & KDBG_PIDCHECK) { proc_t cur_proc = kdebug_current_proc_unsafe(); /* only the process with the kdebug bit set is allowed */ if (cur_proc && !(cur_proc->p_kdebug)) { return false; } } else if (kd_control_trace.kdc_flags & KDBG_PIDEXCLUDE) { proc_t cur_proc = kdebug_current_proc_unsafe(); /* every process except the one with the kdebug bit set is allowed */ if (cur_proc && cur_proc->p_kdebug) { return false; } } return true; } bool kdebug_debugid_enabled(uint32_t debugid) { return _should_emit_debugid(kd_control_trace.kdc_emit, debugid); } bool kdebug_debugid_explicitly_enabled(uint32_t debugid) { if (kd_control_trace.kdc_flags & KDBG_TYPEFILTER_CHECK) { return typefilter_is_debugid_allowed(kdbg_typefilter, debugid); } else if (KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE) { return true; } else if (kd_control_trace.kdc_flags & KDBG_RANGECHECK) { if (debugid < kdlog_beg || debugid > kdlog_end) { return false; } } else if (kd_control_trace.kdc_flags & KDBG_VALCHECK) { if ((debugid & KDBG_EVENTID_MASK) != kdlog_value1 && (debugid & KDBG_EVENTID_MASK) != kdlog_value2 && (debugid & KDBG_EVENTID_MASK) != kdlog_value3 && (debugid & KDBG_EVENTID_MASK) != kdlog_value4) { return false; } } return true; } /* * Returns 0 if a string can be traced with these arguments. Returns errno * value if error occurred. */ static errno_t kdebug_check_trace_string(uint32_t debugid, uint64_t str_id) { if (debugid & (DBG_FUNC_START | DBG_FUNC_END)) { return EINVAL; } if (_kernel_only_event(debugid)) { return EPERM; } if (str_id != 0 && (str_id & STR_ID_SIG_MASK) != g_str_id_signature) { return EINVAL; } return 0; } /* * Implementation of KPI kernel_debug_string. */ int kernel_debug_string(uint32_t debugid, uint64_t *str_id, const char *str) { /* arguments to tracepoints must be word-aligned */ __attribute__((aligned(sizeof(uintptr_t)))) char str_buf[STR_BUF_SIZE]; static_assert(sizeof(str_buf) > MAX_STR_LEN); vm_size_t len_copied; int err; assert(str_id); if (__probable(kdebug_enable == 0)) { return 0; } if (!kdebug_current_proc_enabled(debugid)) { return 0; } if (!kdebug_debugid_enabled(debugid)) { return 0; } if ((err = kdebug_check_trace_string(debugid, *str_id)) != 0) { return err; } if (str == NULL) { if (str_id == 0) { return EINVAL; } *str_id = kernel_debug_string_internal(debugid, *str_id, NULL, 0); return 0; } memset(str_buf, 0, sizeof(str_buf)); len_copied = strlcpy(str_buf, str, MAX_STR_LEN + 1); *str_id = kernel_debug_string_internal(debugid, *str_id, str_buf, len_copied); return 0; } // Support kdebug_trace_string(2). int kdebug_trace_string(__unused struct proc *p, struct kdebug_trace_string_args *uap, uint64_t *retval) { __attribute__((aligned(sizeof(uintptr_t)))) char str_buf[STR_BUF_SIZE]; static_assert(sizeof(str_buf) > MAX_STR_LEN); size_t len_copied; int err; if (__probable(kdebug_enable == 0)) { return 0; } if (!kdebug_current_proc_enabled(uap->debugid)) { return 0; } if (!kdebug_debugid_enabled(uap->debugid)) { return 0; } if ((err = kdebug_check_trace_string(uap->debugid, uap->str_id)) != 0) { return err; } if (uap->str == USER_ADDR_NULL) { if (uap->str_id == 0) { return EINVAL; } *retval = kernel_debug_string_internal(uap->debugid, uap->str_id, NULL, 0); return 0; } memset(str_buf, 0, sizeof(str_buf)); err = copyinstr(uap->str, str_buf, MAX_STR_LEN + 1, &len_copied); /* it's alright to truncate the string, so allow ENAMETOOLONG */ if (err == ENAMETOOLONG) { str_buf[MAX_STR_LEN] = '\0'; } else if (err) { return err; } if (len_copied <= 1) { return EINVAL; } /* convert back to a length */ len_copied--; *retval = kernel_debug_string_internal(uap->debugid, uap->str_id, str_buf, len_copied); return 0; } int kdbg_reinit(unsigned int extra_cpus) { kernel_debug_disable(); // Wait for any event writers to see the disable status. IOSleep(100); delete_buffers_trace(); _clear_thread_map(); kd_control_trace.kdc_live_flags &= ~KDBG_WRAPPED; return create_buffers_trace(extra_cpus); } void kdbg_trace_data(struct proc *proc, long *arg_pid, long *arg_uniqueid) { if (proc) { *arg_pid = proc_getpid(proc); *arg_uniqueid = (long)proc_uniqueid(proc); if ((uint64_t)*arg_uniqueid != proc_uniqueid(proc)) { *arg_uniqueid = 0; } } else { *arg_pid = 0; *arg_uniqueid = 0; } } void kdebug_proc_name_args(struct proc *proc, long args[static 4]); void kdebug_proc_name_args(struct proc *proc, long args[static 4]) { if (proc) { strncpy((char *)args, proc_best_name(proc), 4 * sizeof(args[0])); } } static void _copy_ap_name(unsigned int cpuid, void *dst, size_t size) { const char *name = "AP"; #if defined(__arm64__) const ml_topology_info_t *topology = ml_get_topology_info(); switch (topology->cpus[cpuid].cluster_type) { case CLUSTER_TYPE_E: name = "AP-E"; break; case CLUSTER_TYPE_P: name = "AP-P"; break; default: break; } #else /* defined(__arm64__) */ #pragma unused(cpuid) #endif /* !defined(__arm64__) */ strlcpy(dst, name, size); } // Write the specified `map_version` of CPU map to the `dst` buffer, using at // most `size` bytes. Returns 0 on success and sets `size` to the number of // bytes written, and either ENOMEM or EINVAL on failure. // // If the value pointed to by `dst` is NULL, memory is allocated, and `size` is // adjusted to the allocated buffer's size. // // NB: `coprocs` is used to determine whether the stashed CPU map captured at // the start of tracing should be used. static errno_t _copy_cpu_map(int map_version, void **dst, size_t *size) { _coproc_lock(); struct kd_coproc *coprocs = kd_control_trace.kdc_coprocs; unsigned int cpu_count = kd_control_trace.kdebug_cpus; _coproc_unlock(); assert(cpu_count != 0); assert(coprocs == NULL || coprocs[0].cpu_id + 1 == cpu_count); bool ext = map_version != RAW_VERSION1; size_t stride = ext ? sizeof(kd_cpumap_ext) : sizeof(kd_cpumap); size_t size_needed = sizeof(kd_cpumap_header) + cpu_count * stride; size_t size_avail = *size; *size = size_needed; if (*dst == NULL) { kern_return_t alloc_ret = kmem_alloc(kernel_map, (vm_offset_t *)dst, (vm_size_t)size_needed, KMA_DATA_SHARED | KMA_ZERO, VM_KERN_MEMORY_DIAG); if (alloc_ret != KERN_SUCCESS) { return ENOMEM; } } else if (size_avail < size_needed) { return EINVAL; } kd_cpumap_header *header = *dst; header->version_no = map_version; header->cpu_count = cpu_count; void *cpus = &header[1]; size_t name_size = ext ? sizeof(((kd_cpumap_ext *)NULL)->name) : sizeof(((kd_cpumap *)NULL)->name); int i = cpu_count - 1; for (struct kd_coproc *cur_coproc = coprocs; cur_coproc != NULL; cur_coproc = cur_coproc->next, i--) { kd_cpumap_ext *cpu = (kd_cpumap_ext *)((uintptr_t)cpus + stride * i); cpu->cpu_id = cur_coproc->cpu_id; cpu->flags = KDBG_CPUMAP_IS_IOP; strlcpy((void *)&cpu->name, cur_coproc->full_name, name_size); } for (; i >= 0; i--) { kd_cpumap *cpu = (kd_cpumap *)((uintptr_t)cpus + stride * i); cpu->cpu_id = i; cpu->flags = 0; _copy_ap_name(i, &cpu->name, name_size); } return 0; } static void _threadmap_init(void) { ktrace_assert_lock_held(); if (kd_control_trace.kdc_flags & KDBG_MAPINIT) { return; } kd_mapptr = _thread_map_create_live(0, &kd_mapsize, &kd_mapcount); if (kd_mapptr) { kd_control_trace.kdc_flags |= KDBG_MAPINIT; } } struct kd_resolver { kd_threadmap *krs_map; vm_size_t krs_count; vm_size_t krs_maxcount; }; static int _resolve_iterator(proc_t proc, void *opaque) { if (proc == kernproc) { /* Handled specially as it lacks uthreads. */ return PROC_RETURNED; } struct kd_resolver *resolver = opaque; struct uthread *uth = NULL; const char *proc_name = proc_best_name(proc); pid_t pid = proc_getpid(proc); proc_lock(proc); TAILQ_FOREACH(uth, &proc->p_uthlist, uu_list) { if (resolver->krs_count >= resolver->krs_maxcount) { break; } kd_threadmap *map = &resolver->krs_map[resolver->krs_count]; map->thread = (uintptr_t)uthread_tid(uth); (void)strlcpy(map->command, proc_name, sizeof(map->command)); map->valid = pid; resolver->krs_count++; } proc_unlock(proc); bool done = resolver->krs_count >= resolver->krs_maxcount; return done ? PROC_RETURNED_DONE : PROC_RETURNED; } static void _resolve_kernel_task(thread_t thread, void *opaque) { struct kd_resolver *resolver = opaque; if (resolver->krs_count >= resolver->krs_maxcount) { return; } kd_threadmap *map = &resolver->krs_map[resolver->krs_count]; map->thread = (uintptr_t)thread_tid(thread); (void)strlcpy(map->command, "kernel_task", sizeof(map->command)); map->valid = 1; resolver->krs_count++; } static vm_size_t _resolve_threads(kd_threadmap *map, vm_size_t nthreads) { struct kd_resolver resolver = { .krs_map = map, .krs_count = 0, .krs_maxcount = nthreads, }; // Handle kernel_task specially, as it lacks uthreads. extern void task_act_iterate_wth_args(task_t, void (*)(thread_t, void *), void *); task_act_iterate_wth_args(kernel_task, _resolve_kernel_task, &resolver); proc_iterate(PROC_ALLPROCLIST | PROC_NOWAITTRANS, _resolve_iterator, &resolver, NULL, NULL); return resolver.krs_count; } static kd_threadmap * _thread_map_create_live(size_t maxthreads, vm_size_t *mapsize, vm_size_t *mapcount) { kd_threadmap *thread_map = NULL; assert(mapsize != NULL); assert(mapcount != NULL); extern int threads_count; vm_size_t nthreads = threads_count; // Allow 25% more threads to be started while iterating processes. if (os_add_overflow(nthreads, nthreads / 4, &nthreads)) { return NULL; } *mapcount = nthreads; if (os_mul_overflow(nthreads, sizeof(kd_threadmap), mapsize)) { return NULL; } // Wait until the out-parameters have been filled with the needed size to // do the bounds checking on the provided maximum. if (maxthreads != 0 && maxthreads < nthreads) { return NULL; } // This allocation can be too large for `Z_NOFAIL`. thread_map = kalloc_data_tag(*mapsize, Z_WAITOK | Z_ZERO, VM_KERN_MEMORY_DIAG); if (thread_map != NULL) { *mapcount = _resolve_threads(thread_map, nthreads); } return thread_map; } static void kdbg_clear(void) { kernel_debug_disable(); kdbg_disable_typefilter(); // Wait for any event writers to see the disable status. IOSleep(100); // Reset kdebug status for each process. if (kd_control_trace.kdc_flags & (KDBG_PIDCHECK | KDBG_PIDEXCLUDE)) { proc_list_lock(); proc_t p; ALLPROC_FOREACH(p) { p->p_kdebug = 0; } proc_list_unlock(); } kd_control_trace.kdc_flags &= (unsigned int)~KDBG_CKTYPES; kd_control_trace.kdc_flags &= ~(KDBG_RANGECHECK | KDBG_VALCHECK); kd_control_trace.kdc_flags &= ~(KDBG_PIDCHECK | KDBG_PIDEXCLUDE); kd_control_trace.kdc_flags &= ~KDBG_CONTINUOUS_TIME; kd_control_trace.kdc_flags &= ~KDBG_DISABLE_COPROCS; kd_control_trace.kdc_flags &= ~KDBG_MATCH_DISABLE; kd_control_trace.kdc_flags &= ~(KDBG_NOWRAP | KDBG_WRAPPED); kd_control_trace.kdc_live_flags &= ~(KDBG_NOWRAP | KDBG_WRAPPED); kd_control_trace.kdc_oldest_time = 0; delete_buffers_trace(); kd_buffer_trace.kdb_event_count = 0; _clear_thread_map(); } void kdebug_reset(void) { ktrace_assert_lock_held(); kdbg_clear(); typefilter_reject_all(kdbg_typefilter); typefilter_allow_class(kdbg_typefilter, DBG_TRACE); } void kdebug_free_early_buf(void) { #if defined(__x86_64__) ml_static_mfree((vm_offset_t)&kd_early_buffer, sizeof(kd_early_buffer)); #endif /* defined(__x86_64__) */ // ARM handles this as part of the BOOTDATA segment. } int kdbg_setpid(kd_regtype *kdr) { pid_t pid; int flag, ret = 0; struct proc *p; pid = (pid_t)kdr->value1; flag = (int)kdr->value2; if (pid >= 0) { if ((p = proc_find(pid)) == NULL) { ret = ESRCH; } else { if (flag == 1) { /* * turn on pid check for this and all pids */ kd_control_trace.kdc_flags |= KDBG_PIDCHECK; kd_control_trace.kdc_flags &= ~KDBG_PIDEXCLUDE; p->p_kdebug = 1; } else { /* * turn off pid check for this pid value * Don't turn off all pid checking though * * kd_control_trace.kdc_flags &= ~KDBG_PIDCHECK; */ p->p_kdebug = 0; } proc_rele(p); } } else { ret = EINVAL; } return ret; } /* This is for pid exclusion in the trace buffer */ int kdbg_setpidex(kd_regtype *kdr) { pid_t pid; int flag, ret = 0; struct proc *p; pid = (pid_t)kdr->value1; flag = (int)kdr->value2; if (pid >= 0) { if ((p = proc_find(pid)) == NULL) { ret = ESRCH; } else { if (flag == 1) { /* * turn on pid exclusion */ kd_control_trace.kdc_flags |= KDBG_PIDEXCLUDE; kd_control_trace.kdc_flags &= ~KDBG_PIDCHECK; p->p_kdebug = 1; } else { /* * turn off pid exclusion for this pid value * Don't turn off all pid exclusion though * * kd_control_trace.kdc_flags &= ~KDBG_PIDEXCLUDE; */ p->p_kdebug = 0; } proc_rele(p); } } else { ret = EINVAL; } return ret; } /* * The following functions all operate on the typefilter singleton. */ static int kdbg_copyin_typefilter(user_addr_t addr, size_t size) { int ret = ENOMEM; typefilter_t tf; ktrace_assert_lock_held(); if (size != KDBG_TYPEFILTER_BITMAP_SIZE) { return EINVAL; } if ((tf = typefilter_create())) { if ((ret = copyin(addr, tf, KDBG_TYPEFILTER_BITMAP_SIZE)) == 0) { /* The kernel typefilter must always allow DBG_TRACE */ typefilter_allow_class(tf, DBG_TRACE); typefilter_copy(kdbg_typefilter, tf); kdbg_enable_typefilter(); _coproc_list_callback(KD_CALLBACK_TYPEFILTER_CHANGED, kdbg_typefilter); } if (tf) { typefilter_deallocate(tf); } } return ret; } /* * Enable the flags in the control page for the typefilter. Assumes that * kdbg_typefilter has already been allocated, so events being written * don't see a bad typefilter. */ static void kdbg_enable_typefilter(void) { kd_control_trace.kdc_flags &= ~(KDBG_RANGECHECK | KDBG_VALCHECK); kd_control_trace.kdc_flags |= KDBG_TYPEFILTER_CHECK; if (kdebug_enable) { kd_control_trace.kdc_emit = _trace_emit_filter(); } commpage_update_kdebug_state(); } // Disable the flags in the control page for the typefilter. The typefilter // may be safely deallocated shortly after this function returns. static void kdbg_disable_typefilter(void) { bool notify_coprocs = kd_control_trace.kdc_flags & KDBG_TYPEFILTER_CHECK; kd_control_trace.kdc_flags &= ~KDBG_TYPEFILTER_CHECK; commpage_update_kdebug_state(); if (notify_coprocs) { // Notify coprocessors that the typefilter will now allow everything. // Otherwise, they won't know a typefilter is no longer in effect. typefilter_allow_all(kdbg_typefilter); _coproc_list_callback(KD_CALLBACK_TYPEFILTER_CHANGED, kdbg_typefilter); } } uint32_t kdebug_commpage_state(void) { uint32_t state = 0; if (kdebug_enable) { state |= KDEBUG_COMMPAGE_ENABLE_TRACE; if (kd_control_trace.kdc_flags & KDBG_TYPEFILTER_CHECK) { state |= KDEBUG_COMMPAGE_ENABLE_TYPEFILTER; } if (kd_control_trace.kdc_flags & KDBG_CONTINUOUS_TIME) { state |= KDEBUG_COMMPAGE_CONTINUOUS; } } return state; } static int kdbg_setreg(kd_regtype * kdr) { switch (kdr->type) { case KDBG_CLASSTYPE: kdlog_beg = KDBG_EVENTID(kdr->value1 & 0xff, 0, 0); kdlog_end = KDBG_EVENTID(kdr->value2 & 0xff, 0, 0); kd_control_trace.kdc_flags &= ~KDBG_VALCHECK; kd_control_trace.kdc_flags |= KDBG_RANGECHECK; break; case KDBG_SUBCLSTYPE:; unsigned int cls = kdr->value1 & 0xff; unsigned int subcls = kdr->value2 & 0xff; unsigned int subcls_end = subcls + 1; kdlog_beg = KDBG_EVENTID(cls, subcls, 0); kdlog_end = KDBG_EVENTID(cls, subcls_end, 0); kd_control_trace.kdc_flags &= ~KDBG_VALCHECK; kd_control_trace.kdc_flags |= KDBG_RANGECHECK; break; case KDBG_RANGETYPE: kdlog_beg = kdr->value1; kdlog_end = kdr->value2; kd_control_trace.kdc_flags &= ~KDBG_VALCHECK; kd_control_trace.kdc_flags |= KDBG_RANGECHECK; break; case KDBG_VALCHECK: kdlog_value1 = kdr->value1; kdlog_value2 = kdr->value2; kdlog_value3 = kdr->value3; kdlog_value4 = kdr->value4; kd_control_trace.kdc_flags &= ~KDBG_RANGECHECK; kd_control_trace.kdc_flags |= KDBG_VALCHECK; break; case KDBG_TYPENONE: kd_control_trace.kdc_flags &= ~(KDBG_RANGECHECK | KDBG_VALCHECK); kdlog_beg = 0; kdlog_end = 0; break; default: return EINVAL; } if (kdebug_enable) { kd_control_trace.kdc_emit = _trace_emit_filter(); } return 0; } static int _copyin_event_disable_mask(user_addr_t uaddr, size_t usize) { if (usize < 2 * sizeof(kd_event_matcher)) { return ERANGE; } int ret = copyin(uaddr, &kd_control_trace.disable_event_match, sizeof(kd_event_matcher)); if (ret != 0) { return ret; } ret = copyin(uaddr + sizeof(kd_event_matcher), &kd_control_trace.disable_event_mask, sizeof(kd_event_matcher)); if (ret != 0) { memset(&kd_control_trace.disable_event_match, 0, sizeof(kd_event_matcher)); return ret; } return 0; } static int _copyout_event_disable_mask(user_addr_t uaddr, size_t usize) { if (usize < 2 * sizeof(kd_event_matcher)) { return ERANGE; } int ret = copyout(&kd_control_trace.disable_event_match, uaddr, sizeof(kd_event_matcher)); if (ret != 0) { return ret; } ret = copyout(&kd_control_trace.disable_event_mask, uaddr + sizeof(kd_event_matcher), sizeof(kd_event_matcher)); if (ret != 0) { return ret; } return 0; } static errno_t _copyout_cpu_map(int map_version, user_addr_t udst, size_t *usize) { if ((kd_control_trace.kdc_flags & KDBG_BUFINIT) == 0) { return EINVAL; } void *cpu_map = NULL; size_t size = 0; int error = _copy_cpu_map(map_version, &cpu_map, &size); if (0 == error) { if (udst) { size_t copy_size = MIN(*usize, size); error = copyout(cpu_map, udst, copy_size); } *usize = size; kmem_free(kernel_map, (vm_offset_t)cpu_map, size); } if (EINVAL == error && 0 == udst) { *usize = size; // User space only needs the size if it passes NULL; error = 0; } return error; } int kdbg_readcurthrmap(user_addr_t buffer, size_t *bufsize) { kd_threadmap *mapptr; vm_size_t mapsize; vm_size_t mapcount; int ret = 0; size_t count = *bufsize / sizeof(kd_threadmap); *bufsize = 0; if ((mapptr = _thread_map_create_live(count, &mapsize, &mapcount))) { if (copyout(mapptr, buffer, mapcount * sizeof(kd_threadmap))) { ret = EFAULT; } else { *bufsize = (mapcount * sizeof(kd_threadmap)); } kfree_data(mapptr, mapsize); } else { ret = EINVAL; } return ret; } static void _clear_thread_map(void) { ktrace_assert_lock_held(); if (kd_control_trace.kdc_flags & KDBG_MAPINIT) { assert(kd_mapptr != NULL); kfree_data(kd_mapptr, kd_mapsize); kd_mapptr = NULL; kd_mapsize = 0; kd_mapcount = 0; kd_control_trace.kdc_flags &= ~KDBG_MAPINIT; } } /* * Write out a version 1 header and the thread map, if it is initialized, to a * vnode. Used by KDWRITEMAP and kdbg_dump_trace_to_file. * * Returns write errors from vn_rdwr if a write fails. Returns ENODATA if the * thread map has not been initialized, but the header will still be written. * Returns ENOMEM if padding could not be allocated. Returns 0 otherwise. */ static int kdbg_write_thread_map(struct kd_dest *dest) { ktrace_assert_lock_held(); if (dest->kdd_kind != KD_DEST_VFS) { panic("kdebug: must write thread map to VFS"); } bool map_initialized = (kd_control_trace.kdc_flags & KDBG_MAPINIT); int ret = _write_legacy_header(map_initialized, dest); if (ret == 0) { if (map_initialized) { _clear_thread_map(); } else { ret = ENODATA; } } return ret; } /* * Copy out the thread map to a user space buffer. Used by KDTHRMAP. * * Returns copyout errors if the copyout fails. Returns ENODATA if the thread * map has not been initialized. Returns EINVAL if the buffer provided is not * large enough for the entire thread map. Returns 0 otherwise. */ static int kdbg_copyout_thread_map(user_addr_t buffer, size_t *buffer_size) { bool map_initialized; size_t map_size; int ret = 0; ktrace_assert_lock_held(); assert(buffer_size != NULL); map_initialized = (kd_control_trace.kdc_flags & KDBG_MAPINIT); if (!map_initialized) { return ENODATA; } map_size = kd_mapcount * sizeof(kd_threadmap); if (*buffer_size < map_size) { return EINVAL; } ret = copyout(kd_mapptr, buffer, map_size); if (ret == 0) { _clear_thread_map(); } return ret; } static void kdbg_set_nkdbufs_trace(unsigned int req_nkdbufs_trace) { /* * Only allow allocations of up to half the kernel's data range or "sane * size", whichever is smaller. */ kmem_range_id_t range_id = kmem_needs_data_share_range() ? KMEM_RANGE_ID_DATA_SHARED : KMEM_RANGE_ID_DATA; const uint64_t max_nkdbufs_trace_64 = MIN(kmem_range_id_size(range_id), sane_size) / 2 / sizeof(kd_buf); /* * Can't allocate more than 2^38 (2^32 * 64) bytes of events without * switching to a 64-bit event count; should be fine. */ const unsigned int max_nkdbufs_trace = (unsigned int)MIN(max_nkdbufs_trace_64, UINT_MAX); kd_buffer_trace.kdb_event_count = MIN(req_nkdbufs_trace, max_nkdbufs_trace); } /* * Block until there are `kd_buffer_trace.kdb_storage_threshold` storage units filled with * events or `timeout_ms` milliseconds have passed. If `locked_wait` is true, * `ktrace_lock` is held while waiting. This is necessary while waiting to * write events out of the buffers. * * Returns true if the threshold was reached and false otherwise. * * Called with `ktrace_lock` locked and interrupts enabled. */ static bool kdbg_wait(uint64_t timeout_ms) { int wait_result = THREAD_AWAKENED; uint64_t deadline_mach = 0; ktrace_assert_lock_held(); if (timeout_ms != 0) { uint64_t ns = timeout_ms * NSEC_PER_MSEC; nanoseconds_to_absolutetime(ns, &deadline_mach); clock_absolutetime_interval_to_deadline(deadline_mach, &deadline_mach); } bool s = ml_set_interrupts_enabled(false); if (!s) { panic("kdbg_wait() called with interrupts disabled"); } lck_spin_lock_grp(&kd_wait_lock, &kdebug_lck_grp); /* drop the mutex to allow others to access trace */ ktrace_unlock(); while (wait_result == THREAD_AWAKENED && kd_control_trace.kdc_storage_used < kd_buffer_trace.kdb_storage_threshold) { kd_waiter = true; if (deadline_mach) { wait_result = lck_spin_sleep_deadline(&kd_wait_lock, 0, &kd_waiter, THREAD_ABORTSAFE, deadline_mach); } else { wait_result = lck_spin_sleep(&kd_wait_lock, 0, &kd_waiter, THREAD_ABORTSAFE); } } bool threshold_exceeded = (kd_control_trace.kdc_storage_used >= kd_buffer_trace.kdb_storage_threshold); lck_spin_unlock(&kd_wait_lock); ml_set_interrupts_enabled(s); ktrace_lock(); return threshold_exceeded; } /* * Wakeup a thread waiting using `kdbg_wait` if there are at least * `kd_buffer_trace.kdb_storage_threshold` storage units in use. */ static void _try_wakeup_waiter(void) { bool need_kds_wakeup = false; /* * Try to take the lock here to synchronize with the waiter entering * the blocked state. Use the try mode to prevent deadlocks caused by * re-entering this routine due to various trace points triggered in the * lck_spin_sleep_xxxx routines used to actually enter one of our 2 wait * conditions. No problem if we fail, there will be lots of additional * events coming in that will eventually succeed in grabbing this lock. */ bool s = ml_set_interrupts_enabled(false); if (lck_spin_try_lock(&kd_wait_lock)) { if (kd_waiter && (kd_control_trace.kdc_storage_used >= kd_buffer_trace.kdb_storage_threshold)) { kd_waiter = 0; need_kds_wakeup = true; } lck_spin_unlock(&kd_wait_lock); } ml_set_interrupts_enabled(s); if (need_kds_wakeup == true) { wakeup(&kd_waiter); } } static void _wakeup_waiter(void) { bool was_waiting = false; bool s = ml_set_interrupts_enabled(false); lck_spin_lock(&kd_wait_lock); if (kd_waiter) { was_waiting = true; kd_waiter = 0; } lck_spin_unlock(&kd_wait_lock); ml_set_interrupts_enabled(s); if (was_waiting) { wakeup(&kd_waiter); } } static void _storage_free(struct kd_control *kd_ctrl_page, struct kd_buffer *kd_data_page, int cpu, uint32_t kdsp_raw) { struct kd_storage *kdsp_actual; struct kd_bufinfo *kdbp; union kds_ptr kdsp; kdbp = &kd_data_page->kdb_info[cpu]; kdsp.raw = kdsp_raw; int intrs_en = kdebug_storage_lock(kd_ctrl_page); if (kdsp.raw == kdbp->kd_list_head.raw) { /* * it's possible for the storage unit pointed to * by kdsp to have already been stolen... so * check to see if it's still the head of the list * now that we're behind the lock that protects * adding and removing from the queue... * since we only ever release and steal units from * that position, if it's no longer the head * we having nothing to do in this context */ kdsp_actual = POINTER_FROM_KDS_PTR(kd_data_page->kd_bufs, kdsp); kdbp->kd_list_head = kdsp_actual->kds_next; kdsp_actual->kds_next = kd_ctrl_page->kds_free_list; kd_ctrl_page->kds_free_list = kdsp; kd_ctrl_page->kdc_storage_used--; } kdebug_storage_unlock(kd_ctrl_page, intrs_en); } static bool _reading_set_flags( struct kd_control *ctl, kdebug_emit_filter_t *old_emit, kdebug_live_flags_t *old_live) { int intrs_en = kdebug_storage_lock(ctl); *old_emit = ctl->kdc_emit; *old_live = ctl->kdc_live_flags; bool wrapped = ctl->kdc_live_flags & KDBG_WRAPPED; ctl->kdc_live_flags |= KDBG_NOWRAP; kdebug_storage_unlock(ctl, intrs_en); return wrapped; } static bool _reading_restore_flags( struct kd_control *ctl, kdebug_emit_filter_t old_emit, kdebug_live_flags_t old_live) { int intrs_en = kdebug_storage_lock(ctl); bool disabled_during_read = !ctl->enabled; // The wrapped bit was handled already, by adding a lost-events event, don't // replace it. ctl->kdc_live_flags = old_live & ~KDBG_WRAPPED; bool was_wrapping = (old_live & KDBG_NOWRAP) == 0; // Only re-enable trace if the reader causes lost events if wrapping was // previously enabled. if (was_wrapping && old_emit) { ctl->kdc_emit = old_emit; } kdebug_storage_unlock(ctl, intrs_en); return disabled_during_read; } static inline void _clear_oldest_lostevents(void) { for (unsigned int cpu = 0; cpu < kd_control_trace.kdebug_cpus; cpu++) { struct kd_bufinfo *info = &kd_buffer_trace.kdb_info[cpu]; union kds_ptr oldest_ptr = info->kd_list_head; if (oldest_ptr.raw != KDS_PTR_NULL) { struct kd_storage *store = POINTER_FROM_KDS_PTR(kd_buffer_trace.kd_bufs, oldest_ptr); store->kds_lostevents = false; } } } static inline bool _event_should_disable(kd_buf *event) { if ((kd_control_trace.kdc_flags & KDBG_MATCH_DISABLE) == 0) { return false; } kd_event_matcher *match = &kd_control_trace.disable_event_match; kd_event_matcher *mask = &kd_control_trace.disable_event_mask; return (event->debugid & mask->kem_debugid) == match->kem_debugid && (event->arg1 & mask->kem_args[0]) == match->kem_args[0] && (event->arg2 & mask->kem_args[1]) == match->kem_args[1] && (event->arg3 & mask->kem_args[2]) == match->kem_args[2] && (event->arg4 & mask->kem_args[3]) == match->kem_args[3]; } static inline struct kd_storage * _store_read_inc(struct kd_storage *store, struct kd_bufinfo *info, unsigned int cpu, union kds_ptr *store_ptr) { store->kds_readlast++; if (store->kds_readlast < kd_control_trace.kdebug_events_per_storage_unit) { return store; } _storage_free(&kd_control_trace, &kd_buffer_trace, cpu, store_ptr->raw); union kds_ptr oldest_ptr = info->kd_list_head; if (oldest_ptr.raw == KDS_PTR_NULL) { return NULL; } *store_ptr = oldest_ptr; return POINTER_FROM_KDS_PTR(kd_buffer_trace.kd_bufs, oldest_ptr); } static inline uint64_t _store_earliest_timestamp( struct kd_storage *store, uint64_t min, uint64_t max, struct kd_bufinfo *info, unsigned int cpu, union kds_ptr store_ptr) { while (true) { uint32_t rcursor = store->kds_readlast; if (rcursor == store->kds_bufindx) { // Out of events to read on this store. return UINT64_MAX; } uint64_t t = store->kds_records[rcursor].timestamp; if (t > max) { return UINT64_MAX; } else if (__improbable(t < store->kds_timestamp)) { // This can only happen for coprocessors that haven't // finished emitting this event, it will be processed the // next time through. return UINT64_MAX; } else if (t >= min) { return t; } // Skip to the next event. store = _store_read_inc(store, info, cpu, &store_ptr); if (!store) { return UINT64_MAX; } } } static int _read_trace_events_internal(struct kd_dest *dest, size_t event_count, uint64_t barrier_max, bool wrapped, bool *should_disable, size_t *events_written) { bool traced_retrograde = false; bool out_of_events = false; bool const wrapping_enabled = !(kd_control_trace.kdc_flags & KDBG_NOWRAP); struct kd_bufinfo *kdbip = kd_buffer_trace.kdb_info; struct kd_region *kd_bufs = kd_buffer_trace.kd_bufs; event_count = MIN(event_count, kd_buffer_trace.kdb_event_count); if (wrapped) { // If buffers have wrapped, do not emit additional lost events for the // oldest storage units. _clear_oldest_lostevents(); } uint64_t barrier_min = kd_control_trace.kdc_oldest_time; while (event_count && !out_of_events) { kd_buf *tempbuf = kd_buffer_trace.kdcopybuf; uint32_t used_count = 0; size_t avail_count = MIN(event_count, kd_control_trace.kdebug_kdcopybuf_count); while (used_count < avail_count) { bool lostevents = false; int lostcpu = -1; uint64_t earliest_time = UINT64_MAX; int min_cpu = -1; // Find the earliest event from all the oldest storage units. for (unsigned int cpu = 0; cpu < kd_control_trace.kdebug_cpus; cpu++) { struct kd_bufinfo *info = &kdbip[cpu]; union kds_ptr oldest_ptr = info->kd_list_head; if (oldest_ptr.raw == KDS_PTR_NULL) { continue; } struct kd_storage *store = POINTER_FROM_KDS_PTR(kd_bufs, oldest_ptr); // If the storage unit was stolen, make sure to emit a lost // events event with the earliest time to expect an event stream // with no gaps. if (__improbable(store->kds_lostevents)) { store->kds_lostevents = false; lostevents = true; uint64_t lost_time = store->kds_records[0].timestamp; if (kd_control_trace.kdc_oldest_time < lost_time) { // This time is now the oldest that can be read to // ensure an event stream with no gaps from this point // forward. kd_control_trace.kdc_oldest_time = barrier_min = lost_time; lostcpu = cpu; } continue; } else if (__improbable(lostevents)) { // On lost events, just find the latest timestamp of the // gaps. continue; } uint64_t t = _store_earliest_timestamp(store, barrier_min, barrier_max, info, cpu, oldest_ptr); if (t < earliest_time) { earliest_time = t; min_cpu = cpu; } } if (lostevents) { wrapped = false; // Only emit a lost events event if the user allowed wrapping. if (wrapping_enabled) { tempbuf[used_count++] = (kd_buf){ .debugid = TRACE_LOST_EVENTS, .timestamp = barrier_min, .cpuid = lostcpu, .arg1 = 1, }; } continue; } if (min_cpu == -1) { out_of_events = true; break; } if (wrapped) { // Emit a single lost events event in the case of expected // wrapping. wrapped = false; if (wrapping_enabled) { tempbuf[used_count++] = (kd_buf){ .debugid = TRACE_LOST_EVENTS, .timestamp = barrier_min, }; } } struct kd_bufinfo *min_info = &kdbip[min_cpu]; union kds_ptr oldest_ptr = min_info->kd_list_head; struct kd_storage *min_store = POINTER_FROM_KDS_PTR(kd_bufs, oldest_ptr); kd_buf *earliest_event = &min_store->kds_records[min_store->kds_readlast]; if (__improbable(min_info->latest_past_event_timestamp != 0)) { if (__improbable(kdbg_debug)) { printf("kdebug: PAST EVENT: debugid %#8x: " "time %lld from CPU %u " "(barrier at time %lld)\n", earliest_event->debugid, min_info->latest_past_event_timestamp, min_cpu, barrier_min); } tempbuf[used_count++] = (kd_buf){ .timestamp = earliest_time, .cpuid = min_cpu, .arg1 = (kd_buf_argtype)min_info->latest_past_event_timestamp, .arg2 = 0, .arg3 = 0, .arg4 = 0, .debugid = TRACE_PAST_EVENTS, }; min_info->latest_past_event_timestamp = 0; continue; } if (__improbable(_event_should_disable(earliest_event))) { *should_disable = true; } tempbuf[used_count] = *earliest_event; (void)_store_read_inc(min_store, min_info, min_cpu, &oldest_ptr); if (__improbable(earliest_time < min_info->kd_prev_timebase)) { if (traced_retrograde) { continue; } traced_retrograde = true; if (__improbable(kdbg_debug)) { printf("kdebug: RETRO EVENT: debugid %#8x: " "time %lld from CPU %u " "(previous earliest at time %lld)\n", tempbuf[used_count].debugid, earliest_time, min_cpu, min_info->kd_prev_timebase); } tempbuf[used_count] = (kd_buf){ .timestamp = min_info->kd_prev_timebase, .cpuid = tempbuf[used_count].cpuid, .arg1 = tempbuf->debugid, .arg2 = (kd_buf_argtype)earliest_time, .arg3 = 0, .arg4 = 0, .debugid = TRACE_RETROGRADE_EVENTS, }; } else { min_info->kd_prev_timebase = earliest_time; } used_count++; } if (used_count > 0) { /* * Remember the latest timestamp of events that we've merged so we * don't think we've lost events later. */ uint64_t latest_time = tempbuf[used_count - 1].timestamp; if (kd_control_trace.kdc_oldest_time < latest_time) { kd_control_trace.kdc_oldest_time = latest_time; } int error = _send_events(dest, kd_buffer_trace.kdcopybuf, used_count); if (error != 0) { // XXX Why zero this when some events may have been written? *events_written = 0; return error; } event_count -= used_count; *events_written += used_count; } } return 0; } // Read events from kdebug storage units into a user space buffer or file. // // This code runs while events are emitted -- storage unit allocation and // deallocation will synchronize with the emitters under the storage lock. // Otherwise, mutual exclusion for this function must be provided by the caller, // typically using the ktrace lock. static int _read_trace_events(struct kd_dest *dest, size_t event_count, size_t *events_written) { bool should_disable = false; int const prev_kdebug_enable = kdebug_enable; *events_written = 0; if (!(kd_control_trace.kdc_flags & KDBG_BUFINIT) || kd_buffer_trace.kdcopybuf == NULL) { return EINVAL; } thread_set_eager_preempt(current_thread()); /* * Capture the current time. Only sort events that have occured * before now. Since the IOPs are being flushed here, it is possible * that events occur on the AP while running live tracing. */ uint64_t barrier_max = kdebug_timestamp() & KDBG_TIMESTAMP_MASK; // Disable wrap so storage units cannot be stolen while inspecting events. // // With ktrace_lock held, no other control threads can be modifying // kdc_flags. The code that emits new events could be running, but // acquiring new storage units requires holding the storage lock, and it // looks at the flags there. The only issue is if events are being written // to the same chunk being read from. kdebug_emit_filter_t old_emit; kdebug_live_flags_t old_live_flags; bool wrapped = _reading_set_flags(&kd_control_trace, &old_emit, &old_live_flags); bool const no_wrapping = old_live_flags & KDBG_NOWRAP; int error = _read_trace_events_internal(dest, event_count, barrier_max, wrapped, &should_disable, events_written); bool disabled_during_read = _reading_restore_flags(&kd_control_trace, old_emit, old_live_flags); should_disable = should_disable || (disabled_during_read && no_wrapping); thread_clear_eager_preempt(current_thread()); if (should_disable) { kernel_debug_disable(); } else if (disabled_during_read && !no_wrapping && old_emit) { kd_control_trace.kdc_emit = old_emit; kdebug_enable = prev_kdebug_enable; kd_control_trace.enabled = 1; commpage_update_kdebug_state(); } return error; } static int _read_merged_trace_events(struct kd_dest *dest, size_t event_count, size_t *events_written) { ktrace_assert_lock_held(); if (event_count == 0 || !(kd_control_trace.kdc_flags & KDBG_BUFINIT) || kd_buffer_trace.kdcopybuf == 0) { *events_written = 0; return EINVAL; } // Before merging, make sure coprocessors have provided up-to-date events. _coproc_list_callback(KD_CALLBACK_SYNC_FLUSH, NULL); return _read_trace_events(dest, event_count, events_written); } struct event_chunk_header { uint32_t tag; uint32_t sub_tag; uint64_t length; uint64_t future_events_timestamp; }; static int _send_data_vfs(struct kd_dest *dest, const void *src, size_t size) { assert(size < INT_MAX); assert(dest->kdd_kind == KD_DEST_VFS); return vn_rdwr(UIO_WRITE, dest->kdd_vnode, (caddr_t)(uintptr_t)src, (int)size, dest->kdd_cur_offset, UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(&dest->kdd_vfs_ctx), (int *) 0, vfs_context_proc(&dest->kdd_vfs_ctx)); } static int _send_data(struct kd_dest *dest, const void *src, size_t size) { int error = 0; switch (dest->kdd_kind) { case KD_DEST_COPYOUT: if (size > dest->kdd_user_size - dest->kdd_cur_offset) { return ERANGE; } error = copyout(src, dest->kdd_user_buffer + dest->kdd_cur_offset, size); break; case KD_DEST_VFS: error = _send_data_vfs(dest, src, size); // XXX Previous code flushed with `VNOP_FSYNC` every 2MB, still needed? break; default: panic("kdebug: unrecognized destination %d", dest->kdd_kind); } if (error == 0) { dest->kdd_cur_offset += size; } return error; } static int _send_event_chunk_header(struct kd_dest *dest, size_t event_count) { struct event_chunk_header header = { .tag = V3_RAW_EVENTS, .sub_tag = 1, .length = event_count * sizeof(kd_buf), }; return _send_data(dest, &header, sizeof(header)); } int _send_events(struct kd_dest *dest, const void *src, size_t event_count) { if (dest->kdd_chunk_format) { int error = _send_event_chunk_header(dest, event_count); if (error != 0) { return error; } } return _send_data(dest, src, event_count * sizeof(kd_buf)); } static int _write_legacy_header(bool write_thread_map, struct kd_dest *dest) { uint32_t pad_size; uint32_t extra_thread_count = 0; uint32_t cpumap_size; size_t map_size = 0; uint32_t map_count = 0; if (write_thread_map) { assert(kd_control_trace.kdc_flags & KDBG_MAPINIT); if (kd_mapcount > UINT32_MAX) { return ERANGE; } map_count = (uint32_t)kd_mapcount; if (os_mul_overflow(map_count, sizeof(kd_threadmap), &map_size)) { return ERANGE; } if (map_size >= INT_MAX) { return ERANGE; } } /* * Without the buffers initialized, we cannot construct a CPU map or a * thread map, and cannot write a header. */ if (!(kd_control_trace.kdc_flags & KDBG_BUFINIT)) { return EINVAL; } /* * To write a RAW_VERSION1+ file, we must embed a cpumap in the * "padding" used to page align the events following the threadmap. If * the threadmap happens to not require enough padding, we artificially * increase its footprint until it needs enough padding. */ pad_size = 16384 - ((sizeof(RAW_header) + map_size) & PAGE_MASK); cpumap_size = sizeof(kd_cpumap_header) + kd_control_trace.kdebug_cpus * sizeof(kd_cpumap); if (cpumap_size > pad_size) { /* If the cpu map doesn't fit in the current available pad_size, * we increase the pad_size by 16K. We do this so that the event * data is always available on a page aligned boundary for both * 4k and 16k systems. We enforce this alignment for the event * data so that we can take advantage of optimized file/disk writes. */ pad_size += 16384; } /* The way we are silently embedding a cpumap in the "padding" is by artificially * increasing the number of thread entries. However, we'll also need to ensure that * the cpumap is embedded in the last 4K page before when the event data is expected. * This way the tools can read the data starting the next page boundary on both * 4K and 16K systems preserving compatibility with older versions of the tools */ if (pad_size > 4096) { pad_size -= 4096; extra_thread_count = (pad_size / sizeof(kd_threadmap)) + 1; } int error = 0; do { clock_sec_t secs; clock_usec_t usecs; clock_get_calendar_microtime(&secs, &usecs); RAW_header header = { .version_no = RAW_VERSION1, .thread_count = map_count + extra_thread_count, .TOD_secs = secs, .TOD_usecs = usecs, }; error = _send_data(dest, &header, sizeof(header)); if (error != 0) { break; } if (write_thread_map) { error = _send_data(dest, kd_mapptr, map_size); if (error != 0) { break; } } if (extra_thread_count) { pad_size = extra_thread_count * sizeof(kd_threadmap); void *pad_buf = kalloc_data(pad_size, Z_WAITOK | Z_ZERO); if (!pad_buf) { error = ENOMEM; break; } error = _send_data(dest, pad_buf, pad_size); if (error != 0) { break; } } pad_size = PAGE_SIZE - (dest->kdd_cur_offset & PAGE_MASK); if (pad_size) { void *pad_buf = kalloc_data(pad_size, Z_WAITOK | Z_ZERO); if (!pad_buf) { error = ENOMEM; break; } /* * Embed the CPU map in the padding bytes -- old code will skip it, * while newer code knows it's there. */ size_t temp = pad_size; (void)_copy_cpu_map(RAW_VERSION1, &pad_buf, &temp); error = _send_data(dest, pad_buf, pad_size); kfree_data(pad_buf, pad_size); if (error != 0) { break; } } } while (false); return error; } #pragma mark - User space interface static int _kd_sysctl_internal(int op, int value, user_addr_t where, size_t *sizep) { size_t size = *sizep; kd_regtype kd_Reg; bool read_only = (op == KERN_KDGETBUF || op == KERN_KDREADCURTHRMAP); int perm_error = read_only ? ktrace_read_check() : ktrace_configure(KTRACE_KDEBUG); if (perm_error != 0) { return perm_error; } switch (op) { case KERN_KDGETBUF:; pid_t owning_pid = ktrace_get_owning_pid(); const kbufinfo_t info = { .nkdbufs = kd_buffer_trace.kdb_event_count, .nkdthreads = (int)MIN(kd_mapcount, INT_MAX), .nolog = kd_control_trace.kdc_emit == KDEMIT_DISABLE, .flags = kd_control_trace.kdc_flags | kd_control_trace.kdc_live_flags | KDBG_LP64, .bufid = owning_pid ?: -1, }; size = MIN(size, sizeof(info)); return copyout(&info, where, size); case KERN_KDREADCURTHRMAP: return kdbg_readcurthrmap(where, sizep); case KERN_KDEFLAGS: value &= KDBG_USERFLAGS; kd_control_trace.kdc_flags |= value; return 0; case KERN_KDDFLAGS: value &= KDBG_USERFLAGS; kd_control_trace.kdc_flags &= ~value; return 0; case KERN_KDENABLE: if (value) { if (!(kd_control_trace.kdc_flags & KDBG_BUFINIT) || !(value == KDEBUG_ENABLE_TRACE || value == KDEBUG_ENABLE_PPT)) { return EINVAL; } _threadmap_init(); kdbg_set_tracing_enabled(true, value); } else { if (!kdebug_enable) { return 0; } kernel_debug_disable(); } return 0; case KERN_KDSETBUF: kdbg_set_nkdbufs_trace(value); return 0; case KERN_KDSETUP: return kdbg_reinit(EXTRA_COPROC_COUNT); case KERN_KDREMOVE: ktrace_reset(KTRACE_KDEBUG); return 0; case KERN_KDSETREG: if (size < sizeof(kd_regtype)) { return EINVAL; } if (copyin(where, &kd_Reg, sizeof(kd_regtype))) { return EINVAL; } return kdbg_setreg(&kd_Reg); case KERN_KDGETREG: return EINVAL; case KERN_KDREADTR: { struct kd_dest copy_dest = kd_dest_copyout(where, *sizep); size_t event_count = *sizep / sizeof(kd_buf); size_t events_written = 0; int error = _read_merged_trace_events(©_dest, event_count, &events_written); *sizep = events_written; return error; } case KERN_KDWRITETR: case KERN_KDWRITETR_V3: case KERN_KDWRITEMAP: { struct kd_dest write_dest = {}; int fd = value; if (op == KERN_KDWRITETR || op == KERN_KDWRITETR_V3) { (void)kdbg_wait(size); // Re-check whether this process can configure ktrace, since waiting // will drop the ktrace lock. int no_longer_owner_error = ktrace_configure(KTRACE_KDEBUG); if (no_longer_owner_error != 0) { return no_longer_owner_error; } } struct fileproc *fp; int error = kd_dest_init_write(&write_dest, fd, &fp); if (error != 0) { return error; } if (op == KERN_KDWRITETR || op == KERN_KDWRITETR_V3) { size_t event_count = kd_buffer_trace.kdb_event_count; size_t events_written = 0; if (op == KERN_KDWRITETR_V3) { write_dest.kdd_chunk_format = true; } KDBG_RELEASE(TRACE_WRITING_EVENTS | DBG_FUNC_START); error = _read_merged_trace_events(&write_dest, event_count, &events_written); KDBG_RELEASE(TRACE_WRITING_EVENTS | DBG_FUNC_END, events_written); *sizep = events_written; } else { error = kdbg_write_thread_map(&write_dest); if (error == 0) { *sizep = kd_mapcount * sizeof(kd_threadmap); } } kd_dest_finish_write(&write_dest, fp, fd); return error; } case KERN_KDBUFWAIT: *sizep = kdbg_wait(size); return 0; case KERN_KDPIDTR: if (size < sizeof(kd_regtype)) { return EINVAL; } if (copyin(where, &kd_Reg, sizeof(kd_regtype))) { return EINVAL; } return kdbg_setpid(&kd_Reg); case KERN_KDPIDEX: if (size < sizeof(kd_regtype)) { return EINVAL; } if (copyin(where, &kd_Reg, sizeof(kd_regtype))) { return EINVAL; } return kdbg_setpidex(&kd_Reg); case KERN_KDCPUMAP: return _copyout_cpu_map(RAW_VERSION1, where, sizep); case KERN_KDCPUMAP_EXT: return _copyout_cpu_map(1, where, sizep); case KERN_KDTHRMAP: return kdbg_copyout_thread_map(where, sizep); case KERN_KDSET_TYPEFILTER: return kdbg_copyin_typefilter(where, size); case KERN_KDSET_EDM: return _copyin_event_disable_mask(where, size); case KERN_KDGET_EDM: return _copyout_event_disable_mask(where, size); #if DEVELOPMENT || DEBUG case KERN_KDTEST: return kdbg_test(size); #endif // DEVELOPMENT || DEBUG default: return ENOTSUP; } } static int kdebug_sysctl SYSCTL_HANDLER_ARGS { int *names = arg1; int name_count = arg2; user_addr_t udst = req->oldptr; size_t *usize = &req->oldlen; int value = 0; if (name_count == 0) { return ENOTSUP; } int op = names[0]; // Some operations have an argument stuffed into the next OID argument. switch (op) { case KERN_KDWRITETR: case KERN_KDWRITETR_V3: case KERN_KDWRITEMAP: case KERN_KDEFLAGS: case KERN_KDDFLAGS: case KERN_KDENABLE: case KERN_KDSETBUF: if (name_count < 2) { return EINVAL; } value = names[1]; break; default: break; } ktrace_lock(); int ret = _kd_sysctl_internal(op, value, udst, usize); ktrace_unlock(); if (0 == ret) { req->oldidx += req->oldlen; } return ret; } SYSCTL_PROC(_kern, KERN_KDEBUG, kdebug, CTLTYPE_NODE | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, kdebug_sysctl, NULL, ""); #pragma mark - Tests #if DEVELOPMENT || DEBUG static int test_coproc = 0; static int sync_flush_coproc = 0; #define KDEBUG_TEST_CODE(code) BSDDBG_CODE(DBG_BSD_KDEBUG_TEST, (code)) /* * A test IOP for the SYNC_FLUSH callback. */ static void sync_flush_callback(void * __unused context, kd_callback_type reason, void * __unused arg) { assert(sync_flush_coproc > 0); if (reason == KD_CALLBACK_SYNC_FLUSH) { kernel_debug_enter(sync_flush_coproc, KDEBUG_TEST_CODE(0xff), kdebug_timestamp(), 0, 0, 0, 0, 0); } } static struct kd_callback sync_flush_kdcb = { .func = sync_flush_callback, .iop_name = "test_sf", }; #define TEST_COPROC_CTX 0xabadcafe static void test_coproc_cb(__assert_only void *context, kd_callback_type __unused reason, void * __unused arg) { assert((uintptr_t)context == TEST_COPROC_CTX); } static int kdbg_test(size_t flavor) { int code = 0; int dummy_iop = 0; switch (flavor) { case KDTEST_KERNEL_MACROS: /* try each macro */ KDBG(KDEBUG_TEST_CODE(code)); code++; KDBG(KDEBUG_TEST_CODE(code), 1); code++; KDBG(KDEBUG_TEST_CODE(code), 1, 2); code++; KDBG(KDEBUG_TEST_CODE(code), 1, 2, 3); code++; KDBG(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++; KDBG_RELEASE(KDEBUG_TEST_CODE(code)); code++; KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1); code++; KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2); code++; KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2, 3); code++; KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++; KDBG_FILTERED(KDEBUG_TEST_CODE(code)); code++; KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1); code++; KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2); code++; KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2, 3); code++; KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++; KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code)); code++; KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1); code++; KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1, 2); code++; KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1, 2, 3); code++; KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++; KDBG_DEBUG(KDEBUG_TEST_CODE(code)); code++; KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1); code++; KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2); code++; KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2, 3); code++; KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++; break; case KDTEST_OLD_TIMESTAMP: if (kd_control_trace.kdc_coprocs) { /* avoid the assertion in kernel_debug_enter for a valid IOP */ dummy_iop = kd_control_trace.kdc_coprocs[0].cpu_id; } /* ensure old timestamps are not emitted from kernel_debug_enter */ kernel_debug_enter(dummy_iop, KDEBUG_TEST_CODE(code), 100 /* very old timestamp */, 0, 0, 0, 0, 0); code++; kernel_debug_enter(dummy_iop, KDEBUG_TEST_CODE(code), kdebug_timestamp(), 0, 0, 0, 0, 0); code++; break; case KDTEST_FUTURE_TIMESTAMP: if (kd_control_trace.kdc_coprocs) { dummy_iop = kd_control_trace.kdc_coprocs[0].cpu_id; } kernel_debug_enter(dummy_iop, KDEBUG_TEST_CODE(code), kdebug_timestamp() * 2 /* !!! */, 0, 0, 0, 0, 0); break; case KDTEST_SETUP_IOP: if (!sync_flush_coproc) { ktrace_unlock(); int new_sync_flush_coproc = kernel_debug_register_callback( sync_flush_kdcb); assert(new_sync_flush_coproc > 0); ktrace_lock(); if (!sync_flush_coproc) { sync_flush_coproc = new_sync_flush_coproc; } } break; case KDTEST_SETUP_COPROCESSOR: if (!test_coproc) { ktrace_unlock(); int new_test_coproc = kdebug_register_coproc("test_coproc", KDCP_CONTINUOUS_TIME, test_coproc_cb, (void *)TEST_COPROC_CTX); assert(new_test_coproc > 0); ktrace_lock(); if (!test_coproc) { test_coproc = new_test_coproc; } } break; case KDTEST_ABSOLUTE_TIMESTAMP:; uint64_t atime = mach_absolute_time(); kernel_debug_enter(sync_flush_coproc, KDEBUG_TEST_CODE(0), atime, (uintptr_t)atime, (uintptr_t)(atime >> 32), 0, 0, 0); break; case KDTEST_CONTINUOUS_TIMESTAMP:; uint64_t ctime = mach_continuous_time(); kernel_debug_enter(test_coproc, KDEBUG_TEST_CODE(1), ctime, (uintptr_t)ctime, (uintptr_t)(ctime >> 32), 0, 0, 0); break; case KDTEST_PAST_EVENT:; uint64_t old_time = 1; kernel_debug_enter(test_coproc, KDEBUG_TEST_CODE(1), old_time, 0, 0, 0, 0, 0); kernel_debug_enter(test_coproc, KDEBUG_TEST_CODE(1), kdebug_timestamp(), 0, 0, 0, 0, 0); break; default: return ENOTSUP; } return 0; } #undef KDEBUG_TEST_CODE #endif /* DEVELOPMENT || DEBUG */ static void _deferred_coproc_notify(mpsc_queue_chain_t e, mpsc_daemon_queue_t queue __unused) { struct kd_coproc *coproc = mpsc_queue_element(e, struct kd_coproc, chain); if (kd_control_trace.kdc_emit == KDEMIT_TYPEFILTER) { coproc->callback.func(coproc->callback.context, KD_CALLBACK_TYPEFILTER_CHANGED, kdbg_typefilter); } if (kdebug_enable) { coproc->callback.func(coproc->callback.context, KD_CALLBACK_KDEBUG_ENABLED, kdbg_typefilter); } } void kdebug_init(unsigned int n_events, char *filter_desc, enum kdebug_opts opts) { assert(filter_desc != NULL); kdbg_typefilter = typefilter_create(); assert(kdbg_typefilter != NULL); kdbg_typefilter_memory_entry = typefilter_create_memory_entry(kdbg_typefilter); assert(kdbg_typefilter_memory_entry != MACH_PORT_NULL); (void)mpsc_daemon_queue_init_with_thread_call(&_coproc_notify_queue, _deferred_coproc_notify, THREAD_CALL_PRIORITY_KERNEL, MPSC_DAEMON_INIT_NONE); kdebug_trace_start(n_events, filter_desc, opts); } static void kdbg_set_typefilter_string(const char *filter_desc) { char *end = NULL; ktrace_assert_lock_held(); assert(filter_desc != NULL); typefilter_reject_all(kdbg_typefilter); typefilter_allow_class(kdbg_typefilter, DBG_TRACE); /* if the filter description starts with a number, assume it's a csc */ if (filter_desc[0] >= '0' && filter_desc[0] <= '9') { unsigned long csc = strtoul(filter_desc, NULL, 0); if (filter_desc != end && csc <= KDBG_CSC_MAX) { typefilter_allow_csc(kdbg_typefilter, (uint16_t)csc); } return; } while (filter_desc[0] != '\0') { unsigned long allow_value; char filter_type = filter_desc[0]; if (filter_type != 'C' && filter_type != 'S') { printf("kdebug: unexpected filter type `%c'\n", filter_type); return; } filter_desc++; allow_value = strtoul(filter_desc, &end, 0); if (filter_desc == end) { printf("kdebug: cannot parse `%s' as integer\n", filter_desc); return; } switch (filter_type) { case 'C': if (allow_value > KDBG_CLASS_MAX) { printf("kdebug: class 0x%lx is invalid\n", allow_value); return; } printf("kdebug: C 0x%lx\n", allow_value); typefilter_allow_class(kdbg_typefilter, (uint8_t)allow_value); break; case 'S': if (allow_value > KDBG_CSC_MAX) { printf("kdebug: class-subclass 0x%lx is invalid\n", allow_value); return; } printf("kdebug: S 0x%lx\n", allow_value); typefilter_allow_csc(kdbg_typefilter, (uint16_t)allow_value); break; default: __builtin_unreachable(); } /* advance to next filter entry */ filter_desc = end; if (filter_desc[0] == ',') { filter_desc++; } } } uint64_t kdebug_wake(void) { if (!wake_nkdbufs) { return 0; } uint64_t start = mach_absolute_time(); kdebug_trace_start(wake_nkdbufs, NULL, trace_wrap ? KDOPT_WRAPPING : 0); return mach_absolute_time() - start; } /* * This function is meant to be called from the bootstrap thread or kdebug_wake. */ void kdebug_trace_start(unsigned int n_events, const char *filter_desc, enum kdebug_opts opts) { if (!n_events) { kd_early_done = true; return; } ktrace_start_single_threaded(); ktrace_kernel_configure(KTRACE_KDEBUG); kdbg_set_nkdbufs_trace(n_events); kernel_debug_string_early("start_kern_tracing"); int error = kdbg_reinit(EXTRA_COPROC_COUNT_BOOT); if (error != 0) { printf("kdebug: allocation failed, kernel tracing not started: %d\n", error); kd_early_done = true; goto out; } /* * Wrapping is disabled because boot and wake tracing is interested in * the earliest events, at the expense of later ones. */ if ((opts & KDOPT_WRAPPING) == 0) { kd_control_trace.kdc_flags |= KDBG_NOWRAP; } if (filter_desc && filter_desc[0] != '\0') { kdbg_set_typefilter_string(filter_desc); kdbg_enable_typefilter(); } /* * Hold off interrupts between getting a thread map and enabling trace * and until the early traces are recorded. */ bool s = ml_set_interrupts_enabled(false); if (!(opts & KDOPT_ATBOOT)) { _threadmap_init(); } kdbg_set_tracing_enabled(true, KDEBUG_ENABLE_TRACE); if ((opts & KDOPT_ATBOOT)) { /* * Transfer all very early events from the static buffer into the real * buffers. */ kernel_debug_early_end(); } ml_set_interrupts_enabled(s); printf("kernel tracing started with %u events, filter = %s\n", n_events, filter_desc ?: "none"); out: ktrace_end_single_threaded(); } void kdbg_dump_trace_to_file(const char *filename, bool reenable) { vfs_context_t ctx; vnode_t vp; int ret; int reenable_trace = 0; ktrace_lock(); if (!(kdebug_enable & KDEBUG_ENABLE_TRACE)) { goto out; } if (ktrace_get_owning_pid() != 0) { /* * Another process owns ktrace and is still active, disable tracing to * prevent wrapping. */ kdebug_enable = 0; kd_control_trace.enabled = 0; commpage_update_kdebug_state(); goto out; } KDBG_RELEASE(TRACE_WRITING_EVENTS | DBG_FUNC_START); reenable_trace = reenable ? kdebug_enable : 0; kdebug_enable = 0; kd_control_trace.enabled = 0; commpage_update_kdebug_state(); ctx = vfs_context_kernel(); if (vnode_open(filename, (O_CREAT | FWRITE | O_NOFOLLOW), 0600, 0, &vp, ctx)) { goto out; } struct kd_dest file_dest = { .kdd_kind = KD_DEST_VFS, .kdd_vnode = vp, .kdd_vfs_ctx = *ctx, }; kdbg_write_thread_map(&file_dest); size_t events_written = 0; ret = _read_merged_trace_events(&file_dest, kd_buffer_trace.kdb_event_count, &events_written); if (ret) { goto out_close; } /* * Wait to synchronize the file to capture the I/O in the * TRACE_WRITING_EVENTS interval. */ ret = VNOP_FSYNC(vp, MNT_WAIT, ctx); if (ret == KERN_SUCCESS) { ret = VNOP_IOCTL(vp, F_FULLFSYNC, (caddr_t)NULL, 0, ctx); } /* * Balance the starting TRACE_WRITING_EVENTS tracepoint manually. */ kd_buf end_event = { .debugid = TRACE_WRITING_EVENTS | DBG_FUNC_END, .arg1 = events_written, .arg2 = ret, .arg5 = (kd_buf_argtype)thread_tid(current_thread()), .timestamp = kdebug_timestamp(), .cpuid = cpu_number(), }; /* this is best effort -- ignore any errors */ (void)_send_data_vfs(&file_dest, &end_event, sizeof(kd_buf)); out_close: vnode_close(vp, FWRITE, ctx); sync(current_proc(), (void *)NULL, (int *)NULL); out: if (reenable_trace != 0) { kdebug_enable = reenable_trace; kd_control_trace.enabled = 1; commpage_update_kdebug_state(); } ktrace_unlock(); } SYSCTL_NODE(_kern, OID_AUTO, kdbg, CTLFLAG_RD | CTLFLAG_LOCKED, 0, "kdbg"); SYSCTL_INT(_kern_kdbg, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_LOCKED, &kdbg_debug, 0, "Set kdebug debug mode"); SYSCTL_QUAD(_kern_kdbg, OID_AUTO, oldest_time, CTLTYPE_QUAD | CTLFLAG_RD | CTLFLAG_LOCKED, &kd_control_trace.kdc_oldest_time, "Find the oldest timestamp still in trace"); |