|
root / base / usr / src / uts / i86pc / io / pcplusmp
pcplusmp Plain Text 4807 lines 122.9 KB
   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
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1993, 2010, Oracle and/or its affiliates. All rights reserved.
 */
/*
 * Copyright (c) 2010, Intel Corporation.
 * All rights reserved.
 * Copyright 2019 Joyent, Inc.
 * Copyright 2020 Oxide Computer Company
 */

/*
 * To understand how the pcplusmp module interacts with the interrupt subsystem
 * read the theory statement in uts/i86pc/os/intr.c.
 */

/*
 * PSMI 1.1 extensions are supported only in 2.6 and later versions.
 * PSMI 1.2 extensions are supported only in 2.7 and later versions.
 * PSMI 1.3 and 1.4 extensions are supported in Solaris 10.
 * PSMI 1.5 extensions are supported in Solaris Nevada.
 * PSMI 1.6 extensions are supported in Solaris Nevada.
 * PSMI 1.7 extensions are supported in Solaris Nevada.
 */
#define	PSMI_1_7

#include <sys/processor.h>
#include <sys/time.h>
#include <sys/psm.h>
#include <sys/smp_impldefs.h>
#include <sys/cram.h>
#include <sys/acpi/acpi.h>
#include <sys/acpica.h>
#include <sys/psm_common.h>
#include <sys/apic.h>
#include <sys/pit.h>
#include <sys/ddi.h>
#include <sys/sunddi.h>
#include <sys/ddi_impldefs.h>
#include <sys/pci.h>
#include <sys/promif.h>
#include <sys/prom_debug.h>
#include <sys/x86_archext.h>
#include <sys/cpc_impl.h>
#include <sys/uadmin.h>
#include <sys/panic.h>
#include <sys/debug.h>
#include <sys/archsystm.h>
#include <sys/trap.h>
#include <sys/machsystm.h>
#include <sys/sysmacros.h>
#include <sys/cpuvar.h>
#include <sys/rm_platter.h>
#include <sys/privregs.h>
#include <sys/note.h>
#include <sys/pci_intr_lib.h>
#include <sys/spl.h>
#include <sys/clock.h>
#include <sys/cyclic.h>
#include <sys/dditypes.h>
#include <sys/sunddi.h>
#include <sys/x_call.h>
#include <sys/reboot.h>
#include <sys/hpet.h>
#include <sys/apic_common.h>
#include <sys/apic_timer.h>
#include <sys/smt.h>

/*
 *	Local Function Prototypes
 */
static void apic_init_intr(void);

/*
 *	standard MP entries
 */
static int	apic_probe(void);
static int	apic_getclkirq(int ipl);
static void	apic_init(void);
static void	apic_picinit(void);
static int	apic_post_cpu_start(void);
static int	apic_intr_enter(int ipl, int *vect);
static void	apic_setspl(int ipl);
static int	apic_addspl(int ipl, int vector, int min_ipl, int max_ipl);
static int	apic_delspl(int ipl, int vector, int min_ipl, int max_ipl);
static int	apic_disable_intr(processorid_t cpun);
static void	apic_enable_intr(processorid_t cpun);
static int		apic_get_ipivect(int ipl, int type);
static void	apic_post_cyclic_setup(void *arg);

/*
 * The following vector assignments influence the value of ipltopri and
 * vectortoipl. Note that vectors 0 - 0x1f are not used. We can program
 * idle to 0 and IPL 0 to 0xf to differentiate idle in case
 * we care to do so in future. Note some IPLs which are rarely used
 * will share the vector ranges and heavily used IPLs (5 and 6) have
 * a wide range.
 *
 * This array is used to initialize apic_ipls[] (in apic_init()).
 *
 *	IPL		Vector range.		as passed to intr_enter
 *	0		none.
 *	1,2,3		0x20-0x2f		0x0-0xf
 *	4		0x30-0x3f		0x10-0x1f
 *	5		0x40-0x5f		0x20-0x3f
 *	6		0x60-0x7f		0x40-0x5f
 *	7,8,9		0x80-0x8f		0x60-0x6f
 *	10		0x90-0x9f		0x70-0x7f
 *	11		0xa0-0xaf		0x80-0x8f
 *	...		...
 *	15		0xe0-0xef		0xc0-0xcf
 *	15		0xf0-0xff		0xd0-0xdf
 */
uchar_t apic_vectortoipl[APIC_AVAIL_VECTOR / APIC_VECTOR_PER_IPL] = {
	3, 4, 5, 5, 6, 6, 9, 10, 11, 12, 13, 14, 15, 15
};
	/*
	 * The ipl of an ISR at vector X is apic_vectortoipl[X>>4]
	 * NOTE that this is vector as passed into intr_enter which is
	 * programmed vector - 0x20 (APIC_BASE_VECT)
	 */

uchar_t	apic_ipltopri[MAXIPL + 1];	/* unix ipl to apic pri	*/
	/* The taskpri to be programmed into apic to mask given ipl */

/*
 * Correlation of the hardware vector to the IPL in use, initialized
 * from apic_vectortoipl[] in apic_init().  The final IPLs may not correlate
 * to the IPLs in apic_vectortoipl on some systems that share interrupt lines
 * connected to errata-stricken IOAPICs
 */
uchar_t apic_ipls[APIC_AVAIL_VECTOR];

/*
 * Patchable global variables.
 */
int	apic_enable_hwsoftint = 0;	/* 0 - disable, 1 - enable	*/
int	apic_enable_bind_log = 1;	/* 1 - display interrupt binding log */

/*
 *	Local static data
 */
static struct	psm_ops apic_ops = {
	apic_probe,

	apic_init,
	apic_picinit,
	apic_intr_enter,
	apic_intr_exit,
	apic_setspl,
	apic_addspl,
	apic_delspl,
	apic_disable_intr,
	apic_enable_intr,
	(int (*)(int))NULL,		/* psm_softlvl_to_irq */
	(void (*)(int))NULL,		/* psm_set_softintr */

	apic_set_idlecpu,
	apic_unset_idlecpu,

	apic_clkinit,
	apic_getclkirq,
	(void (*)(void))NULL,		/* psm_hrtimeinit */
	apic_gethrtime,

	apic_get_next_processorid,
	apic_cpu_start,
	apic_post_cpu_start,
	apic_shutdown,
	apic_get_ipivect,
	apic_send_ipi,

	(int (*)(dev_info_t *, int))NULL,	/* psm_translate_irq */
	(void (*)(int, char *))NULL,	/* psm_notify_error */
	(void (*)(int))NULL,		/* psm_notify_func */
	apic_timer_reprogram,
	apic_timer_enable,
	apic_timer_disable,
	apic_post_cyclic_setup,
	apic_preshutdown,
	apic_intr_ops,			/* Advanced DDI Interrupt framework */
	apic_state,			/* save, restore apic state for S3 */
	apic_cpu_ops,			/* CPU control interface. */

	apic_get_pir_ipivect,
	apic_send_pir_ipi,
	apic_cmci_setup,
};

struct psm_ops *psmops = &apic_ops;

static struct	psm_info apic_psm_info = {
	PSM_INFO_VER01_7,			/* version */
	PSM_OWN_EXCLUSIVE,			/* ownership */
	(struct psm_ops *)&apic_ops,		/* operation */
	APIC_PCPLUSMP_NAME,			/* machine name */
	"pcplusmp v1.4 compatible",
};

static void *apic_hdlp;

/* to gather intr data and redistribute */
static void apic_redistribute_compute(void);

/*
 *	This is the loadable module wrapper
 */

int
_init(void)
{
	if (apic_coarse_hrtime)
		apic_ops.psm_gethrtime = &apic_gettime;
	return (psm_mod_init(&apic_hdlp, &apic_psm_info));
}

int
_fini(void)
{
	return (psm_mod_fini(&apic_hdlp, &apic_psm_info));
}

int
_info(struct modinfo *modinfop)
{
	return (psm_mod_info(&apic_hdlp, &apic_psm_info, modinfop));
}

static int
apic_probe(void)
{
	PRM_POINT("apic_probe()");

	/* check if apix is initialized */
	if (apix_enable && apix_loaded()) {
		PRM_POINT("apic_probe FAILURE: apix is loaded");
		return (PSM_FAILURE);
	}

	/*
	 * Check whether x2APIC mode was activated by BIOS. We don't support
	 * that in pcplusmp as apix normally handles that.
	 */
	PRM_POINT("apic_local_mode()");
	if (apic_local_mode() == LOCAL_X2APIC) {
		PRM_POINT("apic_probe FAILURE: in x2apic mode");
		return (PSM_FAILURE);
	}

	/* continue using pcplusmp PSM */
	apix_enable = 0;

	return (apic_probe_common(apic_psm_info.p_mach_idstring));
}

static uchar_t
apic_xlate_vector_by_irq(uchar_t irq)
{
	if (apic_irq_table[irq] == NULL)
		return (0);

	return (apic_irq_table[irq]->airq_vector);
}

void
apic_init(void)
{
	int i;
	int	j = 1;

	psm_get_ioapicid = apic_get_ioapicid;
	psm_get_localapicid = apic_get_localapicid;
	psm_xlate_vector_by_irq = apic_xlate_vector_by_irq;

	apic_ipltopri[0] = APIC_VECTOR_PER_IPL; /* leave 0 for idle */
	for (i = 0; i < (APIC_AVAIL_VECTOR / APIC_VECTOR_PER_IPL); i++) {
		if ((i < ((APIC_AVAIL_VECTOR / APIC_VECTOR_PER_IPL) - 1)) &&
		    (apic_vectortoipl[i + 1] == apic_vectortoipl[i]))
			/* get to highest vector at the same ipl */
			continue;
		for (; j <= apic_vectortoipl[i]; j++) {
			apic_ipltopri[j] = (i << APIC_IPL_SHIFT) +
			    APIC_BASE_VECT;
		}
	}
	for (; j < MAXIPL + 1; j++)
		/* fill up any empty ipltopri slots */
		apic_ipltopri[j] = (i << APIC_IPL_SHIFT) + APIC_BASE_VECT;
	apic_init_common();

	/*
	 * For pcplusmp, we'll keep things simple and always disable this.
	 */
	smt_intr_alloc_pil(XC_CPUPOKE_PIL);

	apic_pir_vect = apic_get_ipivect(XC_CPUPOKE_PIL, -1);

}

static void
apic_init_intr(void)
{
	processorid_t	cpun = psm_get_cpu_id();
	uint_t nlvt;
	uint32_t svr = AV_UNIT_ENABLE | APIC_SPUR_INTR;

	apic_reg_ops->apic_write_task_reg(APIC_MASK_ALL);

	ASSERT(apic_mode == LOCAL_APIC);

	/*
	 * We are running APIC in MMIO mode.
	 */
	if (apic_flat_model) {
		apic_reg_ops->apic_write(APIC_FORMAT_REG, APIC_FLAT_MODEL);
	} else {
		apic_reg_ops->apic_write(APIC_FORMAT_REG, APIC_CLUSTER_MODEL);
	}

	apic_reg_ops->apic_write(APIC_DEST_REG, AV_HIGH_ORDER >> cpun);

	if (apic_directed_EOI_supported()) {
		/*
		 * Setting the 12th bit in the Spurious Interrupt Vector
		 * Register suppresses broadcast EOIs generated by the local
		 * APIC. The suppression of broadcast EOIs happens only when
		 * interrupts are level-triggered.
		 */
		svr |= APIC_SVR_SUPPRESS_BROADCAST_EOI;
	}

	/* need to enable APIC before unmasking NMI */
	apic_reg_ops->apic_write(APIC_SPUR_INT_REG, svr);

	/*
	 * Presence of an invalid vector with delivery mode AV_FIXED can
	 * cause an error interrupt, even if the entry is masked...so
	 * write a valid vector to LVT entries along with the mask bit
	 */

	/* All APICs have timer and LINT0/1 */
	apic_reg_ops->apic_write(APIC_LOCAL_TIMER, AV_MASK|APIC_RESV_IRQ);
	apic_reg_ops->apic_write(APIC_INT_VECT0, AV_MASK|APIC_RESV_IRQ);
	apic_reg_ops->apic_write(APIC_INT_VECT1, AV_NMI);	/* enable NMI */

	/*
	 * On integrated APICs, the number of LVT entries is
	 * 'Max LVT entry' + 1; on 82489DX's (non-integrated
	 * APICs), nlvt is "3" (LINT0, LINT1, and timer)
	 */

	if (apic_cpus[cpun].aci_local_ver < APIC_INTEGRATED_VERS) {
		nlvt = 3;
	} else {
		nlvt = ((apic_reg_ops->apic_read(APIC_VERS_REG) >> 16) &
		    0xFF) + 1;
	}

	if (nlvt >= 5) {
		/* Enable performance counter overflow interrupt */

		if (!is_x86_feature(x86_featureset, X86FSET_MSR))
			apic_enable_cpcovf_intr = 0;
		if (apic_enable_cpcovf_intr) {
			if (apic_cpcovf_vect == 0) {
				int ipl = APIC_PCINT_IPL;
				int irq = apic_get_ipivect(ipl, -1);

				ASSERT(irq != -1);
				apic_cpcovf_vect =
				    apic_irq_table[irq]->airq_vector;
				ASSERT(apic_cpcovf_vect);
				(void) add_avintr(NULL, ipl,
				    (avfunc)kcpc_hw_overflow_intr,
				    "apic pcint", irq, NULL, NULL, NULL, NULL);
				kcpc_hw_overflow_intr_installed = 1;
				kcpc_hw_enable_cpc_intr =
				    apic_cpcovf_mask_clear;
			}
			apic_reg_ops->apic_write(APIC_PCINT_VECT,
			    apic_cpcovf_vect);
		}
	}

	if (nlvt >= 6) {
		/* Only mask TM intr if the BIOS apparently doesn't use it */

		uint32_t lvtval;

		lvtval = apic_reg_ops->apic_read(APIC_THERM_VECT);
		if (((lvtval & AV_MASK) == AV_MASK) ||
		    ((lvtval & AV_DELIV_MODE) != AV_SMI)) {
			apic_reg_ops->apic_write(APIC_THERM_VECT,
			    AV_MASK|APIC_RESV_IRQ);
		}
	}

	/* Enable error interrupt */

	if (nlvt >= 4 && apic_enable_error_intr) {
		if (apic_errvect == 0) {
			int ipl = 0xf;	/* get highest priority intr */
			int irq = apic_get_ipivect(ipl, -1);

			ASSERT(irq != -1);
			apic_errvect = apic_irq_table[irq]->airq_vector;
			ASSERT(apic_errvect);
			/*
			 * Not PSMI compliant, but we are going to merge
			 * with ON anyway
			 */
			(void) add_avintr((void *)NULL, ipl,
			    (avfunc)apic_error_intr, "apic error intr",
			    irq, NULL, NULL, NULL, NULL);
		}
		apic_reg_ops->apic_write(APIC_ERR_VECT, apic_errvect);
		apic_reg_ops->apic_write(APIC_ERROR_STATUS, 0);
		apic_reg_ops->apic_write(APIC_ERROR_STATUS, 0);
	}

	/*
	 * Ensure a CMCI interrupt is allocated, regardless of whether it is
	 * enabled or not.
	 */
	if (apic_cmci_vect == 0) {
		const int ipl = 0x2;
		int irq = apic_get_ipivect(ipl, -1);

		ASSERT(irq != -1);
		apic_cmci_vect = apic_irq_table[irq]->airq_vector;
		ASSERT(apic_cmci_vect);

		(void) add_avintr(NULL, ipl,
		    (avfunc)cmi_cmci_trap,
		    "apic cmci intr", irq, NULL, NULL, NULL, NULL);
	}
}

static void
apic_picinit(void)
{
	int i, j;
	uint_t isr;

	/*
	 * Initialize and enable interrupt remapping before apic
	 * hardware initialization
	 */
	apic_intrmap_init(apic_mode);

	/*
	 * On UniSys Model 6520, the BIOS leaves vector 0x20 isr
	 * bit on without clearing it with EOI.  Since softint
	 * uses vector 0x20 to interrupt itself, so softint will
	 * not work on this machine.  In order to fix this problem
	 * a check is made to verify all the isr bits are clear.
	 * If not, EOIs are issued to clear the bits.
	 */
	for (i = 7; i >= 1; i--) {
		isr = apic_reg_ops->apic_read(APIC_ISR_REG + (i * 4));
		if (isr != 0)
			for (j = 0; ((j < 32) && (isr != 0)); j++)
				if (isr & (1 << j)) {
					apic_reg_ops->apic_write(
					    APIC_EOI_REG, 0);
					isr &= ~(1 << j);
					apic_error |= APIC_ERR_BOOT_EOI;
				}
	}

	/* set a flag so we know we have run apic_picinit() */
	apic_picinit_called = 1;
	LOCK_INIT_CLEAR(&apic_gethrtime_lock);
	LOCK_INIT_CLEAR(&apic_ioapic_lock);
	LOCK_INIT_CLEAR(&apic_error_lock);
	LOCK_INIT_CLEAR(&apic_mode_switch_lock);

	picsetup();	 /* initialise the 8259 */

	/* add nmi handler - least priority nmi handler */
	LOCK_INIT_CLEAR(&apic_nmi_lock);

	if (!psm_add_nmintr(0, (avfunc) apic_nmi_intr,
	    "pcplusmp NMI handler", (caddr_t)NULL))
		cmn_err(CE_WARN, "pcplusmp: Unable to add nmi handler");

	/*
	 * Check for directed-EOI capability in the local APIC.
	 */
	if (apic_directed_EOI_supported() == 1) {
		apic_set_directed_EOI_handler();
	}

	apic_init_intr();

	/* enable apic mode if imcr present */
	if (apic_imcrp) {
		outb(APIC_IMCR_P1, (uchar_t)APIC_IMCR_SELECT);
		outb(APIC_IMCR_P2, (uchar_t)APIC_IMCR_APIC);
	}

	ioapic_init_intr(IOAPIC_MASK);
}

#ifdef	DEBUG
void
apic_break(void)
{
}
#endif /* DEBUG */

/*
 * platform_intr_enter
 *
 *	Called at the beginning of the interrupt service routine to
 *	mask all level equal to and below the interrupt priority
 *	of the interrupting vector.  An EOI should be given to
 *	the interrupt controller to enable other HW interrupts.
 *
 *	Return -1 for spurious interrupts
 *
 */
/*ARGSUSED*/
static int
apic_intr_enter(int ipl, int *vectorp)
{
	uchar_t vector;
	int nipl;
	int irq;
	ulong_t iflag;
	apic_cpus_info_t *cpu_infop;

	/*
	 * The real vector delivered is (*vectorp + 0x20), but our caller
	 * subtracts 0x20 from the vector before passing it to us.
	 * (That's why APIC_BASE_VECT is 0x20.)
	 */
	vector = (uchar_t)*vectorp;

	/* if interrupted by the clock, increment apic_nsec_since_boot */
	if (vector == apic_clkvect) {
		if (!apic_oneshot) {
			/* NOTE: this is not MT aware */
			apic_hrtime_stamp++;
			apic_nsec_since_boot += apic_nsec_per_intr;
			apic_hrtime_stamp++;
			last_count_read = apic_hertz_count;
			apic_redistribute_compute();
		}

		/* We will avoid all the book keeping overhead for clock */
		nipl = apic_ipls[vector];

		*vectorp = apic_vector_to_irq[vector + APIC_BASE_VECT];

		apic_reg_ops->apic_write_task_reg(apic_ipltopri[nipl]);
		apic_reg_ops->apic_send_eoi(0);

		return (nipl);
	}

	cpu_infop = &apic_cpus[psm_get_cpu_id()];

	if (vector == (APIC_SPUR_INTR - APIC_BASE_VECT)) {
		cpu_infop->aci_spur_cnt++;
		return (APIC_INT_SPURIOUS);
	}

	/* Check if the vector we got is really what we need */
	if (apic_revector_pending) {
		/*
		 * Disable interrupts for the duration of
		 * the vector translation to prevent a self-race for
		 * the apic_revector_lock.  This cannot be done
		 * in apic_xlate_vector because it is recursive and
		 * we want the vector translation to be atomic with
		 * respect to other (higher-priority) interrupts.
		 */
		iflag = intr_clear();
		vector = apic_xlate_vector(vector + APIC_BASE_VECT) -
		    APIC_BASE_VECT;
		intr_restore(iflag);
	}

	nipl = apic_ipls[vector];
	*vectorp = irq = apic_vector_to_irq[vector + APIC_BASE_VECT];

	apic_reg_ops->apic_write_task_reg(apic_ipltopri[nipl]);

	cpu_infop->aci_current[nipl] = (uchar_t)irq;
	cpu_infop->aci_curipl = (uchar_t)nipl;
	cpu_infop->aci_ISR_in_progress |= 1 << nipl;

	/*
	 * apic_level_intr could have been assimilated into the irq struct.
	 * but, having it as a character array is more efficient in terms of
	 * cache usage. So, we leave it as is.
	 */
	if (!apic_level_intr[irq]) {
		apic_reg_ops->apic_send_eoi(0);
	}

#ifdef	DEBUG
	APIC_DEBUG_BUF_PUT(vector);
	APIC_DEBUG_BUF_PUT(irq);
	APIC_DEBUG_BUF_PUT(nipl);
	APIC_DEBUG_BUF_PUT(psm_get_cpu_id());
	if ((apic_stretch_interrupts) && (apic_stretch_ISR & (1 << nipl)))
		drv_usecwait(apic_stretch_interrupts);

	if (apic_break_on_cpu == psm_get_cpu_id())
		apic_break();
#endif /* DEBUG */
	return (nipl);
}

void
apic_intr_exit(int prev_ipl, int irq)
{
	apic_cpus_info_t *cpu_infop;

	apic_reg_ops->apic_write_task_reg(apic_ipltopri[prev_ipl]);

	cpu_infop = &apic_cpus[psm_get_cpu_id()];
	if (apic_level_intr[irq])
		apic_reg_ops->apic_send_eoi(irq);
	cpu_infop->aci_curipl = (uchar_t)prev_ipl;
	/* ISR above current pri could not be in progress */
	cpu_infop->aci_ISR_in_progress &= (2 << prev_ipl) - 1;
}

intr_exit_fn_t
psm_intr_exit_fn(void)
{
	return (apic_intr_exit);
}

/*
 * Mask all interrupts below or equal to the given IPL.
 */
static void
apic_setspl(int ipl)
{
	apic_reg_ops->apic_write_task_reg(apic_ipltopri[ipl]);

	/* interrupts at ipl above this cannot be in progress */
	apic_cpus[psm_get_cpu_id()].aci_ISR_in_progress &= (2 << ipl) - 1;
	/*
	 * this is a patch fix for the ALR QSMP P5 machine, so that interrupts
	 * have enough time to come in before the priority is raised again
	 * during the idle() loop.
	 */
	if (apic_setspl_delay)
		(void) apic_reg_ops->apic_get_pri();
}

/*ARGSUSED*/
static int
apic_addspl(int irqno, int ipl, int min_ipl, int max_ipl)
{
	return (apic_addspl_common(irqno, ipl, min_ipl, max_ipl));
}

static int
apic_delspl(int irqno, int ipl, int min_ipl, int max_ipl)
{
	return (apic_delspl_common(irqno, ipl, min_ipl,  max_ipl));
}

static int
apic_post_cpu_start(void)
{
	int cpun;
	static int cpus_started = 1;

	/* We know this CPU + BSP  started successfully. */
	cpus_started++;

	splx(ipltospl(LOCK_LEVEL));
	apic_init_intr();

	APIC_AV_PENDING_SET();

	/*
	 * We may be booting, or resuming from suspend; aci_status will
	 * be APIC_CPU_INTR_ENABLE if coming from suspend, so we add the
	 * APIC_CPU_ONLINE flag here rather than setting aci_status completely.
	 */
	cpun = psm_get_cpu_id();
	apic_cpus[cpun].aci_status |= APIC_CPU_ONLINE;

	apic_reg_ops->apic_write(APIC_DIVIDE_REG, apic_divide_reg_init);
	return (PSM_SUCCESS);
}

/*
 * type == -1 indicates it is an internal request. Do not change
 * resv_vector for these requests
 */
static int
apic_get_ipivect(int ipl, int type)
{
	uchar_t vector;
	int irq;

	if ((irq = apic_allocate_irq(APIC_VECTOR(ipl))) != -1) {
		if ((vector = apic_allocate_vector(ipl, irq, 1))) {
			apic_irq_table[irq]->airq_mps_intr_index =
			    RESERVE_INDEX;
			apic_irq_table[irq]->airq_vector = vector;
			if (type != -1) {
				apic_resv_vector[ipl] = vector;
			}
			return (irq);
		}
	}
	apic_error |= APIC_ERR_GET_IPIVECT_FAIL;
	return (-1);	/* shouldn't happen */
}

static int
apic_getclkirq(int ipl)
{
	int	irq;

	if ((irq = apic_get_ipivect(ipl, -1)) == -1)
		return (-1);
	/*
	 * Note the vector in apic_clkvect for per clock handling.
	 */
	apic_clkvect = apic_irq_table[irq]->airq_vector - APIC_BASE_VECT;
	APIC_VERBOSE_IOAPIC((CE_NOTE, "get_clkirq: vector = %x\n",
	    apic_clkvect));
	return (irq);
}

/*
 * Try and disable all interrupts. We just assign interrupts to other
 * processors based on policy. If any were bound by user request, we
 * let them continue and return failure. We do not bother to check
 * for cache affinity while rebinding.
 */

static int
apic_disable_intr(processorid_t cpun)
{
	int bind_cpu = 0, i, hardbound = 0;
	apic_irq_t *irq_ptr;
	ulong_t iflag;

	iflag = intr_clear();
	lock_set(&apic_ioapic_lock);

	for (i = 0; i <= APIC_MAX_VECTOR; i++) {
		if (apic_reprogram_info[i].done == B_FALSE) {
			if (apic_reprogram_info[i].bindcpu == cpun) {
				/*
				 * CPU is busy -- it's the target of
				 * a pending reprogramming attempt
				 */
				lock_clear(&apic_ioapic_lock);
				intr_restore(iflag);
				return (PSM_FAILURE);
			}
		}
	}

	apic_cpus[cpun].aci_status &= ~APIC_CPU_INTR_ENABLE;

	apic_cpus[cpun].aci_curipl = 0;

	i = apic_min_device_irq;
	for (; i <= apic_max_device_irq; i++) {
		/*
		 * If there are bound interrupts on this cpu, then
		 * rebind them to other processors.
		 */
		if ((irq_ptr = apic_irq_table[i]) != NULL) {
			ASSERT((irq_ptr->airq_temp_cpu == IRQ_UNBOUND) ||
			    (irq_ptr->airq_temp_cpu == IRQ_UNINIT) ||
			    (apic_cpu_in_range(irq_ptr->airq_temp_cpu)));

			if (irq_ptr->airq_temp_cpu == (cpun | IRQ_USER_BOUND)) {
				hardbound = 1;
				continue;
			}

			if (irq_ptr->airq_temp_cpu == cpun) {
				do {
					bind_cpu =
					    apic_find_cpu(APIC_CPU_INTR_ENABLE);
				} while (apic_rebind_all(irq_ptr, bind_cpu));
			}
		}
	}

	lock_clear(&apic_ioapic_lock);
	intr_restore(iflag);

	if (hardbound) {
		cmn_err(CE_WARN, "Could not disable interrupts on %d"
		    "due to user bound interrupts", cpun);
		return (PSM_FAILURE);
	}
	else
		return (PSM_SUCCESS);
}

/*
 * Bind interrupts to the CPU's local APIC.
 * Interrupts should not be bound to a CPU's local APIC until the CPU
 * is ready to receive interrupts.
 */
static void
apic_enable_intr(processorid_t cpun)
{
	int	i;
	apic_irq_t *irq_ptr;
	ulong_t iflag;

	iflag = intr_clear();
	lock_set(&apic_ioapic_lock);

	apic_cpus[cpun].aci_status |= APIC_CPU_INTR_ENABLE;

	i = apic_min_device_irq;
	for (i = apic_min_device_irq; i <= apic_max_device_irq; i++) {
		if ((irq_ptr = apic_irq_table[i]) != NULL) {
			if ((irq_ptr->airq_cpu & ~IRQ_USER_BOUND) == cpun) {
				(void) apic_rebind_all(irq_ptr,
				    irq_ptr->airq_cpu);
			}
		}
	}

	if (apic_cpus[cpun].aci_status & APIC_CPU_SUSPEND)
		apic_cpus[cpun].aci_status &= ~APIC_CPU_SUSPEND;

	lock_clear(&apic_ioapic_lock);
	intr_restore(iflag);
}

/*
 * If this module needs a periodic handler for the interrupt distribution, it
 * can be added here. The argument to the periodic handler is not currently
 * used, but is reserved for future.
 */
static void
apic_post_cyclic_setup(void *arg)
{
_NOTE(ARGUNUSED(arg))

	cyc_handler_t cyh;
	cyc_time_t cyt;

	/* cpu_lock is held */
	/* set up a periodic handler for intr redistribution */

	/*
	 * In peridoc mode intr redistribution processing is done in
	 * apic_intr_enter during clk intr processing
	 */
	if (!apic_oneshot)
		return;

	/*
	 * Register a periodical handler for the redistribution processing.
	 * Though we would generally prefer to use the DDI interface for
	 * periodic handler invocation, ddi_periodic_add(9F), we are
	 * unfortunately already holding cpu_lock, which ddi_periodic_add will
	 * attempt to take for us.  Thus, we add our own cyclic directly:
	 */
	cyh.cyh_func = (void (*)(void *))apic_redistribute_compute;
	cyh.cyh_arg = NULL;
	cyh.cyh_level = CY_LOW_LEVEL;

	cyt.cyt_when = 0;
	cyt.cyt_interval = apic_redistribute_sample_interval;

	apic_cyclic_id = cyclic_add(&cyh, &cyt);
}

static void
apic_redistribute_compute(void)
{
	int	i, j, max_busy;

	if (apic_enable_dynamic_migration) {
		if (++apic_nticks == apic_sample_factor_redistribution) {
			/*
			 * Time to call apic_intr_redistribute().
			 * reset apic_nticks. This will cause max_busy
			 * to be calculated below and if it is more than
			 * apic_int_busy, we will do the whole thing
			 */
			apic_nticks = 0;
		}
		max_busy = 0;
		for (i = 0; i < apic_nproc; i++) {
			if (!apic_cpu_in_range(i))
				continue;

			/*
			 * Check if curipl is non zero & if ISR is in
			 * progress
			 */
			if (((j = apic_cpus[i].aci_curipl) != 0) &&
			    (apic_cpus[i].aci_ISR_in_progress & (1 << j))) {

				int	irq;
				apic_cpus[i].aci_busy++;
				irq = apic_cpus[i].aci_current[j];
				apic_irq_table[irq]->airq_busy++;
			}

			if (!apic_nticks &&
			    (apic_cpus[i].aci_busy > max_busy))
				max_busy = apic_cpus[i].aci_busy;
		}
		if (!apic_nticks) {
			if (max_busy > apic_int_busy_mark) {
			/*
			 * We could make the following check be
			 * skipped > 1 in which case, we get a
			 * redistribution at half the busy mark (due to
			 * double interval). Need to be able to collect
			 * more empirical data to decide if that is a
			 * good strategy. Punt for now.
			 */
				if (apic_skipped_redistribute) {
					apic_cleanup_busy();
					apic_skipped_redistribute = 0;
				} else {
					apic_intr_redistribute();
				}
			} else
				apic_skipped_redistribute++;
		}
	}
}


/*
 * The following functions are in the platform specific file so that they
 * can be different functions depending on whether we are running on
 * bare metal or a hypervisor.
 */

/*
 * Check to make sure there are enough irq slots
 */
int
apic_check_free_irqs(int count)
{
	int i, avail;

	avail = 0;
	for (i = APIC_FIRST_FREE_IRQ; i < APIC_RESV_IRQ; i++) {
		if ((apic_irq_table[i] == NULL) ||
		    apic_irq_table[i]->airq_mps_intr_index == FREE_INDEX) {
			if (++avail >= count)
				return (PSM_SUCCESS);
		}
	}
	return (PSM_FAILURE);
}

/*
 * This function allocates "count" MSI vector(s) for the given "dip/pri/type"
 */
int
apic_alloc_msi_vectors(dev_info_t *dip, int inum, int count, int pri,
    int behavior)
{
	int	rcount, i;
	uchar_t	start, irqno;
	uint32_t cpu = 0;
	major_t	major;
	apic_irq_t	*irqptr;

	DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: dip=0x%p "
	    "inum=0x%x  pri=0x%x count=0x%x behavior=%d\n",
	    (void *)dip, inum, pri, count, behavior));

	if (count > 1) {
		if (behavior == DDI_INTR_ALLOC_STRICT &&
		    apic_multi_msi_enable == 0)
			return (0);
		if (apic_multi_msi_enable == 0)
			count = 1;
	}

	if ((rcount = apic_navail_vector(dip, pri)) > count)
		rcount = count;
	else if (rcount == 0 || (rcount < count &&
	    behavior == DDI_INTR_ALLOC_STRICT))
		return (0);

	/* if not ISP2, then round it down */
	if (!ISP2(rcount))
		rcount = 1 << (highbit(rcount) - 1);

	mutex_enter(&airq_mutex);

	for (start = 0; rcount > 0; rcount >>= 1) {
		if ((start = apic_find_multi_vectors(pri, rcount)) != 0 ||
		    behavior == DDI_INTR_ALLOC_STRICT)
			break;
	}

	if (start == 0) {
		/* no vector available */
		mutex_exit(&airq_mutex);
		return (0);
	}

	if (apic_check_free_irqs(rcount) == PSM_FAILURE) {
		/* not enough free irq slots available */
		mutex_exit(&airq_mutex);
		return (0);
	}

	major = (dip != NULL) ? ddi_driver_major(dip) : 0;
	for (i = 0; i < rcount; i++) {
		if ((irqno = apic_allocate_irq(apic_first_avail_irq)) ==
		    (uchar_t)-1) {
			/*
			 * shouldn't happen because of the
			 * apic_check_free_irqs() check earlier
			 */
			mutex_exit(&airq_mutex);
			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: "
			    "apic_allocate_irq failed\n"));
			return (i);
		}
		apic_max_device_irq = max(irqno, apic_max_device_irq);
		apic_min_device_irq = min(irqno, apic_min_device_irq);
		irqptr = apic_irq_table[irqno];
#ifdef	DEBUG
		if (apic_vector_to_irq[start + i] != APIC_RESV_IRQ)
			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: "
			    "apic_vector_to_irq is not APIC_RESV_IRQ\n"));
#endif
		apic_vector_to_irq[start + i] = (uchar_t)irqno;

		irqptr->airq_vector = (uchar_t)(start + i);
		irqptr->airq_ioapicindex = (uchar_t)inum;	/* start */
		irqptr->airq_intin_no = (uchar_t)rcount;
		ASSERT(pri >= 0 && pri <= UCHAR_MAX);
		irqptr->airq_ipl = (uchar_t)pri;
		irqptr->airq_vector = start + i;
		irqptr->airq_origirq = (uchar_t)(inum + i);
		irqptr->airq_share_id = 0;
		irqptr->airq_mps_intr_index = MSI_INDEX;
		irqptr->airq_dip = dip;
		irqptr->airq_major = major;
		if (i == 0) /* they all bound to the same cpu */
			cpu = irqptr->airq_cpu = apic_bind_intr(dip, irqno,
			    0xff, 0xff);
		else
			irqptr->airq_cpu = cpu;
		DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: irq=0x%x "
		    "dip=0x%p vector=0x%x origirq=0x%x pri=0x%x\n", irqno,
		    (void *)irqptr->airq_dip, irqptr->airq_vector,
		    irqptr->airq_origirq, pri));
	}
	mutex_exit(&airq_mutex);
	return (rcount);
}

/*
 * This function allocates "count" MSI-X vector(s) for the given "dip/pri/type"
 */
int
apic_alloc_msix_vectors(dev_info_t *dip, int inum, int count, int pri,
    int behavior)
{
	int	rcount, i;
	major_t	major;

	mutex_enter(&airq_mutex);

	if ((rcount = apic_navail_vector(dip, pri)) > count)
		rcount = count;
	else if (rcount == 0 || (rcount < count &&
	    behavior == DDI_INTR_ALLOC_STRICT)) {
		rcount = 0;
		goto out;
	}

	if (apic_check_free_irqs(rcount) == PSM_FAILURE) {
		/* not enough free irq slots available */
		rcount = 0;
		goto out;
	}

	major = (dip != NULL) ? ddi_driver_major(dip) : 0;
	for (i = 0; i < rcount; i++) {
		uchar_t	vector, irqno;
		apic_irq_t	*irqptr;

		if ((irqno = apic_allocate_irq(apic_first_avail_irq)) ==
		    (uchar_t)-1) {
			/*
			 * shouldn't happen because of the
			 * apic_check_free_irqs() check earlier
			 */
			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msix_vectors: "
			    "apic_allocate_irq failed\n"));
			rcount = i;
			goto out;
		}
		if ((vector = apic_allocate_vector(pri, irqno, 1)) == 0) {
			/*
			 * shouldn't happen because of the
			 * apic_navail_vector() call earlier
			 */
			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msix_vectors: "
			    "apic_allocate_vector failed\n"));
			rcount = i;
			goto out;
		}
		apic_max_device_irq = max(irqno, apic_max_device_irq);
		apic_min_device_irq = min(irqno, apic_min_device_irq);
		irqptr = apic_irq_table[irqno];
		irqptr->airq_vector = (uchar_t)vector;
		ASSERT(pri >= 0 && pri <= UCHAR_MAX);
		irqptr->airq_ipl = (uchar_t)pri;
		irqptr->airq_origirq = (uchar_t)(inum + i);
		irqptr->airq_share_id = 0;
		irqptr->airq_mps_intr_index = MSIX_INDEX;
		irqptr->airq_dip = dip;
		irqptr->airq_major = major;
		irqptr->airq_cpu = apic_bind_intr(dip, irqno, 0xff, 0xff);
	}
out:
	mutex_exit(&airq_mutex);
	return (rcount);
}

/*
 * Allocate a free vector for irq at ipl. Takes care of merging of multiple
 * IPLs into a single APIC level as well as stretching some IPLs onto multiple
 * levels. APIC_HI_PRI_VECTS interrupts are reserved for high priority
 * requests and allocated only when pri is set.
 */
uchar_t
apic_allocate_vector(int ipl, int irq, int pri)
{
	int	lowest, highest, i;

	highest = apic_ipltopri[ipl] + APIC_VECTOR_MASK;
	lowest = apic_ipltopri[ipl - 1] + APIC_VECTOR_PER_IPL;

	if (highest < lowest) /* Both ipl and ipl - 1 map to same pri */
		lowest -= APIC_VECTOR_PER_IPL;

#ifdef	DEBUG
	if (apic_restrict_vector)	/* for testing shared interrupt logic */
		highest = lowest + apic_restrict_vector + APIC_HI_PRI_VECTS;
#endif /* DEBUG */
	if (pri == 0)
		highest -= APIC_HI_PRI_VECTS;

	for (i = lowest; i <= highest; i++) {
		if (APIC_CHECK_RESERVE_VECTORS(i))
			continue;
		if (apic_vector_to_irq[i] == APIC_RESV_IRQ) {
			apic_vector_to_irq[i] = (uchar_t)irq;
			ASSERT(i >= 0 && i <= UCHAR_MAX);
			return ((uchar_t)i);
		}
	}

	return (0);
}

/* Mark vector as not being used by any irq */
void
apic_free_vector(uchar_t vector)
{
	apic_vector_to_irq[vector] = APIC_RESV_IRQ;
}

/*
 * Call rebind to do the actual programming.
 * Must be called with interrupts disabled and apic_ioapic_lock held
 * 'p' is polymorphic -- if this function is called to process a deferred
 * reprogramming, p is of type 'struct ioapic_reprogram_data *', from which
 * the irq pointer is retrieved.  If not doing deferred reprogramming,
 * p is of the type 'apic_irq_t *'.
 *
 * apic_ioapic_lock must be held across this call, as it protects apic_rebind
 * and it protects apic_get_next_bind_cpu() from a race in which a CPU can be
 * taken offline after a cpu is selected, but before apic_rebind is called to
 * bind interrupts to it.
 */
int
apic_setup_io_intr(void *p, int irq, boolean_t deferred)
{
	apic_irq_t *irqptr;
	struct ioapic_reprogram_data *drep = NULL;
	int rv;

	if (deferred) {
		drep = (struct ioapic_reprogram_data *)p;
		ASSERT(drep != NULL);
		irqptr = drep->irqp;
	} else
		irqptr = (apic_irq_t *)p;

	ASSERT(irqptr != NULL);

	rv = apic_rebind(irqptr, apic_irq_table[irq]->airq_cpu, drep);
	if (rv) {
		/*
		 * CPU is not up or interrupts are disabled. Fall back to
		 * the first available CPU
		 */
		rv = apic_rebind(irqptr, apic_find_cpu(APIC_CPU_INTR_ENABLE),
		    drep);
	}

	return (rv);
}


uchar_t
apic_modify_vector(uchar_t vector, int irq)
{
	apic_vector_to_irq[vector] = (uchar_t)irq;
	return (vector);
}

char *
apic_get_apic_type(void)
{
	return (apic_psm_info.p_mach_idstring);
}

void
apic_switch_ipi_callback(boolean_t enter)
{
	ASSERT(enter == B_TRUE);
}

int
apic_detect_x2apic(void)
{
	return (0);
}

void
apic_enable_x2apic(void)
{
	cmn_err(CE_PANIC, "apic_enable_x2apic() called in pcplusmp");
}

void
x2apic_update_psm(void)
{
	cmn_err(CE_PANIC, "x2apic_update_psm() called in pcplusmp");
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
 */
/*
 * Copyright 2021 Joyent, Inc.
 * Copyright (c) 2016, 2017 by Delphix. All rights reserved.
 * Copyright 2019 Joshua M. Clulow <josh@sysmgr.org>
 */

/*
 * PSMI 1.1 extensions are supported only in 2.6 and later versions.
 * PSMI 1.2 extensions are supported only in 2.7 and later versions.
 * PSMI 1.3 and 1.4 extensions are supported in Solaris 10.
 * PSMI 1.5 extensions are supported in Solaris Nevada.
 * PSMI 1.6 extensions are supported in Solaris Nevada.
 * PSMI 1.7 extensions are supported in Solaris Nevada.
 */
#define	PSMI_1_7

#include <sys/processor.h>
#include <sys/time.h>
#include <sys/psm.h>
#include <sys/smp_impldefs.h>
#include <sys/cram.h>
#include <sys/acpi/acpi.h>
#include <sys/acpica.h>
#include <sys/psm_common.h>
#include <sys/apic.h>
#include <sys/pit.h>
#include <sys/ddi.h>
#include <sys/sunddi.h>
#include <sys/ddi_impldefs.h>
#include <sys/pci.h>
#include <sys/promif.h>
#include <sys/x86_archext.h>
#include <sys/cpc_impl.h>
#include <sys/uadmin.h>
#include <sys/panic.h>
#include <sys/debug.h>
#include <sys/archsystm.h>
#include <sys/trap.h>
#include <sys/machsystm.h>
#include <sys/sysmacros.h>
#include <sys/cpuvar.h>
#include <sys/rm_platter.h>
#include <sys/privregs.h>
#include <sys/note.h>
#include <sys/pci_intr_lib.h>
#include <sys/spl.h>
#include <sys/clock.h>
#include <sys/dditypes.h>
#include <sys/sunddi.h>
#include <sys/x_call.h>
#include <sys/reboot.h>
#include <sys/hpet.h>
#include <sys/apic_common.h>
#include <sys/apic_timer.h>
#include <sys/tsc.h>

static void	apic_record_ioapic_rdt(void *intrmap_private,
		    ioapic_rdt_t *irdt);
static void	apic_record_msi(void *intrmap_private, msi_regs_t *mregs);

/*
 * Common routines between pcplusmp & apix (taken from apic.c).
 */

int	apic_clkinit(int);
hrtime_t apic_gethrtime(void);
void	apic_send_ipi(int, int);
void	apic_set_idlecpu(processorid_t);
void	apic_unset_idlecpu(processorid_t);
void	apic_shutdown(int, int);
void	apic_preshutdown(int, int);
processorid_t	apic_get_next_processorid(processorid_t);

hrtime_t apic_gettime();

enum apic_ioapic_method_type apix_mul_ioapic_method = APIC_MUL_IOAPIC_PCPLUSMP;

/* Now the ones for Dynamic Interrupt distribution */
int	apic_enable_dynamic_migration = 0;

/* maximum loop count when sending Start IPIs. */
int apic_sipi_max_loop_count = 0x1000;

/*
 * These variables are frequently accessed in apic_intr_enter(),
 * apic_intr_exit and apic_setspl, so group them together
 */
volatile uint32_t *apicadr =  NULL;	/* virtual addr of local APIC	*/
int apic_setspl_delay = 1;		/* apic_setspl - delay enable	*/
int apic_clkvect;

/* vector at which error interrupts come in */
int apic_errvect;
int apic_enable_error_intr = 1;
int apic_error_display_delay = 100;

/* vector at which performance counter overflow interrupts come in */
int apic_cpcovf_vect;
int apic_enable_cpcovf_intr = 1;

/* vector at which CMCI interrupts come in */
int apic_cmci_vect;
extern void cmi_cmci_trap(void);

lock_t apic_mode_switch_lock;

int apic_pir_vect;

/*
 * Patchable global variables.
 */
int	apic_forceload = 0;

int	apic_coarse_hrtime = 1;		/* 0 - use accurate slow gethrtime() */

int	apic_flat_model = 0;		/* 0 - clustered. 1 - flat */
int	apic_panic_on_nmi = 0;
int	apic_panic_on_apic_error = 0;

int	apic_verbose = 0;	/* 0x1ff */

/* If set, force APIC calibration to use the PIT instead of the TSC */
int	apic_calibrate_use_pit = 0;

/*
 * It was found empirically that 5 measurements seem sufficient to give a good
 * accuracy. Most spurious measurements are higher than the target value thus
 * we eliminate up to 2/5 spurious measurements.
 */
#define	APIC_CALIBRATE_MEASUREMENTS		5

#define	APIC_CALIBRATE_PERCENT_OFF_WARNING	10

extern int pit_is_broken; /* from tscc_pit.c */

uint64_t apic_info_tsc[APIC_CALIBRATE_MEASUREMENTS];
uint64_t apic_info_pit[APIC_CALIBRATE_MEASUREMENTS];

#ifdef DEBUG
int	apic_debug = 0;
int	apic_restrict_vector = 0;

int	apic_debug_msgbuf[APIC_DEBUG_MSGBUFSIZE];
int	apic_debug_msgbufindex = 0;

#endif /* DEBUG */

uint_t apic_nticks = 0;
uint_t apic_skipped_redistribute = 0;

uint_t last_count_read = 0;
lock_t	apic_gethrtime_lock;
volatile int	apic_hrtime_stamp = 0;
volatile hrtime_t apic_nsec_since_boot = 0;

static	hrtime_t	apic_last_hrtime = 0;
int		apic_hrtime_error = 0;
int		apic_remote_hrterr = 0;
int		apic_num_nmis = 0;
int		apic_apic_error = 0;
int		apic_num_apic_errors = 0;
int		apic_num_cksum_errors = 0;

int	apic_error = 0;

static	int	apic_cmos_ssb_set = 0;

/* use to make sure only one cpu handles the nmi */
lock_t	apic_nmi_lock;
/* use to make sure only one cpu handles the error interrupt */
lock_t	apic_error_lock;

static	struct {
	uchar_t	cntl;
	uchar_t	data;
} aspen_bmc[] = {
	{ CC_SMS_WR_START,	0x18 },		/* NetFn/LUN */
	{ CC_SMS_WR_NEXT,	0x24 },		/* Cmd SET_WATCHDOG_TIMER */
	{ CC_SMS_WR_NEXT,	0x84 },		/* DataByte 1: SMS/OS no log */
	{ CC_SMS_WR_NEXT,	0x2 },		/* DataByte 2: Power Down */
	{ CC_SMS_WR_NEXT,	0x0 },		/* DataByte 3: no pre-timeout */
	{ CC_SMS_WR_NEXT,	0x0 },		/* DataByte 4: timer expir. */
	{ CC_SMS_WR_NEXT,	0xa },		/* DataByte 5: init countdown */
	{ CC_SMS_WR_END,	0x0 },		/* DataByte 6: init countdown */

	{ CC_SMS_WR_START,	0x18 },		/* NetFn/LUN */
	{ CC_SMS_WR_END,	0x22 }		/* Cmd RESET_WATCHDOG_TIMER */
};

static	struct {
	int	port;
	uchar_t	data;
} sitka_bmc[] = {
	{ SMS_COMMAND_REGISTER,	SMS_WRITE_START },
	{ SMS_DATA_REGISTER,	0x18 },		/* NetFn/LUN */
	{ SMS_DATA_REGISTER,	0x24 },		/* Cmd SET_WATCHDOG_TIMER */
	{ SMS_DATA_REGISTER,	0x84 },		/* DataByte 1: SMS/OS no log */
	{ SMS_DATA_REGISTER,	0x2 },		/* DataByte 2: Power Down */
	{ SMS_DATA_REGISTER,	0x0 },		/* DataByte 3: no pre-timeout */
	{ SMS_DATA_REGISTER,	0x0 },		/* DataByte 4: timer expir. */
	{ SMS_DATA_REGISTER,	0xa },		/* DataByte 5: init countdown */
	{ SMS_COMMAND_REGISTER,	SMS_WRITE_END },
	{ SMS_DATA_REGISTER,	0x0 },		/* DataByte 6: init countdown */

	{ SMS_COMMAND_REGISTER,	SMS_WRITE_START },
	{ SMS_DATA_REGISTER,	0x18 },		/* NetFn/LUN */
	{ SMS_COMMAND_REGISTER,	SMS_WRITE_END },
	{ SMS_DATA_REGISTER,	0x22 }		/* Cmd RESET_WATCHDOG_TIMER */
};

/* Patchable global variables. */
int		apic_kmdb_on_nmi = 0;		/* 0 - no, 1 - yes enter kmdb */
uint32_t	apic_divide_reg_init = 0;	/* 0 - divide by 2 */

/* default apic ops without interrupt remapping */
static apic_intrmap_ops_t apic_nointrmap_ops = {
	(int (*)(int))return_instr,
	(void (*)(int))return_instr,
	(void (*)(void **, dev_info_t *, uint16_t, int, uchar_t))return_instr,
	(void (*)(void *, void *, uint16_t, int))return_instr,
	(void (*)(void **))return_instr,
	apic_record_ioapic_rdt,
	apic_record_msi,
};

apic_intrmap_ops_t *apic_vt_ops = &apic_nointrmap_ops;
apic_cpus_info_t	*apic_cpus = NULL;
cpuset_t	apic_cpumask;
uint_t		apic_picinit_called;

/* Flag to indicate that we need to shut down all processors */
static uint_t	apic_shutdown_processors;

/*
 * Probe the ioapic method for apix module. Called in apic_probe_common()
 */
int
apic_ioapic_method_probe()
{
	if (apix_enable == 0)
		return (PSM_SUCCESS);

	/*
	 * Set IOAPIC EOI handling method. The priority from low to high is:
	 *	1. IOxAPIC: with EOI register
	 *	2. IOMMU interrupt mapping
	 *	3. Mask-Before-EOI method for systems without boot
	 *	interrupt routing, such as systems with only one IOAPIC;
	 *	NVIDIA CK8-04/MCP55 systems; systems with bridge solution
	 *	which disables the boot interrupt routing already.
	 *	4. Directed EOI
	 */
	if (apic_io_ver[0] >= 0x20)
		apix_mul_ioapic_method = APIC_MUL_IOAPIC_IOXAPIC;
	if ((apic_io_max == 1) || (apic_nvidia_io_max == apic_io_max))
		apix_mul_ioapic_method = APIC_MUL_IOAPIC_MASK;
	if (apic_directed_EOI_supported())
		apix_mul_ioapic_method = APIC_MUL_IOAPIC_DEOI;

	/* fall back to pcplusmp */
	if (apix_mul_ioapic_method == APIC_MUL_IOAPIC_PCPLUSMP) {
		/* make sure apix is after pcplusmp in /etc/mach */
		apix_enable = 0; /* go ahead with pcplusmp install next */
		return (PSM_FAILURE);
	}

	return (PSM_SUCCESS);
}

/*
 * handler for APIC Error interrupt. Just print a warning and continue
 */
int
apic_error_intr()
{
	uint_t	error0, error1, error;
	uint_t	i;

	/*
	 * We need to write before read as per 7.4.17 of system prog manual.
	 * We do both and or the results to be safe
	 */
	error0 = apic_reg_ops->apic_read(APIC_ERROR_STATUS);
	apic_reg_ops->apic_write(APIC_ERROR_STATUS, 0);
	error1 = apic_reg_ops->apic_read(APIC_ERROR_STATUS);
	error = error0 | error1;

	/*
	 * Clear the APIC error status (do this on all cpus that enter here)
	 * (two writes are required due to the semantics of accessing the
	 * error status register.)
	 */
	apic_reg_ops->apic_write(APIC_ERROR_STATUS, 0);
	apic_reg_ops->apic_write(APIC_ERROR_STATUS, 0);

	/*
	 * Prevent more than 1 CPU from handling error interrupt causing
	 * double printing (interleave of characters from multiple
	 * CPU's when using prom_printf)
	 */
	if (lock_try(&apic_error_lock) == 0)
		return (error ? DDI_INTR_CLAIMED : DDI_INTR_UNCLAIMED);
	if (error) {
#if	DEBUG
		if (apic_debug)
			debug_enter("pcplusmp: APIC Error interrupt received");
#endif /* DEBUG */
		if (apic_panic_on_apic_error)
			cmn_err(CE_PANIC,
			    "APIC Error interrupt on CPU %d. Status = %x",
			    psm_get_cpu_id(), error);
		else {
			if ((error & ~APIC_CS_ERRORS) == 0) {
				/* cksum error only */
				apic_error |= APIC_ERR_APIC_ERROR;
				apic_apic_error |= error;
				apic_num_apic_errors++;
				apic_num_cksum_errors++;
			} else {
				/*
				 * prom_printf is the best shot we have of
				 * something which is problem free from
				 * high level/NMI type of interrupts
				 */
				prom_printf("APIC Error interrupt on CPU %d. "
				    "Status 0 = %x, Status 1 = %x\n",
				    psm_get_cpu_id(), error0, error1);
				apic_error |= APIC_ERR_APIC_ERROR;
				apic_apic_error |= error;
				apic_num_apic_errors++;
				for (i = 0; i < apic_error_display_delay; i++) {
					tenmicrosec();
				}
				/*
				 * provide more delay next time limited to
				 * roughly 1 clock tick time
				 */
				if (apic_error_display_delay < 500)
					apic_error_display_delay *= 2;
			}
		}
		lock_clear(&apic_error_lock);
		return (DDI_INTR_CLAIMED);
	} else {
		lock_clear(&apic_error_lock);
		return (DDI_INTR_UNCLAIMED);
	}
}

/*
 * Turn off the mask bit in the performance counter Local Vector Table entry.
 */
void
apic_cpcovf_mask_clear(void)
{
	apic_reg_ops->apic_write(APIC_PCINT_VECT,
	    (apic_reg_ops->apic_read(APIC_PCINT_VECT) & ~APIC_LVT_MASK));
}

static int
apic_cmci_enable(xc_arg_t arg1 __unused, xc_arg_t arg2 __unused,
    xc_arg_t arg3 __unused)
{
	apic_reg_ops->apic_write(APIC_CMCI_VECT, apic_cmci_vect);
	return (0);
}

static int
apic_cmci_disable(xc_arg_t arg1 __unused, xc_arg_t arg2 __unused,
    xc_arg_t arg3 __unused)
{
	apic_reg_ops->apic_write(APIC_CMCI_VECT, apic_cmci_vect | AV_MASK);
	return (0);
}

void
apic_cmci_setup(processorid_t cpuid, boolean_t enable)
{
	cpuset_t	cpu_set;

	CPUSET_ONLY(cpu_set, cpuid);

	if (enable) {
		xc_call(0, 0, 0, CPUSET2BV(cpu_set),
		    (xc_func_t)apic_cmci_enable);
	} else {
		xc_call(0, 0, 0, CPUSET2BV(cpu_set),
		    (xc_func_t)apic_cmci_disable);
	}
}

static void
apic_disable_local_apic(void)
{
	apic_reg_ops->apic_write_task_reg(APIC_MASK_ALL);
	apic_reg_ops->apic_write(APIC_LOCAL_TIMER, AV_MASK);

	/* local intr reg 0 */
	apic_reg_ops->apic_write(APIC_INT_VECT0, AV_MASK);

	/* disable NMI */
	apic_reg_ops->apic_write(APIC_INT_VECT1, AV_MASK);

	/* and error interrupt */
	apic_reg_ops->apic_write(APIC_ERR_VECT, AV_MASK);

	/* and perf counter intr */
	apic_reg_ops->apic_write(APIC_PCINT_VECT, AV_MASK);

	apic_reg_ops->apic_write(APIC_SPUR_INT_REG, APIC_SPUR_INTR);
}

static void
apic_cpu_send_SIPI(processorid_t cpun, boolean_t start)
{
	int		loop_count;
	uint32_t	vector;
	uint_t		apicid;
	ulong_t		iflag;

	apicid =  apic_cpus[cpun].aci_local_id;

	/*
	 * Interrupts on current CPU will be disabled during the
	 * steps in order to avoid unwanted side effects from
	 * executing interrupt handlers on a problematic BIOS.
	 */
	iflag = intr_clear();

	if (start) {
		outb(CMOS_ADDR, SSB);
		outb(CMOS_DATA, BIOS_SHUTDOWN);
	}

	/*
	 * According to X2APIC specification in section '2.3.5.1' of
	 * Interrupt Command Register Semantics, the semantics of
	 * programming the Interrupt Command Register to dispatch an interrupt
	 * is simplified. A single MSR write to the 64-bit ICR is required
	 * for dispatching an interrupt. Specifically, with the 64-bit MSR
	 * interface to ICR, system software is not required to check the
	 * status of the delivery status bit prior to writing to the ICR
	 * to send an IPI. With the removal of the Delivery Status bit,
	 * system software no longer has a reason to read the ICR. It remains
	 * readable only to aid in debugging.
	 */
#ifdef	DEBUG
	APIC_AV_PENDING_SET();
#else
	if (apic_mode == LOCAL_APIC) {
		APIC_AV_PENDING_SET();
	}
#endif /* DEBUG */

	/* for integrated - make sure there is one INIT IPI in buffer */
	/* for external - it will wake up the cpu */
	apic_reg_ops->apic_write_int_cmd(apicid, AV_ASSERT | AV_RESET);

	/* If only 1 CPU is installed, PENDING bit will not go low */
	for (loop_count = apic_sipi_max_loop_count; loop_count; loop_count--) {
		if (apic_mode == LOCAL_APIC &&
		    apic_reg_ops->apic_read(APIC_INT_CMD1) & AV_PENDING)
			apic_ret();
		else
			break;
	}

	apic_reg_ops->apic_write_int_cmd(apicid, AV_DEASSERT | AV_RESET);
	drv_usecwait(20000);		/* 20 milli sec */

	if (apic_cpus[cpun].aci_local_ver >= APIC_INTEGRATED_VERS) {
		/* integrated apic */

		vector = (rm_platter_pa >> MMU_PAGESHIFT) &
		    (APIC_VECTOR_MASK | APIC_IPL_MASK);

		/* to offset the INIT IPI queue up in the buffer */
		apic_reg_ops->apic_write_int_cmd(apicid, vector | AV_STARTUP);
		drv_usecwait(200);		/* 20 micro sec */

		/*
		 * send the second SIPI (Startup IPI) as recommended by Intel
		 * software development manual.
		 */
		apic_reg_ops->apic_write_int_cmd(apicid, vector | AV_STARTUP);
		drv_usecwait(200);	/* 20 micro sec */
	}

	intr_restore(iflag);
}

/*ARGSUSED1*/
int
apic_cpu_start(processorid_t cpun, caddr_t arg __unused)
{
	ASSERT(MUTEX_HELD(&cpu_lock));

	if (!apic_cpu_in_range(cpun)) {
		return (EINVAL);
	}

	/*
	 * Switch to apic_common_send_ipi for safety during starting other CPUs.
	 */
	if (apic_mode == LOCAL_X2APIC) {
		apic_switch_ipi_callback(B_TRUE);
	}

	apic_cmos_ssb_set = 1;
	apic_cpu_send_SIPI(cpun, B_TRUE);

	return (0);
}

/*
 * Put CPU into halted state with interrupts disabled.
 */
/*ARGSUSED1*/
int
apic_cpu_stop(processorid_t cpun, caddr_t arg __unused)
{
	int		rc;
	cpu_t		*cp;
	extern cpuset_t cpu_ready_set;
	extern void cpu_idle_intercept_cpu(cpu_t *cp);

	ASSERT(MUTEX_HELD(&cpu_lock));

	if (!apic_cpu_in_range(cpun)) {
		return (EINVAL);
	}
	if (apic_cpus[cpun].aci_local_ver < APIC_INTEGRATED_VERS) {
		return (ENOTSUP);
	}

	cp = cpu_get(cpun);
	ASSERT(cp != NULL);
	ASSERT((cp->cpu_flags & CPU_OFFLINE) != 0);
	ASSERT((cp->cpu_flags & CPU_QUIESCED) != 0);
	ASSERT((cp->cpu_flags & CPU_ENABLE) == 0);

	/* Clear CPU_READY flag to disable cross calls. */
	cp->cpu_flags &= ~CPU_READY;
	CPUSET_ATOMIC_DEL(cpu_ready_set, cpun);
	rc = xc_flush_cpu(cp);
	if (rc != 0) {
		CPUSET_ATOMIC_ADD(cpu_ready_set, cpun);
		cp->cpu_flags |= CPU_READY;
		return (rc);
	}

	/* Intercept target CPU at a safe point before powering it off. */
	cpu_idle_intercept_cpu(cp);

	apic_cpu_send_SIPI(cpun, B_FALSE);
	cp->cpu_flags &= ~CPU_RUNNING;

	return (0);
}

int
apic_cpu_ops(psm_cpu_request_t *reqp)
{
	if (reqp == NULL) {
		return (EINVAL);
	}

	switch (reqp->pcr_cmd) {
	case PSM_CPU_ADD:
		return (apic_cpu_add(reqp));

	case PSM_CPU_REMOVE:
		return (apic_cpu_remove(reqp));

	case PSM_CPU_STOP:
		return (apic_cpu_stop(reqp->req.cpu_stop.cpuid,
		    reqp->req.cpu_stop.ctx));

	default:
		return (ENOTSUP);
	}
}

#ifdef	DEBUG
int	apic_break_on_cpu = 9;
int	apic_stretch_interrupts = 0;
int	apic_stretch_ISR = 1 << 3;	/* IPL of 3 matches nothing now */
#endif /* DEBUG */

/*
 * generates an interprocessor interrupt to another CPU. Any changes made to
 * this routine must be accompanied by similar changes to
 * apic_common_send_ipi().
 */
void
apic_send_ipi(int cpun, int ipl)
{
	int vector;
	ulong_t flag;

	vector = apic_resv_vector[ipl];

	ASSERT((vector >= APIC_BASE_VECT) && (vector <= APIC_SPUR_INTR));

	flag = intr_clear();

	APIC_AV_PENDING_SET();

	apic_reg_ops->apic_write_int_cmd(apic_cpus[cpun].aci_local_id,
	    vector);

	intr_restore(flag);
}

void
apic_send_pir_ipi(processorid_t cpun)
{
	const int vector = apic_pir_vect;
	ulong_t flag;

	ASSERT((vector >= APIC_BASE_VECT) && (vector <= APIC_SPUR_INTR));

	flag = intr_clear();

	/* Self-IPI for inducing PIR makes no sense. */
	if ((cpun != psm_get_cpu_id())) {
		APIC_AV_PENDING_SET();
		apic_reg_ops->apic_write_int_cmd(apic_cpus[cpun].aci_local_id,
		    vector);
	}

	intr_restore(flag);
}

int
apic_get_pir_ipivect(void)
{
	return (apic_pir_vect);
}

void
apic_set_idlecpu(processorid_t cpun __unused)
{
}

void
apic_unset_idlecpu(processorid_t cpun __unused)
{
}


void
apic_ret()
{
}

/*
 * If apic_coarse_time == 1, then apic_gettime() is used instead of
 * apic_gethrtime().  This is used for performance instead of accuracy.
 */

hrtime_t
apic_gettime()
{
	int old_hrtime_stamp;
	hrtime_t temp;

	/*
	 * In one-shot mode, we do not keep time, so if anyone
	 * calls psm_gettime() directly, we vector over to
	 * gethrtime().
	 * one-shot mode MUST NOT be enabled if this psm is the source of
	 * hrtime.
	 */

	if (apic_oneshot)
		return (gethrtime());


gettime_again:
	while ((old_hrtime_stamp = apic_hrtime_stamp) & 1)
		apic_ret();

	temp = apic_nsec_since_boot;

	if (apic_hrtime_stamp != old_hrtime_stamp) {	/* got an interrupt */
		goto gettime_again;
	}
	return (temp);
}

/*
 * Here we return the number of nanoseconds since booting.  Note every
 * clock interrupt increments apic_nsec_since_boot by the appropriate
 * amount.
 */
hrtime_t
apic_gethrtime(void)
{
	int curr_timeval, countval, elapsed_ticks;
	int old_hrtime_stamp, status;
	hrtime_t temp;
	uint32_t cpun;
	ulong_t oflags;

	/*
	 * In one-shot mode, we do not keep time, so if anyone
	 * calls psm_gethrtime() directly, we vector over to
	 * gethrtime().
	 * one-shot mode MUST NOT be enabled if this psm is the source of
	 * hrtime.
	 */

	if (apic_oneshot)
		return (gethrtime());

	oflags = intr_clear();	/* prevent migration */

	cpun = apic_reg_ops->apic_read(APIC_LID_REG);
	if (apic_mode == LOCAL_APIC)
		cpun >>= APIC_ID_BIT_OFFSET;

	lock_set(&apic_gethrtime_lock);

gethrtime_again:
	while ((old_hrtime_stamp = apic_hrtime_stamp) & 1)
		apic_ret();

	/*
	 * Check to see which CPU we are on.  Note the time is kept on
	 * the local APIC of CPU 0.  If on CPU 0, simply read the current
	 * counter.  If on another CPU, issue a remote read command to CPU 0.
	 */
	if (cpun == apic_cpus[0].aci_local_id) {
		countval = apic_reg_ops->apic_read(APIC_CURR_COUNT);
	} else {
#ifdef	DEBUG
		APIC_AV_PENDING_SET();
#else
		if (apic_mode == LOCAL_APIC)
			APIC_AV_PENDING_SET();
#endif /* DEBUG */

		apic_reg_ops->apic_write_int_cmd(
		    apic_cpus[0].aci_local_id, APIC_CURR_ADD | AV_REMOTE);

		while ((status = apic_reg_ops->apic_read(APIC_INT_CMD1))
		    & AV_READ_PENDING) {
			apic_ret();
		}

		if (status & AV_REMOTE_STATUS)	/* 1 = valid */
			countval = apic_reg_ops->apic_read(APIC_REMOTE_READ);
		else {	/* 0 = invalid */
			apic_remote_hrterr++;
			/*
			 * return last hrtime right now, will need more
			 * testing if change to retry
			 */
			temp = apic_last_hrtime;

			lock_clear(&apic_gethrtime_lock);

			intr_restore(oflags);

			return (temp);
		}
	}
	if (countval > last_count_read)
		countval = 0;
	else
		last_count_read = countval;

	elapsed_ticks = apic_hertz_count - countval;

	curr_timeval = APIC_TICKS_TO_NSECS(elapsed_ticks);
	temp = apic_nsec_since_boot + curr_timeval;

	if (apic_hrtime_stamp != old_hrtime_stamp) {	/* got an interrupt */
		/* we might have clobbered last_count_read. Restore it */
		last_count_read = apic_hertz_count;
		goto gethrtime_again;
	}

	if (temp < apic_last_hrtime) {
		/* return last hrtime if error occurs */
		apic_hrtime_error++;
		temp = apic_last_hrtime;
	}
	else
		apic_last_hrtime = temp;

	lock_clear(&apic_gethrtime_lock);
	intr_restore(oflags);

	return (temp);
}

/* apic NMI handler */
uint_t
apic_nmi_intr(caddr_t arg __unused, caddr_t arg1 __unused)
{
	nmi_action_t action = nmi_action;

	if (apic_shutdown_processors) {
		apic_disable_local_apic();
		return (DDI_INTR_CLAIMED);
	}

	apic_error |= APIC_ERR_NMI;

	if (!lock_try(&apic_nmi_lock))
		return (DDI_INTR_CLAIMED);
	apic_num_nmis++;

	/*
	 * "nmi_action" always over-rides the older way of doing this, unless we
	 * can't actually drop into kmdb when requested.
	 */
	if (action == NMI_ACTION_KMDB && !psm_debugger())
		action = NMI_ACTION_UNSET;

	if (action == NMI_ACTION_UNSET) {
		if (apic_kmdb_on_nmi && psm_debugger())
			action = NMI_ACTION_KMDB;
		else if (apic_panic_on_nmi)
			action = NMI_ACTION_PANIC;
		else
			action = NMI_ACTION_IGNORE;
	}

	switch (action) {
	case NMI_ACTION_IGNORE:
		/*
		 * prom_printf is the best shot we have of something which is
		 * problem free from high level/NMI type of interrupts
		 */
		prom_printf("NMI received\n");
		break;

	case NMI_ACTION_PANIC:
		/* Keep panic from entering kmdb. */
		nopanicdebug = 1;
		panic("NMI received\n");
		break;

	case NMI_ACTION_KMDB:
	default:
		debug_enter("NMI received: entering kmdb\n");
		break;
	}

	lock_clear(&apic_nmi_lock);
	return (DDI_INTR_CLAIMED);
}

processorid_t
apic_get_next_processorid(processorid_t cpu_id)
{

	int i;

	if (cpu_id == -1)
		return ((processorid_t)0);

	for (i = cpu_id + 1; i < NCPU; i++) {
		if (apic_cpu_in_range(i))
			return (i);
	}

	return ((processorid_t)-1);
}

int
apic_cpu_add(psm_cpu_request_t *reqp)
{
	int i, rv = 0;
	ulong_t iflag;
	boolean_t first = B_TRUE;
	uchar_t localver = 0;
	uint32_t localid, procid;
	processorid_t cpuid = (processorid_t)-1;
	mach_cpu_add_arg_t *ap;

	ASSERT(reqp != NULL);
	reqp->req.cpu_add.cpuid = (processorid_t)-1;

	/* Check whether CPU hotplug is supported. */
	if (!plat_dr_support_cpu() || apic_max_nproc == -1) {
		return (ENOTSUP);
	}

	ap = (mach_cpu_add_arg_t *)reqp->req.cpu_add.argp;
	switch (ap->type) {
	case MACH_CPU_ARG_LOCAL_APIC:
		localid = ap->arg.apic.apic_id;
		procid = ap->arg.apic.proc_id;
		if (localid >= 255 || procid > 255) {
			cmn_err(CE_WARN,
			    "!apic: apicid(%u) or procid(%u) is invalid.",
			    localid, procid);
			return (EINVAL);
		}
		break;

	case MACH_CPU_ARG_LOCAL_X2APIC:
		localid = ap->arg.apic.apic_id;
		procid = ap->arg.apic.proc_id;
		if (localid >= UINT32_MAX) {
			cmn_err(CE_WARN,
			    "!apic: x2apicid(%u) is invalid.", localid);
			return (EINVAL);
		} else if (localid >= 255 && apic_mode == LOCAL_APIC) {
			cmn_err(CE_WARN, "!apic: system is in APIC mode, "
			    "can't support x2APIC processor.");
			return (ENOTSUP);
		}
		break;

	default:
		cmn_err(CE_WARN,
		    "!apic: unknown argument type %d to apic_cpu_add().",
		    ap->type);
		return (EINVAL);
	}

	/* Use apic_ioapic_lock to sync with apic_get_next_bind_cpu. */
	iflag = intr_clear();
	lock_set(&apic_ioapic_lock);

	/* Check whether local APIC id already exists. */
	for (i = 0; i < apic_nproc; i++) {
		if (!CPU_IN_SET(apic_cpumask, i))
			continue;
		if (apic_cpus[i].aci_local_id == localid) {
			lock_clear(&apic_ioapic_lock);
			intr_restore(iflag);
			cmn_err(CE_WARN,
			    "!apic: local apic id %u already exists.",
			    localid);
			return (EEXIST);
		} else if (apic_cpus[i].aci_processor_id == procid) {
			lock_clear(&apic_ioapic_lock);
			intr_restore(iflag);
			cmn_err(CE_WARN,
			    "!apic: processor id %u already exists.",
			    (int)procid);
			return (EEXIST);
		}

		/*
		 * There's no local APIC version number available in MADT table,
		 * so assume that all CPUs are homogeneous and use local APIC
		 * version number of the first existing CPU.
		 */
		if (first) {
			first = B_FALSE;
			localver = apic_cpus[i].aci_local_ver;
		}
	}
	ASSERT(first == B_FALSE);

	/*
	 * Try to assign the same cpuid if APIC id exists in the dirty cache.
	 */
	for (i = 0; i < apic_max_nproc; i++) {
		if (CPU_IN_SET(apic_cpumask, i)) {
			ASSERT((apic_cpus[i].aci_status & APIC_CPU_FREE) == 0);
			continue;
		}
		ASSERT(apic_cpus[i].aci_status & APIC_CPU_FREE);
		if ((apic_cpus[i].aci_status & APIC_CPU_DIRTY) &&
		    apic_cpus[i].aci_local_id == localid &&
		    apic_cpus[i].aci_processor_id == procid) {
			cpuid = i;
			break;
		}
	}

	/* Avoid the dirty cache and allocate fresh slot if possible. */
	if (cpuid == (processorid_t)-1) {
		for (i = 0; i < apic_max_nproc; i++) {
			if ((apic_cpus[i].aci_status & APIC_CPU_FREE) &&
			    (apic_cpus[i].aci_status & APIC_CPU_DIRTY) == 0) {
				cpuid = i;
				break;
			}
		}
	}

	/* Try to find any free slot as last resort. */
	if (cpuid == (processorid_t)-1) {
		for (i = 0; i < apic_max_nproc; i++) {
			if (apic_cpus[i].aci_status & APIC_CPU_FREE) {
				cpuid = i;
				break;
			}
		}
	}

	if (cpuid == (processorid_t)-1) {
		lock_clear(&apic_ioapic_lock);
		intr_restore(iflag);
		cmn_err(CE_NOTE,
		    "!apic: failed to allocate cpu id for processor %u.",
		    procid);
		rv = EAGAIN;
	} else if (ACPI_FAILURE(acpica_map_cpu(cpuid, procid))) {
		lock_clear(&apic_ioapic_lock);
		intr_restore(iflag);
		cmn_err(CE_NOTE,
		    "!apic: failed to build mapping for processor %u.",
		    procid);
		rv = EBUSY;
	} else {
		ASSERT(cpuid >= 0 && cpuid < NCPU);
		ASSERT(cpuid < apic_max_nproc && cpuid < max_ncpus);
		bzero(&apic_cpus[cpuid], sizeof (apic_cpus[0]));
		apic_cpus[cpuid].aci_processor_id = procid;
		apic_cpus[cpuid].aci_local_id = localid;
		apic_cpus[cpuid].aci_local_ver = localver;
		CPUSET_ATOMIC_ADD(apic_cpumask, cpuid);
		if (cpuid >= apic_nproc) {
			apic_nproc = cpuid + 1;
		}
		lock_clear(&apic_ioapic_lock);
		intr_restore(iflag);
		reqp->req.cpu_add.cpuid = cpuid;
	}

	return (rv);
}

int
apic_cpu_remove(psm_cpu_request_t *reqp)
{
	int i;
	ulong_t iflag;
	processorid_t cpuid;

	/* Check whether CPU hotplug is supported. */
	if (!plat_dr_support_cpu() || apic_max_nproc == -1) {
		return (ENOTSUP);
	}

	cpuid = reqp->req.cpu_remove.cpuid;

	/* Use apic_ioapic_lock to sync with apic_get_next_bind_cpu. */
	iflag = intr_clear();
	lock_set(&apic_ioapic_lock);

	if (!apic_cpu_in_range(cpuid)) {
		lock_clear(&apic_ioapic_lock);
		intr_restore(iflag);
		cmn_err(CE_WARN,
		    "!apic: cpuid %d doesn't exist in apic_cpus array.",
		    cpuid);
		return (ENODEV);
	}
	ASSERT((apic_cpus[cpuid].aci_status & APIC_CPU_FREE) == 0);

	if (ACPI_FAILURE(acpica_unmap_cpu(cpuid))) {
		lock_clear(&apic_ioapic_lock);
		intr_restore(iflag);
		return (ENOENT);
	}

	if (cpuid == apic_nproc - 1) {
		/*
		 * We are removing the highest numbered cpuid so we need to
		 * find the next highest cpuid as the new value for apic_nproc.
		 */
		for (i = apic_nproc; i > 0; i--) {
			if (CPU_IN_SET(apic_cpumask, i - 1)) {
				apic_nproc = i;
				break;
			}
		}
		/* at least one CPU left */
		ASSERT(i > 0);
	}
	CPUSET_ATOMIC_DEL(apic_cpumask, cpuid);
	/* mark slot as free and keep it in the dirty cache */
	apic_cpus[cpuid].aci_status = APIC_CPU_FREE | APIC_CPU_DIRTY;

	lock_clear(&apic_ioapic_lock);
	intr_restore(iflag);

	return (0);
}

/*
 * Return the number of ticks the APIC decrements in SF nanoseconds.
 * The fixed-frequency PIT (aka 8254) is used for the measurement.
 */
static uint64_t
apic_calibrate_pit(void)
{
	uint8_t		pit_tick_lo;
	uint16_t	pit_tick, target_pit_tick, pit_ticks_adj;
	uint32_t	pit_ticks;
	uint32_t	start_apic_tick, end_apic_tick, apic_ticks;
	ulong_t		iflag;

	if (pit_is_broken)
		return (0);

	apic_reg_ops->apic_write(APIC_DIVIDE_REG, apic_divide_reg_init);
	apic_reg_ops->apic_write(APIC_INIT_COUNT, APIC_MAXVAL);

	iflag = intr_clear();

	/*
	 * Put the PIT in mode 0, "Interrupt On Terminal Count":
	 */
	outb(PITCTL_PORT, PIT_C0 | PIT_LOADMODE | PIT_ENDSIGMODE);

	/*
	 * The PIT counts down and then the counter value wraps around.  Load
	 * the maximum counter value:
	 */
	outb(PITCTR0_PORT, 0xFF);
	outb(PITCTR0_PORT, 0xFF);

	do {
		pit_tick_lo = inb(PITCTR0_PORT);
		pit_tick = (inb(PITCTR0_PORT) << 8) | pit_tick_lo;
	} while (pit_tick < APIC_TIME_MIN ||
	    pit_tick_lo <= APIC_LB_MIN || pit_tick_lo >= APIC_LB_MAX);

	/*
	 * Wait for the PIT to decrement by 5 ticks to ensure
	 * we didn't start in the middle of a tick.
	 * Compare with 0x10 for the wrap around case.
	 */
	target_pit_tick = pit_tick - 5;
	do {
		pit_tick_lo = inb(PITCTR0_PORT);
		pit_tick = (inb(PITCTR0_PORT) << 8) | pit_tick_lo;
	} while (pit_tick > target_pit_tick || pit_tick_lo < 0x10);

	start_apic_tick = apic_reg_ops->apic_read(APIC_CURR_COUNT);

	/*
	 * Wait for the PIT to decrement by APIC_TIME_COUNT ticks
	 */
	target_pit_tick = pit_tick - APIC_TIME_COUNT;
	do {
		pit_tick_lo = inb(PITCTR0_PORT);
		pit_tick = (inb(PITCTR0_PORT) << 8) | pit_tick_lo;
	} while (pit_tick > target_pit_tick || pit_tick_lo < 0x10);

	end_apic_tick = apic_reg_ops->apic_read(APIC_CURR_COUNT);

	intr_restore(iflag);

	apic_ticks = start_apic_tick - end_apic_tick;

	/* The PIT might have decremented by more ticks than planned */
	pit_ticks_adj = target_pit_tick - pit_tick;
	/* total number of PIT ticks corresponding to apic_ticks */
	pit_ticks = APIC_TIME_COUNT + pit_ticks_adj;

	/*
	 * Determine the number of nanoseconds per APIC clock tick
	 * and then determine how many APIC ticks to interrupt at the
	 * desired frequency
	 * apic_ticks / (pitticks / PIT_HZ) = apic_ticks_per_s
	 * (apic_ticks * PIT_HZ) / pitticks = apic_ticks_per_s
	 * apic_ticks_per_ns = (apic_ticks * PIT_HZ) / (pitticks * 10^9)
	 * apic_ticks_per_SFns =
	 * (SF * apic_ticks * PIT_HZ) / (pitticks * 10^9)
	 */
	return ((SF * apic_ticks * PIT_HZ) / ((uint64_t)pit_ticks * NANOSEC));
}

/*
 * Return the number of ticks the APIC decrements in SF nanoseconds.
 * The TSC is used for the measurement.
 */
static uint64_t
apic_calibrate_tsc(void)
{
	uint64_t	tsc_now, tsc_end, tsc_amt, tsc_hz;
	uint64_t	apic_ticks;
	uint32_t	start_apic_tick, end_apic_tick;
	ulong_t		iflag;

	tsc_hz = tsc_get_freq();

	/*
	 * APIC_TIME_COUNT is in i8254 PIT ticks, which have a period
	 * slightly under 1us. We can just treat the value as the number of
	 * microseconds for our sampling period -- that is we wait
	 * APIC_TIME_COUNT microseconds (corresponding to 'tsc_amt' of TSC
	 * ticks).
	 */
	tsc_amt = tsc_hz * APIC_TIME_COUNT / MICROSEC;

	apic_reg_ops->apic_write(APIC_DIVIDE_REG, apic_divide_reg_init);
	apic_reg_ops->apic_write(APIC_INIT_COUNT, APIC_MAXVAL);

	iflag = intr_clear();

	tsc_now = tsc_read();
	tsc_end = tsc_now + tsc_amt;
	start_apic_tick = apic_reg_ops->apic_read(APIC_CURR_COUNT);

	while (tsc_now < tsc_end)
		tsc_now = tsc_read();

	end_apic_tick = apic_reg_ops->apic_read(APIC_CURR_COUNT);

	intr_restore(iflag);

	apic_ticks = start_apic_tick - end_apic_tick;

	/*
	 * We likely did not wait exactly APIC_TIME_COUNT microseconds, but
	 * slightly longer. Add the additional amount to tsc_amt.
	 */
	tsc_amt += tsc_now - tsc_end;

	/*
	 * This calculation is analogous to the one used with the PIT.
	 * However, due to the typically _much_ higher precision of the
	 * TSC compared to the PIT, we have to be careful we do not overflow.
	 *
	 * Since contemporary APIC timers have frequencies on the order of
	 * tens of MHz (i.e. 66MHz), we calculate that first. Then we
	 * scale the result by SF (because the caller wants it scaled by
	 * that amount), then convert the result to scaled (SF) ticks per ns.
	 *
	 */
	uint64_t apic_freq = apic_ticks * tsc_hz / tsc_amt;

	return (apic_freq * SF / NANOSEC);
}

/*
 * Return the number of ticks the APIC decrements in SF nanoseconds.
 * Several measurements are taken to filter out outliers.
 */
uint64_t
apic_calibrate()
{
	uint64_t	measurements[APIC_CALIBRATE_MEASUREMENTS];
	int		median_idx;
	uint64_t	median;

	/*
	 * When running under a virtual machine, the emulated PIT and APIC
	 * counters do not always return the right values and can roll over.
	 * Those spurious measurements are relatively rare but could
	 * significantly affect the calibration.
	 * Therefore we take several measurements and then keep the median.
	 * The median is preferred to the average here as we only want to
	 * discard outliers.
	 *
	 * Traditionally, only the PIT was used to calibrate the APIC as the
	 * the TSC was not calibrated at this point in the boot process (or
	 * on even (much, much) older systems, possibly not present). On
	 * newer systems, the PIT is not always present. We now default to
	 * using the TSC (since it's now calibrated early enough in the boot
	 * process to be usable), but for debugging purposes as we transition,
	 * we still try to use the PIT and record those values. On systems
	 * without a functioning PIT, the PIT measurements will always be 0.
	 */
	for (int i = 0; i < APIC_CALIBRATE_MEASUREMENTS; i++) {
		apic_info_tsc[i] = apic_calibrate_tsc();
		apic_info_pit[i] = apic_calibrate_pit();

		if (apic_calibrate_use_pit) {
			if (pit_is_broken) {
				panic("Failed to calibrate APIC due to broken "
				    "PIT");
			}
			measurements[i] = apic_info_pit[i];
		} else {
			measurements[i] = apic_info_tsc[i];
		}
	}

	/*
	 * sort results and retrieve median.
	 */
	for (int i = 0; i < APIC_CALIBRATE_MEASUREMENTS; i++) {
		for (int j = i + 1; j < APIC_CALIBRATE_MEASUREMENTS; j++) {
			if (measurements[j] < measurements[i]) {
				uint64_t tmp = measurements[i];
				measurements[i] = measurements[j];
				measurements[j] = tmp;
			}
		}
	}
	median_idx = APIC_CALIBRATE_MEASUREMENTS / 2;
	median = measurements[median_idx];

#if (APIC_CALIBRATE_MEASUREMENTS >= 3)
	/*
	 * Check that measurements are consistent. Post a warning
	 * if the three middle values are not close to each other.
	 */
	uint64_t delta_warn = median *
	    APIC_CALIBRATE_PERCENT_OFF_WARNING / 100;
	if ((median - measurements[median_idx - 1]) > delta_warn ||
	    (measurements[median_idx + 1] - median) > delta_warn) {
		cmn_err(CE_WARN, "apic_calibrate measurements lack "
		    "precision: %llu, %llu, %llu.",
		    (u_longlong_t)measurements[median_idx - 1],
		    (u_longlong_t)median,
		    (u_longlong_t)measurements[median_idx + 1]);
	}
#endif

	return (median);
}

/*
 * Initialise the APIC timer on the local APIC of CPU 0 to the desired
 * frequency.  Note at this stage in the boot sequence, the boot processor
 * is the only active processor.
 * hertz value of 0 indicates a one-shot mode request.  In this case
 * the function returns the resolution (in nanoseconds) for the hardware
 * timer interrupt.  If one-shot mode capability is not available,
 * the return value will be 0. apic_enable_oneshot is a global switch
 * for disabling the functionality.
 * A non-zero positive value for hertz indicates a periodic mode request.
 * In this case the hardware will be programmed to generate clock interrupts
 * at hertz frequency and returns the resolution of interrupts in
 * nanosecond.
 */

int
apic_clkinit(int hertz)
{
	int		ret;

	apic_int_busy_mark = (apic_int_busy_mark *
	    apic_sample_factor_redistribution) / 100;
	apic_int_free_mark = (apic_int_free_mark *
	    apic_sample_factor_redistribution) / 100;
	apic_diff_for_redistribution = (apic_diff_for_redistribution *
	    apic_sample_factor_redistribution) / 100;

	ret = apic_timer_init(hertz);
	return (ret);

}

/*
 * apic_preshutdown:
 * Called early in shutdown whilst we can still access filesystems to do
 * things like loading modules which will be required to complete shutdown
 * after filesystems are all unmounted.
 */
void
apic_preshutdown(int cmd __unused, int fcn __unused)
{
	APIC_VERBOSE_POWEROFF(("apic_preshutdown(%d,%d); m=%d a=%d\n",
	    cmd, fcn, apic_poweroff_method, apic_enable_acpi));
}

void
apic_shutdown(int cmd, int fcn)
{
	int restarts, attempts;
	int i;
	uchar_t	byte;
	ulong_t iflag;

	hpet_acpi_fini();

	/* Send NMI to all CPUs except self to do per processor shutdown */
	iflag = intr_clear();
#ifdef	DEBUG
	APIC_AV_PENDING_SET();
#else
	if (apic_mode == LOCAL_APIC)
		APIC_AV_PENDING_SET();
#endif /* DEBUG */
	apic_shutdown_processors = 1;
	apic_reg_ops->apic_write(APIC_INT_CMD1,
	    AV_NMI | AV_LEVEL | AV_SH_ALL_EXCSELF);

	/* restore cmos shutdown byte before reboot */
	if (apic_cmos_ssb_set) {
		outb(CMOS_ADDR, SSB);
		outb(CMOS_DATA, 0);
	}

	ioapic_disable_redirection();

	/*	disable apic mode if imcr present	*/
	if (apic_imcrp) {
		outb(APIC_IMCR_P1, (uchar_t)APIC_IMCR_SELECT);
		outb(APIC_IMCR_P2, (uchar_t)APIC_IMCR_PIC);
	}

	apic_disable_local_apic();

	intr_restore(iflag);

	/* remainder of function is for shutdown cases only */
	if (cmd != A_SHUTDOWN)
		return;

	/*
	 * Switch system back into Legacy-Mode if using ACPI and
	 * not powering-off.  Some BIOSes need to remain in ACPI-mode
	 * for power-off to succeed (Dell Dimension 4600)
	 * Do not disable ACPI while doing fastreboot
	 */
	if (apic_enable_acpi && fcn != AD_POWEROFF && fcn != AD_FASTREBOOT)
		(void) AcpiDisable();

	if (fcn == AD_FASTREBOOT) {
		apic_reg_ops->apic_write(APIC_INT_CMD1,
		    AV_ASSERT | AV_RESET | AV_SH_ALL_EXCSELF);
	}

	/* remainder of function is for shutdown+poweroff case only */
	if (fcn != AD_POWEROFF)
		return;

	switch (apic_poweroff_method) {
		case APIC_POWEROFF_VIA_RTC:

			/* select the extended NVRAM bank in the RTC */
			outb(CMOS_ADDR, RTC_REGA);
			byte = inb(CMOS_DATA);
			outb(CMOS_DATA, (byte | EXT_BANK));

			outb(CMOS_ADDR, PFR_REG);

			/* for Predator must toggle the PAB bit */
			byte = inb(CMOS_DATA);

			/*
			 * clear power active bar, wakeup alarm and
			 * kickstart
			 */
			byte &= ~(PAB_CBIT | WF_FLAG | KS_FLAG);
			outb(CMOS_DATA, byte);

			/* delay before next write */
			drv_usecwait(1000);

			/* for S40 the following would suffice */
			byte = inb(CMOS_DATA);

			/* power active bar control bit */
			byte |= PAB_CBIT;
			outb(CMOS_DATA, byte);

			break;

		case APIC_POWEROFF_VIA_ASPEN_BMC:
			restarts = 0;
restart_aspen_bmc:
			if (++restarts == 3)
				break;
			attempts = 0;
			do {
				byte = inb(MISMIC_FLAG_REGISTER);
				byte &= MISMIC_BUSY_MASK;
				if (byte != 0) {
					drv_usecwait(1000);
					if (attempts >= 3)
						goto restart_aspen_bmc;
					++attempts;
				}
			} while (byte != 0);
			outb(MISMIC_CNTL_REGISTER, CC_SMS_GET_STATUS);
			byte = inb(MISMIC_FLAG_REGISTER);
			byte |= 0x1;
			outb(MISMIC_FLAG_REGISTER, byte);
			i = 0;
			for (; i < (sizeof (aspen_bmc)/sizeof (aspen_bmc[0]));
			    i++) {
				attempts = 0;
				do {
					byte = inb(MISMIC_FLAG_REGISTER);
					byte &= MISMIC_BUSY_MASK;
					if (byte != 0) {
						drv_usecwait(1000);
						if (attempts >= 3)
							goto restart_aspen_bmc;
						++attempts;
					}
				} while (byte != 0);
				outb(MISMIC_CNTL_REGISTER, aspen_bmc[i].cntl);
				outb(MISMIC_DATA_REGISTER, aspen_bmc[i].data);
				byte = inb(MISMIC_FLAG_REGISTER);
				byte |= 0x1;
				outb(MISMIC_FLAG_REGISTER, byte);
			}
			break;

		case APIC_POWEROFF_VIA_SITKA_BMC:
			restarts = 0;
restart_sitka_bmc:
			if (++restarts == 3)
				break;
			attempts = 0;
			do {
				byte = inb(SMS_STATUS_REGISTER);
				byte &= SMS_STATE_MASK;
				if ((byte == SMS_READ_STATE) ||
				    (byte == SMS_WRITE_STATE)) {
					drv_usecwait(1000);
					if (attempts >= 3)
						goto restart_sitka_bmc;
					++attempts;
				}
			} while ((byte == SMS_READ_STATE) ||
			    (byte == SMS_WRITE_STATE));
			outb(SMS_COMMAND_REGISTER, SMS_GET_STATUS);
			i = 0;
			for (; i < (sizeof (sitka_bmc)/sizeof (sitka_bmc[0]));
			    i++) {
				attempts = 0;
				do {
					byte = inb(SMS_STATUS_REGISTER);
					byte &= SMS_IBF_MASK;
					if (byte != 0) {
						drv_usecwait(1000);
						if (attempts >= 3)
							goto restart_sitka_bmc;
						++attempts;
					}
				} while (byte != 0);
				outb(sitka_bmc[i].port, sitka_bmc[i].data);
			}
			break;

		case APIC_POWEROFF_NONE:

			/* If no APIC direct method, we will try using ACPI */
			if (apic_enable_acpi) {
				if (acpi_poweroff() == 1)
					return;
			} else
				return;

			break;
	}
	/*
	 * Wait a limited time here for power to go off.
	 * If the power does not go off, then there was a
	 * problem and we should continue to the halt which
	 * prints a message for the user to press a key to
	 * reboot.
	 */
	drv_usecwait(7000000); /* wait seven seconds */

}

cyclic_id_t apic_cyclic_id;

/*
 * The following functions are in the platform specific file so that they
 * can be different functions depending on whether we are running on
 * bare metal or a hypervisor.
 */

/*
 * map an apic for memory-mapped access
 */
uint32_t *
mapin_apic(uint32_t addr, size_t len, int flags)
{
	return ((void *)psm_map_phys(addr, len, flags));
}

uint32_t *
mapin_ioapic(uint32_t addr, size_t len, int flags)
{
	return (mapin_apic(addr, len, flags));
}

/*
 * unmap an apic
 */
void
mapout_apic(caddr_t addr, size_t len)
{
	psm_unmap_phys(addr, len);
}

void
mapout_ioapic(caddr_t addr, size_t len)
{
	mapout_apic(addr, len);
}

uint32_t
ioapic_read(int ioapic_ix, uint32_t reg)
{
	volatile uint32_t *ioapic;

	ioapic = apicioadr[ioapic_ix];
	ioapic[APIC_IO_REG] = reg;
	return (ioapic[APIC_IO_DATA]);
}

void
ioapic_write(int ioapic_ix, uint32_t reg, uint32_t value)
{
	volatile uint32_t *ioapic;

	ioapic = apicioadr[ioapic_ix];
	ioapic[APIC_IO_REG] = reg;
	ioapic[APIC_IO_DATA] = value;
}

void
ioapic_write_eoi(int ioapic_ix, uint32_t value)
{
	volatile uint32_t *ioapic;

	ioapic = apicioadr[ioapic_ix];
	ioapic[APIC_IO_EOI] = value;
}

/*
 * Round-robin algorithm to find the next CPU with interrupts enabled.
 * It can't share the same static variable apic_next_bind_cpu with
 * apic_get_next_bind_cpu(), since that will cause all interrupts to be
 * bound to CPU1 at boot time.  During boot, only CPU0 is online with
 * interrupts enabled when apic_get_next_bind_cpu() and apic_find_cpu()
 * are called.  However, the pcplusmp driver assumes that there will be
 * boot_ncpus CPUs configured eventually so it tries to distribute all
 * interrupts among CPU0 - CPU[boot_ncpus - 1].  Thus to prevent all
 * interrupts being targetted at CPU1, we need to use a dedicated static
 * variable for find_next_cpu() instead of sharing apic_next_bind_cpu.
 */

processorid_t
apic_find_cpu(int flag)
{
	int i;
	static processorid_t acid = 0;

	/* Find the first CPU with the passed-in flag set */
	for (i = 0; i < apic_nproc; i++) {
		if (++acid >= apic_nproc) {
			acid = 0;
		}
		if (apic_cpu_in_range(acid) &&
		    (apic_cpus[acid].aci_status & flag)) {
			break;
		}
	}

	ASSERT((apic_cpus[acid].aci_status & flag) != 0);
	return (acid);
}

void
apic_intrmap_init(int apic_mode)
{
	int suppress_brdcst_eoi = 0;

	/*
	 * Intel Software Developer's Manual 3A, 10.12.7:
	 *
	 * Routing of device interrupts to local APIC units operating in
	 * x2APIC mode requires use of the interrupt-remapping architecture
	 * specified in the Intel Virtualization Technology for Directed
	 * I/O, Revision 1.3.  Because of this, BIOS must enumerate support
	 * for and software must enable this interrupt remapping with
	 * Extended Interrupt Mode Enabled before it enabling x2APIC mode in
	 * the local APIC units.
	 *
	 *
	 * In other words, to use the APIC in x2APIC mode, we need interrupt
	 * remapping.  Since we don't start up the IOMMU by default, we
	 * won't be able to do any interrupt remapping and therefore have to
	 * use the APIC in traditional 'local APIC' mode with memory mapped
	 * I/O.
	 */

	if (psm_vt_ops != NULL) {
		if (((apic_intrmap_ops_t *)psm_vt_ops)->
		    apic_intrmap_init(apic_mode) == DDI_SUCCESS) {

			apic_vt_ops = psm_vt_ops;

			/*
			 * We leverage the interrupt remapping engine to
			 * suppress broadcast EOI; thus we must send the
			 * directed EOI with the directed-EOI handler.
			 */
			if (apic_directed_EOI_supported() == 0) {
				suppress_brdcst_eoi = 1;
			}

			apic_vt_ops->apic_intrmap_enable(suppress_brdcst_eoi);

			if (apic_detect_x2apic()) {
				apic_enable_x2apic();
			}

			if (apic_directed_EOI_supported() == 0) {
				apic_set_directed_EOI_handler();
			}
		}
	}
}

static void
apic_record_ioapic_rdt(void *intrmap_private __unused, ioapic_rdt_t *irdt)
{
	irdt->ir_hi <<= APIC_ID_BIT_OFFSET;
}

static void
apic_record_msi(void *intrmap_private __unused, msi_regs_t *mregs)
{
	mregs->mr_addr = MSI_ADDR_HDR |
	    (MSI_ADDR_RH_FIXED << MSI_ADDR_RH_SHIFT) |
	    (MSI_ADDR_DM_PHYSICAL << MSI_ADDR_DM_SHIFT) |
	    (mregs->mr_addr << MSI_ADDR_DEST_SHIFT);
	mregs->mr_data = (MSI_DATA_TM_EDGE << MSI_DATA_TM_SHIFT) |
	    mregs->mr_data;
}

/*
 * Functions from apic_introp.c
 *
 * Those functions are used by apic_intr_ops().
 */

/*
 * MSI support flag:
 * reflects whether MSI is supported at APIC level
 * it can also be patched through /etc/system
 *
 *  0 = default value - don't know and need to call apic_check_msi_support()
 *      to find out then set it accordingly
 *  1 = supported
 * -1 = not supported
 */
int	apic_support_msi = 0;

/* Multiple vector support for MSI-X */
int	apic_msix_enable = 1;

/* Multiple vector support for MSI */
int	apic_multi_msi_enable = 1;

/*
 * Check whether the system supports MSI.
 *
 * MSI is required for PCI-E and for PCI versions later than 2.2, so if we find
 * a PCI-E bus or we find a PCI bus whose version we know is >= 2.2, then we
 * return PSM_SUCCESS to indicate this system supports MSI.
 *
 * (Currently the only way we check whether a given PCI bus supports >= 2.2 is
 * by detecting if we are running inside the KVM hypervisor, which guarantees
 * this version number.)
 */
int
apic_check_msi_support()
{
	dev_info_t *cdip;
	char dev_type[16];
	int dev_len;
	int hwenv = get_hwenv();

	DDI_INTR_IMPLDBG((CE_CONT, "apic_check_msi_support:\n"));

	/*
	 * check whether the first level children of root_node have
	 * PCI-E or PCI capability.
	 */
	for (cdip = ddi_get_child(ddi_root_node()); cdip != NULL;
	    cdip = ddi_get_next_sibling(cdip)) {

		DDI_INTR_IMPLDBG((CE_CONT, "apic_check_msi_support: cdip: 0x%p,"
		    " driver: %s, binding: %s, nodename: %s\n", (void *)cdip,
		    ddi_driver_name(cdip), ddi_binding_name(cdip),
		    ddi_node_name(cdip)));
		dev_len = sizeof (dev_type);
		if (ddi_getlongprop_buf(DDI_DEV_T_ANY, cdip, DDI_PROP_DONTPASS,
		    "device_type", (caddr_t)dev_type, &dev_len)
		    != DDI_PROP_SUCCESS)
			continue;
		if (strcmp(dev_type, "pciex") == 0)
			return (PSM_SUCCESS);
		if (strcmp(dev_type, "pci") == 0 &&
		    (hwenv == HW_KVM || hwenv == HW_BHYVE))
			return (PSM_SUCCESS);
	}

	/* MSI is not supported on this system */
	DDI_INTR_IMPLDBG((CE_CONT, "apic_check_msi_support: no 'pciex' "
	    "device_type found\n"));
	return (PSM_FAILURE);
}

/*
 * apic_pci_msi_unconfigure:
 *
 * This and next two interfaces are copied from pci_intr_lib.c
 * Do ensure that these two files stay in sync.
 * These needed to be copied over here to avoid a deadlock situation on
 * certain mp systems that use MSI interrupts.
 *
 * IMPORTANT regards next three interfaces:
 * i) are called only for MSI/X interrupts.
 * ii) called with interrupts disabled, and must not block
 */
void
apic_pci_msi_unconfigure(dev_info_t *rdip, int type, int inum)
{
	ushort_t		msi_ctrl;
	int			cap_ptr = i_ddi_get_msi_msix_cap_ptr(rdip);
	ddi_acc_handle_t	handle = i_ddi_get_pci_config_handle(rdip);

	ASSERT((handle != NULL) && (cap_ptr != 0));

	if (type == DDI_INTR_TYPE_MSI) {
		msi_ctrl = pci_config_get16(handle, cap_ptr + PCI_MSI_CTRL);
		msi_ctrl &= (~PCI_MSI_MME_MASK);
		pci_config_put16(handle, cap_ptr + PCI_MSI_CTRL, msi_ctrl);
		pci_config_put32(handle, cap_ptr + PCI_MSI_ADDR_OFFSET, 0);

		if (msi_ctrl &  PCI_MSI_64BIT_MASK) {
			pci_config_put16(handle,
			    cap_ptr + PCI_MSI_64BIT_DATA, 0);
			pci_config_put32(handle,
			    cap_ptr + PCI_MSI_ADDR_OFFSET + 4, 0);
		} else {
			pci_config_put16(handle,
			    cap_ptr + PCI_MSI_32BIT_DATA, 0);
		}

	} else if (type == DDI_INTR_TYPE_MSIX) {
		uintptr_t	off;
		uint32_t	mask;
		ddi_intr_msix_t	*msix_p = i_ddi_get_msix(rdip);

		ASSERT(msix_p != NULL);

		/* Offset into "inum"th entry in the MSI-X table & mask it */
		off = (uintptr_t)msix_p->msix_tbl_addr + (inum *
		    PCI_MSIX_VECTOR_SIZE) + PCI_MSIX_VECTOR_CTRL_OFFSET;

		mask = ddi_get32(msix_p->msix_tbl_hdl, (uint32_t *)off);

		ddi_put32(msix_p->msix_tbl_hdl, (uint32_t *)off, (mask | 1));

		/* Offset into the "inum"th entry in the MSI-X table */
		off = (uintptr_t)msix_p->msix_tbl_addr +
		    (inum * PCI_MSIX_VECTOR_SIZE);

		/* Reset the "data" and "addr" bits */
		ddi_put32(msix_p->msix_tbl_hdl,
		    (uint32_t *)(off + PCI_MSIX_DATA_OFFSET), 0);
		ddi_put64(msix_p->msix_tbl_hdl, (uint64_t *)off, 0);
	}
}

/*
 * apic_pci_msi_disable_mode:
 */
void
apic_pci_msi_disable_mode(dev_info_t *rdip, int type)
{
	ushort_t		msi_ctrl;
	int			cap_ptr = i_ddi_get_msi_msix_cap_ptr(rdip);
	ddi_acc_handle_t	handle = i_ddi_get_pci_config_handle(rdip);

	ASSERT((handle != NULL) && (cap_ptr != 0));

	if (type == DDI_INTR_TYPE_MSI) {
		msi_ctrl = pci_config_get16(handle, cap_ptr + PCI_MSI_CTRL);
		if (!(msi_ctrl & PCI_MSI_ENABLE_BIT))
			return;

		msi_ctrl &= ~PCI_MSI_ENABLE_BIT;	/* MSI disable */
		pci_config_put16(handle, cap_ptr + PCI_MSI_CTRL, msi_ctrl);

	} else if (type == DDI_INTR_TYPE_MSIX) {
		msi_ctrl = pci_config_get16(handle, cap_ptr + PCI_MSIX_CTRL);
		if (msi_ctrl & PCI_MSIX_ENABLE_BIT) {
			msi_ctrl &= ~PCI_MSIX_ENABLE_BIT;
			pci_config_put16(handle, cap_ptr + PCI_MSIX_CTRL,
			    msi_ctrl);
		}
	}
}

uint32_t
apic_get_localapicid(uint32_t cpuid)
{
	ASSERT(cpuid < apic_nproc && apic_cpus != NULL);

	return (apic_cpus[cpuid].aci_local_id);
}

uchar_t
apic_get_ioapicid(uchar_t ioapicindex)
{
	ASSERT(ioapicindex < MAX_IO_APIC);

	return (apic_io_id[ioapicindex]);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright 2013 Pluribus Networks, Inc.
 * Copyright 2017 Joyent, Inc.
 */

/*
 * apic_introp.c:
 *	Has code for Advanced DDI interrupt framework support.
 */

#include <sys/cpuvar.h>
#include <sys/psm.h>
#include <sys/archsystm.h>
#include <sys/apic.h>
#include <sys/sunddi.h>
#include <sys/ddi_impldefs.h>
#include <sys/mach_intr.h>
#include <sys/sysmacros.h>
#include <sys/trap.h>
#include <sys/pci.h>
#include <sys/pci_intr_lib.h>
#include <sys/apic_common.h>

extern struct av_head autovect[];

/*
 *	Local Function Prototypes
 */
apic_irq_t	*apic_find_irq(dev_info_t *, struct intrspec *, int);

/*
 * apic_pci_msi_enable_vector:
 *	Set the address/data fields in the MSI/X capability structure
 *	XXX: MSI-X support
 */
/* ARGSUSED */
void
apic_pci_msi_enable_vector(apic_irq_t *irq_ptr, int type, int inum, int vector,
    int count, int target_apic_id)
{
	uint64_t		msi_addr, msi_data;
	ushort_t		msi_ctrl;
	dev_info_t		*dip = irq_ptr->airq_dip;
	int			cap_ptr = i_ddi_get_msi_msix_cap_ptr(dip);
	ddi_acc_handle_t	handle = i_ddi_get_pci_config_handle(dip);
	msi_regs_t		msi_regs;
	int			irqno, i;
	void			*intrmap_tbl[PCI_MSI_MAX_INTRS];

	DDI_INTR_IMPLDBG((CE_CONT, "apic_pci_msi_enable_vector: dip=0x%p\n"
	    "\tdriver = %s, inum=0x%x vector=0x%x apicid=0x%x\n", (void *)dip,
	    ddi_driver_name(dip), inum, vector, target_apic_id));

	ASSERT((handle != NULL) && (cap_ptr != 0));

	msi_regs.mr_data = vector;
	msi_regs.mr_addr = target_apic_id;

	for (i = 0; i < count; i++) {
		irqno = apic_vector_to_irq[vector + i];
		intrmap_tbl[i] = apic_irq_table[irqno]->airq_intrmap_private;
	}
	apic_vt_ops->apic_intrmap_alloc_entry(intrmap_tbl, dip, type,
	    count, 0xff);
	for (i = 0; i < count; i++) {
		irqno = apic_vector_to_irq[vector + i];
		apic_irq_table[irqno]->airq_intrmap_private =
		    intrmap_tbl[i];
	}

	apic_vt_ops->apic_intrmap_map_entry(irq_ptr->airq_intrmap_private,
	    (void *)&msi_regs, type, count);
	apic_vt_ops->apic_intrmap_record_msi(irq_ptr->airq_intrmap_private,
	    &msi_regs);

	/* MSI Address */
	msi_addr = msi_regs.mr_addr;

	/* MSI Data: MSI is edge triggered according to spec */
	msi_data = msi_regs.mr_data;

	DDI_INTR_IMPLDBG((CE_CONT, "apic_pci_msi_enable_vector: addr=0x%lx "
	    "data=0x%lx\n", (long)msi_addr, (long)msi_data));

	if (type == DDI_INTR_TYPE_MSI) {
		msi_ctrl = pci_config_get16(handle, cap_ptr + PCI_MSI_CTRL);

		/* Set the bits to inform how many MSIs are enabled */
		msi_ctrl |= ((highbit(count) -1) << PCI_MSI_MME_SHIFT);
		pci_config_put16(handle, cap_ptr + PCI_MSI_CTRL, msi_ctrl);

		/*
		 * Only set vector if not on hypervisor
		 */
		pci_config_put32(handle,
		    cap_ptr + PCI_MSI_ADDR_OFFSET, msi_addr);

		if (msi_ctrl &  PCI_MSI_64BIT_MASK) {
			pci_config_put32(handle,
			    cap_ptr + PCI_MSI_ADDR_OFFSET + 4, msi_addr >> 32);
			pci_config_put16(handle,
			    cap_ptr + PCI_MSI_64BIT_DATA, msi_data);
		} else {
			pci_config_put16(handle,
			    cap_ptr + PCI_MSI_32BIT_DATA, msi_data);
		}

	} else if (type == DDI_INTR_TYPE_MSIX) {
		uintptr_t	off;
		ddi_intr_msix_t	*msix_p = i_ddi_get_msix(dip);

		ASSERT(msix_p != NULL);

		/* Offset into the "inum"th entry in the MSI-X table */
		off = (uintptr_t)msix_p->msix_tbl_addr +
		    (inum  * PCI_MSIX_VECTOR_SIZE);

		ddi_put32(msix_p->msix_tbl_hdl,
		    (uint32_t *)(off + PCI_MSIX_DATA_OFFSET), msi_data);
		ddi_put32(msix_p->msix_tbl_hdl,
		    (uint32_t *)(off + PCI_MSIX_LOWER_ADDR_OFFSET), msi_addr);
		ddi_put32(msix_p->msix_tbl_hdl,
		    (uint32_t *)(off + PCI_MSIX_UPPER_ADDR_OFFSET),
		    msi_addr >> 32);
	}
}

/*
 * This function returns the no. of vectors available for the pri.
 * dip is not used at this moment.  If we really don't need that,
 * it will be removed.
 */
/*ARGSUSED*/
int
apic_navail_vector(dev_info_t *dip, int pri)
{
	int	lowest, highest, i, navail, count;

	DDI_INTR_IMPLDBG((CE_CONT, "apic_navail_vector: dip: %p, pri: %x\n",
	    (void *)dip, pri));

	highest = apic_ipltopri[pri] + APIC_VECTOR_MASK;
	lowest = apic_ipltopri[pri - 1] + APIC_VECTOR_PER_IPL;
	navail = count = 0;

	if (highest < lowest) /* Both ipl and ipl - 1 map to same pri */
		lowest -= APIC_VECTOR_PER_IPL;

	/* It has to be contiguous */
	for (i = lowest; i <= highest; i++) {
		count = 0;
		while ((apic_vector_to_irq[i] == APIC_RESV_IRQ) &&
		    (i <= highest)) {
			if (APIC_CHECK_RESERVE_VECTORS(i))
				break;
			count++;
			i++;
		}
		if (count > navail)
			navail = count;
	}
	return (navail);
}

/*
 * Finds "count" contiguous MSI vectors starting at the proper alignment
 * at "pri".
 * Caller needs to make sure that count has to be power of 2 and should not
 * be < 1.
 */
uchar_t
apic_find_multi_vectors(int pri, int count)
{
	int	lowest, highest, i, navail, start, msibits;

	DDI_INTR_IMPLDBG((CE_CONT, "apic_find_mult: pri: %x, count: %x\n",
	    pri, count));

	highest = apic_ipltopri[pri] + APIC_VECTOR_MASK;
	lowest = apic_ipltopri[pri - 1] + APIC_VECTOR_PER_IPL;
	navail = 0;

	if (highest < lowest) /* Both ipl and ipl - 1 map to same pri */
		lowest -= APIC_VECTOR_PER_IPL;

	/*
	 * msibits is the no. of lower order message data bits for the
	 * allocated MSI vectors and is used to calculate the aligned
	 * starting vector
	 */
	msibits = count - 1;

	/* It has to be contiguous */
	for (i = lowest; i <= highest; i++) {
		navail = 0;

		/*
		 * starting vector has to be aligned accordingly for
		 * multiple MSIs
		 */
		if (msibits)
			i = (i + msibits) & ~msibits;
		start = i;
		while ((apic_vector_to_irq[i] == APIC_RESV_IRQ) &&
		    (i <= highest)) {
			if (APIC_CHECK_RESERVE_VECTORS(i))
				break;
			navail++;
			if (navail >= count) {
				ASSERT(start >= 0 && start <= UCHAR_MAX);
				return ((uchar_t)start);
			}
			i++;
		}
	}
	return (0);
}


/*
 * It finds the apic_irq_t associates with the dip, ispec and type.
 */
apic_irq_t *
apic_find_irq(dev_info_t *dip, struct intrspec *ispec, int type)
{
	apic_irq_t	*irqp;
	int i;

	DDI_INTR_IMPLDBG((CE_CONT, "apic_find_irq: dip=0x%p vec=0x%x "
	    "ipl=0x%x type=0x%x\n", (void *)dip, ispec->intrspec_vec,
	    ispec->intrspec_pri, type));

	for (i = apic_min_device_irq; i <= apic_max_device_irq; i++) {
		for (irqp = apic_irq_table[i]; irqp; irqp = irqp->airq_next) {
			if ((irqp->airq_dip == dip) &&
			    (irqp->airq_origirq == ispec->intrspec_vec) &&
			    (irqp->airq_ipl == ispec->intrspec_pri)) {
				if (type == DDI_INTR_TYPE_MSI) {
					if (irqp->airq_mps_intr_index ==
					    MSI_INDEX)
						return (irqp);
				} else if (type == DDI_INTR_TYPE_MSIX) {
					if (irqp->airq_mps_intr_index ==
					    MSIX_INDEX)
						return (irqp);
				} else
					return (irqp);
			}
		}
	}
	DDI_INTR_IMPLDBG((CE_CONT, "apic_find_irq: return NULL\n"));
	return (NULL);
}

/*
 * This function will return the pending bit of the irqp.
 * It either comes from the IRR register of the APIC or the RDT
 * entry of the I/O APIC.
 * For the IRR to work, it needs to be to its binding CPU
 */
static int
apic_get_pending(apic_irq_t *irqp, int type)
{
	int			bit, index, irr, pending;
	int			intin_no;
	int			apic_ix;

	DDI_INTR_IMPLDBG((CE_CONT, "apic_get_pending: irqp: %p, cpuid: %x "
	    "type: %x\n", (void *)irqp, irqp->airq_cpu & ~IRQ_USER_BOUND,
	    type));

	/* need to get on the bound cpu */
	mutex_enter(&cpu_lock);
	affinity_set(irqp->airq_cpu & ~IRQ_USER_BOUND);

	index = irqp->airq_vector / 32;
	bit = irqp->airq_vector % 32;
	irr = apic_reg_ops->apic_read(APIC_IRR_REG + index);

	affinity_clear();
	mutex_exit(&cpu_lock);

	pending = (irr & (1 << bit)) ? 1 : 0;
	if (!pending && (type == DDI_INTR_TYPE_FIXED)) {
		/* check I/O APIC for fixed interrupt */
		intin_no = irqp->airq_intin_no;
		apic_ix = irqp->airq_ioapicindex;
		pending = (READ_IOAPIC_RDT_ENTRY_LOW_DWORD(apic_ix, intin_no) &
		    AV_PENDING) ? 1 : 0;
	}
	return (pending);
}


/*
 * This function will clear the mask for the interrupt on the I/O APIC
 */
static void
apic_clear_mask(apic_irq_t *irqp)
{
	int			intin_no;
	ulong_t			iflag;
	int32_t			rdt_entry;
	int			apic_ix;

	DDI_INTR_IMPLDBG((CE_CONT, "apic_clear_mask: irqp: %p\n",
	    (void *)irqp));

	intin_no = irqp->airq_intin_no;
	apic_ix = irqp->airq_ioapicindex;

	iflag = intr_clear();
	lock_set(&apic_ioapic_lock);

	rdt_entry = READ_IOAPIC_RDT_ENTRY_LOW_DWORD(apic_ix, intin_no);

	/* clear mask */
	WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(apic_ix, intin_no,
	    ((~AV_MASK) & rdt_entry));

	lock_clear(&apic_ioapic_lock);
	intr_restore(iflag);
}


/*
 * This function will mask the interrupt on the I/O APIC
 */
static void
apic_set_mask(apic_irq_t *irqp)
{
	int			intin_no;
	int			apic_ix;
	ulong_t			iflag;
	int32_t			rdt_entry;

	DDI_INTR_IMPLDBG((CE_CONT, "apic_set_mask: irqp: %p\n", (void *)irqp));

	intin_no = irqp->airq_intin_no;
	apic_ix = irqp->airq_ioapicindex;

	iflag = intr_clear();

	lock_set(&apic_ioapic_lock);

	rdt_entry = READ_IOAPIC_RDT_ENTRY_LOW_DWORD(apic_ix, intin_no);

	/* mask it */
	WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(apic_ix, intin_no,
	    (AV_MASK | rdt_entry));

	lock_clear(&apic_ioapic_lock);
	intr_restore(iflag);
}


void
apic_free_vectors(dev_info_t *dip, int inum, int count, int pri, int type)
{
	int i;
	apic_irq_t *irqptr;
	struct intrspec ispec;

	DDI_INTR_IMPLDBG((CE_CONT, "apic_free_vectors: dip: %p inum: %x "
	    "count: %x pri: %x type: %x\n",
	    (void *)dip, inum, count, pri, type));

	/* for MSI/X only */
	if (!DDI_INTR_IS_MSI_OR_MSIX(type))
		return;

	for (i = 0; i < count; i++) {
		DDI_INTR_IMPLDBG((CE_CONT, "apic_free_vectors: inum=0x%x "
		    "pri=0x%x count=0x%x\n", inum, pri, count));
		ispec.intrspec_vec = inum + i;
		ispec.intrspec_pri = pri;
		if ((irqptr = apic_find_irq(dip, &ispec, type)) == NULL) {
			DDI_INTR_IMPLDBG((CE_CONT, "apic_free_vectors: "
			    "dip=0x%p inum=0x%x pri=0x%x apic_find_irq() "
			    "failed\n", (void *)dip, inum, pri));
			continue;
		}
		irqptr->airq_mps_intr_index = FREE_INDEX;
		apic_vector_to_irq[irqptr->airq_vector] = APIC_RESV_IRQ;
	}
}

/*
 * apic_pci_msi_enable_mode:
 */
void
apic_pci_msi_enable_mode(dev_info_t *rdip, int type, int inum)
{
	ushort_t		msi_ctrl;
	int			cap_ptr = i_ddi_get_msi_msix_cap_ptr(rdip);
	ddi_acc_handle_t	handle = i_ddi_get_pci_config_handle(rdip);

	ASSERT((handle != NULL) && (cap_ptr != 0));

	if (type == DDI_INTR_TYPE_MSI) {
		msi_ctrl = pci_config_get16(handle, cap_ptr + PCI_MSI_CTRL);
		if ((msi_ctrl & PCI_MSI_ENABLE_BIT))
			return;

		msi_ctrl |= PCI_MSI_ENABLE_BIT;
		pci_config_put16(handle, cap_ptr + PCI_MSI_CTRL, msi_ctrl);

	} else if (type == DDI_INTR_TYPE_MSIX) {
		uintptr_t	off;
		uint32_t	mask;
		ddi_intr_msix_t	*msix_p;

		msix_p = i_ddi_get_msix(rdip);

		ASSERT(msix_p != NULL);

		/* Offset into "inum"th entry in the MSI-X table & clear mask */
		off = (uintptr_t)msix_p->msix_tbl_addr + (inum *
		    PCI_MSIX_VECTOR_SIZE) + PCI_MSIX_VECTOR_CTRL_OFFSET;

		mask = ddi_get32(msix_p->msix_tbl_hdl, (uint32_t *)off);

		ddi_put32(msix_p->msix_tbl_hdl, (uint32_t *)off, (mask & ~1));

		msi_ctrl = pci_config_get16(handle, cap_ptr + PCI_MSIX_CTRL);

		if (!(msi_ctrl & PCI_MSIX_ENABLE_BIT)) {
			msi_ctrl |= PCI_MSIX_ENABLE_BIT;
			pci_config_put16(handle, cap_ptr + PCI_MSIX_CTRL,
			    msi_ctrl);
		}
	}
}

static int
apic_set_cpu(int irqno, int cpu, int *result)
{
	apic_irq_t *irqp;
	ulong_t iflag;
	int ret;

	DDI_INTR_IMPLDBG((CE_CONT, "APIC_SET_CPU\n"));

	mutex_enter(&airq_mutex);
	irqp = apic_irq_table[irqno];
	mutex_exit(&airq_mutex);

	if (irqp == NULL) {
		*result = ENXIO;
		return (PSM_FAILURE);
	}

	/* Fail if this is an MSI intr and is part of a group. */
	if ((irqp->airq_mps_intr_index == MSI_INDEX) &&
	    (irqp->airq_intin_no > 1)) {
		*result = ENXIO;
		return (PSM_FAILURE);
	}

	iflag = intr_clear();
	lock_set(&apic_ioapic_lock);

	ret = apic_rebind_all(irqp, cpu);

	lock_clear(&apic_ioapic_lock);
	intr_restore(iflag);

	if (ret) {
		*result = EIO;
		return (PSM_FAILURE);
	}
	/*
	 * keep tracking the default interrupt cpu binding
	 */
	irqp->airq_cpu = cpu;

	*result = 0;
	return (PSM_SUCCESS);
}

static int
apic_grp_set_cpu(int irqno, int new_cpu, int *result)
{
	dev_info_t *orig_dip;
	uint32_t orig_cpu;
	ulong_t iflag;
	apic_irq_t *irqps[PCI_MSI_MAX_INTRS];
	int i;
	int cap_ptr;
	int msi_mask_off = 0;
	ushort_t msi_ctrl;
	uint32_t msi_pvm = 0;
	ddi_acc_handle_t handle;
	int num_vectors = 0;
	uint32_t vector;

	DDI_INTR_IMPLDBG((CE_CONT, "APIC_GRP_SET_CPU\n"));

	/*
	 * Take mutex to insure that table doesn't change out from underneath
	 * us while we're playing with it.
	 */
	mutex_enter(&airq_mutex);
	irqps[0] = apic_irq_table[irqno];
	orig_cpu = irqps[0]->airq_temp_cpu;
	orig_dip = irqps[0]->airq_dip;
	num_vectors = irqps[0]->airq_intin_no;
	vector = irqps[0]->airq_vector;

	/* A "group" of 1 */
	if (num_vectors == 1) {
		mutex_exit(&airq_mutex);
		return (apic_set_cpu(irqno, new_cpu, result));
	}

	*result = ENXIO;

	if (irqps[0]->airq_mps_intr_index != MSI_INDEX) {
		mutex_exit(&airq_mutex);
		DDI_INTR_IMPLDBG((CE_CONT, "set_grp: intr not MSI\n"));
		goto set_grp_intr_done;
	}
	if ((num_vectors < 1) || ((num_vectors - 1) & vector)) {
		mutex_exit(&airq_mutex);
		DDI_INTR_IMPLDBG((CE_CONT,
		    "set_grp: base vec not part of a grp or not aligned: "
		    "vec:0x%x, num_vec:0x%x\n", vector, num_vectors));
		goto set_grp_intr_done;
	}
	DDI_INTR_IMPLDBG((CE_CONT, "set_grp: num intrs in grp: %d\n",
	    num_vectors));

	ASSERT((num_vectors + vector) < APIC_MAX_VECTOR);

	*result = EIO;

	/*
	 * All IRQ entries in the table for the given device will be not
	 * shared.  Since they are not shared, the dip in the table will
	 * be true to the device of interest.
	 */
	for (i = 1; i < num_vectors; i++) {
		irqps[i] = apic_irq_table[apic_vector_to_irq[vector + i]];
		if (irqps[i] == NULL) {
			mutex_exit(&airq_mutex);
			goto set_grp_intr_done;
		}
#ifdef DEBUG
		/* Sanity check: CPU and dip is the same for all entries. */
		if ((irqps[i]->airq_dip != orig_dip) ||
		    (irqps[i]->airq_temp_cpu != orig_cpu)) {
			mutex_exit(&airq_mutex);
			DDI_INTR_IMPLDBG((CE_CONT,
			    "set_grp: cpu or dip for vec 0x%x difft than for "
			    "vec 0x%x\n", vector, vector + i));
			DDI_INTR_IMPLDBG((CE_CONT,
			    "  cpu: %d vs %d, dip: 0x%p vs 0x%p\n", orig_cpu,
			    irqps[i]->airq_temp_cpu, (void *)orig_dip,
			    (void *)irqps[i]->airq_dip));
			goto set_grp_intr_done;
		}
#endif /* DEBUG */
	}
	mutex_exit(&airq_mutex);

	cap_ptr = i_ddi_get_msi_msix_cap_ptr(orig_dip);
	handle = i_ddi_get_pci_config_handle(orig_dip);
	msi_ctrl = pci_config_get16(handle, cap_ptr + PCI_MSI_CTRL);

	/* MSI Per vector masking is supported. */
	if (msi_ctrl & PCI_MSI_PVM_MASK) {
		if (msi_ctrl &  PCI_MSI_64BIT_MASK)
			msi_mask_off = cap_ptr + PCI_MSI_64BIT_MASKBITS;
		else
			msi_mask_off = cap_ptr + PCI_MSI_32BIT_MASK;
		msi_pvm = pci_config_get32(handle, msi_mask_off);
		pci_config_put32(handle, msi_mask_off, (uint32_t)-1);
		DDI_INTR_IMPLDBG((CE_CONT,
		    "set_grp: pvm supported.  Mask set to 0x%x\n",
		    pci_config_get32(handle, msi_mask_off)));
	}

	iflag = intr_clear();
	lock_set(&apic_ioapic_lock);

	/*
	 * Do the first rebind and check for errors.  Apic_rebind_all returns
	 * an error if the CPU is not accepting interrupts.  If the first one
	 * succeeds they all will.
	 */
	if (apic_rebind_all(irqps[0], new_cpu))
		(void) apic_rebind_all(irqps[0], orig_cpu);
	else {
		irqps[0]->airq_cpu = new_cpu;

		for (i = 1; i < num_vectors; i++) {
			(void) apic_rebind_all(irqps[i], new_cpu);
			irqps[i]->airq_cpu = new_cpu;
		}
		*result = 0;	/* SUCCESS */
	}

	lock_clear(&apic_ioapic_lock);
	intr_restore(iflag);

	/* Reenable vectors if per vector masking is supported. */
	if (msi_ctrl & PCI_MSI_PVM_MASK) {
		pci_config_put32(handle, msi_mask_off, msi_pvm);
		DDI_INTR_IMPLDBG((CE_CONT,
		    "set_grp: pvm supported.  Mask restored to 0x%x\n",
		    pci_config_get32(handle, msi_mask_off)));
	}

set_grp_intr_done:
	if (*result != 0)
		return (PSM_FAILURE);

	return (PSM_SUCCESS);
}

int
apic_get_vector_intr_info(int vecirq, apic_get_intr_t *intr_params_p)
{
	struct autovec *av_dev;
	uchar_t irqno;
	uint_t i;
	apic_irq_t *irq_p;

	/* Sanity check the vector/irq argument. */
	ASSERT((vecirq >= 0) || (vecirq <= APIC_MAX_VECTOR));

	mutex_enter(&airq_mutex);

	/*
	 * Convert the vecirq arg to an irq using vector_to_irq table
	 * if the arg is a vector.  Pass thru if already an irq.
	 */
	if ((intr_params_p->avgi_req_flags & PSMGI_INTRBY_FLAGS) ==
	    PSMGI_INTRBY_VEC)
		irqno = apic_vector_to_irq[vecirq];
	else
		irqno = (uchar_t)vecirq;

	irq_p = apic_irq_table[irqno];

	if ((irq_p == NULL) ||
	    ((irq_p->airq_mps_intr_index != RESERVE_INDEX) &&
	    ((irq_p->airq_temp_cpu == IRQ_UNBOUND) ||
	    (irq_p->airq_temp_cpu == IRQ_UNINIT)))) {
		mutex_exit(&airq_mutex);
		return (PSM_FAILURE);
	}

	if (intr_params_p->avgi_req_flags & PSMGI_REQ_CPUID) {

		/* Get the (temp) cpu from apic_irq table, indexed by irq. */
		intr_params_p->avgi_cpu_id = irq_p->airq_temp_cpu;

		/* Return user bound info for intrd. */
		if (intr_params_p->avgi_cpu_id & IRQ_USER_BOUND) {
			intr_params_p->avgi_cpu_id &= ~IRQ_USER_BOUND;
			intr_params_p->avgi_cpu_id |= PSMGI_CPU_USER_BOUND;
		}
	}

	if (intr_params_p->avgi_req_flags & PSMGI_REQ_VECTOR)
		intr_params_p->avgi_vector = irq_p->airq_vector;

	if (intr_params_p->avgi_req_flags &
	    (PSMGI_REQ_NUM_DEVS | PSMGI_REQ_GET_DEVS))
		/* Get number of devices from apic_irq table shared field. */
		intr_params_p->avgi_num_devs = irq_p->airq_share;

	if (intr_params_p->avgi_req_flags &  PSMGI_REQ_GET_DEVS) {

		intr_params_p->avgi_req_flags  |= PSMGI_REQ_NUM_DEVS;

		/* Some devices have NULL dip.  Don't count these. */
		if (intr_params_p->avgi_num_devs > 0) {
			for (i = 0, av_dev = autovect[irqno].avh_link;
			    av_dev; av_dev = av_dev->av_link)
				if (av_dev->av_vector && av_dev->av_dip)
					i++;
			intr_params_p->avgi_num_devs =
			    (uchar_t)MIN(intr_params_p->avgi_num_devs, i);
		}

		/* There are no viable dips to return. */
		if (intr_params_p->avgi_num_devs == 0)
			intr_params_p->avgi_dip_list = NULL;

		else {	/* Return list of dips */

			/* Allocate space in array for that number of devs. */
			intr_params_p->avgi_dip_list = kmem_zalloc(
			    intr_params_p->avgi_num_devs *
			    sizeof (dev_info_t *),
			    KM_SLEEP);

			/*
			 * Loop through the device list of the autovec table
			 * filling in the dip array.
			 *
			 * Note that the autovect table may have some special
			 * entries which contain NULL dips.  These will be
			 * ignored.
			 */
			for (i = 0, av_dev = autovect[irqno].avh_link;
			    av_dev; av_dev = av_dev->av_link)
				if (av_dev->av_vector && av_dev->av_dip)
					intr_params_p->avgi_dip_list[i++] =
					    av_dev->av_dip;
		}
	}

	mutex_exit(&airq_mutex);

	return (PSM_SUCCESS);
}

/*
 * This function provides external interface to the nexus for all
 * functionalities related to the new DDI interrupt framework.
 *
 * Input:
 * dip     - pointer to the dev_info structure of the requested device
 * hdlp    - pointer to the internal interrupt handle structure for the
 *	     requested interrupt
 * intr_op - opcode for this call
 * result  - pointer to the integer that will hold the result to be
 *	     passed back if return value is PSM_SUCCESS
 *
 * Output:
 * return value is either PSM_SUCCESS or PSM_FAILURE
 */
int
apic_intr_ops(dev_info_t *dip, ddi_intr_handle_impl_t *hdlp,
    psm_intr_op_t intr_op, int *result)
{
	int		cap;
	int		count_vec;
	int		old_priority;
	int		new_priority;
	int		new_cpu;
	apic_irq_t	*irqp;
	struct intrspec *ispec, intr_spec;

	DDI_INTR_IMPLDBG((CE_CONT, "apic_intr_ops: dip: %p hdlp: %p "
	    "intr_op: %x\n", (void *)dip, (void *)hdlp, intr_op));

	ispec = &intr_spec;
	ispec->intrspec_pri = hdlp->ih_pri;
	ispec->intrspec_vec = hdlp->ih_inum;
	ispec->intrspec_func = hdlp->ih_cb_func;

	switch (intr_op) {
	case PSM_INTR_OP_CHECK_MSI:
		/*
		 * Check MSI/X is supported or not at APIC level and
		 * masked off the MSI/X bits in hdlp->ih_type if not
		 * supported before return.  If MSI/X is supported,
		 * leave the ih_type unchanged and return.
		 *
		 * hdlp->ih_type passed in from the nexus has all the
		 * interrupt types supported by the device.
		 */
		if (apic_support_msi == 0) {
			/*
			 * if apic_support_msi is not set, call
			 * apic_check_msi_support() to check whether msi
			 * is supported first
			 */
			if (apic_check_msi_support() == PSM_SUCCESS)
				apic_support_msi = 1;
			else
				apic_support_msi = -1;
		}
		if (apic_support_msi == 1) {
			if (apic_msix_enable)
				*result = hdlp->ih_type;
			else
				*result = hdlp->ih_type & ~DDI_INTR_TYPE_MSIX;
		} else
			*result = hdlp->ih_type & ~(DDI_INTR_TYPE_MSI |
			    DDI_INTR_TYPE_MSIX);
		break;
	case PSM_INTR_OP_ALLOC_VECTORS:
		if (hdlp->ih_type == DDI_INTR_TYPE_MSI)
			*result = apic_alloc_msi_vectors(dip, hdlp->ih_inum,
			    hdlp->ih_scratch1, hdlp->ih_pri,
			    (int)(uintptr_t)hdlp->ih_scratch2);
		else
			*result = apic_alloc_msix_vectors(dip, hdlp->ih_inum,
			    hdlp->ih_scratch1, hdlp->ih_pri,
			    (int)(uintptr_t)hdlp->ih_scratch2);
		break;
	case PSM_INTR_OP_FREE_VECTORS:
		apic_free_vectors(dip, hdlp->ih_inum, hdlp->ih_scratch1,
		    hdlp->ih_pri, hdlp->ih_type);
		break;
	case PSM_INTR_OP_NAVAIL_VECTORS:
		*result = apic_navail_vector(dip, hdlp->ih_pri);
		break;
	case PSM_INTR_OP_XLATE_VECTOR:
		ispec = ((ihdl_plat_t *)hdlp->ih_private)->ip_ispecp;
		*result = apic_introp_xlate(dip, ispec, hdlp->ih_type);
		if (*result == -1)
			return (PSM_FAILURE);
		break;
	case PSM_INTR_OP_GET_PENDING:
		if ((irqp = apic_find_irq(dip, ispec, hdlp->ih_type)) == NULL)
			return (PSM_FAILURE);
		*result = apic_get_pending(irqp, hdlp->ih_type);
		break;
	case PSM_INTR_OP_CLEAR_MASK:
		if (hdlp->ih_type != DDI_INTR_TYPE_FIXED)
			return (PSM_FAILURE);
		irqp = apic_find_irq(dip, ispec, hdlp->ih_type);
		if (irqp == NULL)
			return (PSM_FAILURE);
		apic_clear_mask(irqp);
		break;
	case PSM_INTR_OP_SET_MASK:
		if (hdlp->ih_type != DDI_INTR_TYPE_FIXED)
			return (PSM_FAILURE);
		if ((irqp = apic_find_irq(dip, ispec, hdlp->ih_type)) == NULL)
			return (PSM_FAILURE);
		apic_set_mask(irqp);
		break;
	case PSM_INTR_OP_GET_CAP:
		cap = DDI_INTR_FLAG_PENDING;
		if (hdlp->ih_type == DDI_INTR_TYPE_FIXED)
			cap |= DDI_INTR_FLAG_MASKABLE;
		*result = cap;
		break;
	case PSM_INTR_OP_GET_SHARED:
		if (hdlp->ih_type != DDI_INTR_TYPE_FIXED)
			return (PSM_FAILURE);
		ispec = ((ihdl_plat_t *)hdlp->ih_private)->ip_ispecp;
		if ((irqp = apic_find_irq(dip, ispec, hdlp->ih_type)) == NULL)
			return (PSM_FAILURE);
		*result = (irqp->airq_share > 1) ? 1: 0;
		break;
	case PSM_INTR_OP_SET_PRI:
		old_priority = hdlp->ih_pri;	/* save old value */
		new_priority = *(int *)result;	/* try the new value */

		if (hdlp->ih_type == DDI_INTR_TYPE_FIXED) {
			return (PSM_SUCCESS);
		}

		/* Now allocate the vectors */
		if (hdlp->ih_type == DDI_INTR_TYPE_MSI) {
			/* SET_PRI does not support the case of multiple MSI */
			if (i_ddi_intr_get_current_nintrs(hdlp->ih_dip) > 1)
				return (PSM_FAILURE);

			count_vec = apic_alloc_msi_vectors(dip, hdlp->ih_inum,
			    1, new_priority,
			    DDI_INTR_ALLOC_STRICT);
		} else {
			count_vec = apic_alloc_msix_vectors(dip, hdlp->ih_inum,
			    1, new_priority,
			    DDI_INTR_ALLOC_STRICT);
		}

		/* Did we get new vectors? */
		if (!count_vec)
			return (PSM_FAILURE);

		/* Finally, free the previously allocated vectors */
		apic_free_vectors(dip, hdlp->ih_inum, count_vec,
		    old_priority, hdlp->ih_type);
		break;
	case PSM_INTR_OP_SET_CPU:
	case PSM_INTR_OP_GRP_SET_CPU:
		/*
		 * The interrupt handle given here has been allocated
		 * specifically for this command, and ih_private carries
		 * a CPU value.
		 */
		new_cpu = (int)(intptr_t)hdlp->ih_private;
		if (!apic_cpu_in_range(new_cpu)) {
			DDI_INTR_IMPLDBG((CE_CONT,
			    "[grp_]set_cpu: cpu out of range: %d\n", new_cpu));
			*result = EINVAL;
			return (PSM_FAILURE);
		}
		if (hdlp->ih_vector > APIC_MAX_VECTOR) {
			DDI_INTR_IMPLDBG((CE_CONT,
			    "[grp_]set_cpu: vector out of range: %d\n",
			    hdlp->ih_vector));
			*result = EINVAL;
			return (PSM_FAILURE);
		}
		if ((hdlp->ih_flags & PSMGI_INTRBY_FLAGS) == PSMGI_INTRBY_VEC)
			hdlp->ih_vector = apic_vector_to_irq[hdlp->ih_vector];
		if (intr_op == PSM_INTR_OP_SET_CPU) {
			if (apic_set_cpu(hdlp->ih_vector, new_cpu, result) !=
			    PSM_SUCCESS)
				return (PSM_FAILURE);
		} else {
			if (apic_grp_set_cpu(hdlp->ih_vector, new_cpu,
			    result) != PSM_SUCCESS)
				return (PSM_FAILURE);
		}
		break;
	case PSM_INTR_OP_GET_INTR:
		/*
		 * The interrupt handle given here has been allocated
		 * specifically for this command, and ih_private carries
		 * a pointer to a apic_get_intr_t.
		 */
		if (apic_get_vector_intr_info(
		    hdlp->ih_vector, hdlp->ih_private) != PSM_SUCCESS)
			return (PSM_FAILURE);
		break;
	case PSM_INTR_OP_APIC_TYPE:
		((apic_get_type_t *)(hdlp->ih_private))->avgi_type =
		    apic_get_apic_type();
		((apic_get_type_t *)(hdlp->ih_private))->avgi_num_intr =
		    APIC_MAX_VECTOR;
		((apic_get_type_t *)(hdlp->ih_private))->avgi_num_cpu =
		    boot_ncpus;
		hdlp->ih_ver = apic_get_apic_version();
		break;
	case PSM_INTR_OP_SET_CAP:
	default:
		return (PSM_FAILURE);
	}
	return (PSM_SUCCESS);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */
/*
 * Copyright 2014 Josef 'Jeff' Sipek <jeffpc@josefsipek.net>
 * Copyright (c) 2014 by Delphix. All rights reserved.
 * Copyright 2017 Joyent, Inc.
 */

#include <sys/cpuvar.h>
#include <sys/psm.h>
#include <sys/archsystm.h>
#include <sys/apic.h>
#include <sys/sunddi.h>
#include <sys/ddi_impldefs.h>
#include <sys/mach_intr.h>
#include <sys/sysmacros.h>
#include <sys/trap.h>
#include <sys/x86_archext.h>
#include <sys/privregs.h>
#include <sys/psm_common.h>

/* Function prototypes of local apic */
static uint64_t local_apic_read(uint32_t reg);
static void local_apic_write(uint32_t reg, uint64_t value);
static int get_local_apic_pri(void);
static void local_apic_write_task_reg(uint64_t value);
static void local_apic_write_int_cmd(uint32_t cpu_id, uint32_t cmd1);

/*
 * According to the X2APIC specification:
 *
 *   xAPIC global enable    X2APIC enable         Description
 *   (IA32_APIC_BASE[11])   (IA32_APIC_BASE[10])
 * -----------------------------------------------------------
 *	0			0	APIC is disabled
 *	0			1	Invalid
 *	1			0	APIC is enabled in xAPIC mode
 *	1			1	APIC is enabled in X2APIC mode
 * -----------------------------------------------------------
 */
apic_mode_t apic_mode = LOCAL_APIC;	/* Default mode is Local APIC */

/* See apic_directed_EOI_supported().  Currently 3-state variable. */
volatile int apic_directed_eoi_state = 2;

/* Uses MMIO (Memory Mapped IO) */
apic_reg_ops_t local_apic_regs_ops = {
	local_apic_read,
	local_apic_write,
	get_local_apic_pri,
	local_apic_write_task_reg,
	local_apic_write_int_cmd,
	apic_send_EOI,
};

/* The default ops is local APIC (Memory Mapped IO) */
apic_reg_ops_t *apic_reg_ops = &local_apic_regs_ops;

/*
 * APIC register ops related data sturctures and functions.
 */
void apic_send_EOI();
void apic_send_directed_EOI(uint32_t irq);

/*
 * Local APIC Implementation
 */
static uint64_t
local_apic_read(uint32_t reg)
{
	return ((uint32_t)apicadr[reg]);
}

static void
local_apic_write(uint32_t reg, uint64_t value)
{
	apicadr[reg] = (uint32_t)value;
}

static int
get_local_apic_pri(void)
{
	return ((int)getcr8());
}

static void
local_apic_write_task_reg(uint64_t value)
{
	setcr8((ulong_t)(value >> APIC_IPL_SHIFT));
}

static void
local_apic_write_int_cmd(uint32_t cpu_id, uint32_t cmd1)
{
	apicadr[APIC_INT_CMD2] = cpu_id << APIC_ICR_ID_BIT_OFFSET;
	apicadr[APIC_INT_CMD1] = cmd1;
}


/*ARGSUSED*/
void
apic_send_EOI(uint32_t irq)
{
	apic_reg_ops->apic_write(APIC_EOI_REG, 0);
}

/*
 * Support for Directed EOI capability is available in both the xAPIC
 * and x2APIC mode.
 */
void
apic_send_directed_EOI(uint32_t irq)
{
	uchar_t ioapicindex;
	uchar_t vector;
	apic_irq_t *apic_irq;
	short intr_index;

	/*
	 * Following the EOI to the local APIC unit, perform a directed
	 * EOI to the IOxAPIC generating the interrupt by writing to its
	 * EOI register.
	 *
	 * A broadcast EOI is not generated.
	 */
	apic_reg_ops->apic_write(APIC_EOI_REG, 0);

	apic_irq = apic_irq_table[irq];
	while (apic_irq) {
		intr_index = apic_irq->airq_mps_intr_index;
		if (intr_index == ACPI_INDEX || intr_index >= 0) {
			ioapicindex = apic_irq->airq_ioapicindex;
			vector = apic_irq->airq_vector;
			ioapic_write_eoi(ioapicindex, vector);
		}
		apic_irq = apic_irq->airq_next;
	}
}

/*
 * Determine which mode the current CPU is in. See the table above.
 * (IA32_APIC_BASE[11])   (IA32_APIC_BASE[10])
 */
int
apic_local_mode(void)
{
	uint64_t apic_base_msr;
	int bit = ((0x1 << (X2APIC_ENABLE_BIT + 1)) |
	    (0x1 << X2APIC_ENABLE_BIT));

	apic_base_msr = rdmsr(REG_APIC_BASE_MSR);

	if ((apic_base_msr & bit) == bit)
		return (LOCAL_X2APIC);
	else
		return (LOCAL_APIC);
}

void
apic_set_directed_EOI_handler()
{
	apic_reg_ops->apic_send_eoi = apic_send_directed_EOI;
}

int
apic_directed_EOI_supported()
{
	uint32_t ver;

	/*
	 * There are some known issues with some versions of Linux KVM and QEMU
	 * where by directed EOIs do not properly function and instead get
	 * coalesced at the hypervisor, causing the host not to see interrupts.
	 * Thus, when the platform is KVM, we would like to disable it by
	 * default, but keep it available otherwise.
	 *
	 * We use a three-state variable (apic_directed_eoi_state) to determine
	 * how we handle directed EOI.
	 *
	 * 0 --> Don't do directed EOI at all.
	 * 1 --> Do directed EOI if available, no matter the HW environment.
	 * 2 --> Don't do directed EOI on KVM, but do it otherwise if available.
	 *
	 * If some grinning weirdo put something else in there, treat it as '2'
	 * (i.e. the current default).
	 *
	 * Note, at this time illumos KVM does not identify as KVM. If it does,
	 * we'll need to do some work to determine if it should be caught by
	 * this or if it should show up as its own value of platform_type.
	 */
	switch (apic_directed_eoi_state) {
	case 0:
		/* Don't do it at all. */
		return (0);
	case 1:
		break;
	case 2:
	default:
		/* Only do it if we aren't on KVM. */
		if (get_hwenv() == HW_KVM)
			return (0);
		/* FALLTHRU */
	}

	ver = apic_reg_ops->apic_read(APIC_VERS_REG);
	if (ver & APIC_DIRECTED_EOI_BIT)
		return (1);

	return (0);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright (c) 2017 by Delphix. All rights reserved.
 */
/*
 * Copyright (c) 2010, Intel Corporation.
 * All rights reserved.
 */
/*
 * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
 */

#include <sys/time.h>
#include <sys/psm.h>
#include <sys/psm_common.h>
#include <sys/apic.h>
#include <sys/pit.h>
#include <sys/x86_archext.h>
#include <sys/archsystm.h>
#include <sys/machsystm.h>
#include <sys/cpuvar.h>
#include <sys/clock.h>
#include <sys/apic_timer.h>

/*
 * preferred apic timer mode, allow tuning from the /etc/system file.
 */
int		apic_timer_preferred_mode = APIC_TIMER_MODE_DEADLINE;

int		apic_oneshot = 0;
uint_t		apic_hertz_count;
uint_t		apic_nsec_per_intr = 0;
uint64_t	apic_ticks_per_SFnsecs;		/* # of ticks in SF nsecs */

static int		apic_min_timer_ticks = 1; /* minimum timer tick */
static hrtime_t		apic_nsec_max;

static void	periodic_timer_enable(void);
static void	periodic_timer_disable(void);
static void	periodic_timer_reprogram(hrtime_t);
static void	oneshot_timer_enable(void);
static void	oneshot_timer_disable(void);
static void	oneshot_timer_reprogram(hrtime_t);
static void	deadline_timer_enable(void);
static void	deadline_timer_disable(void);
static void	deadline_timer_reprogram(hrtime_t);

extern int	apic_clkvect;
extern uint32_t	apic_divide_reg_init;

/*
 * apic timer data structure
 */
typedef struct apic_timer {
	int	mode;
	void	(*apic_timer_enable_ops)(void);
	void	(*apic_timer_disable_ops)(void);
	void	(*apic_timer_reprogram_ops)(hrtime_t);
} apic_timer_t;

static apic_timer_t	apic_timer;

/*
 * apic timer initialization
 *
 * For the one-shot mode request case, the function returns the
 * resolution (in nanoseconds) for the hardware timer interrupt.
 * If one-shot mode capability is not available, the return value
 * will be 0.
 */
int
apic_timer_init(int hertz)
{
	int		ret, timer_mode;
	static int	firsttime = 1;

	if (firsttime) {
		/* first time calibrate on CPU0 only */
		apic_ticks_per_SFnsecs = apic_calibrate();

		/* the interval timer initial count is 32 bit max */
		apic_nsec_max = APIC_TICKS_TO_NSECS(APIC_MAXVAL);
		firsttime = 0;
	}

	if (hertz == 0) {
		/* requested one_shot */

		/*
		 * return 0 if TSC is not supported.
		 */
		if (!tsc_gethrtime_enable)
			return (0);
		/*
		 * return 0 if one_shot is not preferred.
		 * here, APIC_TIMER_DEADLINE is also an one_shot mode.
		 */
		if ((apic_timer_preferred_mode != APIC_TIMER_MODE_ONESHOT) &&
		    (apic_timer_preferred_mode != APIC_TIMER_MODE_DEADLINE))
			return (0);

		apic_oneshot = 1;
		ret = (int)APIC_TICKS_TO_NSECS(1);
		if ((apic_timer_preferred_mode == APIC_TIMER_MODE_DEADLINE) &&
		    cpuid_deadline_tsc_supported()) {
			timer_mode = APIC_TIMER_MODE_DEADLINE;
		} else {
			timer_mode = APIC_TIMER_MODE_ONESHOT;
		}
	} else {
		/* periodic */
		apic_nsec_per_intr = NANOSEC / hertz;
		apic_hertz_count = APIC_NSECS_TO_TICKS(apic_nsec_per_intr);

		/* program the local APIC to interrupt at the given frequency */
		apic_reg_ops->apic_write(APIC_INIT_COUNT, apic_hertz_count);
		apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
		    (apic_clkvect + APIC_BASE_VECT) | AV_PERIODIC);
		apic_oneshot = 0;
		timer_mode = APIC_TIMER_MODE_PERIODIC;
		ret = NANOSEC / hertz;
	}

	/*
	 * initialize apic_timer data structure, install the timer ops
	 */
	apic_timer.mode = timer_mode;
	switch (timer_mode) {
	default:
		/* FALLTHROUGH */
	case APIC_TIMER_MODE_ONESHOT:
		apic_timer.apic_timer_enable_ops = oneshot_timer_enable;
		apic_timer.apic_timer_disable_ops = oneshot_timer_disable;
		apic_timer.apic_timer_reprogram_ops = oneshot_timer_reprogram;
		break;

	case APIC_TIMER_MODE_PERIODIC:
		apic_timer.apic_timer_enable_ops = periodic_timer_enable;
		apic_timer.apic_timer_disable_ops = periodic_timer_disable;
		apic_timer.apic_timer_reprogram_ops = periodic_timer_reprogram;
		break;

	case APIC_TIMER_MODE_DEADLINE:
		apic_timer.apic_timer_enable_ops = deadline_timer_enable;
		apic_timer.apic_timer_disable_ops = deadline_timer_disable;
		apic_timer.apic_timer_reprogram_ops = deadline_timer_reprogram;
		break;
	}

	return (ret);
}

/*
 * periodic timer mode ops
 */
/* periodic timer enable */
static void
periodic_timer_enable(void)
{
	apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
	    (apic_clkvect + APIC_BASE_VECT) | AV_PERIODIC);
}

/* periodic timer disable */
static void
periodic_timer_disable(void)
{
	apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
	    (apic_clkvect + APIC_BASE_VECT) | AV_MASK);
}

/* periodic timer reprogram */
static void
periodic_timer_reprogram(hrtime_t time)
{
	uint_t	ticks;
	/* time is the interval for periodic mode */
	ticks = APIC_NSECS_TO_TICKS(time);

	if (ticks < apic_min_timer_ticks)
		ticks = apic_min_timer_ticks;

	apic_reg_ops->apic_write(APIC_INIT_COUNT, ticks);
}

/*
 * oneshot timer mode ops
 */
/* oneshot timer enable */
static void
oneshot_timer_enable(void)
{
	apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
	    (apic_clkvect + APIC_BASE_VECT));
}

/* oneshot timer disable */
static void
oneshot_timer_disable(void)
{
	apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
	    (apic_clkvect + APIC_BASE_VECT) | AV_MASK);
}

/* oneshot timer reprogram */
static void
oneshot_timer_reprogram(hrtime_t time)
{
	hrtime_t	now;
	int64_t		delta;
	uint_t		ticks;

	now = gethrtime();
	delta = time - now;

	if (delta <= 0) {
		/*
		 * requested to generate an interrupt in the past
		 * generate an interrupt as soon as possible
		 */
		ticks = apic_min_timer_ticks;
	} else if (delta > apic_nsec_max) {
		/*
		 * requested to generate an interrupt at a time
		 * further than what we are capable of. Set to max
		 * the hardware can handle
		 */
		ticks = APIC_MAXVAL;
#ifdef DEBUG
		cmn_err(CE_CONT, "apic_timer_reprogram, request at"
		    "  %lld  too far in future, current time"
		    "  %lld \n", time, now);
#endif
	} else {
		ticks = APIC_NSECS_TO_TICKS(delta);
	}

	if (ticks < apic_min_timer_ticks)
		ticks = apic_min_timer_ticks;

	apic_reg_ops->apic_write(APIC_INIT_COUNT, ticks);
}

/*
 * deadline timer mode ops
 */
/* deadline timer enable */
static void
deadline_timer_enable(void)
{
	uint64_t ticks;

	apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
	    (apic_clkvect + APIC_BASE_VECT) | AV_DEADLINE);
	/*
	 * Now we have to serialize this per the SDM.  That is to
	 * say, the above enabling can race in the pipeline with
	 * changes to the MSR.  We need to make sure the above
	 * operation is complete before we proceed to reprogram
	 * the deadline value in reprogram().  The algorithm
	 * recommended by the Intel SDM 3A in 10.5.1.4 is:
	 *
	 * a) write a big value to the deadline register
	 * b) read the register back
	 * c) if it reads zero, go back to a and try again
	 */

	do {
		/* write a really big value */
		wrmsr(IA32_DEADLINE_TSC_MSR, 1ULL << 63);
		ticks = rdmsr(IA32_DEADLINE_TSC_MSR);
	} while (ticks == 0);
}

/* deadline timer disable */
static void
deadline_timer_disable(void)
{
	apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
	    (apic_clkvect + APIC_BASE_VECT) | AV_MASK);
}

/* deadline timer reprogram */
static void
deadline_timer_reprogram(hrtime_t time)
{
	int64_t		delta;
	uint64_t	ticks;

	/*
	 * Note that this entire routine is called with
	 * CBE_HIGH_PIL, so we needn't worry about preemption.
	 */
	delta = time - gethrtime();

	/* The unscalehrtime wants unsigned values. */
	delta = max(delta, 0);

	/* Now we shouldn't be interrupted, we can set the deadline */
	ticks = (uint64_t)tsc_read() + unscalehrtime(delta);
	wrmsr(IA32_DEADLINE_TSC_MSR, ticks);
}

/*
 * This function will reprogram the timer.
 *
 * When in oneshot mode the argument is the absolute time in future to
 * generate the interrupt at.
 *
 * When in periodic mode, the argument is the interval at which the
 * interrupts should be generated. There is no need to support the periodic
 * mode timer change at this time.
 */
void
apic_timer_reprogram(hrtime_t time)
{
	/*
	 * we should be Called from high PIL context (CBE_HIGH_PIL),
	 * so kpreempt is disabled.
	 */
	apic_timer.apic_timer_reprogram_ops(time);
}

/*
 * This function will enable timer interrupts.
 */
void
apic_timer_enable(void)
{
	/*
	 * we should be Called from high PIL context (CBE_HIGH_PIL),
	 * so kpreempt is disabled.
	 */
	apic_timer.apic_timer_enable_ops();
}

/*
 * This function will disable timer interrupts.
 */
void
apic_timer_disable(void)
{
	/*
	 * we should be Called from high PIL context (CBE_HIGH_PIL),
	 * so kpreempt is disabled.
	 */
	apic_timer.apic_timer_disable_ops();
}

/*
 * Set timer far into the future and return timer
 * current count in nanoseconds.
 */
hrtime_t
apic_timer_stop_count(void)
{
	hrtime_t	ns_val;
	int		enable_val, count_val;

	/*
	 * Should be called with interrupts disabled.
	 */
	ASSERT(!interrupts_enabled());

	enable_val = apic_reg_ops->apic_read(APIC_LOCAL_TIMER);
	if ((enable_val & AV_MASK) == AV_MASK)
		return ((hrtime_t)-1);	/* timer is disabled */

	count_val = apic_reg_ops->apic_read(APIC_CURR_COUNT);
	ns_val = APIC_TICKS_TO_NSECS(count_val);

	apic_reg_ops->apic_write(APIC_INIT_COUNT, APIC_MAXVAL);

	return (ns_val);
}

/*
 * Reprogram timer after Deep C-State.
 */
void
apic_timer_restart(hrtime_t time)
{
	apic_timer_reprogram(time);
}