Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
/*-
 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
 *
 * Copyright (c) 2003-2008 Joseph Koshy
 * Copyright (c) 2007 The FreeBSD Foundation
 * Copyright (c) 2018 Matthew Macy
 * All rights reserved.
 *
 * Portions of this software were developed by A. Joseph Koshy under
 * sponsorship from the FreeBSD Foundation and Google, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/domainset.h>
#include <sys/eventhandler.h>
#include <sys/jail.h>
#include <sys/kernel.h>
#include <sys/kthread.h>
#include <sys/limits.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <sys/mount.h>
#include <sys/mutex.h>
#include <sys/pmc.h>
#include <sys/pmckern.h>
#include <sys/pmclog.h>
#include <sys/priv.h>
#include <sys/proc.h>
#include <sys/queue.h>
#include <sys/resourcevar.h>
#include <sys/rwlock.h>
#include <sys/sched.h>
#include <sys/signalvar.h>
#include <sys/smp.h>
#include <sys/sx.h>
#include <sys/sysctl.h>
#include <sys/sysent.h>
#include <sys/syslog.h>
#include <sys/taskqueue.h>
#include <sys/vnode.h>

#include <sys/linker.h>		/* needs to be after <sys/malloc.h> */

#include <machine/atomic.h>
#include <machine/md_var.h>

#include <vm/vm.h>
#include <vm/vm_extern.h>
#include <vm/pmap.h>
#include <vm/vm_map.h>
#include <vm/vm_object.h>

#include "hwpmc_soft.h"

#define PMC_EPOCH_ENTER() struct epoch_tracker pmc_et; epoch_enter_preempt(global_epoch_preempt, &pmc_et)
#define PMC_EPOCH_EXIT() epoch_exit_preempt(global_epoch_preempt, &pmc_et)

/*
 * Types
 */

enum pmc_flags {
	PMC_FLAG_NONE	  = 0x00, /* do nothing */
	PMC_FLAG_REMOVE   = 0x01, /* atomically remove entry from hash */
	PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */
	PMC_FLAG_NOWAIT   = 0x04, /* do not wait for mallocs */
};

/*
 * The offset in sysent where the syscall is allocated.
 */

static int pmc_syscall_num = NO_SYSCALL;
struct pmc_cpu		**pmc_pcpu;	 /* per-cpu state */
pmc_value_t		*pmc_pcpu_saved; /* saved PMC values: CSW handling */

#define	PMC_PCPU_SAVED(C,R)	pmc_pcpu_saved[(R) + md->pmd_npmc*(C)]

struct mtx_pool		*pmc_mtxpool;
static int		*pmc_pmcdisp;	 /* PMC row dispositions */

#define	PMC_ROW_DISP_IS_FREE(R)		(pmc_pmcdisp[(R)] == 0)
#define	PMC_ROW_DISP_IS_THREAD(R)	(pmc_pmcdisp[(R)] > 0)
#define	PMC_ROW_DISP_IS_STANDALONE(R)	(pmc_pmcdisp[(R)] < 0)

#define	PMC_MARK_ROW_FREE(R) do {					  \
	pmc_pmcdisp[(R)] = 0;						  \
} while (0)

#define	PMC_MARK_ROW_STANDALONE(R) do {					  \
	KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
		    __LINE__));						  \
	atomic_add_int(&pmc_pmcdisp[(R)], -1);				  \
	KASSERT(pmc_pmcdisp[(R)] >= (-pmc_cpu_max_active()),		  \
		("[pmc,%d] row disposition error", __LINE__));		  \
} while (0)

#define	PMC_UNMARK_ROW_STANDALONE(R) do { 				  \
	atomic_add_int(&pmc_pmcdisp[(R)], 1);				  \
	KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
		    __LINE__));						  \
} while (0)

#define	PMC_MARK_ROW_THREAD(R) do {					  \
	KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
		    __LINE__));						  \
	atomic_add_int(&pmc_pmcdisp[(R)], 1);				  \
} while (0)

#define	PMC_UNMARK_ROW_THREAD(R) do {					  \
	atomic_add_int(&pmc_pmcdisp[(R)], -1);				  \
	KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
		    __LINE__));						  \
} while (0)


/* various event handlers */
static eventhandler_tag	pmc_exit_tag, pmc_fork_tag, pmc_kld_load_tag,
    pmc_kld_unload_tag;

/* Module statistics */
struct pmc_driverstats pmc_stats;


/* Machine/processor dependent operations */
static struct pmc_mdep  *md;

/*
 * Hash tables mapping owner processes and target threads to PMCs.
 */

struct mtx pmc_processhash_mtx;		/* spin mutex */
static u_long pmc_processhashmask;
static LIST_HEAD(pmc_processhash, pmc_process)	*pmc_processhash;

/*
 * Hash table of PMC owner descriptors.  This table is protected by
 * the shared PMC "sx" lock.
 */

static u_long pmc_ownerhashmask;
static LIST_HEAD(pmc_ownerhash, pmc_owner)	*pmc_ownerhash;

/*
 * List of PMC owners with system-wide sampling PMCs.
 */

static CK_LIST_HEAD(, pmc_owner)			pmc_ss_owners;

/*
 * List of free thread entries. This is protected by the spin
 * mutex.
 */
static struct mtx pmc_threadfreelist_mtx;	/* spin mutex */
static LIST_HEAD(, pmc_thread)			pmc_threadfreelist;
static int pmc_threadfreelist_entries=0;
#define	THREADENTRY_SIZE						\
(sizeof(struct pmc_thread) + (md->pmd_npmc * sizeof(struct pmc_threadpmcstate)))

/*
 * Task to free thread descriptors
 */
static struct task free_task;

/*
 * A map of row indices to classdep structures.
 */
static struct pmc_classdep **pmc_rowindex_to_classdep;

/*
 * Prototypes
 */

#ifdef	HWPMC_DEBUG
static int	pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS);
static int	pmc_debugflags_parse(char *newstr, char *fence);
#endif

static int	load(struct module *module, int cmd, void *arg);
static int	pmc_add_sample(ring_type_t ring, struct pmc *pm, struct trapframe *tf);
static void	pmc_add_thread_descriptors_from_proc(struct proc *p,
    struct pmc_process *pp);
static int	pmc_attach_process(struct proc *p, struct pmc *pm);
static struct pmc *pmc_allocate_pmc_descriptor(void);
static struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p);
static int	pmc_attach_one_process(struct proc *p, struct pmc *pm);
static int	pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
    int cpu);
static int	pmc_can_attach(struct pmc *pm, struct proc *p);
static void	pmc_capture_user_callchain(int cpu, int soft, struct trapframe *tf);
static void	pmc_cleanup(void);
static int	pmc_detach_process(struct proc *p, struct pmc *pm);
static int	pmc_detach_one_process(struct proc *p, struct pmc *pm,
    int flags);
static void	pmc_destroy_owner_descriptor(struct pmc_owner *po);
static void	pmc_destroy_pmc_descriptor(struct pmc *pm);
static void	pmc_destroy_process_descriptor(struct pmc_process *pp);
static struct pmc_owner *pmc_find_owner_descriptor(struct proc *p);
static int	pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm);
static struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po,
    pmc_id_t pmc);
static struct pmc_process *pmc_find_process_descriptor(struct proc *p,
    uint32_t mode);
static struct pmc_thread *pmc_find_thread_descriptor(struct pmc_process *pp,
    struct thread *td, uint32_t mode);
static void	pmc_force_context_switch(void);
static void	pmc_link_target_process(struct pmc *pm,
    struct pmc_process *pp);
static void	pmc_log_all_process_mappings(struct pmc_owner *po);
static void	pmc_log_kernel_mappings(struct pmc *pm);
static void	pmc_log_process_mappings(struct pmc_owner *po, struct proc *p);
static void	pmc_maybe_remove_owner(struct pmc_owner *po);
static void	pmc_process_csw_in(struct thread *td);
static void	pmc_process_csw_out(struct thread *td);
static void	pmc_process_exit(void *arg, struct proc *p);
static void	pmc_process_fork(void *arg, struct proc *p1,
    struct proc *p2, int n);
static void	pmc_process_samples(int cpu, ring_type_t soft);
static void	pmc_release_pmc_descriptor(struct pmc *pmc);
static void	pmc_process_thread_add(struct thread *td);
static void	pmc_process_thread_delete(struct thread *td);
static void	pmc_process_thread_userret(struct thread *td);
static void	pmc_remove_owner(struct pmc_owner *po);
static void	pmc_remove_process_descriptor(struct pmc_process *pp);
static void	pmc_restore_cpu_binding(struct pmc_binding *pb);
static void	pmc_save_cpu_binding(struct pmc_binding *pb);
static void	pmc_select_cpu(int cpu);
static int	pmc_start(struct pmc *pm);
static int	pmc_stop(struct pmc *pm);
static int	pmc_syscall_handler(struct thread *td, void *syscall_args);
static struct pmc_thread *pmc_thread_descriptor_pool_alloc(void);
static void	pmc_thread_descriptor_pool_drain(void);
static void	pmc_thread_descriptor_pool_free(struct pmc_thread *pt);
static void	pmc_unlink_target_process(struct pmc *pmc,
    struct pmc_process *pp);
static int generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp);
static int generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp);
static struct pmc_mdep *pmc_generic_cpu_initialize(void);
static void pmc_generic_cpu_finalize(struct pmc_mdep *md);
static void pmc_post_callchain_callback(void);
static void pmc_process_threadcreate(struct thread *td);
static void pmc_process_threadexit(struct thread *td);
static void pmc_process_proccreate(struct proc *p);
static void pmc_process_allproc(struct pmc *pm);

/*
 * Kernel tunables and sysctl(8) interface.
 */

SYSCTL_DECL(_kern_hwpmc);
SYSCTL_NODE(_kern_hwpmc, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
    "HWPMC stats");


/* Stats. */
SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_ignored, CTLFLAG_RW,
				   &pmc_stats.pm_intr_ignored, "# of interrupts ignored");
SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_processed, CTLFLAG_RW,
				   &pmc_stats.pm_intr_processed, "# of interrupts processed");
SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_bufferfull, CTLFLAG_RW,
				   &pmc_stats.pm_intr_bufferfull, "# of interrupts where buffer was full");
SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, syscalls, CTLFLAG_RW,
				   &pmc_stats.pm_syscalls, "# of syscalls");
SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, syscall_errors, CTLFLAG_RW,
				   &pmc_stats.pm_syscall_errors, "# of syscall_errors");
SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, buffer_requests, CTLFLAG_RW,
				   &pmc_stats.pm_buffer_requests, "# of buffer requests");
SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, buffer_requests_failed, CTLFLAG_RW,
				   &pmc_stats.pm_buffer_requests_failed, "# of buffer requests which failed");
SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, log_sweeps, CTLFLAG_RW,
				   &pmc_stats.pm_log_sweeps, "# of ?");
SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, merges, CTLFLAG_RW,
				   &pmc_stats.pm_merges, "# of times kernel stack was found for user trace");
SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, overwrites, CTLFLAG_RW,
				   &pmc_stats.pm_overwrites, "# of times a sample was overwritten before being logged");

static int pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
SYSCTL_INT(_kern_hwpmc, OID_AUTO, callchaindepth, CTLFLAG_RDTUN,
    &pmc_callchaindepth, 0, "depth of call chain records");

char pmc_cpuid[PMC_CPUID_LEN];
SYSCTL_STRING(_kern_hwpmc, OID_AUTO, cpuid, CTLFLAG_RD,
	pmc_cpuid, 0, "cpu version string");
#ifdef	HWPMC_DEBUG
struct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS;
char	pmc_debugstr[PMC_DEBUG_STRSIZE];
TUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr,
    sizeof(pmc_debugstr));
SYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags,
    CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_NEEDGIANT,
    0, 0, pmc_debugflags_sysctl_handler, "A",
    "debug flags");
#endif


/*
 * kern.hwpmc.hashrows -- determines the number of rows in the
 * of the hash table used to look up threads
 */

static int pmc_hashsize = PMC_HASH_SIZE;
SYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_RDTUN,
    &pmc_hashsize, 0, "rows in hash tables");

/*
 * kern.hwpmc.nsamples --- number of PC samples/callchain stacks per CPU
 */

static int pmc_nsamples = PMC_NSAMPLES;
SYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_RDTUN,
    &pmc_nsamples, 0, "number of PC samples per CPU");

static uint64_t pmc_sample_mask = PMC_NSAMPLES-1;

/*
 * kern.hwpmc.mtxpoolsize -- number of mutexes in the mutex pool.
 */

static int pmc_mtxpool_size = PMC_MTXPOOL_SIZE;
SYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_RDTUN,
    &pmc_mtxpool_size, 0, "size of spin mutex pool");


/*
 * kern.hwpmc.threadfreelist_entries -- number of free entries
 */

SYSCTL_INT(_kern_hwpmc, OID_AUTO, threadfreelist_entries, CTLFLAG_RD,
    &pmc_threadfreelist_entries, 0, "number of avalable thread entries");


/*
 * kern.hwpmc.threadfreelist_max -- maximum number of free entries
 */

static int pmc_threadfreelist_max = PMC_THREADLIST_MAX;
SYSCTL_INT(_kern_hwpmc, OID_AUTO, threadfreelist_max, CTLFLAG_RW,
    &pmc_threadfreelist_max, 0,
    "maximum number of available thread entries before freeing some");


/*
 * security.bsd.unprivileged_syspmcs -- allow non-root processes to
 * allocate system-wide PMCs.
 *
 * Allowing unprivileged processes to allocate system PMCs is convenient
 * if system-wide measurements need to be taken concurrently with other
 * per-process measurements.  This feature is turned off by default.
 */

static int pmc_unprivileged_syspmcs = 0;
SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RWTUN,
    &pmc_unprivileged_syspmcs, 0,
    "allow unprivileged process to allocate system PMCs");

/*
 * Hash function.  Discard the lower 2 bits of the pointer since
 * these are always zero for our uses.  The hash multiplier is
 * round((2^LONG_BIT) * ((sqrt(5)-1)/2)).
 */

#if	LONG_BIT == 64
#define	_PMC_HM		11400714819323198486u
#elif	LONG_BIT == 32
#define	_PMC_HM		2654435769u
#else
#error 	Must know the size of 'long' to compile
#endif

#define	PMC_HASH_PTR(P,M)	((((unsigned long) (P) >> 2) * _PMC_HM) & (M))

/*
 * Syscall structures
 */

/* The `sysent' for the new syscall */
static struct sysent pmc_sysent = {
	.sy_narg =	2,
	.sy_call =	pmc_syscall_handler,
};

static struct syscall_module_data pmc_syscall_mod = {
	.chainevh =	load,
	.chainarg =	NULL,
	.offset =	&pmc_syscall_num,
	.new_sysent =	&pmc_sysent,
	.old_sysent =	{ .sy_narg = 0, .sy_call = NULL },
	.flags =	SY_THR_STATIC_KLD,
};

static moduledata_t pmc_mod = {
	.name =		PMC_MODULE_NAME,
	.evhand =	syscall_module_handler,
	.priv =		&pmc_syscall_mod,
};

#ifdef EARLY_AP_STARTUP
DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SYSCALLS, SI_ORDER_ANY);
#else
DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
#endif
MODULE_VERSION(pmc, PMC_VERSION);

#ifdef	HWPMC_DEBUG
enum pmc_dbgparse_state {
	PMCDS_WS,		/* in whitespace */
	PMCDS_MAJOR,		/* seen a major keyword */
	PMCDS_MINOR
};

static int
pmc_debugflags_parse(char *newstr, char *fence)
{
	char c, *p, *q;
	struct pmc_debugflags *tmpflags;
	int error, found, *newbits, tmp;
	size_t kwlen;

	tmpflags = malloc(sizeof(*tmpflags), M_PMC, M_WAITOK|M_ZERO);

	p = newstr;
	error = 0;

	for (; p < fence && (c = *p); p++) {

		/* skip white space */
		if (c == ' ' || c == '\t')
			continue;

		/* look for a keyword followed by "=" */
		for (q = p; p < fence && (c = *p) && c != '='; p++)
			;
		if (c != '=') {
			error = EINVAL;
			goto done;
		}

		kwlen = p - q;
		newbits = NULL;

		/* lookup flag group name */
#define	DBG_SET_FLAG_MAJ(S,F)						\
		if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)	\
			newbits = &tmpflags->pdb_ ## F;

		DBG_SET_FLAG_MAJ("cpu",		CPU);
		DBG_SET_FLAG_MAJ("csw",		CSW);
		DBG_SET_FLAG_MAJ("logging",	LOG);
		DBG_SET_FLAG_MAJ("module",	MOD);
		DBG_SET_FLAG_MAJ("md", 		MDP);
		DBG_SET_FLAG_MAJ("owner",	OWN);
		DBG_SET_FLAG_MAJ("pmc",		PMC);
		DBG_SET_FLAG_MAJ("process",	PRC);
		DBG_SET_FLAG_MAJ("sampling", 	SAM);

		if (newbits == NULL) {
			error = EINVAL;
			goto done;
		}

		p++;		/* skip the '=' */

		/* Now parse the individual flags */
		tmp = 0;
	newflag:
		for (q = p; p < fence && (c = *p); p++)
			if (c == ' ' || c == '\t' || c == ',')
				break;

		/* p == fence or c == ws or c == "," or c == 0 */

		if ((kwlen = p - q) == 0) {
			*newbits = tmp;
			continue;
		}

		found = 0;
#define	DBG_SET_FLAG_MIN(S,F)						\
		if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)	\
			tmp |= found = (1 << PMC_DEBUG_MIN_ ## F)

		/* a '*' denotes all possible flags in the group */
		if (kwlen == 1 && *q == '*')
			tmp = found = ~0;
		/* look for individual flag names */
		DBG_SET_FLAG_MIN("allocaterow", ALR);
		DBG_SET_FLAG_MIN("allocate",	ALL);
		DBG_SET_FLAG_MIN("attach",	ATT);
		DBG_SET_FLAG_MIN("bind",	BND);
		DBG_SET_FLAG_MIN("config",	CFG);
		DBG_SET_FLAG_MIN("exec",	EXC);
		DBG_SET_FLAG_MIN("exit",	EXT);
		DBG_SET_FLAG_MIN("find",	FND);
		DBG_SET_FLAG_MIN("flush",	FLS);
		DBG_SET_FLAG_MIN("fork",	FRK);
		DBG_SET_FLAG_MIN("getbuf",	GTB);
		DBG_SET_FLAG_MIN("hook",	PMH);
		DBG_SET_FLAG_MIN("init",	INI);
		DBG_SET_FLAG_MIN("intr",	INT);
		DBG_SET_FLAG_MIN("linktarget",	TLK);
		DBG_SET_FLAG_MIN("mayberemove", OMR);
		DBG_SET_FLAG_MIN("ops",		OPS);
		DBG_SET_FLAG_MIN("read",	REA);
		DBG_SET_FLAG_MIN("register",	REG);
		DBG_SET_FLAG_MIN("release",	REL);
		DBG_SET_FLAG_MIN("remove",	ORM);
		DBG_SET_FLAG_MIN("sample",	SAM);
		DBG_SET_FLAG_MIN("scheduleio",	SIO);
		DBG_SET_FLAG_MIN("select",	SEL);
		DBG_SET_FLAG_MIN("signal",	SIG);
		DBG_SET_FLAG_MIN("swi",		SWI);
		DBG_SET_FLAG_MIN("swo",		SWO);
		DBG_SET_FLAG_MIN("start",	STA);
		DBG_SET_FLAG_MIN("stop",	STO);
		DBG_SET_FLAG_MIN("syscall",	PMS);
		DBG_SET_FLAG_MIN("unlinktarget", TUL);
		DBG_SET_FLAG_MIN("write",	WRI);
		if (found == 0) {
			/* unrecognized flag name */
			error = EINVAL;
			goto done;
		}

		if (c == 0 || c == ' ' || c == '\t') {	/* end of flag group */
			*newbits = tmp;
			continue;
		}

		p++;
		goto newflag;
	}

	/* save the new flag set */
	bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags));

 done:
	free(tmpflags, M_PMC);
	return error;
}

static int
pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)
{
	char *fence, *newstr;
	int error;
	unsigned int n;

	(void) arg1; (void) arg2; /* unused parameters */

	n = sizeof(pmc_debugstr);
	newstr = malloc(n, M_PMC, M_WAITOK|M_ZERO);
	(void) strlcpy(newstr, pmc_debugstr, n);

	error = sysctl_handle_string(oidp, newstr, n, req);

	/* if there is a new string, parse and copy it */
	if (error == 0 && req->newptr != NULL) {
		fence = newstr + (n < req->newlen ? n : req->newlen + 1);
		if ((error = pmc_debugflags_parse(newstr, fence)) == 0)
			(void) strlcpy(pmc_debugstr, newstr,
			    sizeof(pmc_debugstr));
	}

	free(newstr, M_PMC);

	return error;
}
#endif

/*
 * Map a row index to a classdep structure and return the adjusted row
 * index for the PMC class index.
 */
static struct pmc_classdep *
pmc_ri_to_classdep(struct pmc_mdep *md, int ri, int *adjri)
{
	struct pmc_classdep *pcd;

	(void) md;

	KASSERT(ri >= 0 && ri < md->pmd_npmc,
	    ("[pmc,%d] illegal row-index %d", __LINE__, ri));

	pcd = pmc_rowindex_to_classdep[ri];

	KASSERT(pcd != NULL,
	    ("[pmc,%d] ri %d null pcd", __LINE__, ri));

	*adjri = ri - pcd->pcd_ri;

	KASSERT(*adjri >= 0 && *adjri < pcd->pcd_num,
	    ("[pmc,%d] adjusted row-index %d", __LINE__, *adjri));

	return (pcd);
}

/*
 * Concurrency Control
 *
 * The driver manages the following data structures:
 *
 *   - target process descriptors, one per target process
 *   - owner process descriptors (and attached lists), one per owner process
 *   - lookup hash tables for owner and target processes
 *   - PMC descriptors (and attached lists)
 *   - per-cpu hardware state
 *   - the 'hook' variable through which the kernel calls into
 *     this module
 *   - the machine hardware state (managed by the MD layer)
 *
 * These data structures are accessed from:
 *
 * - thread context-switch code
 * - interrupt handlers (possibly on multiple cpus)
 * - kernel threads on multiple cpus running on behalf of user
 *   processes doing system calls
 * - this driver's private kernel threads
 *
 * = Locks and Locking strategy =
 *
 * The driver uses four locking strategies for its operation:
 *
 * - The global SX lock "pmc_sx" is used to protect internal
 *   data structures.
 *
 *   Calls into the module by syscall() start with this lock being
 *   held in exclusive mode.  Depending on the requested operation,
 *   the lock may be downgraded to 'shared' mode to allow more
 *   concurrent readers into the module.  Calls into the module from
 *   other parts of the kernel acquire the lock in shared mode.
 *
 *   This SX lock is held in exclusive mode for any operations that
 *   modify the linkages between the driver's internal data structures.
 *
 *   The 'pmc_hook' function pointer is also protected by this lock.
 *   It is only examined with the sx lock held in exclusive mode.  The
 *   kernel module is allowed to be unloaded only with the sx lock held
 *   in exclusive mode.  In normal syscall handling, after acquiring the
 *   pmc_sx lock we first check that 'pmc_hook' is non-null before
 *   proceeding.  This prevents races between the thread unloading the module
 *   and other threads seeking to use the module.
 *
 * - Lookups of target process structures and owner process structures
 *   cannot use the global "pmc_sx" SX lock because these lookups need
 *   to happen during context switches and in other critical sections
 *   where sleeping is not allowed.  We protect these lookup tables
 *   with their own private spin-mutexes, "pmc_processhash_mtx" and
 *   "pmc_ownerhash_mtx".
 *
 * - Interrupt handlers work in a lock free manner.  At interrupt
 *   time, handlers look at the PMC pointer (phw->phw_pmc) configured
 *   when the PMC was started.  If this pointer is NULL, the interrupt
 *   is ignored after updating driver statistics.  We ensure that this
 *   pointer is set (using an atomic operation if necessary) before the
 *   PMC hardware is started.  Conversely, this pointer is unset atomically
 *   only after the PMC hardware is stopped.
 *
 *   We ensure that everything needed for the operation of an
 *   interrupt handler is available without it needing to acquire any
 *   locks.  We also ensure that a PMC's software state is destroyed only
 *   after the PMC is taken off hardware (on all CPUs).
 *
 * - Context-switch handling with process-private PMCs needs more
 *   care.
 *
 *   A given process may be the target of multiple PMCs.  For example,
 *   PMCATTACH and PMCDETACH may be requested by a process on one CPU
 *   while the target process is running on another.  A PMC could also
 *   be getting released because its owner is exiting.  We tackle
 *   these situations in the following manner:
 *
 *   - each target process structure 'pmc_process' has an array
 *     of 'struct pmc *' pointers, one for each hardware PMC.
 *
 *   - At context switch IN time, each "target" PMC in RUNNING state
 *     gets started on hardware and a pointer to each PMC is copied into
 *     the per-cpu phw array.  The 'runcount' for the PMC is
 *     incremented.
 *
 *   - At context switch OUT time, all process-virtual PMCs are stopped
 *     on hardware.  The saved value is added to the PMCs value field
 *     only if the PMC is in a non-deleted state (the PMCs state could
 *     have changed during the current time slice).
 *
 *     Note that since in-between a switch IN on a processor and a switch
 *     OUT, the PMC could have been released on another CPU.  Therefore
 *     context switch OUT always looks at the hardware state to turn
 *     OFF PMCs and will update a PMC's saved value only if reachable
 *     from the target process record.
 *
 *   - OP PMCRELEASE could be called on a PMC at any time (the PMC could
 *     be attached to many processes at the time of the call and could
 *     be active on multiple CPUs).
 *
 *     We prevent further scheduling of the PMC by marking it as in
 *     state 'DELETED'.  If the runcount of the PMC is non-zero then
 *     this PMC is currently running on a CPU somewhere.  The thread
 *     doing the PMCRELEASE operation waits by repeatedly doing a
 *     pause() till the runcount comes to zero.
 *
 * The contents of a PMC descriptor (struct pmc) are protected using
 * a spin-mutex.  In order to save space, we use a mutex pool.
 *
 * In terms of lock types used by witness(4), we use:
 * - Type "pmc-sx", used by the global SX lock.
 * - Type "pmc-sleep", for sleep mutexes used by logger threads.
 * - Type "pmc-per-proc", for protecting PMC owner descriptors.
 * - Type "pmc-leaf", used for all other spin mutexes.
 */

/*
 * save the cpu binding of the current kthread
 */

static void
pmc_save_cpu_binding(struct pmc_binding *pb)
{
	PMCDBG0(CPU,BND,2, "save-cpu");
	thread_lock(curthread);
	pb->pb_bound = sched_is_bound(curthread);
	pb->pb_cpu   = curthread->td_oncpu;
	thread_unlock(curthread);
	PMCDBG1(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu);
}

/*
 * restore the cpu binding of the current thread
 */

static void
pmc_restore_cpu_binding(struct pmc_binding *pb)
{
	PMCDBG2(CPU,BND,2, "restore-cpu curcpu=%d restore=%d",
	    curthread->td_oncpu, pb->pb_cpu);
	thread_lock(curthread);
	if (pb->pb_bound)
		sched_bind(curthread, pb->pb_cpu);
	else
		sched_unbind(curthread);
	thread_unlock(curthread);
	PMCDBG0(CPU,BND,2, "restore-cpu done");
}

/*
 * move execution over the specified cpu and bind it there.
 */

static void
pmc_select_cpu(int cpu)
{
	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
	    ("[pmc,%d] bad cpu number %d", __LINE__, cpu));

	/* Never move to an inactive CPU. */
	KASSERT(pmc_cpu_is_active(cpu), ("[pmc,%d] selecting inactive "
	    "CPU %d", __LINE__, cpu));

	PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d", cpu);
	thread_lock(curthread);
	sched_bind(curthread, cpu);
	thread_unlock(curthread);

	KASSERT(curthread->td_oncpu == cpu,
	    ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__,
		cpu, curthread->td_oncpu));

	PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d ok", cpu);
}

/*
 * Force a context switch.
 *
 * We do this by pause'ing for 1 tick -- invoking mi_switch() is not
 * guaranteed to force a context switch.
 */

static void
pmc_force_context_switch(void)
{

	pause("pmcctx", 1);
}

uint64_t
pmc_rdtsc(void)
{
#if defined(__i386__) || defined(__amd64__)
	if (__predict_true(amd_feature & AMDID_RDTSCP))
		return rdtscp();
	else
		return rdtsc();
#else
	return get_cyclecount();
#endif
}

/*
 * Get the file name for an executable.  This is a simple wrapper
 * around vn_fullpath(9).
 */

static void
pmc_getfilename(struct vnode *v, char **fullpath, char **freepath)
{

	*fullpath = "unknown";
	*freepath = NULL;
	vn_fullpath(v, fullpath, freepath);
}

/*
 * remove an process owning PMCs
 */

void
pmc_remove_owner(struct pmc_owner *po)
{
	struct pmc *pm, *tmp;

	sx_assert(&pmc_sx, SX_XLOCKED);

	PMCDBG1(OWN,ORM,1, "remove-owner po=%p", po);

	/* Remove descriptor from the owner hash table */
	LIST_REMOVE(po, po_next);

	/* release all owned PMC descriptors */
	LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) {
		PMCDBG1(OWN,ORM,2, "pmc=%p", pm);
		KASSERT(pm->pm_owner == po,
		    ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po));

		pmc_release_pmc_descriptor(pm);	/* will unlink from the list */
		pmc_destroy_pmc_descriptor(pm);
	}

	KASSERT(po->po_sscount == 0,
	    ("[pmc,%d] SS count not zero", __LINE__));
	KASSERT(LIST_EMPTY(&po->po_pmcs),
	    ("[pmc,%d] PMC list not empty", __LINE__));

	/* de-configure the log file if present */
	if (po->po_flags & PMC_PO_OWNS_LOGFILE)
		pmclog_deconfigure_log(po);
}

/*
 * remove an owner process record if all conditions are met.
 */

static void
pmc_maybe_remove_owner(struct pmc_owner *po)
{

	PMCDBG1(OWN,OMR,1, "maybe-remove-owner po=%p", po);

	/*
	 * Remove owner record if
	 * - this process does not own any PMCs
	 * - this process has not allocated a system-wide sampling buffer
	 */

	if (LIST_EMPTY(&po->po_pmcs) &&
	    ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) {
		pmc_remove_owner(po);
		pmc_destroy_owner_descriptor(po);
	}
}

/*
 * Add an association between a target process and a PMC.
 */

static void
pmc_link_target_process(struct pmc *pm, struct pmc_process *pp)
{
	int ri;
	struct pmc_target *pt;
#ifdef INVARIANTS
	struct pmc_thread *pt_td;
#endif

	sx_assert(&pmc_sx, SX_XLOCKED);

	KASSERT(pm != NULL && pp != NULL,
	    ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
	KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
	    ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d",
		__LINE__, pm, pp->pp_proc->p_pid));
	KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= ((int) md->pmd_npmc - 1),
	    ("[pmc,%d] Illegal reference count %d for process record %p",
		__LINE__, pp->pp_refcnt, (void *) pp));

	ri = PMC_TO_ROWINDEX(pm);

	PMCDBG3(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p",
	    pm, ri, pp);

#ifdef	HWPMC_DEBUG
	LIST_FOREACH(pt, &pm->pm_targets, pt_next)
	    if (pt->pt_process == pp)
		    KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets",
				__LINE__, pp, pm));
#endif

	pt = malloc(sizeof(struct pmc_target), M_PMC, M_WAITOK|M_ZERO);
	pt->pt_process = pp;

	LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next);

	atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc,
	    (uintptr_t)pm);

	if (pm->pm_owner->po_owner == pp->pp_proc)
		pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER;

	/*
	 * Initialize the per-process values at this row index.
	 */
	pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ?
	    pm->pm_sc.pm_reloadcount : 0;

	pp->pp_refcnt++;

#ifdef INVARIANTS
	/* Confirm that the per-thread values at this row index are cleared. */
	if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
		mtx_lock_spin(pp->pp_tdslock);
		LIST_FOREACH(pt_td, &pp->pp_tds, pt_next) {
			KASSERT(pt_td->pt_pmcs[ri].pt_pmcval == (pmc_value_t) 0,
			    ("[pmc,%d] pt_pmcval not cleared for pid=%d at "
			    "ri=%d", __LINE__, pp->pp_proc->p_pid, ri));
		}
		mtx_unlock_spin(pp->pp_tdslock);
	}
#endif
}

/*
 * Removes the association between a target process and a PMC.
 */

static void
pmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp)
{
	int ri;
	struct proc *p;
	struct pmc_target *ptgt;
	struct pmc_thread *pt;

	sx_assert(&pmc_sx, SX_XLOCKED);

	KASSERT(pm != NULL && pp != NULL,
	    ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));

	KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt <= (int) md->pmd_npmc,
	    ("[pmc,%d] Illegal ref count %d on process record %p",
		__LINE__, pp->pp_refcnt, (void *) pp));

	ri = PMC_TO_ROWINDEX(pm);

	PMCDBG3(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p",
	    pm, ri, pp);

	KASSERT(pp->pp_pmcs[ri].pp_pmc == pm,
	    ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__,
		ri, pm, pp->pp_pmcs[ri].pp_pmc));

	pp->pp_pmcs[ri].pp_pmc = NULL;
	pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t) 0;

	/* Clear the per-thread values at this row index. */
	if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
		mtx_lock_spin(pp->pp_tdslock);
		LIST_FOREACH(pt, &pp->pp_tds, pt_next)
			pt->pt_pmcs[ri].pt_pmcval = (pmc_value_t) 0;
		mtx_unlock_spin(pp->pp_tdslock);
	}

	/* Remove owner-specific flags */
	if (pm->pm_owner->po_owner == pp->pp_proc) {
		pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS;
		pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER;
	}

	pp->pp_refcnt--;

	/* Remove the target process from the PMC structure */
	LIST_FOREACH(ptgt, &pm->pm_targets, pt_next)
		if (ptgt->pt_process == pp)
			break;

	KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found "
		    "in pmc %p", __LINE__, pp->pp_proc, pp, pm));

	LIST_REMOVE(ptgt, pt_next);
	free(ptgt, M_PMC);

	/* if the PMC now lacks targets, send the owner a SIGIO */
	if (LIST_EMPTY(&pm->pm_targets)) {
		p = pm->pm_owner->po_owner;
		PROC_LOCK(p);
		kern_psignal(p, SIGIO);
		PROC_UNLOCK(p);

		PMCDBG2(PRC,SIG,2, "signalling proc=%p signal=%d", p,
		    SIGIO);
	}
}

/*
 * Check if PMC 'pm' may be attached to target process 't'.
 */

static int
pmc_can_attach(struct pmc *pm, struct proc *t)
{
	struct proc *o;		/* pmc owner */
	struct ucred *oc, *tc;	/* owner, target credentials */
	int decline_attach, i;

	/*
	 * A PMC's owner can always attach that PMC to itself.
	 */

	if ((o = pm->pm_owner->po_owner) == t)
		return 0;

	PROC_LOCK(o);
	oc = o->p_ucred;
	crhold(oc);
	PROC_UNLOCK(o);

	PROC_LOCK(t);
	tc = t->p_ucred;
	crhold(tc);
	PROC_UNLOCK(t);

	/*
	 * The effective uid of the PMC owner should match at least one
	 * of the {effective,real,saved} uids of the target process.
	 */

	decline_attach = oc->cr_uid != tc->cr_uid &&
	    oc->cr_uid != tc->cr_svuid &&
	    oc->cr_uid != tc->cr_ruid;

	/*
	 * Every one of the target's group ids, must be in the owner's
	 * group list.
	 */
	for (i = 0; !decline_attach && i < tc->cr_ngroups; i++)
		decline_attach = !groupmember(tc->cr_groups[i], oc);

	/* check the read and saved gids too */
	if (decline_attach == 0)
		decline_attach = !groupmember(tc->cr_rgid, oc) ||
		    !groupmember(tc->cr_svgid, oc);

	crfree(tc);
	crfree(oc);

	return !decline_attach;
}

/*
 * Attach a process to a PMC.
 */

static int
pmc_attach_one_process(struct proc *p, struct pmc *pm)
{
	int ri, error;
	char *fullpath, *freepath;
	struct pmc_process	*pp;

	sx_assert(&pmc_sx, SX_XLOCKED);

	PMCDBG5(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm,
	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);

	/*
	 * Locate the process descriptor corresponding to process 'p',
	 * allocating space as needed.
	 *
	 * Verify that rowindex 'pm_rowindex' is free in the process
	 * descriptor.
	 *
	 * If not, allocate space for a descriptor and link the
	 * process descriptor and PMC.
	 */
	ri = PMC_TO_ROWINDEX(pm);

	/* mark process as using HWPMCs */
	PROC_LOCK(p);
	p->p_flag |= P_HWPMC;
	PROC_UNLOCK(p);

	if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL) {
		error = ENOMEM;
		goto fail;
	}

	if (pp->pp_pmcs[ri].pp_pmc == pm) {/* already present at slot [ri] */
		error = EEXIST;
		goto fail;
	}

	if (pp->pp_pmcs[ri].pp_pmc != NULL) {
		error = EBUSY;
		goto fail;
	}

	pmc_link_target_process(pm, pp);

	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) &&
	    (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0)
		pm->pm_flags |= PMC_F_NEEDS_LOGFILE;

	pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */

	/* issue an attach event to a configured log file */
	if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) {
		if (p->p_flag & P_KPROC) {
			fullpath = kernelname;
			freepath = NULL;
		} else {
			pmc_getfilename(p->p_textvp, &fullpath, &freepath);
			pmclog_process_pmcattach(pm, p->p_pid, fullpath);
		}
		free(freepath, M_TEMP);
		if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
			pmc_log_process_mappings(pm->pm_owner, p);
	}

	return (0);
 fail:
	PROC_LOCK(p);
	p->p_flag &= ~P_HWPMC;
	PROC_UNLOCK(p);
	return (error);
}

/*
 * Attach a process and optionally its children
 */

static int
pmc_attach_process(struct proc *p, struct pmc *pm)
{
	int error;
	struct proc *top;

	sx_assert(&pmc_sx, SX_XLOCKED);

	PMCDBG5(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);


	/*
	 * If this PMC successfully allowed a GETMSR operation
	 * in the past, disallow further ATTACHes.
	 */

	if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
		return EPERM;

	if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
		return pmc_attach_one_process(p, pm);

	/*
	 * Traverse all child processes, attaching them to
	 * this PMC.
	 */

	sx_slock(&proctree_lock);

	top = p;

	for (;;) {
		if ((error = pmc_attach_one_process(p, pm)) != 0)
			break;
		if (!LIST_EMPTY(&p->p_children))
			p = LIST_FIRST(&p->p_children);
		else for (;;) {
			if (p == top)
				goto done;
			if (LIST_NEXT(p, p_sibling)) {
				p = LIST_NEXT(p, p_sibling);
				break;
			}
			p = p->p_pptr;
		}
	}

	if (error)
		(void) pmc_detach_process(top, pm);

 done:
	sx_sunlock(&proctree_lock);
	return error;
}

/*
 * Detach a process from a PMC.  If there are no other PMCs tracking
 * this process, remove the process structure from its hash table.  If
 * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
 */

static int
pmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
{
	int ri;
	struct pmc_process *pp;

	sx_assert(&pmc_sx, SX_XLOCKED);

	KASSERT(pm != NULL,
	    ("[pmc,%d] null pm pointer", __LINE__));

	ri = PMC_TO_ROWINDEX(pm);

	PMCDBG6(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
	    pm, ri, p, p->p_pid, p->p_comm, flags);

	if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
		return ESRCH;

	if (pp->pp_pmcs[ri].pp_pmc != pm)
		return EINVAL;

	pmc_unlink_target_process(pm, pp);

	/* Issue a detach entry if a log file is configured */
	if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
		pmclog_process_pmcdetach(pm, p->p_pid);

	/*
	 * If there are no PMCs targeting this process, we remove its
	 * descriptor from the target hash table and unset the P_HWPMC
	 * flag in the struct proc.
	 */
	KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
	    ("[pmc,%d] Illegal refcnt %d for process struct %p",
		__LINE__, pp->pp_refcnt, pp));

	if (pp->pp_refcnt != 0)	/* still a target of some PMC */
		return 0;

	pmc_remove_process_descriptor(pp);

	if (flags & PMC_FLAG_REMOVE)
		pmc_destroy_process_descriptor(pp);

	PROC_LOCK(p);
	p->p_flag &= ~P_HWPMC;
	PROC_UNLOCK(p);

	return 0;
}

/*
 * Detach a process and optionally its descendants from a PMC.
 */

static int
pmc_detach_process(struct proc *p, struct pmc *pm)
{
	struct proc *top;

	sx_assert(&pmc_sx, SX_XLOCKED);

	PMCDBG5(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);

	if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
		return pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);

	/*
	 * Traverse all children, detaching them from this PMC.  We
	 * ignore errors since we could be detaching a PMC from a
	 * partially attached proc tree.
	 */

	sx_slock(&proctree_lock);

	top = p;

	for (;;) {
		(void) pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);

		if (!LIST_EMPTY(&p->p_children))
			p = LIST_FIRST(&p->p_children);
		else for (;;) {
			if (p == top)
				goto done;
			if (LIST_NEXT(p, p_sibling)) {
				p = LIST_NEXT(p, p_sibling);
				break;
			}
			p = p->p_pptr;
		}
	}

 done:
	sx_sunlock(&proctree_lock);

	if (LIST_EMPTY(&pm->pm_targets))
		pm->pm_flags &= ~PMC_F_ATTACH_DONE;

	return 0;
}


/*
 * Thread context switch IN
 */

static void
pmc_process_csw_in(struct thread *td)
{
	int cpu;
	unsigned int adjri, ri;
	struct pmc *pm;
	struct proc *p;
	struct pmc_cpu *pc;
	struct pmc_hw *phw;
	pmc_value_t newvalue;
	struct pmc_process *pp;
	struct pmc_thread *pt;
	struct pmc_classdep *pcd;

	p = td->td_proc;
	pt = NULL;
	if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
		return;

	KASSERT(pp->pp_proc == td->td_proc,
	    ("[pmc,%d] not my thread state", __LINE__));

	critical_enter(); /* no preemption from this point */

	cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */

	PMCDBG5(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
	    p->p_pid, p->p_comm, pp);

	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
	    ("[pmc,%d] weird CPU id %d", __LINE__, cpu));

	pc = pmc_pcpu[cpu];

	for (ri = 0; ri < md->pmd_npmc; ri++) {

		if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
			continue;

		KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
		    ("[pmc,%d] Target PMC in non-virtual mode (%d)",
			__LINE__, PMC_TO_MODE(pm)));

		KASSERT(PMC_TO_ROWINDEX(pm) == ri,
		    ("[pmc,%d] Row index mismatch pmc %d != ri %d",
			__LINE__, PMC_TO_ROWINDEX(pm), ri));

		/*
		 * Only PMCs that are marked as 'RUNNING' need
		 * be placed on hardware.
		 */

		if (pm->pm_state != PMC_STATE_RUNNING)
			continue;

		KASSERT(counter_u64_fetch(pm->pm_runcount) >= 0,
	    ("[pmc,%d] pm=%p runcount %ld", __LINE__, (void *) pm,
		 (unsigned long)counter_u64_fetch(pm->pm_runcount)));

		/* increment PMC runcount */
		counter_u64_add(pm->pm_runcount, 1);

		/* configure the HWPMC we are going to use. */
		pcd = pmc_ri_to_classdep(md, ri, &adjri);
		pcd->pcd_config_pmc(cpu, adjri, pm);

		phw = pc->pc_hwpmcs[ri];

		KASSERT(phw != NULL,
		    ("[pmc,%d] null hw pointer", __LINE__));

		KASSERT(phw->phw_pmc == pm,
		    ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
			phw->phw_pmc, pm));

		/*
		 * Write out saved value and start the PMC.
		 *
		 * Sampling PMCs use a per-thread value, while
		 * counting mode PMCs use a per-pmc value that is
		 * inherited across descendants.
		 */
		if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
			if (pt == NULL)
				pt = pmc_find_thread_descriptor(pp, td,
				    PMC_FLAG_NONE);

			KASSERT(pt != NULL,
			    ("[pmc,%d] No thread found for td=%p", __LINE__,
			    td));

			mtx_pool_lock_spin(pmc_mtxpool, pm);

			/*
			 * If we have a thread descriptor, use the per-thread
			 * counter in the descriptor. If not, we will use
			 * a per-process counter. 
			 *
			 * TODO: Remove the per-process "safety net" once
			 * we have thoroughly tested that we don't hit the
			 * above assert.
			 */
			if (pt != NULL) {
				if (pt->pt_pmcs[ri].pt_pmcval > 0)
					newvalue = pt->pt_pmcs[ri].pt_pmcval;
				else
					newvalue = pm->pm_sc.pm_reloadcount;
			} else {
				/*
				 * Use the saved value calculated after the most
				 * recent time a thread using the shared counter
				 * switched out. Reset the saved count in case
				 * another thread from this process switches in
				 * before any threads switch out.
				 */

				newvalue = pp->pp_pmcs[ri].pp_pmcval;
				pp->pp_pmcs[ri].pp_pmcval =
				    pm->pm_sc.pm_reloadcount;
			}
			mtx_pool_unlock_spin(pmc_mtxpool, pm);
			KASSERT(newvalue > 0 && newvalue <=
			    pm->pm_sc.pm_reloadcount,
			    ("[pmc,%d] pmcval outside of expected range cpu=%d "
			    "ri=%d pmcval=%jx pm_reloadcount=%jx", __LINE__,
			    cpu, ri, newvalue, pm->pm_sc.pm_reloadcount));
		} else {
			KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
			    ("[pmc,%d] illegal mode=%d", __LINE__,
			    PMC_TO_MODE(pm)));
			mtx_pool_lock_spin(pmc_mtxpool, pm);
			newvalue = PMC_PCPU_SAVED(cpu, ri) =
			    pm->pm_gv.pm_savedvalue;
			mtx_pool_unlock_spin(pmc_mtxpool, pm);
		}

		PMCDBG3(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);

		pcd->pcd_write_pmc(cpu, adjri, newvalue);

		/* If a sampling mode PMC, reset stalled state. */
		if (PMC_TO_MODE(pm) == PMC_MODE_TS)
			pm->pm_pcpu_state[cpu].pps_stalled = 0;

		/* Indicate that we desire this to run. */
		pm->pm_pcpu_state[cpu].pps_cpustate = 1;

		/* Start the PMC. */
		pcd->pcd_start_pmc(cpu, adjri);
	}

	/*
	 * perform any other architecture/cpu dependent thread
	 * switch-in actions.
	 */

	(void) (*md->pmd_switch_in)(pc, pp);

	critical_exit();

}

/*
 * Thread context switch OUT.
 */

static void
pmc_process_csw_out(struct thread *td)
{
	int cpu;
	int64_t tmp;
	struct pmc *pm;
	struct proc *p;
	enum pmc_mode mode;
	struct pmc_cpu *pc;
	pmc_value_t newvalue;
	unsigned int adjri, ri;
	struct pmc_process *pp;
	struct pmc_thread *pt = NULL;
	struct pmc_classdep *pcd;


	/*
	 * Locate our process descriptor; this may be NULL if
	 * this process is exiting and we have already removed
	 * the process from the target process table.
	 *
	 * Note that due to kernel preemption, multiple
	 * context switches may happen while the process is
	 * exiting.
	 *
	 * Note also that if the target process cannot be
	 * found we still need to deconfigure any PMCs that
	 * are currently running on hardware.
	 */

	p = td->td_proc;
	pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);

	/*
	 * save PMCs
	 */

	critical_enter();

	cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */

	PMCDBG5(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
	    p->p_pid, p->p_comm, pp);

	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
	    ("[pmc,%d weird CPU id %d", __LINE__, cpu));

	pc = pmc_pcpu[cpu];

	/*
	 * When a PMC gets unlinked from a target PMC, it will
	 * be removed from the target's pp_pmc[] array.
	 *
	 * However, on a MP system, the target could have been
	 * executing on another CPU at the time of the unlink.
	 * So, at context switch OUT time, we need to look at
	 * the hardware to determine if a PMC is scheduled on
	 * it.
	 */

	for (ri = 0; ri < md->pmd_npmc; ri++) {

		pcd = pmc_ri_to_classdep(md, ri, &adjri);
		pm  = NULL;
		(void) (*pcd->pcd_get_config)(cpu, adjri, &pm);

		if (pm == NULL)	/* nothing at this row index */
			continue;

		mode = PMC_TO_MODE(pm);
		if (!PMC_IS_VIRTUAL_MODE(mode))
			continue; /* not a process virtual PMC */

		KASSERT(PMC_TO_ROWINDEX(pm) == ri,
		    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
			__LINE__, PMC_TO_ROWINDEX(pm), ri));

		/*
		 * Change desired state, and then stop if not stalled.
		 * This two-step dance should avoid race conditions where
		 * an interrupt re-enables the PMC after this code has
		 * already checked the pm_stalled flag.
		 */
		pm->pm_pcpu_state[cpu].pps_cpustate = 0;
		if (pm->pm_pcpu_state[cpu].pps_stalled == 0)
			pcd->pcd_stop_pmc(cpu, adjri);

		KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
			("[pmc,%d] pm=%p runcount %ld", __LINE__, (void *) pm,
			 (unsigned long)counter_u64_fetch(pm->pm_runcount)));

		/* reduce this PMC's runcount */
		counter_u64_add(pm->pm_runcount, -1);

		/*
		 * If this PMC is associated with this process,
		 * save the reading.
		 */

		if (pm->pm_state != PMC_STATE_DELETED && pp != NULL &&
		    pp->pp_pmcs[ri].pp_pmc != NULL) {
			KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
			    ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
				pm, ri, pp->pp_pmcs[ri].pp_pmc));

			KASSERT(pp->pp_refcnt > 0,
			    ("[pmc,%d] pp refcnt = %d", __LINE__,
				pp->pp_refcnt));

			pcd->pcd_read_pmc(cpu, adjri, &newvalue);

			if (mode == PMC_MODE_TS) {
				PMCDBG3(CSW,SWO,1,"cpu=%d ri=%d val=%jd (samp)",
				    cpu, ri, newvalue);

				if (pt == NULL)
					pt = pmc_find_thread_descriptor(pp, td,
					    PMC_FLAG_NONE);

				KASSERT(pt != NULL,
				    ("[pmc,%d] No thread found for td=%p",
				    __LINE__, td));

				mtx_pool_lock_spin(pmc_mtxpool, pm);

				/*
				 * If we have a thread descriptor, save the
				 * per-thread counter in the descriptor. If not,
				 * we will update the per-process counter.
				 *
				 * TODO: Remove the per-process "safety net"
				 * once we have thoroughly tested that we
				 * don't hit the above assert.
				 */
				if (pt != NULL)
					pt->pt_pmcs[ri].pt_pmcval = newvalue;
				else {
					/*
					 * For sampling process-virtual PMCs,
					 * newvalue is the number of events to
					 * be seen until the next sampling
					 * interrupt. We can just add the events
					 * left from this invocation to the
					 * counter, then adjust in case we
					 * overflow our range.
					 *
					 * (Recall that we reload the counter
					 * every time we use it.)
					 */
					pp->pp_pmcs[ri].pp_pmcval += newvalue;
					if (pp->pp_pmcs[ri].pp_pmcval >
					    pm->pm_sc.pm_reloadcount)
						pp->pp_pmcs[ri].pp_pmcval -=
						    pm->pm_sc.pm_reloadcount;
				}
				mtx_pool_unlock_spin(pmc_mtxpool, pm);
			} else {
				tmp = newvalue - PMC_PCPU_SAVED(cpu,ri);

				PMCDBG3(CSW,SWO,1,"cpu=%d ri=%d tmp=%jd (count)",
				    cpu, ri, tmp);

				/*
				 * For counting process-virtual PMCs,
				 * we expect the count to be
				 * increasing monotonically, modulo a 64
				 * bit wraparound.
				 */
				KASSERT(tmp >= 0,
				    ("[pmc,%d] negative increment cpu=%d "
				     "ri=%d newvalue=%jx saved=%jx "
				     "incr=%jx", __LINE__, cpu, ri,
				     newvalue, PMC_PCPU_SAVED(cpu,ri), tmp));

				mtx_pool_lock_spin(pmc_mtxpool, pm);
				pm->pm_gv.pm_savedvalue += tmp;
				pp->pp_pmcs[ri].pp_pmcval += tmp;
				mtx_pool_unlock_spin(pmc_mtxpool, pm);

				if (pm->pm_flags & PMC_F_LOG_PROCCSW)
					pmclog_process_proccsw(pm, pp, tmp, td);
			}
		}

		/* mark hardware as free */
		pcd->pcd_config_pmc(cpu, adjri, NULL);
	}

	/*
	 * perform any other architecture/cpu dependent thread
	 * switch out functions.
	 */

	(void) (*md->pmd_switch_out)(pc, pp);

	critical_exit();
}

/*
 * A new thread for a process.
 */
static void
pmc_process_thread_add(struct thread *td)
{
	struct pmc_process *pmc;

	pmc = pmc_find_process_descriptor(td->td_proc, PMC_FLAG_NONE);
	if (pmc != NULL)
		pmc_find_thread_descriptor(pmc, td, PMC_FLAG_ALLOCATE);
}

/*
 * A thread delete for a process.
 */
static void
pmc_process_thread_delete(struct thread *td)
{
	struct pmc_process *pmc;

	pmc = pmc_find_process_descriptor(td->td_proc, PMC_FLAG_NONE);
	if (pmc != NULL)
		pmc_thread_descriptor_pool_free(pmc_find_thread_descriptor(pmc,
		    td, PMC_FLAG_REMOVE));
}

/*
 * A userret() call for a thread.
 */
static void
pmc_process_thread_userret(struct thread *td)
{
	sched_pin();
	pmc_capture_user_callchain(curcpu, PMC_UR, td->td_frame);
	sched_unpin();
}

/*
 * A mapping change for a process.
 */

static void
pmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm)
{
	int ri;
	pid_t pid;
	char *fullpath, *freepath;
	const struct pmc *pm;
	struct pmc_owner *po;
	const struct pmc_process *pp;

	freepath = fullpath = NULL;
	MPASS(!in_epoch(global_epoch_preempt));
	pmc_getfilename((struct vnode *) pkm->pm_file, &fullpath, &freepath);

	pid = td->td_proc->p_pid;

	PMC_EPOCH_ENTER();
	/* Inform owners of all system-wide sampling PMCs. */
	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
			pmclog_process_map_in(po, pid, pkm->pm_address, fullpath);

	if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
		goto done;

	/*
	 * Inform sampling PMC owners tracking this process.
	 */
	for (ri = 0; ri < md->pmd_npmc; ri++)
		if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
		    PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
			pmclog_process_map_in(pm->pm_owner,
			    pid, pkm->pm_address, fullpath);

  done:
	if (freepath)
		free(freepath, M_TEMP);
	PMC_EPOCH_EXIT();
}


/*
 * Log an munmap request.
 */

static void
pmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm)
{
	int ri;
	pid_t pid;
	struct pmc_owner *po;
	const struct pmc *pm;
	const struct pmc_process *pp;

	pid = td->td_proc->p_pid;

	PMC_EPOCH_ENTER();
	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
		pmclog_process_map_out(po, pid, pkm->pm_address,
		    pkm->pm_address + pkm->pm_size);
	PMC_EPOCH_EXIT();

	if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
		return;

	for (ri = 0; ri < md->pmd_npmc; ri++)
		if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
		    PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
			pmclog_process_map_out(pm->pm_owner, pid,
			    pkm->pm_address, pkm->pm_address + pkm->pm_size);
}

/*
 * Log mapping information about the kernel.
 */

static void
pmc_log_kernel_mappings(struct pmc *pm)
{
	struct pmc_owner *po;
	struct pmckern_map_in *km, *kmbase;

	MPASS(in_epoch(global_epoch_preempt) || sx_xlocked(&pmc_sx));
	KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
	    ("[pmc,%d] non-sampling PMC (%p) desires mapping information",
		__LINE__, (void *) pm));

	po = pm->pm_owner;

	if (po->po_flags & PMC_PO_INITIAL_MAPPINGS_DONE)
		return;
	if (PMC_TO_MODE(pm) == PMC_MODE_SS)
		pmc_process_allproc(pm);
	/*
	 * Log the current set of kernel modules.
	 */
	kmbase = linker_hwpmc_list_objects();
	for (km = kmbase; km->pm_file != NULL; km++) {
		PMCDBG2(LOG,REG,1,"%s %p", (char *) km->pm_file,
		    (void *) km->pm_address);
		pmclog_process_map_in(po, (pid_t) -1, km->pm_address,
		    km->pm_file);
	}
	free(kmbase, M_LINKER);

	po->po_flags |= PMC_PO_INITIAL_MAPPINGS_DONE;
}

/*
 * Log the mappings for a single process.
 */

static void
pmc_log_process_mappings(struct pmc_owner *po, struct proc *p)
{
	vm_map_t map;
	struct vnode *vp;
	struct vmspace *vm;
	vm_map_entry_t entry;
	vm_offset_t last_end;
	u_int last_timestamp;
	struct vnode *last_vp;
	vm_offset_t start_addr;
	vm_object_t obj, lobj, tobj;
	char *fullpath, *freepath;

	last_vp = NULL;
	last_end = (vm_offset_t) 0;
	fullpath = freepath = NULL;

	if ((vm = vmspace_acquire_ref(p)) == NULL)
		return;

	map = &vm->vm_map;
	vm_map_lock_read(map);

	VM_MAP_ENTRY_FOREACH(entry, map) {

		if (entry == NULL) {
			PMCDBG2(LOG,OPS,2, "hwpmc: vm_map entry unexpectedly "
			    "NULL! pid=%d vm_map=%p\n", p->p_pid, map);
			break;
		}

		/*
		 * We only care about executable map entries.
		 */
		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) ||
		    !(entry->protection & VM_PROT_EXECUTE) ||
		    (entry->object.vm_object == NULL)) {
			continue;
		}

		obj = entry->object.vm_object;
		VM_OBJECT_RLOCK(obj);

		/* 
		 * Walk the backing_object list to find the base
		 * (non-shadowed) vm_object.
		 */
		for (lobj = tobj = obj; tobj != NULL; tobj = tobj->backing_object) {
			if (tobj != obj)
				VM_OBJECT_RLOCK(tobj);
			if (lobj != obj)
				VM_OBJECT_RUNLOCK(lobj);
			lobj = tobj;
		}

		/*
		 * At this point lobj is the base vm_object and it is locked.
		 */
		if (lobj == NULL) {
			PMCDBG3(LOG,OPS,2, "hwpmc: lobj unexpectedly NULL! pid=%d "
			    "vm_map=%p vm_obj=%p\n", p->p_pid, map, obj);
			VM_OBJECT_RUNLOCK(obj);
			continue;
		}

		vp = vm_object_vnode(lobj);
		if (vp == NULL) {
			if (lobj != obj)
				VM_OBJECT_RUNLOCK(lobj);
			VM_OBJECT_RUNLOCK(obj);
			continue;
		}

		/*
		 * Skip contiguous regions that point to the same
		 * vnode, so we don't emit redundant MAP-IN
		 * directives.
		 */
		if (entry->start == last_end && vp == last_vp) {
			last_end = entry->end;
			if (lobj != obj)
				VM_OBJECT_RUNLOCK(lobj);
			VM_OBJECT_RUNLOCK(obj);
			continue;
		}

		/* 
		 * We don't want to keep the proc's vm_map or this
		 * vm_object locked while we walk the pathname, since
		 * vn_fullpath() can sleep.  However, if we drop the
		 * lock, it's possible for concurrent activity to
		 * modify the vm_map list.  To protect against this,
		 * we save the vm_map timestamp before we release the
		 * lock, and check it after we reacquire the lock
		 * below.
		 */
		start_addr = entry->start;
		last_end = entry->end;
		last_timestamp = map->timestamp;
		vm_map_unlock_read(map);

		vref(vp);
		if (lobj != obj)
			VM_OBJECT_RUNLOCK(lobj);

		VM_OBJECT_RUNLOCK(obj);

		freepath = NULL;
		pmc_getfilename(vp, &fullpath, &freepath);
		last_vp = vp;

		vrele(vp);

		vp = NULL;
		pmclog_process_map_in(po, p->p_pid, start_addr, fullpath);
		if (freepath)
			free(freepath, M_TEMP);

		vm_map_lock_read(map);

		/*
		 * If our saved timestamp doesn't match, this means
		 * that the vm_map was modified out from under us and
		 * we can't trust our current "entry" pointer.  Do a
		 * new lookup for this entry.  If there is no entry
		 * for this address range, vm_map_lookup_entry() will
		 * return the previous one, so we always want to go to
		 * the next entry on the next loop iteration.
		 * 
		 * There is an edge condition here that can occur if
		 * there is no entry at or before this address.  In
		 * this situation, vm_map_lookup_entry returns
		 * &map->header, which would cause our loop to abort
		 * without processing the rest of the map.  However,
		 * in practice this will never happen for process
		 * vm_map.  This is because the executable's text
		 * segment is the first mapping in the proc's address
		 * space, and this mapping is never removed until the
		 * process exits, so there will always be a non-header
		 * entry at or before the requested address for
		 * vm_map_lookup_entry to return.
		 */
		if (map->timestamp != last_timestamp)
			vm_map_lookup_entry(map, last_end - 1, &entry);
	}

	vm_map_unlock_read(map);
	vmspace_free(vm);
	return;
}

/*
 * Log mappings for all processes in the system.
 */

static void
pmc_log_all_process_mappings(struct pmc_owner *po)
{
	struct proc *p, *top;

	sx_assert(&pmc_sx, SX_XLOCKED);

	if ((p = pfind(1)) == NULL)
		panic("[pmc,%d] Cannot find init", __LINE__);

	PROC_UNLOCK(p);

	sx_slock(&proctree_lock);

	top = p;

	for (;;) {
		pmc_log_process_mappings(po, p);
		if (!LIST_EMPTY(&p->p_children))
			p = LIST_FIRST(&p->p_children);
		else for (;;) {
			if (p == top)
				goto done;
			if (LIST_NEXT(p, p_sibling)) {
				p = LIST_NEXT(p, p_sibling);
				break;
			}
			p = p->p_pptr;
		}
	}
 done:
	sx_sunlock(&proctree_lock);
}

/*
 * The 'hook' invoked from the kernel proper
 */


#ifdef	HWPMC_DEBUG
const char *pmc_hooknames[] = {
	/* these strings correspond to PMC_FN_* in <sys/pmckern.h> */
	"",
	"EXEC",
	"CSW-IN",
	"CSW-OUT",
	"SAMPLE",
	"UNUSED1",
	"UNUSED2",
	"MMAP",
	"MUNMAP",
	"CALLCHAIN-NMI",
	"CALLCHAIN-SOFT",
	"SOFTSAMPLING",
	"THR-CREATE",
	"THR-EXIT",
	"THR-USERRET",
	"THR-CREATE-LOG",
	"THR-EXIT-LOG",
	"PROC-CREATE-LOG"
};
#endif

static int
pmc_hook_handler(struct thread *td, int function, void *arg)
{
	int cpu;

	PMCDBG4(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
	    pmc_hooknames[function], arg);

	switch (function)
	{

	/*
	 * Process exec()
	 */

	case PMC_FN_PROCESS_EXEC:
	{
		char *fullpath, *freepath;
		unsigned int ri;
		int is_using_hwpmcs;
		struct pmc *pm;
		struct proc *p;
		struct pmc_owner *po;
		struct pmc_process *pp;
		struct pmckern_procexec *pk;

		sx_assert(&pmc_sx, SX_XLOCKED);

		p = td->td_proc;
		pmc_getfilename(p->p_textvp, &fullpath, &freepath);

		pk = (struct pmckern_procexec *) arg;

		PMC_EPOCH_ENTER();
		/* Inform owners of SS mode PMCs of the exec event. */
		CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
		    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
			    pmclog_process_procexec(po, PMC_ID_INVALID,
				p->p_pid, pk->pm_entryaddr, fullpath);
		PMC_EPOCH_EXIT();

		PROC_LOCK(p);
		is_using_hwpmcs = p->p_flag & P_HWPMC;
		PROC_UNLOCK(p);

		if (!is_using_hwpmcs) {
			if (freepath)
				free(freepath, M_TEMP);
			break;
		}

		/*
		 * PMCs are not inherited across an exec():  remove any
		 * PMCs that this process is the owner of.
		 */

		if ((po = pmc_find_owner_descriptor(p)) != NULL) {
			pmc_remove_owner(po);
			pmc_destroy_owner_descriptor(po);
		}

		/*
		 * If the process being exec'ed is not the target of any
		 * PMC, we are done.
		 */
		if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
			if (freepath)
				free(freepath, M_TEMP);
			break;
		}

		/*
		 * Log the exec event to all monitoring owners.  Skip
		 * owners who have already received the event because
		 * they had system sampling PMCs active.
		 */
		for (ri = 0; ri < md->pmd_npmc; ri++)
			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
				po = pm->pm_owner;
				if (po->po_sscount == 0 &&
				    po->po_flags & PMC_PO_OWNS_LOGFILE)
					pmclog_process_procexec(po, pm->pm_id,
					    p->p_pid, pk->pm_entryaddr,
					    fullpath);
			}

		if (freepath)
			free(freepath, M_TEMP);


		PMCDBG4(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
		    p, p->p_pid, p->p_comm, pk->pm_credentialschanged);

		if (pk->pm_credentialschanged == 0) /* no change */
			break;

		/*
		 * If the newly exec()'ed process has a different credential
		 * than before, allow it to be the target of a PMC only if
		 * the PMC's owner has sufficient privilege.
		 */

		for (ri = 0; ri < md->pmd_npmc; ri++)
			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL)
				if (pmc_can_attach(pm, td->td_proc) != 0)
					pmc_detach_one_process(td->td_proc,
					    pm, PMC_FLAG_NONE);

		KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
		    ("[pmc,%d] Illegal ref count %d on pp %p", __LINE__,
			pp->pp_refcnt, pp));

		/*
		 * If this process is no longer the target of any
		 * PMCs, we can remove the process entry and free
		 * up space.
		 */

		if (pp->pp_refcnt == 0) {
			pmc_remove_process_descriptor(pp);
			pmc_destroy_process_descriptor(pp);
			break;
		}

	}
	break;

	case PMC_FN_CSW_IN:
		pmc_process_csw_in(td);
		break;

	case PMC_FN_CSW_OUT:
		pmc_process_csw_out(td);
		break;

	/*
	 * Process accumulated PC samples.
	 *
	 * This function is expected to be called by hardclock() for
	 * each CPU that has accumulated PC samples.
	 *
	 * This function is to be executed on the CPU whose samples
	 * are being processed.
	 */
	case PMC_FN_DO_SAMPLES:

		/*
		 * Clear the cpu specific bit in the CPU mask before
		 * do the rest of the processing.  If the NMI handler
		 * gets invoked after the "atomic_clear_int()" call
		 * below but before "pmc_process_samples()" gets
		 * around to processing the interrupt, then we will
		 * come back here at the next hardclock() tick (and
		 * may find nothing to do if "pmc_process_samples()"
		 * had already processed the interrupt).  We don't
		 * lose the interrupt sample.
		 */
		DPCPU_SET(pmc_sampled, 0);
		cpu = PCPU_GET(cpuid);
		pmc_process_samples(cpu, PMC_HR);
		pmc_process_samples(cpu, PMC_SR);
		pmc_process_samples(cpu, PMC_UR);
		break;

	case PMC_FN_MMAP:
		pmc_process_mmap(td, (struct pmckern_map_in *) arg);
		break;

	case PMC_FN_MUNMAP:
		MPASS(in_epoch(global_epoch_preempt) || sx_xlocked(&pmc_sx));
		pmc_process_munmap(td, (struct pmckern_map_out *) arg);
		break;

	case PMC_FN_PROC_CREATE_LOG:
		pmc_process_proccreate((struct proc *)arg);
		break;

	case PMC_FN_USER_CALLCHAIN:
		/*
		 * Record a call chain.
		 */
		KASSERT(td == curthread, ("[pmc,%d] td != curthread",
		    __LINE__));

		pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_HR,
		    (struct trapframe *) arg);

		KASSERT(td->td_pinned == 1,
			("[pmc,%d] invalid td_pinned value", __LINE__));
		sched_unpin();  /* Can migrate safely now. */

		td->td_pflags &= ~TDP_CALLCHAIN;
		break;

	case PMC_FN_USER_CALLCHAIN_SOFT:
		/*
		 * Record a call chain.
		 */
		KASSERT(td == curthread, ("[pmc,%d] td != curthread",
		    __LINE__));

		cpu = PCPU_GET(cpuid);
		pmc_capture_user_callchain(cpu, PMC_SR,
		    (struct trapframe *) arg);

		KASSERT(td->td_pinned == 1,
		    ("[pmc,%d] invalid td_pinned value", __LINE__));

		sched_unpin();  /* Can migrate safely now. */

		td->td_pflags &= ~TDP_CALLCHAIN;
		break;

	case PMC_FN_SOFT_SAMPLING:
		/*
		 * Call soft PMC sampling intr.
		 */
		pmc_soft_intr((struct pmckern_soft *) arg);
		break;

	case PMC_FN_THR_CREATE:
		pmc_process_thread_add(td);
		pmc_process_threadcreate(td);
		break;

	case PMC_FN_THR_CREATE_LOG:
		pmc_process_threadcreate(td);
		break;

	case PMC_FN_THR_EXIT:
		KASSERT(td == curthread, ("[pmc,%d] td != curthread",
		    __LINE__));
		pmc_process_thread_delete(td);
		pmc_process_threadexit(td);
		break;
	case PMC_FN_THR_EXIT_LOG:
		pmc_process_threadexit(td);
		break;
	case PMC_FN_THR_USERRET:
		KASSERT(td == curthread, ("[pmc,%d] td != curthread",
		    __LINE__));
		pmc_process_thread_userret(td);
		break;

	default:
#ifdef	HWPMC_DEBUG
		KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
#endif
		break;

	}

	return 0;
}

/*
 * allocate a 'struct pmc_owner' descriptor in the owner hash table.
 */

static struct pmc_owner *
pmc_allocate_owner_descriptor(struct proc *p)
{
	uint32_t hindex;
	struct pmc_owner *po;
	struct pmc_ownerhash *poh;

	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
	poh = &pmc_ownerhash[hindex];

	/* allocate space for N pointers and one descriptor struct */
	po = malloc(sizeof(struct pmc_owner), M_PMC, M_WAITOK|M_ZERO);
	po->po_owner = p;
	LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */

	TAILQ_INIT(&po->po_logbuffers);
	mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);

	PMCDBG4(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
	    p, p->p_pid, p->p_comm, po);

	return po;
}

static void
pmc_destroy_owner_descriptor(struct pmc_owner *po)
{

	PMCDBG4(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
	    po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);

	mtx_destroy(&po->po_mtx);
	free(po, M_PMC);
}

/*
 * Allocate a thread descriptor from the free pool.
 *
 * NOTE: This *can* return NULL.
 */
static struct pmc_thread *
pmc_thread_descriptor_pool_alloc(void)
{
	struct pmc_thread *pt;

	mtx_lock_spin(&pmc_threadfreelist_mtx);
	if ((pt = LIST_FIRST(&pmc_threadfreelist)) != NULL) {
		LIST_REMOVE(pt, pt_next);
		pmc_threadfreelist_entries--;
	}
	mtx_unlock_spin(&pmc_threadfreelist_mtx);

	return (pt);
}

/*
 * Add a thread descriptor to the free pool. We use this instead of free()
 * to maintain a cache of free entries. Additionally, we can safely call
 * this function when we cannot call free(), such as in a critical section.
 * 
 */
static void
pmc_thread_descriptor_pool_free(struct pmc_thread *pt)
{

	if (pt == NULL)
		return;

	memset(pt, 0, THREADENTRY_SIZE);
	mtx_lock_spin(&pmc_threadfreelist_mtx);
	LIST_INSERT_HEAD(&pmc_threadfreelist, pt, pt_next);
	pmc_threadfreelist_entries++;
	if (pmc_threadfreelist_entries > pmc_threadfreelist_max)
		taskqueue_enqueue(taskqueue_fast, &free_task);
	mtx_unlock_spin(&pmc_threadfreelist_mtx);
}

/*
 * An asynchronous task to manage the free list.
 */
static void
pmc_thread_descriptor_pool_free_task(void *arg __unused, int pending __unused)
{
	struct pmc_thread *pt;
	LIST_HEAD(, pmc_thread) tmplist;
	int delta;

	LIST_INIT(&tmplist);

	/* Determine what changes, if any, we need to make. */
	mtx_lock_spin(&pmc_threadfreelist_mtx);
	delta = pmc_threadfreelist_entries - pmc_threadfreelist_max;
	while (delta > 0 && (pt = LIST_FIRST(&pmc_threadfreelist)) != NULL) {
		delta--;
		pmc_threadfreelist_entries--;
		LIST_REMOVE(pt, pt_next);
		LIST_INSERT_HEAD(&tmplist, pt, pt_next);
	}
	mtx_unlock_spin(&pmc_threadfreelist_mtx);

	/* If there are entries to free, free them. */
	while (!LIST_EMPTY(&tmplist)) {
		pt = LIST_FIRST(&tmplist);
		LIST_REMOVE(pt, pt_next);
		free(pt, M_PMC);
	}
}

/*
 * Drain the thread free pool, freeing all allocations.
 */
static void
pmc_thread_descriptor_pool_drain()
{
	struct pmc_thread *pt, *next;

	LIST_FOREACH_SAFE(pt, &pmc_threadfreelist, pt_next, next) {
		LIST_REMOVE(pt, pt_next);
		free(pt, M_PMC);
	}
}

/*
 * find the descriptor corresponding to thread 'td', adding or removing it
 * as specified by 'mode'.
 *
 * Note that this supports additional mode flags in addition to those
 * supported by pmc_find_process_descriptor():
 * PMC_FLAG_NOWAIT: Causes the function to not wait for mallocs.
 *     This makes it safe to call while holding certain other locks.
 */

static struct pmc_thread *
pmc_find_thread_descriptor(struct pmc_process *pp, struct thread *td,
    uint32_t mode)
{
	struct pmc_thread *pt = NULL, *ptnew = NULL;
	int wait_flag;

	KASSERT(td != NULL, ("[pmc,%d] called to add NULL td", __LINE__));

	/*
	 * Pre-allocate memory in the PMC_FLAG_ALLOCATE case prior to
	 * acquiring the lock.
	 */
	if (mode & PMC_FLAG_ALLOCATE) {
		if ((ptnew = pmc_thread_descriptor_pool_alloc()) == NULL) {
			wait_flag = M_WAITOK;
			if ((mode & PMC_FLAG_NOWAIT) || in_epoch(global_epoch_preempt))
				wait_flag = M_NOWAIT;

			ptnew = malloc(THREADENTRY_SIZE, M_PMC,
			    wait_flag|M_ZERO);
		}
	}

	mtx_lock_spin(pp->pp_tdslock);

	LIST_FOREACH(pt, &pp->pp_tds, pt_next)
		if (pt->pt_td == td)
			break;

	if ((mode & PMC_FLAG_REMOVE) && pt != NULL)
		LIST_REMOVE(pt, pt_next);

	if ((mode & PMC_FLAG_ALLOCATE) && pt == NULL && ptnew != NULL) {
		pt = ptnew;
		ptnew = NULL;
		pt->pt_td = td;
		LIST_INSERT_HEAD(&pp->pp_tds, pt, pt_next);
	}

	mtx_unlock_spin(pp->pp_tdslock);

	if (ptnew != NULL) {
		free(ptnew, M_PMC);
	}

	return pt;
}

/*
 * Try to add thread descriptors for each thread in a process.
 */

static void
pmc_add_thread_descriptors_from_proc(struct proc *p, struct pmc_process *pp)
{
	struct thread *curtd;
	struct pmc_thread **tdlist;
	int i, tdcnt, tdlistsz;

	KASSERT(!PROC_LOCKED(p), ("[pmc,%d] proc unexpectedly locked",
	    __LINE__));
	tdcnt = 32;
 restart:
	tdlistsz = roundup2(tdcnt, 32);

	tdcnt = 0;
	tdlist = malloc(sizeof(struct pmc_thread*) * tdlistsz, M_TEMP, M_WAITOK);

	PROC_LOCK(p);
	FOREACH_THREAD_IN_PROC(p, curtd)
		tdcnt++;
	if (tdcnt >= tdlistsz) {
		PROC_UNLOCK(p);
		free(tdlist, M_TEMP);
		goto restart;
	}
	/*
	 * Try to add each thread to the list without sleeping. If unable,
	 * add to a queue to retry after dropping the process lock.
	 */
	tdcnt = 0;
	FOREACH_THREAD_IN_PROC(p, curtd) {
		tdlist[tdcnt] = pmc_find_thread_descriptor(pp, curtd,
						   PMC_FLAG_ALLOCATE|PMC_FLAG_NOWAIT);
		if (tdlist[tdcnt] == NULL) {
			PROC_UNLOCK(p);
			for (i = 0; i <= tdcnt; i++)
				pmc_thread_descriptor_pool_free(tdlist[i]);
			free(tdlist, M_TEMP);
			goto restart;
		}
		tdcnt++;
	}
	PROC_UNLOCK(p);
	free(tdlist, M_TEMP);
}

/*
 * find the descriptor corresponding to process 'p', adding or removing it
 * as specified by 'mode'.
 */

static struct pmc_process *
pmc_find_process_descriptor(struct proc *p, uint32_t mode)
{
	uint32_t hindex;
	struct pmc_process *pp, *ppnew;
	struct pmc_processhash *pph;

	hindex = PMC_HASH_PTR(p, pmc_processhashmask);
	pph = &pmc_processhash[hindex];

	ppnew = NULL;

	/*
	 * Pre-allocate memory in the PMC_FLAG_ALLOCATE case since we
	 * cannot call malloc(9) once we hold a spin lock.
	 */
	if (mode & PMC_FLAG_ALLOCATE)
		ppnew = malloc(sizeof(struct pmc_process) + md->pmd_npmc *
		    sizeof(struct pmc_targetstate), M_PMC, M_WAITOK|M_ZERO);

	mtx_lock_spin(&pmc_processhash_mtx);
	LIST_FOREACH(pp, pph, pp_next)
	    if (pp->pp_proc == p)
		    break;

	if ((mode & PMC_FLAG_REMOVE) && pp != NULL)
		LIST_REMOVE(pp, pp_next);

	if ((mode & PMC_FLAG_ALLOCATE) && pp == NULL &&
	    ppnew != NULL) {
		ppnew->pp_proc = p;
		LIST_INIT(&ppnew->pp_tds);
		ppnew->pp_tdslock = mtx_pool_find(pmc_mtxpool, ppnew);
		LIST_INSERT_HEAD(pph, ppnew, pp_next);
		mtx_unlock_spin(&pmc_processhash_mtx);
		pp = ppnew;
		ppnew = NULL;

		/* Add thread descriptors for this process' current threads. */
		pmc_add_thread_descriptors_from_proc(p, pp);
	}
	else
		mtx_unlock_spin(&pmc_processhash_mtx);

	if (ppnew != NULL)
		free(ppnew, M_PMC);

	return pp;
}

/*
 * remove a process descriptor from the process hash table.
 */

static void
pmc_remove_process_descriptor(struct pmc_process *pp)
{
	KASSERT(pp->pp_refcnt == 0,
	    ("[pmc,%d] Removing process descriptor %p with count %d",
		__LINE__, pp, pp->pp_refcnt));

	mtx_lock_spin(&pmc_processhash_mtx);
	LIST_REMOVE(pp, pp_next);
	mtx_unlock_spin(&pmc_processhash_mtx);
}

/*
 * destroy a process descriptor.
 */

static void
pmc_destroy_process_descriptor(struct pmc_process *pp)
{
	struct pmc_thread *pmc_td;

	while ((pmc_td = LIST_FIRST(&pp->pp_tds)) != NULL) {
		LIST_REMOVE(pmc_td, pt_next);
		pmc_thread_descriptor_pool_free(pmc_td);
	}
	free(pp, M_PMC);
}


/*
 * find an owner descriptor corresponding to proc 'p'
 */

static struct pmc_owner *
pmc_find_owner_descriptor(struct proc *p)
{
	uint32_t hindex;
	struct pmc_owner *po;
	struct pmc_ownerhash *poh;

	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
	poh = &pmc_ownerhash[hindex];

	po = NULL;
	LIST_FOREACH(po, poh, po_next)
	    if (po->po_owner == p)
		    break;

	PMCDBG5(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
	    "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);

	return po;
}

/*
 * pmc_allocate_pmc_descriptor
 *
 * Allocate a pmc descriptor and initialize its
 * fields.
 */

static struct pmc *
pmc_allocate_pmc_descriptor(void)
{
	struct pmc *pmc;

	pmc = malloc(sizeof(struct pmc), M_PMC, M_WAITOK|M_ZERO);
	pmc->pm_runcount = counter_u64_alloc(M_WAITOK);
	pmc->pm_pcpu_state = malloc(sizeof(struct pmc_pcpu_state)*mp_ncpus, M_PMC, M_WAITOK|M_ZERO);
	PMCDBG1(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);

	return pmc;
}

/*
 * Destroy a pmc descriptor.
 */

static void
pmc_destroy_pmc_descriptor(struct pmc *pm)
{

	KASSERT(pm->pm_state == PMC_STATE_DELETED ||
	    pm->pm_state == PMC_STATE_FREE,
	    ("[pmc,%d] destroying non-deleted PMC", __LINE__));
	KASSERT(LIST_EMPTY(&pm->pm_targets),
	    ("[pmc,%d] destroying pmc with targets", __LINE__));
	KASSERT(pm->pm_owner == NULL,
	    ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
	KASSERT(counter_u64_fetch(pm->pm_runcount) == 0,
	    ("[pmc,%d] pmc has non-zero run count %ld", __LINE__,
		 (unsigned long)counter_u64_fetch(pm->pm_runcount)));

	counter_u64_free(pm->pm_runcount);
	free(pm->pm_pcpu_state, M_PMC);
	free(pm, M_PMC);
}

static void
pmc_wait_for_pmc_idle(struct pmc *pm)
{
#ifdef INVARIANTS
	volatile int maxloop;

	maxloop = 100 * pmc_cpu_max();
#endif
	/*
	 * Loop (with a forced context switch) till the PMC's runcount
	 * comes down to zero.
	 */
	pmclog_flush(pm->pm_owner, 1);
	while (counter_u64_fetch(pm->pm_runcount) > 0) {
		pmclog_flush(pm->pm_owner, 1);
#ifdef INVARIANTS
		maxloop--;
		KASSERT(maxloop > 0,
		    ("[pmc,%d] (ri%d, rc%ld) waiting too long for "
			"pmc to be free", __LINE__,
			 PMC_TO_ROWINDEX(pm), (unsigned long)counter_u64_fetch(pm->pm_runcount)));
#endif
		pmc_force_context_switch();
	}
}

/*
 * This function does the following things:
 *
 *  - detaches the PMC from hardware
 *  - unlinks all target threads that were attached to it
 *  - removes the PMC from its owner's list
 *  - destroys the PMC private mutex
 *
 * Once this function completes, the given pmc pointer can be freed by
 * calling pmc_destroy_pmc_descriptor().
 */

static void
pmc_release_pmc_descriptor(struct pmc *pm)
{
	enum pmc_mode mode;
	struct pmc_hw *phw;
	u_int adjri, ri, cpu;
	struct pmc_owner *po;
	struct pmc_binding pb;
	struct pmc_process *pp;
	struct pmc_classdep *pcd;
	struct pmc_target *ptgt, *tmp;

	sx_assert(&pmc_sx, SX_XLOCKED);

	KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));

	ri   = PMC_TO_ROWINDEX(pm);
	pcd  = pmc_ri_to_classdep(md, ri, &adjri);
	mode = PMC_TO_MODE(pm);

	PMCDBG3(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
	    mode);

	/*
	 * First, we take the PMC off hardware.
	 */
	cpu = 0;
	if (PMC_IS_SYSTEM_MODE(mode)) {

		/*
		 * A system mode PMC runs on a specific CPU.  Switch
		 * to this CPU and turn hardware off.
		 */
		pmc_save_cpu_binding(&pb);

		cpu = PMC_TO_CPU(pm);

		pmc_select_cpu(cpu);

		/* switch off non-stalled CPUs */
		pm->pm_pcpu_state[cpu].pps_cpustate = 0;
		if (pm->pm_state == PMC_STATE_RUNNING &&
			pm->pm_pcpu_state[cpu].pps_stalled == 0) {

			phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];

			KASSERT(phw->phw_pmc == pm,
			    ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
				__LINE__, ri, phw->phw_pmc, pm));
			PMCDBG2(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);

			critical_enter();
			pcd->pcd_stop_pmc(cpu, adjri);
			critical_exit();
		}

		PMCDBG2(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);

		critical_enter();
		pcd->pcd_config_pmc(cpu, adjri, NULL);
		critical_exit();

		/* adjust the global and process count of SS mode PMCs */
		if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
			po = pm->pm_owner;
			po->po_sscount--;
			if (po->po_sscount == 0) {
				atomic_subtract_rel_int(&pmc_ss_count, 1);
				CK_LIST_REMOVE(po, po_ssnext);
				epoch_wait_preempt(global_epoch_preempt);
			}
		}

		pm->pm_state = PMC_STATE_DELETED;

		pmc_restore_cpu_binding(&pb);

		/*
		 * We could have references to this PMC structure in
		 * the per-cpu sample queues.  Wait for the queue to
		 * drain.
		 */
		pmc_wait_for_pmc_idle(pm);

	} else if (PMC_IS_VIRTUAL_MODE(mode)) {

		/*
		 * A virtual PMC could be running on multiple CPUs at
		 * a given instant.
		 *
		 * By marking its state as DELETED, we ensure that
		 * this PMC is never further scheduled on hardware.
		 *
		 * Then we wait till all CPUs are done with this PMC.
		 */
		pm->pm_state = PMC_STATE_DELETED;


		/* Wait for the PMCs runcount to come to zero. */
		pmc_wait_for_pmc_idle(pm);

		/*
		 * At this point the PMC is off all CPUs and cannot be
		 * freshly scheduled onto a CPU.  It is now safe to
		 * unlink all targets from this PMC.  If a
		 * process-record's refcount falls to zero, we remove
		 * it from the hash table.  The module-wide SX lock
		 * protects us from races.
		 */
		LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
			pp = ptgt->pt_process;
			pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */

			PMCDBG1(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);

			/*
			 * If the target process record shows that no
			 * PMCs are attached to it, reclaim its space.
			 */

			if (pp->pp_refcnt == 0) {
				pmc_remove_process_descriptor(pp);
				pmc_destroy_process_descriptor(pp);
			}
		}

		cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */

	}

	/*
	 * Release any MD resources
	 */
	(void) pcd->pcd_release_pmc(cpu, adjri, pm);

	/*
	 * Update row disposition
	 */

	if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
		PMC_UNMARK_ROW_STANDALONE(ri);
	else
		PMC_UNMARK_ROW_THREAD(ri);

	/* unlink from the owner's list */
	if (pm->pm_owner) {
		LIST_REMOVE(pm, pm_next);
		pm->pm_owner = NULL;
	}
}

/*
 * Register an owner and a pmc.
 */

static int
pmc_register_owner(struct proc *p, struct pmc *pmc)
{
	struct pmc_owner *po;

	sx_assert(&pmc_sx, SX_XLOCKED);

	if ((po = pmc_find_owner_descriptor(p)) == NULL)
		if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
			return ENOMEM;

	KASSERT(pmc->pm_owner == NULL,
	    ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
	pmc->pm_owner  = po;

	LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);

	PROC_LOCK(p);
	p->p_flag |= P_HWPMC;
	PROC_UNLOCK(p);

	if (po->po_flags & PMC_PO_OWNS_LOGFILE)
		pmclog_process_pmcallocate(pmc);

	PMCDBG2(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
	    po, pmc);

	return 0;
}

/*
 * Return the current row disposition:
 * == 0 => FREE
 *  > 0 => PROCESS MODE
 *  < 0 => SYSTEM MODE
 */

int
pmc_getrowdisp(int ri)
{
	return pmc_pmcdisp[ri];
}

/*
 * Check if a PMC at row index 'ri' can be allocated to the current
 * process.
 *
 * Allocation can fail if:
 *   - the current process is already being profiled by a PMC at index 'ri',
 *     attached to it via OP_PMCATTACH.
 *   - the current process has already allocated a PMC at index 'ri'
 *     via OP_ALLOCATE.
 */

static int
pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
{
	enum pmc_mode mode;
	struct pmc *pm;
	struct pmc_owner *po;
	struct pmc_process *pp;

	PMCDBG5(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
	    "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);

	/*
	 * We shouldn't have already allocated a process-mode PMC at
	 * row index 'ri'.
	 *
	 * We shouldn't have allocated a system-wide PMC on the same
	 * CPU and same RI.
	 */
	if ((po = pmc_find_owner_descriptor(p)) != NULL)
		LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
		    if (PMC_TO_ROWINDEX(pm) == ri) {
			    mode = PMC_TO_MODE(pm);
			    if (PMC_IS_VIRTUAL_MODE(mode))
				    return EEXIST;
			    if (PMC_IS_SYSTEM_MODE(mode) &&
				(int) PMC_TO_CPU(pm) == cpu)
				    return EEXIST;
		    }
	        }

	/*
	 * We also shouldn't be the target of any PMC at this index
	 * since otherwise a PMC_ATTACH to ourselves will fail.
	 */
	if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
		if (pp->pp_pmcs[ri].pp_pmc)
			return EEXIST;

	PMCDBG4(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
	    p, p->p_pid, p->p_comm, ri);

	return 0;
}

/*
 * Check if a given PMC at row index 'ri' can be currently used in
 * mode 'mode'.
 */

static int
pmc_can_allocate_row(int ri, enum pmc_mode mode)
{
	enum pmc_disp	disp;

	sx_assert(&pmc_sx, SX_XLOCKED);

	PMCDBG2(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);

	if (PMC_IS_SYSTEM_MODE(mode))
		disp = PMC_DISP_STANDALONE;
	else
		disp = PMC_DISP_THREAD;

	/*
	 * check disposition for PMC row 'ri':
	 *
	 * Expected disposition		Row-disposition		Result
	 *
	 * STANDALONE			STANDALONE or FREE	proceed
	 * STANDALONE			THREAD			fail
	 * THREAD			THREAD or FREE		proceed
	 * THREAD			STANDALONE		fail
	 */

	if (!PMC_ROW_DISP_IS_FREE(ri) &&
	    !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
	    !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
		return EBUSY;

	/*
	 * All OK
	 */

	PMCDBG2(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);

	return 0;

}

/*
 * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
 */

static struct pmc *
pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
{
	struct pmc *pm;

	KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
	    ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
		PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));

	LIST_FOREACH(pm, &po->po_pmcs, pm_next)
	    if (pm->pm_id == pmcid)
		    return pm;

	return NULL;
}

static int
pmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
{

	struct pmc *pm, *opm;
	struct pmc_owner *po;
	struct pmc_process *pp;

	PMCDBG1(PMC,FND,1, "find-pmc id=%d", pmcid);
	if (PMC_ID_TO_ROWINDEX(pmcid) >= md->pmd_npmc)
		return (EINVAL);

	if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL) {
		/*
		 * In case of PMC_F_DESCENDANTS child processes we will not find
		 * the current process in the owners hash list.  Find the owner
		 * process first and from there lookup the po.
		 */
		if ((pp = pmc_find_process_descriptor(curthread->td_proc,
		    PMC_FLAG_NONE)) == NULL) {
			return ESRCH;
		} else {
			opm = pp->pp_pmcs[PMC_ID_TO_ROWINDEX(pmcid)].pp_pmc;
			if (opm == NULL)
				return ESRCH;
			if ((opm->pm_flags & (PMC_F_ATTACHED_TO_OWNER|
			    PMC_F_DESCENDANTS)) != (PMC_F_ATTACHED_TO_OWNER|
			    PMC_F_DESCENDANTS))
				return ESRCH;
			po = opm->pm_owner;
		}
	}

	if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
		return EINVAL;

	PMCDBG2(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);

	*pmc = pm;
	return 0;
}

/*
 * Start a PMC.
 */

static int
pmc_start(struct pmc *pm)
{
	enum pmc_mode mode;
	struct pmc_owner *po;
	struct pmc_binding pb;
	struct pmc_classdep *pcd;
	int adjri, error, cpu, ri;

	KASSERT(pm != NULL,
	    ("[pmc,%d] null pm", __LINE__));

	mode = PMC_TO_MODE(pm);
	ri   = PMC_TO_ROWINDEX(pm);
	pcd  = pmc_ri_to_classdep(md, ri, &adjri);

	error = 0;

	PMCDBG3(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);

	po = pm->pm_owner;

	/*
	 * Disallow PMCSTART if a logfile is required but has not been
	 * configured yet.
	 */
	if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
	    (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
		return (EDOOFUS);	/* programming error */

	/*
	 * If this is a sampling mode PMC, log mapping information for
	 * the kernel modules that are currently loaded.
	 */
	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
	    pmc_log_kernel_mappings(pm);

	if (PMC_IS_VIRTUAL_MODE(mode)) {

		/*
		 * If a PMCATTACH has never been done on this PMC,
		 * attach it to its owner process.
		 */

		if (LIST_EMPTY(&pm->pm_targets))
			error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
			    pmc_attach_process(po->po_owner, pm);

		/*
		 * If the PMC is attached to its owner, then force a context
		 * switch to ensure that the MD state gets set correctly.
		 */

		if (error == 0) {
			pm->pm_state = PMC_STATE_RUNNING;
			if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
				pmc_force_context_switch();
		}

		return (error);
	}


	/*
	 * A system-wide PMC.
	 *
	 * Add the owner to the global list if this is a system-wide
	 * sampling PMC.
	 */

	if (mode == PMC_MODE_SS) {
		/*
		 * Log mapping information for all existing processes in the
		 * system.  Subsequent mappings are logged as they happen;
		 * see pmc_process_mmap().
		 */
		if (po->po_logprocmaps == 0) {
			pmc_log_all_process_mappings(po);
			po->po_logprocmaps = 1;
		}
		po->po_sscount++;
		if (po->po_sscount == 1) {
			atomic_add_rel_int(&pmc_ss_count, 1);
			CK_LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
			PMCDBG1(PMC,OPS,1, "po=%p in global list", po);
		}
	}

	/*
	 * Move to the CPU associated with this
	 * PMC, and start the hardware.
	 */

	pmc_save_cpu_binding(&pb);

	cpu = PMC_TO_CPU(pm);

	if (!pmc_cpu_is_active(cpu))
		return (ENXIO);

	pmc_select_cpu(cpu);

	/*
	 * global PMCs are configured at allocation time
	 * so write out the initial value and start the PMC.
	 */

	pm->pm_state = PMC_STATE_RUNNING;

	critical_enter();
	if ((error = pcd->pcd_write_pmc(cpu, adjri,
		 PMC_IS_SAMPLING_MODE(mode) ?
		 pm->pm_sc.pm_reloadcount :
		 pm->pm_sc.pm_initial)) == 0) {
		/* If a sampling mode PMC, reset stalled state. */
		if (PMC_IS_SAMPLING_MODE(mode))
			pm->pm_pcpu_state[cpu].pps_stalled = 0;

		/* Indicate that we desire this to run. Start it. */
		pm->pm_pcpu_state[cpu].pps_cpustate = 1;
		error = pcd->pcd_start_pmc(cpu, adjri);
	}
	critical_exit();

	pmc_restore_cpu_binding(&pb);

	return (error);
}

/*
 * Stop a PMC.
 */

static int
pmc_stop(struct pmc *pm)
{
	struct pmc_owner *po;
	struct pmc_binding pb;
	struct pmc_classdep *pcd;
	int adjri, cpu, error, ri;

	KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));

	PMCDBG3(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
	    PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));

	pm->pm_state = PMC_STATE_STOPPED;

	/*
	 * If the PMC is a virtual mode one, changing the state to
	 * non-RUNNING is enough to ensure that the PMC never gets
	 * scheduled.
	 *
	 * If this PMC is current running on a CPU, then it will
	 * handled correctly at the time its target process is context
	 * switched out.
	 */

	if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
		return 0;

	/*
	 * A system-mode PMC.  Move to the CPU associated with
	 * this PMC, and stop the hardware.  We update the
	 * 'initial count' so that a subsequent PMCSTART will
	 * resume counting from the current hardware count.
	 */

	pmc_save_cpu_binding(&pb);

	cpu = PMC_TO_CPU(pm);

	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
	    ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));

	if (!pmc_cpu_is_active(cpu))
		return ENXIO;

	pmc_select_cpu(cpu);

	ri = PMC_TO_ROWINDEX(pm);
	pcd = pmc_ri_to_classdep(md, ri, &adjri);

	pm->pm_pcpu_state[cpu].pps_cpustate = 0;
	critical_enter();
	if ((error = pcd->pcd_stop_pmc(cpu, adjri)) == 0)
		error = pcd->pcd_read_pmc(cpu, adjri, &pm->pm_sc.pm_initial);
	critical_exit();

	pmc_restore_cpu_binding(&pb);

	po = pm->pm_owner;

	/* remove this owner from the global list of SS PMC owners */
	if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
		po->po_sscount--;
		if (po->po_sscount == 0) {
			atomic_subtract_rel_int(&pmc_ss_count, 1);
			CK_LIST_REMOVE(po, po_ssnext);
			epoch_wait_preempt(global_epoch_preempt);
			PMCDBG1(PMC,OPS,2,"po=%p removed from global list", po);
		}
	}

	return (error);
}

static struct pmc_classdep *
pmc_class_to_classdep(enum pmc_class class)
{
	int n;

	for (n = 0; n < md->pmd_nclass; n++)
		if (md->pmd_classdep[n].pcd_class == class)
			return (&md->pmd_classdep[n]);
	return (NULL);
}

#if defined(HWPMC_DEBUG) && defined(KTR)
static const char *pmc_op_to_name[] = {
#undef	__PMC_OP
#define	__PMC_OP(N, D)	#N ,
	__PMC_OPS()
	NULL
};
#endif

/*
 * The syscall interface
 */

#define	PMC_GET_SX_XLOCK(...) do {		\
	sx_xlock(&pmc_sx);			\
	if (pmc_hook == NULL) {			\
		sx_xunlock(&pmc_sx);		\
		return __VA_ARGS__;		\
	}					\
} while (0)

#define	PMC_DOWNGRADE_SX() do {			\
	sx_downgrade(&pmc_sx);			\
	is_sx_downgraded = 1;			\
} while (0)

static int
pmc_syscall_handler(struct thread *td, void *syscall_args)
{
	int error, is_sx_downgraded, op;
	struct pmc_syscall_args *c;
	void *pmclog_proc_handle;
	void *arg;

	c = (struct pmc_syscall_args *)syscall_args;
	op = c->pmop_code;
	arg = c->pmop_data;
	/* PMC isn't set up yet */
	if (pmc_hook == NULL)
		return (EINVAL);
	if (op == PMC_OP_CONFIGURELOG) {
		/*
		 * We cannot create the logging process inside
		 * pmclog_configure_log() because there is a LOR
		 * between pmc_sx and process structure locks.
		 * Instead, pre-create the process and ignite the loop
		 * if everything is fine, otherwise direct the process
		 * to exit.
		 */
		error = pmclog_proc_create(td, &pmclog_proc_handle);
		if (error != 0)
			goto done_syscall;
	}

	PMC_GET_SX_XLOCK(ENOSYS);
	is_sx_downgraded = 0;
	PMCDBG3(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
	    pmc_op_to_name[op], arg);

	error = 0;
	counter_u64_add(pmc_stats.pm_syscalls, 1);

	switch (op) {


	/*
	 * Configure a log file.
	 *
	 * XXX This OP will be reworked.
	 */

	case PMC_OP_CONFIGURELOG:
	{
		struct proc *p;
		struct pmc *pm;
		struct pmc_owner *po;
		struct pmc_op_configurelog cl;

		if ((error = copyin(arg, &cl, sizeof(cl))) != 0) {
			pmclog_proc_ignite(pmclog_proc_handle, NULL);
			break;
		}

		/* mark this process as owning a log file */
		p = td->td_proc;
		if ((po = pmc_find_owner_descriptor(p)) == NULL)
			if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
				pmclog_proc_ignite(pmclog_proc_handle, NULL);
				error = ENOMEM;
				break;
			}

		/*
		 * If a valid fd was passed in, try to configure that,
		 * otherwise if 'fd' was less than zero and there was
		 * a log file configured, flush its buffers and
		 * de-configure it.
		 */
		if (cl.pm_logfd >= 0) {
			error = pmclog_configure_log(md, po, cl.pm_logfd);
			pmclog_proc_ignite(pmclog_proc_handle, error == 0 ?
			    po : NULL);
		} else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
			pmclog_proc_ignite(pmclog_proc_handle, NULL);
			error = pmclog_close(po);
			if (error == 0) {
				LIST_FOREACH(pm, &po->po_pmcs, pm_next)
				    if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
					pm->pm_state == PMC_STATE_RUNNING)
					    pmc_stop(pm);
				error = pmclog_deconfigure_log(po);
			}
		} else {
			pmclog_proc_ignite(pmclog_proc_handle, NULL);
			error = EINVAL;
		}
	}
	break;

	/*
	 * Flush a log file.
	 */

	case PMC_OP_FLUSHLOG:
	{
		struct pmc_owner *po;

		sx_assert(&pmc_sx, SX_XLOCKED);

		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
			error = EINVAL;
			break;
		}

		error = pmclog_flush(po, 0);
	}
	break;

	/*
	 * Close a log file.
	 */

	case PMC_OP_CLOSELOG:
	{
		struct pmc_owner *po;

		sx_assert(&pmc_sx, SX_XLOCKED);

		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
			error = EINVAL;
			break;
		}

		error = pmclog_close(po);
	}
	break;

	/*
	 * Retrieve hardware configuration.
	 */

	case PMC_OP_GETCPUINFO:	/* CPU information */
	{
		struct pmc_op_getcpuinfo gci;
		struct pmc_classinfo *pci;
		struct pmc_classdep *pcd;
		int cl;

		memset(&gci, 0, sizeof(gci));
		gci.pm_cputype = md->pmd_cputype;
		gci.pm_ncpu    = pmc_cpu_max();
		gci.pm_npmc    = md->pmd_npmc;
		gci.pm_nclass  = md->pmd_nclass;
		pci = gci.pm_classes;
		pcd = md->pmd_classdep;
		for (cl = 0; cl < md->pmd_nclass; cl++, pci++, pcd++) {
			pci->pm_caps  = pcd->pcd_caps;
			pci->pm_class = pcd->pcd_class;
			pci->pm_width = pcd->pcd_width;
			pci->pm_num   = pcd->pcd_num;
		}
		error = copyout(&gci, arg, sizeof(gci));
	}
	break;

	/*
	 * Retrieve soft events list.
	 */
	case PMC_OP_GETDYNEVENTINFO:
	{
		enum pmc_class			cl;
		enum pmc_event			ev;
		struct pmc_op_getdyneventinfo	*gei;
		struct pmc_dyn_event_descr	dev;
		struct pmc_soft			*ps;
		uint32_t			nevent;

		sx_assert(&pmc_sx, SX_LOCKED);

		gei = (struct pmc_op_getdyneventinfo *) arg;

		if ((error = copyin(&gei->pm_class, &cl, sizeof(cl))) != 0)
			break;

		/* Only SOFT class is dynamic. */
		if (cl != PMC_CLASS_SOFT) {
			error = EINVAL;
			break;
		}

		nevent = 0;
		for (ev = PMC_EV_SOFT_FIRST; (int)ev <= PMC_EV_SOFT_LAST; ev++) {
			ps = pmc_soft_ev_acquire(ev);
			if (ps == NULL)
				continue;
			bcopy(&ps->ps_ev, &dev, sizeof(dev));
			pmc_soft_ev_release(ps);

			error = copyout(&dev,
			    &gei->pm_events[nevent],
			    sizeof(struct pmc_dyn_event_descr));
			if (error != 0)
				break;
			nevent++;
		}
		if (error != 0)
			break;

		error = copyout(&nevent, &gei->pm_nevent,
		    sizeof(nevent));
	}
	break;

	/*
	 * Get module statistics
	 */

	case PMC_OP_GETDRIVERSTATS:
	{
		struct pmc_op_getdriverstats gms;
#define CFETCH(a, b, field) a.field = counter_u64_fetch(b.field)
		CFETCH(gms, pmc_stats, pm_intr_ignored);
		CFETCH(gms, pmc_stats, pm_intr_processed);
		CFETCH(gms, pmc_stats, pm_intr_bufferfull);
		CFETCH(gms, pmc_stats, pm_syscalls);
		CFETCH(gms, pmc_stats, pm_syscall_errors);
		CFETCH(gms, pmc_stats, pm_buffer_requests);
		CFETCH(gms, pmc_stats, pm_buffer_requests_failed);
		CFETCH(gms, pmc_stats, pm_log_sweeps);
#undef CFETCH
		error = copyout(&gms, arg, sizeof(gms));
	}
	break;


	/*
	 * Retrieve module version number
	 */

	case PMC_OP_GETMODULEVERSION:
	{
		uint32_t cv, modv;

		/* retrieve the client's idea of the ABI version */
		if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
			break;
		/* don't service clients newer than our driver */
		modv = PMC_VERSION;
		if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
			error = EPROGMISMATCH;
			break;
		}
		error = copyout(&modv, arg, sizeof(int));
	}
	break;


	/*
	 * Retrieve the state of all the PMCs on a given
	 * CPU.
	 */

	case PMC_OP_GETPMCINFO:
	{
		int ari;
		struct pmc *pm;
		size_t pmcinfo_size;
		uint32_t cpu, n, npmc;
		struct pmc_owner *po;
		struct pmc_binding pb;
		struct pmc_classdep *pcd;
		struct pmc_info *p, *pmcinfo;
		struct pmc_op_getpmcinfo *gpi;

		PMC_DOWNGRADE_SX();

		gpi = (struct pmc_op_getpmcinfo *) arg;

		if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
			break;

		if (cpu >= pmc_cpu_max()) {
			error = EINVAL;
			break;
		}

		if (!pmc_cpu_is_active(cpu)) {
			error = ENXIO;
			break;
		}

		/* switch to CPU 'cpu' */
		pmc_save_cpu_binding(&pb);
		pmc_select_cpu(cpu);

		npmc = md->pmd_npmc;

		pmcinfo_size = npmc * sizeof(struct pmc_info);
		pmcinfo = malloc(pmcinfo_size, M_PMC, M_WAITOK | M_ZERO);

		p = pmcinfo;

		for (n = 0; n < md->pmd_npmc; n++, p++) {

			pcd = pmc_ri_to_classdep(md, n, &ari);

			KASSERT(pcd != NULL,
			    ("[pmc,%d] null pcd ri=%d", __LINE__, n));

			if ((error = pcd->pcd_describe(cpu, ari, p, &pm)) != 0)
				break;

			if (PMC_ROW_DISP_IS_STANDALONE(n))
				p->pm_rowdisp = PMC_DISP_STANDALONE;
			else if (PMC_ROW_DISP_IS_THREAD(n))
				p->pm_rowdisp = PMC_DISP_THREAD;
			else
				p->pm_rowdisp = PMC_DISP_FREE;

			p->pm_ownerpid = -1;

			if (pm == NULL)	/* no PMC associated */
				continue;

			po = pm->pm_owner;

			KASSERT(po->po_owner != NULL,
			    ("[pmc,%d] pmc_owner had a null proc pointer",
				__LINE__));

			p->pm_ownerpid = po->po_owner->p_pid;
			p->pm_mode     = PMC_TO_MODE(pm);
			p->pm_event    = pm->pm_event;
			p->pm_flags    = pm->pm_flags;

			if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
				p->pm_reloadcount =
				    pm->pm_sc.pm_reloadcount;
		}

		pmc_restore_cpu_binding(&pb);

		/* now copy out the PMC info collected */
		if (error == 0)
			error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);

		free(pmcinfo, M_PMC);
	}
	break;


	/*
	 * Set the administrative state of a PMC.  I.e. whether
	 * the PMC is to be used or not.
	 */

	case PMC_OP_PMCADMIN:
	{
		int cpu, ri;
		enum pmc_state request;
		struct pmc_cpu *pc;
		struct pmc_hw *phw;
		struct pmc_op_pmcadmin pma;
		struct pmc_binding pb;

		sx_assert(&pmc_sx, SX_XLOCKED);

		KASSERT(td == curthread,
		    ("[pmc,%d] td != curthread", __LINE__));

		error = priv_check(td, PRIV_PMC_MANAGE);
		if (error)
			break;

		if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
			break;

		cpu = pma.pm_cpu;

		if (cpu < 0 || cpu >= (int) pmc_cpu_max()) {
			error = EINVAL;
			break;
		}

		if (!pmc_cpu_is_active(cpu)) {
			error = ENXIO;
			break;
		}

		request = pma.pm_state;

		if (request != PMC_STATE_DISABLED &&
		    request != PMC_STATE_FREE) {
			error = EINVAL;
			break;
		}

		ri = pma.pm_pmc; /* pmc id == row index */
		if (ri < 0 || ri >= (int) md->pmd_npmc) {
			error = EINVAL;
			break;
		}

		/*
		 * We can't disable a PMC with a row-index allocated
		 * for process virtual PMCs.
		 */

		if (PMC_ROW_DISP_IS_THREAD(ri) &&
		    request == PMC_STATE_DISABLED) {
			error = EBUSY;
			break;
		}

		/*
		 * otherwise, this PMC on this CPU is either free or
		 * in system-wide mode.
		 */

		pmc_save_cpu_binding(&pb);
		pmc_select_cpu(cpu);

		pc  = pmc_pcpu[cpu];
		phw = pc->pc_hwpmcs[ri];

		/*
		 * XXX do we need some kind of 'forced' disable?
		 */

		if (phw->phw_pmc == NULL) {
			if (request == PMC_STATE_DISABLED &&
			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
				phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
				PMC_MARK_ROW_STANDALONE(ri);
			} else if (request == PMC_STATE_FREE &&
			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
				phw->phw_state |=  PMC_PHW_FLAG_IS_ENABLED;
				PMC_UNMARK_ROW_STANDALONE(ri);
			}
			/* other cases are a no-op */
		} else
			error = EBUSY;

		pmc_restore_cpu_binding(&pb);
	}
	break;


	/*
	 * Allocate a PMC.
	 */

	case PMC_OP_PMCALLOCATE:
	{
		int adjri, n;
		u_int cpu;
		uint32_t caps;
		struct pmc *pmc;
		enum pmc_mode mode;
		struct pmc_hw *phw;
		struct pmc_binding pb;
		struct pmc_classdep *pcd;
		struct pmc_op_pmcallocate pa;

		if ((error = copyin(arg, &pa, sizeof(pa))) != 0)
			break;

		caps = pa.pm_caps;
		mode = pa.pm_mode;
		cpu  = pa.pm_cpu;

		if ((mode != PMC_MODE_SS  &&  mode != PMC_MODE_SC  &&
		     mode != PMC_MODE_TS  &&  mode != PMC_MODE_TC) ||
		    (cpu != (u_int) PMC_CPU_ANY && cpu >= pmc_cpu_max())) {
			error = EINVAL;
			break;
		}

		/*
		 * Virtual PMCs should only ask for a default CPU.
		 * System mode PMCs need to specify a non-default CPU.
		 */

		if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != (u_int) PMC_CPU_ANY) ||
		    (PMC_IS_SYSTEM_MODE(mode) && cpu == (u_int) PMC_CPU_ANY)) {
			error = EINVAL;
			break;
		}

		/*
		 * Check that an inactive CPU is not being asked for.
		 */

		if (PMC_IS_SYSTEM_MODE(mode) && !pmc_cpu_is_active(cpu)) {
			error = ENXIO;
			break;
		}

		/*
		 * Refuse an allocation for a system-wide PMC if this
		 * process has been jailed, or if this process lacks
		 * super-user credentials and the sysctl tunable
		 * 'security.bsd.unprivileged_syspmcs' is zero.
		 */

		if (PMC_IS_SYSTEM_MODE(mode)) {
			if (jailed(curthread->td_ucred)) {
				error = EPERM;
				break;
			}
			if (!pmc_unprivileged_syspmcs) {
				error = priv_check(curthread,
				    PRIV_PMC_SYSTEM);
				if (error)
					break;
			}
		}

		/*
		 * Look for valid values for 'pm_flags'
		 */

		if ((pa.pm_flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
		    PMC_F_LOG_PROCEXIT | PMC_F_CALLCHAIN |
		    PMC_F_USERCALLCHAIN)) != 0) {
			error = EINVAL;
			break;
		}

		/* PMC_F_USERCALLCHAIN is only valid with PMC_F_CALLCHAIN */
		if ((pa.pm_flags & (PMC_F_CALLCHAIN | PMC_F_USERCALLCHAIN)) ==
		    PMC_F_USERCALLCHAIN) {
			error = EINVAL;
			break;
		}

		/* PMC_F_USERCALLCHAIN is only valid for sampling mode */
		if (pa.pm_flags & PMC_F_USERCALLCHAIN &&
			mode != PMC_MODE_TS && mode != PMC_MODE_SS) {
			error = EINVAL;
			break;
		}

		/* process logging options are not allowed for system PMCs */
		if (PMC_IS_SYSTEM_MODE(mode) && (pa.pm_flags &
		    (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT))) {
			error = EINVAL;
			break;
		}

		/*
		 * All sampling mode PMCs need to be able to interrupt the
		 * CPU.
		 */
		if (PMC_IS_SAMPLING_MODE(mode))
			caps |= PMC_CAP_INTERRUPT;

		/* A valid class specifier should have been passed in. */
		pcd = pmc_class_to_classdep(pa.pm_class);
		if (pcd == NULL) {
			error = EINVAL;
			break;
		}

		/* The requested PMC capabilities should be feasible. */
		if ((pcd->pcd_caps & caps) != caps) {
			error = EOPNOTSUPP;
			break;
		}

		PMCDBG4(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d",
		    pa.pm_ev, caps, mode, cpu);

		pmc = pmc_allocate_pmc_descriptor();
		pmc->pm_id    = PMC_ID_MAKE_ID(cpu,pa.pm_mode,pa.pm_class,
		    PMC_ID_INVALID);
		pmc->pm_event = pa.pm_ev;
		pmc->pm_state = PMC_STATE_FREE;
		pmc->pm_caps  = caps;
		pmc->pm_flags = pa.pm_flags;

		/* XXX set lower bound on sampling for process counters */
		if (PMC_IS_SAMPLING_MODE(mode)) {
			/*
			 * Don't permit requested sample rate to be less than 1000
			 */
			if (pa.pm_count < 1000)
				log(LOG_WARNING,
					"pmcallocate: passed sample rate %ju - setting to 1000\n",
					(uintmax_t)pa.pm_count);
			pmc->pm_sc.pm_reloadcount = MAX(1000, pa.pm_count);
		} else
			pmc->pm_sc.pm_initial = pa.pm_count;

		/* switch thread to CPU 'cpu' */
		pmc_save_cpu_binding(&pb);

#define	PMC_IS_SHAREABLE_PMC(cpu, n)				\
	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state &		\
	 PMC_PHW_FLAG_IS_SHAREABLE)
#define	PMC_IS_UNALLOCATED(cpu, n)				\
	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)

		if (PMC_IS_SYSTEM_MODE(mode)) {
			pmc_select_cpu(cpu);
			for (n = pcd->pcd_ri; n < (int) md->pmd_npmc; n++) {
				pcd = pmc_ri_to_classdep(md, n, &adjri);
				if (pmc_can_allocate_row(n, mode) == 0 &&
				    pmc_can_allocate_rowindex(
					    curthread->td_proc, n, cpu) == 0 &&
				    (PMC_IS_UNALLOCATED(cpu, n) ||
				     PMC_IS_SHAREABLE_PMC(cpu, n)) &&
				    pcd->pcd_allocate_pmc(cpu, adjri, pmc,
					&pa) == 0)
					break;
			}
		} else {
			/* Process virtual mode */
			for (n = pcd->pcd_ri; n < (int) md->pmd_npmc; n++) {
				pcd = pmc_ri_to_classdep(md, n, &adjri);
				if (pmc_can_allocate_row(n, mode) == 0 &&
				    pmc_can_allocate_rowindex(
					    curthread->td_proc, n,
					    PMC_CPU_ANY) == 0 &&
				    pcd->pcd_allocate_pmc(curthread->td_oncpu,
					adjri, pmc, &pa) == 0)
					break;
			}
		}

#undef	PMC_IS_UNALLOCATED
#undef	PMC_IS_SHAREABLE_PMC

		pmc_restore_cpu_binding(&pb);

		if (n == (int) md->pmd_npmc) {
			pmc_destroy_pmc_descriptor(pmc);
			pmc = NULL;
			error = EINVAL;
			break;
		}

		/* Fill in the correct value in the ID field */
		pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);

		PMCDBG5(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
		    pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);

		/* Process mode PMCs with logging enabled need log files */
		if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;

		/* All system mode sampling PMCs require a log file */
		if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;

		/*
		 * Configure global pmc's immediately
		 */

		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {

			pmc_save_cpu_binding(&pb);
			pmc_select_cpu(cpu);

			phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
			pcd = pmc_ri_to_classdep(md, n, &adjri);

			if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
			    (error = pcd->pcd_config_pmc(cpu, adjri, pmc)) != 0) {
				(void) pcd->pcd_release_pmc(cpu, adjri, pmc);
				pmc_destroy_pmc_descriptor(pmc);
				pmc = NULL;
				pmc_restore_cpu_binding(&pb);
				error = EPERM;
				break;
			}

			pmc_restore_cpu_binding(&pb);
		}

		pmc->pm_state    = PMC_STATE_ALLOCATED;
		pmc->pm_class	= pa.pm_class;

		/*
		 * mark row disposition
		 */

		if (PMC_IS_SYSTEM_MODE(mode))
			PMC_MARK_ROW_STANDALONE(n);
		else
			PMC_MARK_ROW_THREAD(n);

		/*
		 * Register this PMC with the current thread as its owner.
		 */

		if ((error =
		    pmc_register_owner(curthread->td_proc, pmc)) != 0) {
			pmc_release_pmc_descriptor(pmc);
			pmc_destroy_pmc_descriptor(pmc);
			pmc = NULL;
			break;
		}


		/*
		 * Return the allocated index.
		 */

		pa.pm_pmcid = pmc->pm_id;

		error = copyout(&pa, arg, sizeof(pa));
	}
	break;


	/*
	 * Attach a PMC to a process.
	 */

	case PMC_OP_PMCATTACH:
	{
		struct pmc *pm;
		struct proc *p;
		struct pmc_op_pmcattach a;

		sx_assert(&pmc_sx, SX_XLOCKED);

		if ((error = copyin(arg, &a, sizeof(a))) != 0)
			break;

		if (a.pm_pid < 0) {
			error = EINVAL;
			break;
		} else if (a.pm_pid == 0)
			a.pm_pid = td->td_proc->p_pid;

		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
			break;

		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
			error = EINVAL;
			break;
		}

		/* PMCs may be (re)attached only when allocated or stopped */
		if (pm->pm_state == PMC_STATE_RUNNING) {
			error = EBUSY;
			break;
		} else if (pm->pm_state != PMC_STATE_ALLOCATED &&
		    pm->pm_state != PMC_STATE_STOPPED) {
			error = EINVAL;
			break;
		}

		/* lookup pid */
		if ((p = pfind(a.pm_pid)) == NULL) {
			error = ESRCH;
			break;
		}

		/*
		 * Ignore processes that are working on exiting.
		 */
		if (p->p_flag & P_WEXIT) {
			error = ESRCH;
			PROC_UNLOCK(p);	/* pfind() returns a locked process */
			break;
		}

		/*
		 * we are allowed to attach a PMC to a process if
		 * we can debug it.
		 */
		error = p_candebug(curthread, p);

		PROC_UNLOCK(p);

		if (error == 0)
			error = pmc_attach_process(p, pm);
	}
	break;


	/*
	 * Detach an attached PMC from a process.
	 */

	case PMC_OP_PMCDETACH:
	{
		struct pmc *pm;
		struct proc *p;
		struct pmc_op_pmcattach a;

		if ((error = copyin(arg, &a, sizeof(a))) != 0)
			break;

		if (a.pm_pid < 0) {
			error = EINVAL;
			break;
		} else if (a.pm_pid == 0)
			a.pm_pid = td->td_proc->p_pid;

		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
			break;

		if ((p = pfind(a.pm_pid)) == NULL) {
			error = ESRCH;
			break;
		}

		/*
		 * Treat processes that are in the process of exiting
		 * as if they were not present.
		 */

		if (p->p_flag & P_WEXIT)
			error = ESRCH;

		PROC_UNLOCK(p);	/* pfind() returns a locked process */

		if (error == 0)
			error = pmc_detach_process(p, pm);
	}
	break;


	/*
	 * Retrieve the MSR number associated with the counter
	 * 'pmc_id'.  This allows processes to directly use RDPMC
	 * instructions to read their PMCs, without the overhead of a
	 * system call.
	 */

	case PMC_OP_PMCGETMSR:
	{
		int adjri, ri;
		struct pmc *pm;
		struct pmc_target *pt;
		struct pmc_op_getmsr gm;
		struct pmc_classdep *pcd;

		PMC_DOWNGRADE_SX();

		if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
			break;

		if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
			break;

		/*
		 * The allocated PMC has to be a process virtual PMC,
		 * i.e., of type MODE_T[CS].  Global PMCs can only be
		 * read using the PMCREAD operation since they may be
		 * allocated on a different CPU than the one we could
		 * be running on at the time of the RDPMC instruction.
		 *
		 * The GETMSR operation is not allowed for PMCs that
		 * are inherited across processes.
		 */

		if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
			error = EINVAL;
			break;
		}

		/*
		 * It only makes sense to use a RDPMC (or its
		 * equivalent instruction on non-x86 architectures) on
		 * a process that has allocated and attached a PMC to
		 * itself.  Conversely the PMC is only allowed to have
		 * one process attached to it -- its owner.
		 */

		if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
		    LIST_NEXT(pt, pt_next) != NULL ||
		    pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
			error = EINVAL;
			break;
		}

		ri = PMC_TO_ROWINDEX(pm);
		pcd = pmc_ri_to_classdep(md, ri, &adjri);

		/* PMC class has no 'GETMSR' support */
		if (pcd->pcd_get_msr == NULL) {
			error = ENOSYS;
			break;
		}

		if ((error = (*pcd->pcd_get_msr)(adjri, &gm.pm_msr)) < 0)
			break;

		if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
			break;

		/*
		 * Mark our process as using MSRs.  Update machine
		 * state using a forced context switch.
		 */

		pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
		pmc_force_context_switch();

	}
	break;

	/*
	 * Release an allocated PMC
	 */

	case PMC_OP_PMCRELEASE:
	{
		pmc_id_t pmcid;
		struct pmc *pm;
		struct pmc_owner *po;
		struct pmc_op_simple sp;

		/*
		 * Find PMC pointer for the named PMC.
		 *
		 * Use pmc_release_pmc_descriptor() to switch off the
		 * PMC, remove all its target threads, and remove the
		 * PMC from its owner's list.
		 *
		 * Remove the owner record if this is the last PMC
		 * owned.
		 *
		 * Free up space.
		 */

		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
			break;

		pmcid = sp.pm_pmcid;

		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
			break;

		po = pm->pm_owner;
		pmc_release_pmc_descriptor(pm);
		pmc_maybe_remove_owner(po);
		pmc_destroy_pmc_descriptor(pm);
	}
	break;


	/*
	 * Read and/or write a PMC.
	 */

	case PMC_OP_PMCRW:
	{
		int adjri;
		struct pmc *pm;
		uint32_t cpu, ri;
		pmc_value_t oldvalue;
		struct pmc_binding pb;
		struct pmc_op_pmcrw prw;
		struct pmc_classdep *pcd;
		struct pmc_op_pmcrw *pprw;

		PMC_DOWNGRADE_SX();

		if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
			break;

		ri = 0;
		PMCDBG2(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
		    prw.pm_flags);

		/* must have at least one flag set */
		if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
			error = EINVAL;
			break;
		}

		/* locate pmc descriptor */
		if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
			break;

		/* Can't read a PMC that hasn't been started. */
		if (pm->pm_state != PMC_STATE_ALLOCATED &&
		    pm->pm_state != PMC_STATE_STOPPED &&
		    pm->pm_state != PMC_STATE_RUNNING) {
			error = EINVAL;
			break;
		}

		/* writing a new value is allowed only for 'STOPPED' pmcs */
		if (pm->pm_state == PMC_STATE_RUNNING &&
		    (prw.pm_flags & PMC_F_NEWVALUE)) {
			error = EBUSY;
			break;
		}

		if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {

			/*
			 * If this PMC is attached to its owner (i.e.,
			 * the process requesting this operation) and
			 * is running, then attempt to get an
			 * upto-date reading from hardware for a READ.
			 * Writes are only allowed when the PMC is
			 * stopped, so only update the saved value
			 * field.
			 *
			 * If the PMC is not running, or is not
			 * attached to its owner, read/write to the
			 * savedvalue field.
			 */

			ri = PMC_TO_ROWINDEX(pm);
			pcd = pmc_ri_to_classdep(md, ri, &adjri);

			mtx_pool_lock_spin(pmc_mtxpool, pm);
			cpu = curthread->td_oncpu;

			if (prw.pm_flags & PMC_F_OLDVALUE) {
				if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
				    (pm->pm_state == PMC_STATE_RUNNING))
					error = (*pcd->pcd_read_pmc)(cpu, adjri,
					    &oldvalue);
				else
					oldvalue = pm->pm_gv.pm_savedvalue;
			}
			if (prw.pm_flags & PMC_F_NEWVALUE)
				pm->pm_gv.pm_savedvalue = prw.pm_value;

			mtx_pool_unlock_spin(pmc_mtxpool, pm);

		} else { /* System mode PMCs */
			cpu = PMC_TO_CPU(pm);
			ri  = PMC_TO_ROWINDEX(pm);
			pcd = pmc_ri_to_classdep(md, ri, &adjri);

			if (!pmc_cpu_is_active(cpu)) {
				error = ENXIO;
				break;
			}

			/* move this thread to CPU 'cpu' */
			pmc_save_cpu_binding(&pb);
			pmc_select_cpu(cpu);

			critical_enter();
			/* save old value */
			if (prw.pm_flags & PMC_F_OLDVALUE)
				if ((error = (*pcd->pcd_read_pmc)(cpu, adjri,
					 &oldvalue)))
					goto error;
			/* write out new value */
			if (prw.pm_flags & PMC_F_NEWVALUE)
				error = (*pcd->pcd_write_pmc)(cpu, adjri,
				    prw.pm_value);
		error:
			critical_exit();
			pmc_restore_cpu_binding(&pb);
			if (error)
				break;
		}

		pprw = (struct pmc_op_pmcrw *) arg;

#ifdef	HWPMC_DEBUG
		if (prw.pm_flags & PMC_F_NEWVALUE)
			PMCDBG3(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
			    ri, prw.pm_value, oldvalue);
		else if (prw.pm_flags & PMC_F_OLDVALUE)
			PMCDBG2(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
#endif

		/* return old value if requested */
		if (prw.pm_flags & PMC_F_OLDVALUE)
			if ((error = copyout(&oldvalue, &pprw->pm_value,
				 sizeof(prw.pm_value))))
				break;

	}
	break;


	/*
	 * Set the sampling rate for a sampling mode PMC and the
	 * initial count for a counting mode PMC.
	 */

	case PMC_OP_PMCSETCOUNT:
	{
		struct pmc *pm;
		struct pmc_op_pmcsetcount sc;

		PMC_DOWNGRADE_SX();

		if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
			break;

		if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
			break;

		if (pm->pm_state == PMC_STATE_RUNNING) {
			error = EBUSY;
			break;
		}

		if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) {
			/*
			 * Don't permit requested sample rate to be less than 1000
			 */
			if (sc.pm_count < 1000)
				log(LOG_WARNING,
					"pmcsetcount: passed sample rate %ju - setting to 1000\n",
					(uintmax_t)sc.pm_count);
			pm->pm_sc.pm_reloadcount = MAX(1000, sc.pm_count);
		} else
			pm->pm_sc.pm_initial = sc.pm_count;
	}
	break;


	/*
	 * Start a PMC.
	 */

	case PMC_OP_PMCSTART:
	{
		pmc_id_t pmcid;
		struct pmc *pm;
		struct pmc_op_simple sp;

		sx_assert(&pmc_sx, SX_XLOCKED);

		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
			break;

		pmcid = sp.pm_pmcid;

		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
			break;

		KASSERT(pmcid == pm->pm_id,
		    ("[pmc,%d] pmcid %x != id %x", __LINE__,
			pm->pm_id, pmcid));

		if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
			break;
		else if (pm->pm_state != PMC_STATE_STOPPED &&
		    pm->pm_state != PMC_STATE_ALLOCATED) {
			error = EINVAL;
			break;
		}

		error = pmc_start(pm);
	}
	break;


	/*
	 * Stop a PMC.
	 */

	case PMC_OP_PMCSTOP:
	{
		pmc_id_t pmcid;
		struct pmc *pm;
		struct pmc_op_simple sp;

		PMC_DOWNGRADE_SX();

		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
			break;

		pmcid = sp.pm_pmcid;

		/*
		 * Mark the PMC as inactive and invoke the MD stop
		 * routines if needed.
		 */

		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
			break;

		KASSERT(pmcid == pm->pm_id,
		    ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
			pm->pm_id, pmcid));

		if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
			break;
		else if (pm->pm_state != PMC_STATE_RUNNING) {
			error = EINVAL;
			break;
		}

		error = pmc_stop(pm);
	}
	break;


	/*
	 * Write a user supplied value to the log file.
	 */

	case PMC_OP_WRITELOG:
	{
		struct pmc_op_writelog wl;
		struct pmc_owner *po;

		PMC_DOWNGRADE_SX();

		if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
			break;

		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
			error = EINVAL;
			break;
		}

		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
			error = EINVAL;
			break;
		}

		error = pmclog_process_userlog(po, &wl);
	}
	break;


	default:
		error = EINVAL;
		break;
	}

	if (is_sx_downgraded)
		sx_sunlock(&pmc_sx);
	else
		sx_xunlock(&pmc_sx);
done_syscall:
	if (error)
		counter_u64_add(pmc_stats.pm_syscall_errors, 1);

	return (error);
}

/*
 * Helper functions
 */


/*
 * Mark the thread as needing callchain capture and post an AST.  The
 * actual callchain capture will be done in a context where it is safe
 * to take page faults.
 */

static void
pmc_post_callchain_callback(void)
{
	struct thread *td;

	td = curthread;

	/*
	 * If there is multiple PMCs for the same interrupt ignore new post
	 */
	if (td->td_pflags & TDP_CALLCHAIN)
		return;

	/*
	 * Mark this thread as needing callchain capture.
	 * `td->td_pflags' will be safe to touch because this thread
	 * was in user space when it was interrupted.
	 */
	td->td_pflags |= TDP_CALLCHAIN;

	/*
	 * Don't let this thread migrate between CPUs until callchain
	 * capture completes.
	 */
	sched_pin();

	return;
}

/*
 * Find a free slot in the per-cpu array of samples and capture the
 * current callchain there.  If a sample was successfully added, a bit
 * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook
 * needs to be invoked from the clock handler.
 *
 * This function is meant to be called from an NMI handler.  It cannot
 * use any of the locking primitives supplied by the OS.
 */

static int
pmc_add_sample(ring_type_t ring, struct pmc *pm, struct trapframe *tf)
{
	int error, cpu, callchaindepth, inuserspace;
	struct thread *td;
	struct pmc_sample *ps;
	struct pmc_samplebuffer *psb;

	error = 0;

	/*
	 * Allocate space for a sample buffer.
	 */
	cpu = curcpu;
	psb = pmc_pcpu[cpu]->pc_sb[ring];
	inuserspace = TRAPF_USERMODE(tf);
	ps = PMC_PROD_SAMPLE(psb);
	if (psb->ps_considx != psb->ps_prodidx &&
		ps->ps_nsamples) {	/* in use, reader hasn't caught up */
		pm->pm_pcpu_state[cpu].pps_stalled = 1;
		counter_u64_add(pmc_stats.pm_intr_bufferfull, 1);
		PMCDBG6(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d",
		    cpu, pm, (void *) tf, inuserspace,
		    (int) (psb->ps_prodidx & pmc_sample_mask),
		    (int) (psb->ps_considx & pmc_sample_mask));
		callchaindepth = 1;
		error = ENOMEM;
		goto done;
	}

	/* Fill in entry. */
	PMCDBG6(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm,
	    (void *) tf, inuserspace,
	    (int) (psb->ps_prodidx & pmc_sample_mask),
	    (int) (psb->ps_considx & pmc_sample_mask));

	td = curthread;
	ps->ps_pmc = pm;
	ps->ps_td = td;
	ps->ps_pid = td->td_proc->p_pid;
	ps->ps_tid = td->td_tid;
	ps->ps_tsc = pmc_rdtsc();
	ps->ps_ticks = ticks;
	ps->ps_cpu = cpu;
	ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0;

	callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ?
	    pmc_callchaindepth : 1;

	MPASS(ps->ps_pc != NULL);
	if (callchaindepth == 1)
		ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf);
	else {
		/*
		 * Kernel stack traversals can be done immediately,
		 * while we defer to an AST for user space traversals.
		 */
		if (!inuserspace) {
			callchaindepth =
			    pmc_save_kernel_callchain(ps->ps_pc,
				callchaindepth, tf);
		} else {
			pmc_post_callchain_callback();
			callchaindepth = PMC_USER_CALLCHAIN_PENDING;
		}
	}

	ps->ps_nsamples = callchaindepth;	/* mark entry as in use */
	if (ring == PMC_UR) {
		ps->ps_nsamples_actual = callchaindepth;	/* mark entry as in use */
		ps->ps_nsamples = PMC_USER_CALLCHAIN_PENDING;
	} else
		ps->ps_nsamples = callchaindepth;	/* mark entry as in use */

	KASSERT(counter_u64_fetch(pm->pm_runcount) >= 0,
	    ("[pmc,%d] pm=%p runcount %ld", __LINE__, (void *) pm,
		 (unsigned long)counter_u64_fetch(pm->pm_runcount)));

	counter_u64_add(pm->pm_runcount, 1);	/* hold onto PMC */
	/* increment write pointer */
	psb->ps_prodidx++;
 done:
	/* mark CPU as needing processing */
	if (callchaindepth != PMC_USER_CALLCHAIN_PENDING)
		DPCPU_SET(pmc_sampled, 1);

	return (error);
}

/*
 * Interrupt processing.
 *
 * This function is meant to be called from an NMI handler.  It cannot
 * use any of the locking primitives supplied by the OS.
 */

int
pmc_process_interrupt(int ring, struct pmc *pm, struct trapframe *tf)
{
	struct thread *td;

	td = curthread;
	if ((pm->pm_flags & PMC_F_USERCALLCHAIN) &&
	    (td->td_proc->p_flag & P_KPROC) == 0 &&
	    !TRAPF_USERMODE(tf)) {
		atomic_add_int(&td->td_pmcpend, 1);
		return (pmc_add_sample(PMC_UR, pm, tf));
	}
	return (pmc_add_sample(ring, pm, tf));
}

/*
 * Capture a user call chain.  This function will be called from ast()
 * before control returns to userland and before the process gets
 * rescheduled.
 */

static void
pmc_capture_user_callchain(int cpu, int ring, struct trapframe *tf)
{
	struct pmc *pm;
	struct thread *td;
	struct pmc_sample *ps;
	struct pmc_samplebuffer *psb;
	uint64_t considx, prodidx;
	int nsamples, nrecords, pass, iter;
#ifdef	INVARIANTS
	int ncallchains;
	int nfree;
	int start_ticks = ticks;
#endif
	psb = pmc_pcpu[cpu]->pc_sb[ring];
	td = curthread;

	KASSERT(td->td_pflags & TDP_CALLCHAIN,
	    ("[pmc,%d] Retrieving callchain for thread that doesn't want it",
		__LINE__));

#ifdef	INVARIANTS
	ncallchains = 0;
	nfree = 0;
#endif
	nrecords = INT_MAX;
	pass = 0;
 restart:
	if (ring == PMC_UR)
		nrecords = atomic_readandclear_32(&td->td_pmcpend);

	for (iter = 0, considx = psb->ps_considx, prodidx = psb->ps_prodidx;
	    considx < prodidx && iter < pmc_nsamples; considx++, iter++) {
		ps = PMC_CONS_SAMPLE_OFF(psb, considx);

	/*
	 * Iterate through all deferred callchain requests.
	 * Walk from the current read pointer to the current
	 * write pointer.
	 */

#ifdef	INVARIANTS
		if (ps->ps_nsamples == PMC_SAMPLE_FREE) {
			nfree++;
			continue;
		}

		if ((ps->ps_pmc == NULL) ||
		    (ps->ps_pmc->pm_state != PMC_STATE_RUNNING))
			nfree++;
#endif
		if (ps->ps_td != td ||
		   ps->ps_nsamples != PMC_USER_CALLCHAIN_PENDING ||
		   ps->ps_pmc->pm_state != PMC_STATE_RUNNING)
			continue;

		KASSERT(ps->ps_cpu == cpu,
		    ("[pmc,%d] cpu mismatch ps_cpu=%d pcpu=%d", __LINE__,
			ps->ps_cpu, PCPU_GET(cpuid)));

		pm = ps->ps_pmc;

		KASSERT(pm->pm_flags & PMC_F_CALLCHAIN,
		    ("[pmc,%d] Retrieving callchain for PMC that doesn't "
			"want it", __LINE__));

		KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
		    ("[pmc,%d] runcount %ld", __LINE__, (unsigned long)counter_u64_fetch(pm->pm_runcount)));

		if (ring == PMC_UR) {
			nsamples = ps->ps_nsamples_actual;
			counter_u64_add(pmc_stats.pm_merges, 1);
		} else
			nsamples = 0;

		/*
		 * Retrieve the callchain and mark the sample buffer
		 * as 'processable' by the timer tick sweep code.
		 */

#ifdef INVARIANTS
		ncallchains++;
#endif

		if (__predict_true(nsamples < pmc_callchaindepth - 1))
			nsamples += pmc_save_user_callchain(ps->ps_pc + nsamples,
		       pmc_callchaindepth - nsamples - 1, tf);

		/*
		 * We have to prevent hardclock from potentially overwriting
		 * this sample between when we read the value and when we set
		 * it
		 */
		spinlock_enter();
		/*
		 * Verify that the sample hasn't been dropped in the meantime
		 */
		if (ps->ps_nsamples == PMC_USER_CALLCHAIN_PENDING) {
			ps->ps_nsamples = nsamples;
			/*
			 * If we couldn't get a sample, simply drop the reference
			 */
			if (nsamples == 0)
				counter_u64_add(pm->pm_runcount, -1);
		}
		spinlock_exit();
		if (nrecords-- == 1)
			break;
	}
	if (__predict_false(ring == PMC_UR && td->td_pmcpend)) {
		if (pass == 0) {
			pass = 1;
			goto restart;
		}
		/* only collect samples for this part once */
		td->td_pmcpend = 0;
	}

#ifdef INVARIANTS
	if ((ticks - start_ticks) > hz)
		log(LOG_ERR, "%s took %d ticks\n", __func__, (ticks - start_ticks));
#endif

	/* mark CPU as needing processing */
	DPCPU_SET(pmc_sampled, 1);
}

/*
 * Process saved PC samples.
 */

static void
pmc_process_samples(int cpu, ring_type_t ring)
{
	struct pmc *pm;
	int adjri, n;
	struct thread *td;
	struct pmc_owner *po;
	struct pmc_sample *ps;
	struct pmc_classdep *pcd;
	struct pmc_samplebuffer *psb;
	uint64_t delta;

	KASSERT(PCPU_GET(cpuid) == cpu,
	    ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
		PCPU_GET(cpuid), cpu));

	psb = pmc_pcpu[cpu]->pc_sb[ring];
	delta = psb->ps_prodidx - psb->ps_considx;
	MPASS(delta <= pmc_nsamples);
	MPASS(psb->ps_considx <= psb->ps_prodidx);
	for (n = 0; psb->ps_considx < psb->ps_prodidx; psb->ps_considx++, n++) {
		ps = PMC_CONS_SAMPLE(psb);

		if (__predict_false(ps->ps_nsamples == PMC_SAMPLE_FREE))
			continue;
		pm = ps->ps_pmc;
		/* skip non-running samples */
		if (pm->pm_state != PMC_STATE_RUNNING)
			goto entrydone;

		KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
		    ("[pmc,%d] pm=%p runcount %ld", __LINE__, (void *) pm,
			 (unsigned long)counter_u64_fetch(pm->pm_runcount)));

		po = pm->pm_owner;

		KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
		    ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
			pm, PMC_TO_MODE(pm)));


		/* If there is a pending AST wait for completion */
		if (ps->ps_nsamples == PMC_USER_CALLCHAIN_PENDING) {
			/* if we've been waiting more than 1 tick to 
			 * collect a callchain for this record then
			 * drop it and move on.
			 */
			if (ticks - ps->ps_ticks > 1) {
				/*
				 * track how often we hit this as it will
				 * preferentially lose user samples
				 * for long running system calls 
				 */
				counter_u64_add(pmc_stats.pm_overwrites, 1);
				goto entrydone;
			}
			/* Need a rescan at a later time. */
			DPCPU_SET(pmc_sampled, 1);
			break;
		}

		PMCDBG6(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu,
		    pm, ps->ps_nsamples, ps->ps_flags,
		    (int) (psb->ps_prodidx & pmc_sample_mask),
		    (int) (psb->ps_considx & pmc_sample_mask));

		/*
		 * If this is a process-mode PMC that is attached to
		 * its owner, and if the PC is in user mode, update
		 * profiling statistics like timer-based profiling
		 * would have done.
		 *
		 * Otherwise, this is either a sampling-mode PMC that
		 * is attached to a different process than its owner,
		 * or a system-wide sampling PMC. Dispatch a log
		 * entry to the PMC's owner process.
		 */
		if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
			if (ps->ps_flags & PMC_CC_F_USERSPACE) {
				td = FIRST_THREAD_IN_PROC(po->po_owner);
				addupc_intr(td, ps->ps_pc[0], 1);
			}
		} else
			pmclog_process_callchain(pm, ps);

	entrydone:
		ps->ps_nsamples = 0; /* mark entry as free */
		KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
				("[pmc,%d] pm=%p runcount %ld", __LINE__, (void *) pm,
				 (unsigned long)counter_u64_fetch(pm->pm_runcount)));

		counter_u64_add(pm->pm_runcount, -1);
	}

	counter_u64_add(pmc_stats.pm_log_sweeps, 1);

	/* Do not re-enable stalled PMCs if we failed to process any samples */
	if (n == 0)
		return;

	/*
	 * Restart any stalled sampling PMCs on this CPU.
	 *
	 * If the NMI handler sets the pm_stalled field of a PMC after
	 * the check below, we'll end up processing the stalled PMC at
	 * the next hardclock tick.
	 */
	for (n = 0; n < md->pmd_npmc; n++) {
		pcd = pmc_ri_to_classdep(md, n, &adjri);
		KASSERT(pcd != NULL,
		    ("[pmc,%d] null pcd ri=%d", __LINE__, n));
		(void) (*pcd->pcd_get_config)(cpu,adjri,&pm);

		if (pm == NULL ||			 /* !cfg'ed */
		    pm->pm_state != PMC_STATE_RUNNING || /* !active */
		    !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
			!pm->pm_pcpu_state[cpu].pps_cpustate  || /* !desired */
		    !pm->pm_pcpu_state[cpu].pps_stalled) /* !stalled */
			continue;

		pm->pm_pcpu_state[cpu].pps_stalled = 0;
		(*pcd->pcd_start_pmc)(cpu, adjri);
	}
}

/*
 * Event handlers.
 */

/*
 * Handle a process exit.
 *
 * Remove this process from all hash tables.  If this process
 * owned any PMCs, turn off those PMCs and deallocate them,
 * removing any associations with target processes.
 *
 * This function will be called by the last 'thread' of a
 * process.
 *
 * XXX This eventhandler gets called early in the exit process.
 * Consider using a 'hook' invocation from thread_exit() or equivalent
 * spot.  Another negative is that kse_exit doesn't seem to call
 * exit1() [??].
 *
 */

static void
pmc_process_exit(void *arg __unused, struct proc *p)
{
	struct pmc *pm;
	int adjri, cpu;
	unsigned int ri;
	int is_using_hwpmcs;
	struct pmc_owner *po;
	struct pmc_process *pp;
	struct pmc_classdep *pcd;
	pmc_value_t newvalue, tmp;

	PROC_LOCK(p);
	is_using_hwpmcs = p->p_flag & P_HWPMC;
	PROC_UNLOCK(p);

	/*
	 * Log a sysexit event to all SS PMC owners.
	 */
	PMC_EPOCH_ENTER();
	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
		    pmclog_process_sysexit(po, p->p_pid);
	PMC_EPOCH_EXIT();

	if (!is_using_hwpmcs)
		return;

	PMC_GET_SX_XLOCK();
	PMCDBG3(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
	    p->p_comm);

	/*
	 * Since this code is invoked by the last thread in an exiting
	 * process, we would have context switched IN at some prior
	 * point.  However, with PREEMPTION, kernel mode context
	 * switches may happen any time, so we want to disable a
	 * context switch OUT till we get any PMCs targeting this
	 * process off the hardware.
	 *
	 * We also need to atomically remove this process'
	 * entry from our target process hash table, using
	 * PMC_FLAG_REMOVE.
	 */
	PMCDBG3(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
	    p->p_comm);

	critical_enter(); /* no preemption */

	cpu = curthread->td_oncpu;

	if ((pp = pmc_find_process_descriptor(p,
		 PMC_FLAG_REMOVE)) != NULL) {

		PMCDBG2(PRC,EXT,2,
		    "process-exit proc=%p pmc-process=%p", p, pp);

		/*
		 * The exiting process could the target of
		 * some PMCs which will be running on
		 * currently executing CPU.
		 *
		 * We need to turn these PMCs off like we
		 * would do at context switch OUT time.
		 */
		for (ri = 0; ri < md->pmd_npmc; ri++) {

			/*
			 * Pick up the pmc pointer from hardware
			 * state similar to the CSW_OUT code.
			 */
			pm = NULL;

			pcd = pmc_ri_to_classdep(md, ri, &adjri);

			(void) (*pcd->pcd_get_config)(cpu, adjri, &pm);

			PMCDBG2(PRC,EXT,2, "ri=%d pm=%p", ri, pm);

			if (pm == NULL ||
			    !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
				continue;

			PMCDBG4(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
			    "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
			    pm, pm->pm_state);

			KASSERT(PMC_TO_ROWINDEX(pm) == ri,
			    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
				__LINE__, PMC_TO_ROWINDEX(pm), ri));

			KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
			    ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
				__LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));

			KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
			    ("[pmc,%d] bad runcount ri %d rc %ld",
				 __LINE__, ri, (unsigned long)counter_u64_fetch(pm->pm_runcount)));

			/*
			 * Change desired state, and then stop if not
			 * stalled. This two-step dance should avoid
			 * race conditions where an interrupt re-enables
			 * the PMC after this code has already checked
			 * the pm_stalled flag.
			 */
			if (pm->pm_pcpu_state[cpu].pps_cpustate) {
				pm->pm_pcpu_state[cpu].pps_cpustate = 0;
				if (!pm->pm_pcpu_state[cpu].pps_stalled) {
					(void) pcd->pcd_stop_pmc(cpu, adjri);

					if (PMC_TO_MODE(pm) == PMC_MODE_TC) {
						pcd->pcd_read_pmc(cpu, adjri,
						    &newvalue);
						tmp = newvalue -
						    PMC_PCPU_SAVED(cpu,ri);

						mtx_pool_lock_spin(pmc_mtxpool,
						    pm);
						pm->pm_gv.pm_savedvalue += tmp;
						pp->pp_pmcs[ri].pp_pmcval +=
						    tmp;
						mtx_pool_unlock_spin(
						    pmc_mtxpool, pm);
					}
				}
			}

			KASSERT((int64_t) counter_u64_fetch(pm->pm_runcount) > 0,
			    ("[pmc,%d] runcount is %d", __LINE__, ri));

			counter_u64_add(pm->pm_runcount, -1);

			(void) pcd->pcd_config_pmc(cpu, adjri, NULL);
		}

		/*
		 * Inform the MD layer of this pseudo "context switch
		 * out"
		 */
		(void) md->pmd_switch_out(pmc_pcpu[cpu], pp);

		critical_exit(); /* ok to be pre-empted now */

		/*
		 * Unlink this process from the PMCs that are
		 * targeting it.  This will send a signal to
		 * all PMC owner's whose PMCs are orphaned.
		 *
		 * Log PMC value at exit time if requested.
		 */
		for (ri = 0; ri < md->pmd_npmc; ri++)
			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
				if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
				    PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
					pmclog_process_procexit(pm, pp);
				pmc_unlink_target_process(pm, pp);
			}
		free(pp, M_PMC);

	} else
		critical_exit(); /* pp == NULL */


	/*
	 * If the process owned PMCs, free them up and free up
	 * memory.
	 */
	if ((po = pmc_find_owner_descriptor(p)) != NULL) {
		pmc_remove_owner(po);
		pmc_destroy_owner_descriptor(po);
	}

	sx_xunlock(&pmc_sx);
}

/*
 * Handle a process fork.
 *
 * If the parent process 'p1' is under HWPMC monitoring, then copy
 * over any attached PMCs that have 'do_descendants' semantics.
 */

static void
pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
    int flags)
{
	int is_using_hwpmcs;
	unsigned int ri;
	uint32_t do_descendants;
	struct pmc *pm;
	struct pmc_owner *po;
	struct pmc_process *ppnew, *ppold;

	(void) flags;		/* unused parameter */

	PROC_LOCK(p1);
	is_using_hwpmcs = p1->p_flag & P_HWPMC;
	PROC_UNLOCK(p1);

	/*
	 * If there are system-wide sampling PMCs active, we need to
	 * log all fork events to their owner's logs.
	 */
	PMC_EPOCH_ENTER();
	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
	    if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
		    pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
			pmclog_process_proccreate(po, newproc, 1);
		}
	PMC_EPOCH_EXIT();

	if (!is_using_hwpmcs)
		return;

	PMC_GET_SX_XLOCK();
	PMCDBG4(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
	    p1->p_pid, p1->p_comm, newproc);

	/*
	 * If the parent process (curthread->td_proc) is a
	 * target of any PMCs, look for PMCs that are to be
	 * inherited, and link these into the new process
	 * descriptor.
	 */
	if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
		 PMC_FLAG_NONE)) == NULL)
		goto done;		/* nothing to do */

	do_descendants = 0;
	for (ri = 0; ri < md->pmd_npmc; ri++)
		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
			do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
	if (do_descendants == 0) /* nothing to do */
		goto done;

	/*
	 * Now mark the new process as being tracked by this driver.
	 */
	PROC_LOCK(newproc);
	newproc->p_flag |= P_HWPMC;
	PROC_UNLOCK(newproc);

	/* allocate a descriptor for the new process  */
	if ((ppnew = pmc_find_process_descriptor(newproc,
		 PMC_FLAG_ALLOCATE)) == NULL)
		goto done;

	/*
	 * Run through all PMCs that were targeting the old process
	 * and which specified F_DESCENDANTS and attach them to the
	 * new process.
	 *
	 * Log the fork event to all owners of PMCs attached to this
	 * process, if not already logged.
	 */
	for (ri = 0; ri < md->pmd_npmc; ri++)
		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
			pmc_link_target_process(pm, ppnew);
			po = pm->pm_owner;
			if (po->po_sscount == 0 &&
			    po->po_flags & PMC_PO_OWNS_LOGFILE)
				pmclog_process_procfork(po, p1->p_pid,
				    newproc->p_pid);
		}

 done:
	sx_xunlock(&pmc_sx);
}

static void
pmc_process_threadcreate(struct thread *td)
{
	struct pmc_owner *po;

	PMC_EPOCH_ENTER();
	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
			pmclog_process_threadcreate(po, td, 1);
	PMC_EPOCH_EXIT();
}

static void
pmc_process_threadexit(struct thread *td)
{
	struct pmc_owner *po;

	PMC_EPOCH_ENTER();
	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
			pmclog_process_threadexit(po, td);
	PMC_EPOCH_EXIT();
}

static void
pmc_process_proccreate(struct proc *p)
{
	struct pmc_owner *po;

	PMC_EPOCH_ENTER();
	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
			pmclog_process_proccreate(po, p, 1 /* sync */);
	PMC_EPOCH_EXIT();
}

static void
pmc_process_allproc(struct pmc *pm)
{
	struct pmc_owner *po;
	struct thread *td;
	struct proc *p;

	po = pm->pm_owner;
	if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
		return;
	sx_slock(&allproc_lock);
	FOREACH_PROC_IN_SYSTEM(p) {
		pmclog_process_proccreate(po, p, 0 /* sync */);
		PROC_LOCK(p);
		FOREACH_THREAD_IN_PROC(p, td)
			pmclog_process_threadcreate(po, td, 0 /* sync */);
		PROC_UNLOCK(p);
	}
	sx_sunlock(&allproc_lock);
	pmclog_flush(po, 0);
}

static void
pmc_kld_load(void *arg __unused, linker_file_t lf)
{
	struct pmc_owner *po;

	/*
	 * Notify owners of system sampling PMCs about KLD operations.
	 */
	PMC_EPOCH_ENTER();
	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
		if (po->po_flags & PMC_PO_OWNS_LOGFILE)
			pmclog_process_map_in(po, (pid_t) -1,
			    (uintfptr_t) lf->address, lf->filename);
	PMC_EPOCH_EXIT();

	/*
	 * TODO: Notify owners of (all) process-sampling PMCs too.
	 */
}

static void
pmc_kld_unload(void *arg __unused, const char *filename __unused,
    caddr_t address, size_t size)
{
	struct pmc_owner *po;

	PMC_EPOCH_ENTER();
	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
		if (po->po_flags & PMC_PO_OWNS_LOGFILE)
			pmclog_process_map_out(po, (pid_t) -1,
			    (uintfptr_t) address, (uintfptr_t) address + size);
	PMC_EPOCH_EXIT();

	/*
	 * TODO: Notify owners of process-sampling PMCs.
	 */
}

/*
 * initialization
 */
static const char *
pmc_name_of_pmcclass(enum pmc_class class)
{

	switch (class) {
#undef	__PMC_CLASS
#define	__PMC_CLASS(S,V,D)						\
	case PMC_CLASS_##S:						\
		return #S;
	__PMC_CLASSES();
	default:
		return ("<unknown>");
	}
}

/*
 * Base class initializer: allocate structure and set default classes.
 */
struct pmc_mdep *
pmc_mdep_alloc(int nclasses)
{
	struct pmc_mdep *md;
	int	n;

	/* SOFT + md classes */
	n = 1 + nclasses;
	md = malloc(sizeof(struct pmc_mdep) + n *
	    sizeof(struct pmc_classdep), M_PMC, M_WAITOK|M_ZERO);
	md->pmd_nclass = n;

	/* Add base class. */
	pmc_soft_initialize(md);
	return md;
}

void
pmc_mdep_free(struct pmc_mdep *md)
{
	pmc_soft_finalize(md);
	free(md, M_PMC);
}

static int
generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp)
{
	(void) pc; (void) pp;

	return (0);
}

static int
generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp)
{
	(void) pc; (void) pp;

	return (0);
}

static struct pmc_mdep *
pmc_generic_cpu_initialize(void)
{
	struct pmc_mdep *md;

	md = pmc_mdep_alloc(0);

	md->pmd_cputype    = PMC_CPU_GENERIC;

	md->pmd_pcpu_init  = NULL;
	md->pmd_pcpu_fini  = NULL;
	md->pmd_switch_in  = generic_switch_in;
	md->pmd_switch_out = generic_switch_out;

	return (md);
}

static void
pmc_generic_cpu_finalize(struct pmc_mdep *md)
{
	(void) md;
}


static int
pmc_initialize(void)
{
	int c, cpu, error, n, ri;
	unsigned int maxcpu, domain;
	struct pcpu *pc;
	struct pmc_binding pb;
	struct pmc_sample *ps;
	struct pmc_classdep *pcd;
	struct pmc_samplebuffer *sb;

	md = NULL;
	error = 0;

	pmc_stats.pm_intr_ignored = counter_u64_alloc(M_WAITOK);
	pmc_stats.pm_intr_processed = counter_u64_alloc(M_WAITOK);
	pmc_stats.pm_intr_bufferfull = counter_u64_alloc(M_WAITOK);
	pmc_stats.pm_syscalls = counter_u64_alloc(M_WAITOK);
	pmc_stats.pm_syscall_errors = counter_u64_alloc(M_WAITOK);
	pmc_stats.pm_buffer_requests = counter_u64_alloc(M_WAITOK);
	pmc_stats.pm_buffer_requests_failed = counter_u64_alloc(M_WAITOK);
	pmc_stats.pm_log_sweeps = counter_u64_alloc(M_WAITOK);
	pmc_stats.pm_merges = counter_u64_alloc(M_WAITOK);
	pmc_stats.pm_overwrites = counter_u64_alloc(M_WAITOK);

#ifdef	HWPMC_DEBUG
	/* parse debug flags first */
	if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
		pmc_debugstr, sizeof(pmc_debugstr)))
		pmc_debugflags_parse(pmc_debugstr,
		    pmc_debugstr+strlen(pmc_debugstr));
#endif

	PMCDBG1(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);

	/* check kernel version */
	if (pmc_kernel_version != PMC_VERSION) {
		if (pmc_kernel_version == 0)
			printf("hwpmc: this kernel has not been compiled with "
			    "'options HWPMC_HOOKS'.\n");
		else
			printf("hwpmc: kernel version (0x%x) does not match "
			    "module version (0x%x).\n", pmc_kernel_version,
			    PMC_VERSION);
		return EPROGMISMATCH;
	}

	/*
	 * check sysctl parameters
	 */

	if (pmc_hashsize <= 0) {
		(void) printf("hwpmc: tunable \"hashsize\"=%d must be "
		    "greater than zero.\n", pmc_hashsize);
		pmc_hashsize = PMC_HASH_SIZE;
	}

	if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
		(void) printf("hwpmc: tunable \"nsamples\"=%d out of "
		    "range.\n", pmc_nsamples);
		pmc_nsamples = PMC_NSAMPLES;
	}
	pmc_sample_mask = pmc_nsamples-1;

	if (pmc_callchaindepth <= 0 ||
	    pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) {
		(void) printf("hwpmc: tunable \"callchaindepth\"=%d out of "
		    "range - using %d.\n", pmc_callchaindepth,
		    PMC_CALLCHAIN_DEPTH_MAX);
		pmc_callchaindepth = PMC_CALLCHAIN_DEPTH_MAX;
	}

	md = pmc_md_initialize();
	if (md == NULL) {
		/* Default to generic CPU. */
		md = pmc_generic_cpu_initialize();
		if (md == NULL)
			return (ENOSYS);
        }

	KASSERT(md->pmd_nclass >= 1 && md->pmd_npmc >= 1,
	    ("[pmc,%d] no classes or pmcs", __LINE__));

	/* Compute the map from row-indices to classdep pointers. */
	pmc_rowindex_to_classdep = malloc(sizeof(struct pmc_classdep *) *
	    md->pmd_npmc, M_PMC, M_WAITOK|M_ZERO);

	for (n = 0; n < md->pmd_npmc; n++)
		pmc_rowindex_to_classdep[n] = NULL;
	for (ri = c = 0; c < md->pmd_nclass; c++) {
		pcd = &md->pmd_classdep[c];
		for (n = 0; n < pcd->pcd_num; n++, ri++)
			pmc_rowindex_to_classdep[ri] = pcd;
	}

	KASSERT(ri == md->pmd_npmc,
	    ("[pmc,%d] npmc miscomputed: ri=%d, md->npmc=%d", __LINE__,
	    ri, md->pmd_npmc));

	maxcpu = pmc_cpu_max();

	/* allocate space for the per-cpu array */
	pmc_pcpu = malloc(maxcpu * sizeof(struct pmc_cpu *), M_PMC,
	    M_WAITOK|M_ZERO);

	/* per-cpu 'saved values' for managing process-mode PMCs */
	pmc_pcpu_saved = malloc(sizeof(pmc_value_t) * maxcpu * md->pmd_npmc,
	    M_PMC, M_WAITOK);

	/* Perform CPU-dependent initialization. */
	pmc_save_cpu_binding(&pb);
	error = 0;
	for (cpu = 0; error == 0 && cpu < maxcpu; cpu++) {
		if (!pmc_cpu_is_active(cpu))
			continue;
		pmc_select_cpu(cpu);
		pmc_pcpu[cpu] = malloc(sizeof(struct pmc_cpu) +
		    md->pmd_npmc * sizeof(struct pmc_hw *), M_PMC,
		    M_WAITOK|M_ZERO);
		if (md->pmd_pcpu_init)
			error = md->pmd_pcpu_init(md, cpu);
		for (n = 0; error == 0 && n < md->pmd_nclass; n++)
			error = md->pmd_classdep[n].pcd_pcpu_init(md, cpu);
	}
	pmc_restore_cpu_binding(&pb);

	if (error)
		return (error);

	/* allocate space for the sample array */
	for (cpu = 0; cpu < maxcpu; cpu++) {
		if (!pmc_cpu_is_active(cpu))
			continue;
		pc = pcpu_find(cpu);
		domain = pc->pc_domain;
		sb = malloc_domainset(sizeof(struct pmc_samplebuffer) +
		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
		    DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);

		KASSERT(pmc_pcpu[cpu] != NULL,
		    ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));

		sb->ps_callchains = malloc_domainset(pmc_callchaindepth *
		    pmc_nsamples * sizeof(uintptr_t), M_PMC,
		    DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);

		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
			ps->ps_pc = sb->ps_callchains +
			    (n * pmc_callchaindepth);

		pmc_pcpu[cpu]->pc_sb[PMC_HR] = sb;

		sb = malloc_domainset(sizeof(struct pmc_samplebuffer) +
		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
		    DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);

		sb->ps_callchains = malloc_domainset(pmc_callchaindepth *
		    pmc_nsamples * sizeof(uintptr_t), M_PMC,
		    DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
			ps->ps_pc = sb->ps_callchains +
			    (n * pmc_callchaindepth);

		pmc_pcpu[cpu]->pc_sb[PMC_SR] = sb;

		sb = malloc_domainset(sizeof(struct pmc_samplebuffer) +
		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
		    DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
		sb->ps_callchains = malloc_domainset(pmc_callchaindepth *
		    pmc_nsamples * sizeof(uintptr_t), M_PMC,
		    DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
			ps->ps_pc = sb->ps_callchains + n * pmc_callchaindepth;

		pmc_pcpu[cpu]->pc_sb[PMC_UR] = sb;
	}

	/* allocate space for the row disposition array */
	pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
	    M_PMC, M_WAITOK|M_ZERO);

	/* mark all PMCs as available */
	for (n = 0; n < (int) md->pmd_npmc; n++)
		PMC_MARK_ROW_FREE(n);

	/* allocate thread hash tables */
	pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
	    &pmc_ownerhashmask);

	pmc_processhash = hashinit(pmc_hashsize, M_PMC,
	    &pmc_processhashmask);
	mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
	    MTX_SPIN);

	CK_LIST_INIT(&pmc_ss_owners);
	pmc_ss_count = 0;

	/* allocate a pool of spin mutexes */
	pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
	    MTX_SPIN);

	PMCDBG4(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
	    "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
	    pmc_processhash, pmc_processhashmask);

	/* Initialize a spin mutex for the thread free list. */
	mtx_init(&pmc_threadfreelist_mtx, "pmc-threadfreelist", "pmc-leaf",
	    MTX_SPIN);

	/* Initialize the task to prune the thread free list. */
	TASK_INIT(&free_task, 0, pmc_thread_descriptor_pool_free_task, NULL);

	/* register process {exit,fork,exec} handlers */
	pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
	    pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
	pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
	    pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);

	/* register kld event handlers */
	pmc_kld_load_tag = EVENTHANDLER_REGISTER(kld_load, pmc_kld_load,
	    NULL, EVENTHANDLER_PRI_ANY);
	pmc_kld_unload_tag = EVENTHANDLER_REGISTER(kld_unload, pmc_kld_unload,
	    NULL, EVENTHANDLER_PRI_ANY);

	/* initialize logging */
	pmclog_initialize();

	/* set hook functions */
	pmc_intr = md->pmd_intr;
	wmb();
	pmc_hook = pmc_hook_handler;

	if (error == 0) {
		printf(PMC_MODULE_NAME ":");
		for (n = 0; n < (int) md->pmd_nclass; n++) {
			pcd = &md->pmd_classdep[n];
			printf(" %s/%d/%d/0x%b",
			    pmc_name_of_pmcclass(pcd->pcd_class),
			    pcd->pcd_num,
			    pcd->pcd_width,
			    pcd->pcd_caps,
			    "\20"
			    "\1INT\2USR\3SYS\4EDG\5THR"
			    "\6REA\7WRI\10INV\11QUA\12PRC"
			    "\13TAG\14CSC");
		}
		printf("\n");
	}

	return (error);
}

/* prepare to be unloaded */
static void
pmc_cleanup(void)
{
	int c, cpu;
	unsigned int maxcpu;
	struct pmc_ownerhash *ph;
	struct pmc_owner *po, *tmp;
	struct pmc_binding pb;
#ifdef	HWPMC_DEBUG
	struct pmc_processhash *prh;
#endif

	PMCDBG0(MOD,INI,0, "cleanup");

	/* switch off sampling */
	CPU_FOREACH(cpu)
		DPCPU_ID_SET(cpu, pmc_sampled, 0);
	pmc_intr = NULL;

	sx_xlock(&pmc_sx);
	if (pmc_hook == NULL) {	/* being unloaded already */
		sx_xunlock(&pmc_sx);
		return;
	}

	pmc_hook = NULL; /* prevent new threads from entering module */

	/* deregister event handlers */
	EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
	EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
	EVENTHANDLER_DEREGISTER(kld_load, pmc_kld_load_tag);
	EVENTHANDLER_DEREGISTER(kld_unload, pmc_kld_unload_tag);

	/* send SIGBUS to all owner threads, free up allocations */
	if (pmc_ownerhash)
		for (ph = pmc_ownerhash;
		     ph <= &pmc_ownerhash[pmc_ownerhashmask];
		     ph++) {
			LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
				pmc_remove_owner(po);

				/* send SIGBUS to owner processes */
				PMCDBG3(MOD,INI,2, "cleanup signal proc=%p "
				    "(%d, %s)", po->po_owner,
				    po->po_owner->p_pid,
				    po->po_owner->p_comm);

				PROC_LOCK(po->po_owner);
				kern_psignal(po->po_owner, SIGBUS);
				PROC_UNLOCK(po->po_owner);

				pmc_destroy_owner_descriptor(po);
			}
		}

	/* reclaim allocated data structures */
	taskqueue_drain(taskqueue_fast, &free_task);
	mtx_destroy(&pmc_threadfreelist_mtx);
	pmc_thread_descriptor_pool_drain();

	if (pmc_mtxpool)
		mtx_pool_destroy(&pmc_mtxpool);

	mtx_destroy(&pmc_processhash_mtx);
	if (pmc_processhash) {
#ifdef	HWPMC_DEBUG
		struct pmc_process *pp;

		PMCDBG0(MOD,INI,3, "destroy process hash");
		for (prh = pmc_processhash;
		     prh <= &pmc_processhash[pmc_processhashmask];
		     prh++)
			LIST_FOREACH(pp, prh, pp_next)
			    PMCDBG1(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
#endif

		hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
		pmc_processhash = NULL;
	}

	if (pmc_ownerhash) {
		PMCDBG0(MOD,INI,3, "destroy owner hash");
		hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
		pmc_ownerhash = NULL;
	}

	KASSERT(CK_LIST_EMPTY(&pmc_ss_owners),
	    ("[pmc,%d] Global SS owner list not empty", __LINE__));
	KASSERT(pmc_ss_count == 0,
	    ("[pmc,%d] Global SS count not empty", __LINE__));

 	/* do processor and pmc-class dependent cleanup */
	maxcpu = pmc_cpu_max();

	PMCDBG0(MOD,INI,3, "md cleanup");
	if (md) {
		pmc_save_cpu_binding(&pb);
		for (cpu = 0; cpu < maxcpu; cpu++) {
			PMCDBG2(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
			    cpu, pmc_pcpu[cpu]);
			if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL)
				continue;
			pmc_select_cpu(cpu);
			for (c = 0; c < md->pmd_nclass; c++)
				md->pmd_classdep[c].pcd_pcpu_fini(md, cpu);
			if (md->pmd_pcpu_fini)
				md->pmd_pcpu_fini(md, cpu);
		}

		if (md->pmd_cputype == PMC_CPU_GENERIC)
			pmc_generic_cpu_finalize(md);
		else
			pmc_md_finalize(md);

		pmc_mdep_free(md);
		md = NULL;
		pmc_restore_cpu_binding(&pb);
	}

	/* Free per-cpu descriptors. */
	for (cpu = 0; cpu < maxcpu; cpu++) {
		if (!pmc_cpu_is_active(cpu))
			continue;
		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_HR] != NULL,
		    ("[pmc,%d] Null hw cpu sample buffer cpu=%d", __LINE__,
			cpu));
		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_SR] != NULL,
		    ("[pmc,%d] Null sw cpu sample buffer cpu=%d", __LINE__,
			cpu));
		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_UR] != NULL,
		    ("[pmc,%d] Null userret cpu sample buffer cpu=%d", __LINE__,
			cpu));
		free(pmc_pcpu[cpu]->pc_sb[PMC_HR]->ps_callchains, M_PMC);
		free(pmc_pcpu[cpu]->pc_sb[PMC_HR], M_PMC);
		free(pmc_pcpu[cpu]->pc_sb[PMC_SR]->ps_callchains, M_PMC);
		free(pmc_pcpu[cpu]->pc_sb[PMC_SR], M_PMC);
		free(pmc_pcpu[cpu]->pc_sb[PMC_UR]->ps_callchains, M_PMC);
		free(pmc_pcpu[cpu]->pc_sb[PMC_UR], M_PMC);
		free(pmc_pcpu[cpu], M_PMC);
	}

	free(pmc_pcpu, M_PMC);
	pmc_pcpu = NULL;

	free(pmc_pcpu_saved, M_PMC);
	pmc_pcpu_saved = NULL;

	if (pmc_pmcdisp) {
		free(pmc_pmcdisp, M_PMC);
		pmc_pmcdisp = NULL;
	}

	if (pmc_rowindex_to_classdep) {
		free(pmc_rowindex_to_classdep, M_PMC);
		pmc_rowindex_to_classdep = NULL;
	}

	pmclog_shutdown();
	counter_u64_free(pmc_stats.pm_intr_ignored);
	counter_u64_free(pmc_stats.pm_intr_processed);
	counter_u64_free(pmc_stats.pm_intr_bufferfull);
	counter_u64_free(pmc_stats.pm_syscalls);
	counter_u64_free(pmc_stats.pm_syscall_errors);
	counter_u64_free(pmc_stats.pm_buffer_requests);
	counter_u64_free(pmc_stats.pm_buffer_requests_failed);
	counter_u64_free(pmc_stats.pm_log_sweeps);
	counter_u64_free(pmc_stats.pm_merges);
	counter_u64_free(pmc_stats.pm_overwrites);
	sx_xunlock(&pmc_sx); 	/* we are done */
}

/*
 * The function called at load/unload.
 */

static int
load (struct module *module __unused, int cmd, void *arg __unused)
{
	int error;

	error = 0;

	switch (cmd) {
	case MOD_LOAD :
		/* initialize the subsystem */
		error = pmc_initialize();
		if (error != 0)
			break;
		PMCDBG2(MOD,INI,1, "syscall=%d maxcpu=%d",
		    pmc_syscall_num, pmc_cpu_max());
		break;


	case MOD_UNLOAD :
	case MOD_SHUTDOWN:
		pmc_cleanup();
		PMCDBG0(MOD,INI,1, "unloaded");
		break;

	default :
		error = EINVAL;	/* XXX should panic(9) */
		break;
	}

	return error;
}