|
root / base / usr / src / uts / i86pc / os / lgrpplat.c
lgrpplat.c C 3661 lines 97.1 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
/*
 * 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) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
 */
/*
 * Copyright (c) 2010, Intel Corporation.
 * All rights reserved.
 * Copyright 2024 Oxide Computer Company
 */

/*
 * LOCALITY GROUP (LGROUP) PLATFORM SUPPORT FOR X86/AMD64 PLATFORMS
 * ================================================================
 * Multiprocessor AMD and Intel systems may have Non Uniform Memory Access
 * (NUMA).  A NUMA machine consists of one or more "nodes" that each consist of
 * one or more CPUs and some local memory.  The CPUs in each node can access
 * the memory in the other nodes but at a higher latency than accessing their
 * local memory.  Typically, a system with only one node has Uniform Memory
 * Access (UMA), but it may be possible to have a one node system that has
 * some global memory outside of the node which is higher latency.
 *
 * Module Description
 * ------------------
 * This module provides a platform interface for determining which CPUs and
 * which memory (and how much) are in a NUMA node and how far each node is from
 * each other.  The interface is used by the Virtual Memory (VM) system and the
 * common lgroup framework.  The VM system uses the plat_*() routines to fill
 * in its memory node (memnode) array with the physical address range spanned
 * by each NUMA node to know which memory belongs to which node, so it can
 * build and manage a physical page free list for each NUMA node and allocate
 * local memory from each node as needed.  The common lgroup framework uses the
 * exported lgrp_plat_*() routines to figure out which CPUs and memory belong
 * to each node (leaf lgroup) and how far each node is from each other, so it
 * can build the latency (lgroup) topology for the machine in order to optimize
 * for locality.  Also, an lgroup platform handle instead of lgroups are used
 * in the interface with this module, so this module shouldn't need to know
 * anything about lgroups.  Instead, it just needs to know which CPUs, memory,
 * etc. are in each NUMA node, how far each node is from each other, and to use
 * a unique lgroup platform handle to refer to each node through the interface.
 *
 * Determining NUMA Configuration
 * ------------------------------
 * By default, this module will try to determine the NUMA configuration of the
 * machine by reading the ACPI System Resource Affinity Table (SRAT) and System
 * Locality Information Table (SLIT).  The SRAT contains info to tell which
 * CPUs and memory are local to a given proximity domain (NUMA node).  The SLIT
 * is a matrix that gives the distance between each system locality (which is
 * a NUMA node and should correspond to proximity domains in the SRAT).  For
 * more details on the SRAT and SLIT, please refer to an ACPI 3.0 or newer
 * specification.
 *
 * If the SRAT doesn't exist on a system with AMD Opteron processors, we
 * examine registers in PCI configuration space to determine how many nodes are
 * in the system and which CPUs and memory are in each node.
 * do while booting the kernel.
 *
 * NOTE: Using these PCI configuration space registers to determine this
 *       locality info is not guaranteed to work or be compatible across all
 *	 Opteron processor families.
 *
 * If the SLIT does not exist or look right, the kernel will probe to determine
 * the distance between nodes as long as the NUMA CPU and memory configuration
 * has been determined (see lgrp_plat_probe() for details).
 *
 * Data Structures
 * ---------------
 * The main data structures used by this code are the following:
 *
 * - lgrp_plat_cpu_node[]		CPU to node ID mapping table indexed by
 *					CPU ID (only used for SRAT)
 *
 * - lgrp_plat_lat_stats.latencies[][]	Table of latencies between same and
 *					different nodes indexed by node ID
 *
 * - lgrp_plat_node_cnt			Number of NUMA nodes in system for
 *					non-DR-capable systems,
 *					maximum possible number of NUMA nodes
 *					in system for DR capable systems.
 *
 * - lgrp_plat_node_domain[]		Node ID to proximity domain ID mapping
 *					table indexed by node ID (only used
 *					for SRAT)
 *
 * - lgrp_plat_memnode_info[]		Table with physical address range for
 *					each memory node indexed by memory node
 *					ID
 *
 * The code is implemented to make the following always be true:
 *
 *	lgroup platform handle == node ID == memnode ID
 *
 * Moreover, it allows for the proximity domain ID to be equal to all of the
 * above as long as the proximity domains IDs are numbered from 0 to <number of
 * nodes - 1>.  This is done by hashing each proximity domain ID into the range
 * from 0 to <number of nodes - 1>.  Then proximity ID N will hash into node ID
 * N and proximity domain ID N will be entered into lgrp_plat_node_domain[N]
 * and be assigned node ID N.  If the proximity domain IDs aren't numbered
 * from 0 to <number of nodes - 1>, then hashing the proximity domain IDs into
 * lgrp_plat_node_domain[] will still work for assigning proximity domain IDs
 * to node IDs.  However, the proximity domain IDs may not map to the
 * equivalent node ID since we want to keep the node IDs numbered from 0 to
 * <number of nodes - 1> to minimize cost of searching and potentially space.
 *
 * With the introduction of support of memory DR operations on x86 platforms,
 * things get a little complicated. The addresses of hot-added memory may not
 * be continuous with other memory connected to the same lgrp node. In other
 * words, memory addresses may get interleaved among lgrp nodes after memory
 * DR operations. To work around this limitation, we have extended the
 * relationship between lgrp node and memory node from 1:1 map to 1:N map,
 * that means there may be multiple memory nodes associated with a lgrp node
 * after memory DR operations.
 *
 * To minimize the code changes to support memory DR operations, the
 * following policies have been adopted.
 * 1) On non-DR-capable systems, the relationship among lgroup platform handle,
 *    node ID and memnode ID is still kept as:
 *	lgroup platform handle == node ID == memnode ID
 * 2) For memory present at boot time on DR capable platforms, the relationship
 *    is still kept as is.
 *	lgroup platform handle == node ID == memnode ID
 * 3) For hot-added memory, the relationship between lgrp ID and memnode ID have
 *    been changed from 1:1 map to 1:N map. Memnode IDs [0 - lgrp_plat_node_cnt)
 *    are reserved for memory present at boot time, and memnode IDs
 *    [lgrp_plat_node_cnt, max_mem_nodes) are used to dynamically allocate
 *    memnode ID for hot-added memory.
 * 4) All boot code having the assumption "node ID == memnode ID" can live as
 *    is, that's because node ID is always equal to memnode ID at boot time.
 * 5) The lgrp_plat_memnode_info_update(), plat_pfn_to_mem_node() and
 *    lgrp_plat_mem_size() related logics have been enhanced to deal with
 *    the 1:N map relationship.
 * 6) The latency probing related logics, which have the assumption
 *    "node ID == memnode ID" and may be called at run time, is disabled if
 *    memory DR operation is enabled.
 */


#include <sys/archsystm.h>	/* for {in,out}{b,w,l}() */
#include <sys/atomic.h>
#include <sys/bootconf.h>
#include <sys/cmn_err.h>
#include <sys/controlregs.h>
#include <sys/cpupart.h>
#include <sys/cpuvar.h>
#include <sys/lgrp.h>
#include <sys/machsystm.h>
#include <sys/memlist.h>
#include <sys/memnode.h>
#include <sys/mman.h>
#include <sys/note.h>
#include <sys/pci_cfgspace.h>
#include <sys/pci_impl.h>
#include <sys/param.h>
#include <sys/pghw.h>
#include <sys/promif.h>		/* for prom_printf() */
#include <sys/sysmacros.h>
#include <sys/systm.h>
#include <sys/thread.h>
#include <sys/types.h>
#include <sys/var.h>
#include <sys/x86_archext.h>
#include <vm/hat_i86.h>
#include <vm/seg_kmem.h>
#include <vm/vm_dep.h>

#include <sys/acpidev.h>
#include <sys/acpi/acpi.h>		/* for SRAT, SLIT and MSCT */

/* from fakebop.c */
extern ACPI_TABLE_SRAT *srat_ptr;
extern ACPI_TABLE_SLIT *slit_ptr;
extern ACPI_TABLE_MSCT *msct_ptr;

#define	MAX_NODES		8
#define	NLGRP			(MAX_NODES * (MAX_NODES - 1) + 1)

/*
 * Constants for configuring probing
 */
#define	LGRP_PLAT_PROBE_NROUNDS		64	/* default laps for probing */
#define	LGRP_PLAT_PROBE_NSAMPLES	1	/* default samples to take */
#define	LGRP_PLAT_PROBE_NREADS		256	/* number of vendor ID reads */

/*
 * Flags for probing
 */
#define	LGRP_PLAT_PROBE_ENABLE		0x1	/* enable probing */
#define	LGRP_PLAT_PROBE_PGCPY		0x2	/* probe using page copy */
#define	LGRP_PLAT_PROBE_VENDOR		0x4	/* probe vendor ID register */

/*
 * Hash proximity domain ID into node to domain mapping table "mod" number of
 * nodes to minimize span of entries used and try to have lowest numbered
 * proximity domain be node 0
 */
#define	NODE_DOMAIN_HASH(domain, node_cnt) \
	((lgrp_plat_prox_domain_min == UINT32_MAX) ? (domain) % node_cnt : \
	    ((domain) - lgrp_plat_prox_domain_min) % node_cnt)

/*
 * CPU to node ID mapping structure (only used with SRAT)
 */
typedef	struct cpu_node_map {
	int		exists;
	uint_t		node;
	uint32_t	apicid;
	uint32_t	prox_domain;
} cpu_node_map_t;

/*
 * Latency statistics
 */
typedef struct lgrp_plat_latency_stats {
	hrtime_t	latencies[MAX_NODES][MAX_NODES];
	hrtime_t	latency_max;
	hrtime_t	latency_min;
} lgrp_plat_latency_stats_t;

/*
 * Memory configuration for probing
 */
typedef struct lgrp_plat_probe_mem_config {
	size_t	probe_memsize;		/* how much memory to probe per node */
	caddr_t	probe_va[MAX_NODES];	/* where memory mapped for probing */
	pfn_t	probe_pfn[MAX_NODES];	/* physical pages to map for probing */
} lgrp_plat_probe_mem_config_t;

/*
 * Statistics kept for probing
 */
typedef struct lgrp_plat_probe_stats {
	hrtime_t	flush_cost;
	hrtime_t	probe_cost;
	hrtime_t	probe_cost_total;
	hrtime_t	probe_error_code;
	hrtime_t	probe_errors[MAX_NODES][MAX_NODES];
	int		probe_suspect[MAX_NODES][MAX_NODES];
	hrtime_t	probe_max[MAX_NODES][MAX_NODES];
	hrtime_t	probe_min[MAX_NODES][MAX_NODES];
} lgrp_plat_probe_stats_t;

/*
 * Node to proximity domain ID mapping structure (only used with SRAT)
 */
typedef	struct node_domain_map {
	int		exists;
	uint32_t	prox_domain;
} node_domain_map_t;

/*
 * Node ID and starting and ending page for physical memory in memory node
 */
typedef	struct memnode_phys_addr_map {
	pfn_t		start;
	pfn_t		end;
	int		exists;
	uint32_t	prox_domain;
	uint32_t	device_id;
	uint_t		lgrphand;
} memnode_phys_addr_map_t;

/*
 * Number of CPUs for which we got APIC IDs
 */
static int				lgrp_plat_apic_ncpus = 0;

/*
 * CPU to node ID mapping table (only used for SRAT) and its max number of
 * entries
 */
static cpu_node_map_t			*lgrp_plat_cpu_node = NULL;
static uint_t				lgrp_plat_cpu_node_nentries = 0;

/*
 * Latency statistics
 */
lgrp_plat_latency_stats_t		lgrp_plat_lat_stats;

/*
 * Whether memory is interleaved across nodes causing MPO to be disabled
 */
static int				lgrp_plat_mem_intrlv = 0;

/*
 * Node ID to proximity domain ID mapping table (only used for SRAT)
 */
static node_domain_map_t		lgrp_plat_node_domain[MAX_NODES];

/*
 * Physical address range for memory in each node
 */
static memnode_phys_addr_map_t		lgrp_plat_memnode_info[MAX_MEM_NODES];

/*
 * Statistics gotten from probing
 */
static lgrp_plat_probe_stats_t		lgrp_plat_probe_stats;

/*
 * Memory configuration for probing
 */
static lgrp_plat_probe_mem_config_t	lgrp_plat_probe_mem_config;

/*
 * Lowest proximity domain ID seen in ACPI SRAT
 */
static uint32_t				lgrp_plat_prox_domain_min = UINT32_MAX;

/*
 * Error code from processing ACPI SRAT
 */
static int				lgrp_plat_srat_error = 0;

/*
 * Error code from processing ACPI SLIT
 */
static int				lgrp_plat_slit_error = 0;

/*
 * Whether lgrp topology has been flattened to 2 levels.
 */
static int				lgrp_plat_topo_flatten = 0;


/*
 * Maximum memory node ID in use.
 */
static uint_t				lgrp_plat_max_mem_node;

/*
 * Allocate lgroup array statically
 */
static lgrp_t				lgrp_space[NLGRP];
static int				nlgrps_alloc;


/*
 * Enable finding and using minimum proximity domain ID when hashing
 */
int			lgrp_plat_domain_min_enable = 1;

/*
 * Maximum possible number of nodes in system
 */
uint_t			lgrp_plat_node_cnt = 1;

/*
 * Enable sorting nodes in ascending order by starting physical address
 */
int			lgrp_plat_node_sort_enable = 1;

/*
 * Configuration Parameters for Probing
 * - lgrp_plat_probe_flags	Flags to specify enabling probing, probe
 *				operation, etc.
 * - lgrp_plat_probe_nrounds	How many rounds of probing to do
 * - lgrp_plat_probe_nsamples	Number of samples to take when probing each
 *				node
 * - lgrp_plat_probe_nreads	Number of times to read vendor ID from
 *				Northbridge for each probe
 */
uint_t			lgrp_plat_probe_flags = 0;
int			lgrp_plat_probe_nrounds = LGRP_PLAT_PROBE_NROUNDS;
int			lgrp_plat_probe_nsamples = LGRP_PLAT_PROBE_NSAMPLES;
int			lgrp_plat_probe_nreads = LGRP_PLAT_PROBE_NREADS;

/*
 * Enable use of ACPI System Resource Affinity Table (SRAT), System
 * Locality Information Table (SLIT) and Maximum System Capability Table (MSCT)
 */
int			lgrp_plat_srat_enable = 1;
int			lgrp_plat_slit_enable = 1;
int			lgrp_plat_msct_enable = 1;

/*
 * mnode_xwa: set to non-zero value to initiate workaround if large pages are
 * found to be crossing memory node boundaries. The workaround will eliminate
 * a base size page at the end of each memory node boundary to ensure that
 * a large page with constituent pages that span more than 1 memory node
 * can never be formed.
 *
 */
int	mnode_xwa = 1;

/*
 * Static array to hold lgroup statistics
 */
struct lgrp_stats	lgrp_stats[NLGRP];


/*
 * Forward declarations of platform interface routines
 */
void		plat_build_mem_nodes(struct memlist *list);

int		plat_mnode_xcheck(pfn_t pfncnt);

lgrp_handle_t	plat_mem_node_to_lgrphand(int mnode);

int		plat_pfn_to_mem_node(pfn_t pfn);

/*
 * Forward declarations of lgroup platform interface routines
 */
lgrp_t		*lgrp_plat_alloc(lgrp_id_t lgrpid);

void		lgrp_plat_config(lgrp_config_flag_t flag, uintptr_t arg);

lgrp_handle_t	lgrp_plat_cpu_to_hand(processorid_t id);

void		lgrp_plat_init(lgrp_init_stages_t stage);

int		lgrp_plat_latency(lgrp_handle_t from, lgrp_handle_t to);

int		lgrp_plat_max_lgrps(void);

pgcnt_t		lgrp_plat_mem_size(lgrp_handle_t plathand,
    lgrp_mem_query_t query);

lgrp_handle_t	lgrp_plat_pfn_to_hand(pfn_t pfn);

void		lgrp_plat_probe(void);

lgrp_handle_t	lgrp_plat_root_hand(void);


/*
 * Forward declarations of local routines
 */
static int	is_opteron(void);

static int	lgrp_plat_cpu_node_update(node_domain_map_t *node_domain,
    int node_cnt, cpu_node_map_t *cpu_node, int nentries, uint32_t apicid,
    uint32_t domain);

static int	lgrp_plat_cpu_to_node(cpu_t *cp, cpu_node_map_t *cpu_node,
    int cpu_node_nentries);

static int	lgrp_plat_domain_to_node(node_domain_map_t *node_domain,
    int node_cnt, uint32_t domain);

static void	lgrp_plat_get_numa_config(void);

static void	lgrp_plat_latency_adjust(memnode_phys_addr_map_t *memnode_info,
    lgrp_plat_latency_stats_t *lat_stats,
    lgrp_plat_probe_stats_t *probe_stats);

static int	lgrp_plat_latency_verify(memnode_phys_addr_map_t *memnode_info,
    lgrp_plat_latency_stats_t *lat_stats);

static void	lgrp_plat_main_init(void);

static pgcnt_t	lgrp_plat_mem_size_default(lgrp_handle_t, lgrp_mem_query_t);

static int	lgrp_plat_node_domain_update(node_domain_map_t *node_domain,
    int node_cnt, uint32_t domain);

static int	lgrp_plat_memnode_info_update(node_domain_map_t *node_domain,
    int node_cnt, memnode_phys_addr_map_t *memnode_info, int memnode_cnt,
    uint64_t start, uint64_t end, uint32_t domain, uint32_t device_id);

static void	lgrp_plat_node_sort(node_domain_map_t *node_domain,
    int node_cnt, cpu_node_map_t *cpu_node, int cpu_count,
    memnode_phys_addr_map_t *memnode_info);

static hrtime_t	lgrp_plat_probe_time(int to, cpu_node_map_t *cpu_node,
    int cpu_node_nentries, lgrp_plat_probe_mem_config_t *probe_mem_config,
    lgrp_plat_latency_stats_t *lat_stats, lgrp_plat_probe_stats_t *probe_stats);

static int	lgrp_plat_process_cpu_apicids(cpu_node_map_t *cpu_node);

static int	lgrp_plat_process_slit(ACPI_TABLE_SLIT *tp,
    node_domain_map_t *node_domain, uint_t node_cnt,
    memnode_phys_addr_map_t *memnode_info,
    lgrp_plat_latency_stats_t *lat_stats);

static int	lgrp_plat_process_sli(uint32_t domain, uchar_t *sli_info,
    uint32_t sli_cnt, node_domain_map_t *node_domain, uint_t node_cnt,
    lgrp_plat_latency_stats_t *lat_stats);

static int	lgrp_plat_process_srat(ACPI_TABLE_SRAT *tp, ACPI_TABLE_MSCT *mp,
    uint32_t *prox_domain_min, node_domain_map_t *node_domain,
    cpu_node_map_t *cpu_node, int cpu_count,
    memnode_phys_addr_map_t *memnode_info);

static void	lgrp_plat_release_bootstrap(void);

static int	lgrp_plat_srat_domains(ACPI_TABLE_SRAT *tp,
    uint32_t *prox_domain_min);

static int	lgrp_plat_msct_domains(ACPI_TABLE_MSCT *tp,
    uint32_t *prox_domain_min);

static void	lgrp_plat_2level_setup(lgrp_plat_latency_stats_t *lat_stats);

static void	opt_get_numa_config(uint_t *node_cnt, int *mem_intrlv,
    memnode_phys_addr_map_t *memnode_info);

static hrtime_t	opt_probe_vendor(int dest_node, int nreads);


/*
 * PLATFORM INTERFACE ROUTINES
 */

/*
 * Configure memory nodes for machines with more than one node (ie NUMA)
 */
void
plat_build_mem_nodes(struct memlist *list)
{
	pfn_t		cur_start;	/* start addr of subrange */
	pfn_t		cur_end;	/* end addr of subrange */
	pfn_t		start;		/* start addr of whole range */
	pfn_t		end;		/* end addr of whole range */
	pgcnt_t		endcnt;		/* pages to sacrifice */

	/*
	 * Boot install lists are arranged <addr, len>, ...
	 */
	while (list) {
		int	node;

		start = list->ml_address >> PAGESHIFT;
		end = (list->ml_address + list->ml_size - 1) >> PAGESHIFT;

		if (start > physmax) {
			list = list->ml_next;
			continue;
		}
		if (end > physmax)
			end = physmax;

		/*
		 * When there is only one memnode, just add memory to memnode
		 */
		if (max_mem_nodes == 1) {
			mem_node_add_slice(start, end);
			list = list->ml_next;
			continue;
		}

		/*
		 * mem_node_add_slice() expects to get a memory range that
		 * is within one memnode, so need to split any memory range
		 * that spans multiple memnodes into subranges that are each
		 * contained within one memnode when feeding them to
		 * mem_node_add_slice()
		 */
		cur_start = start;
		do {
			node = plat_pfn_to_mem_node(cur_start);

			/*
			 * Panic if DRAM address map registers or SRAT say
			 * memory in node doesn't exist or address from
			 * boot installed memory list entry isn't in this node.
			 * This shouldn't happen and rest of code can't deal
			 * with this if it does.
			 */
			if (node < 0 || node >= lgrp_plat_max_mem_node ||
			    !lgrp_plat_memnode_info[node].exists ||
			    cur_start < lgrp_plat_memnode_info[node].start ||
			    cur_start > lgrp_plat_memnode_info[node].end) {
				cmn_err(CE_PANIC, "Don't know which memnode "
				    "to add installed memory address 0x%lx\n",
				    cur_start);
			}

			/*
			 * End of current subrange should not span memnodes
			 */
			cur_end = end;
			endcnt = 0;
			if (lgrp_plat_memnode_info[node].exists &&
			    cur_end > lgrp_plat_memnode_info[node].end) {
				cur_end = lgrp_plat_memnode_info[node].end;
				if (mnode_xwa > 1) {
					/*
					 * sacrifice the last page in each
					 * node to eliminate large pages
					 * that span more than 1 memory node.
					 */
					endcnt = 1;
					physinstalled--;
				}
			}

			mem_node_add_slice(cur_start, cur_end - endcnt);

			/*
			 * Next subrange starts after end of current one
			 */
			cur_start = cur_end + 1;
		} while (cur_end < end);

		list = list->ml_next;
	}
	mem_node_physalign = 0;
	mem_node_pfn_shift = 0;
}


/*
 * plat_mnode_xcheck: checks the node memory ranges to see if there is a pfncnt
 * range of pages aligned on pfncnt that crosses an node boundary. Returns 1 if
 * a crossing is found and returns 0 otherwise.
 */
int
plat_mnode_xcheck(pfn_t pfncnt)
{
	int	node, prevnode = -1, basenode;
	pfn_t	ea, sa;

	for (node = 0; node < lgrp_plat_max_mem_node; node++) {

		if (lgrp_plat_memnode_info[node].exists == 0)
			continue;

		if (prevnode == -1) {
			prevnode = node;
			basenode = node;
			continue;
		}

		/* assume x86 node pfn ranges are in increasing order */
		ASSERT(lgrp_plat_memnode_info[node].start >
		    lgrp_plat_memnode_info[prevnode].end);

		/*
		 * continue if the starting address of node is not contiguous
		 * with the previous node.
		 */

		if (lgrp_plat_memnode_info[node].start !=
		    (lgrp_plat_memnode_info[prevnode].end + 1)) {
			basenode = node;
			prevnode = node;
			continue;
		}

		/* check if the starting address of node is pfncnt aligned */
		if ((lgrp_plat_memnode_info[node].start & (pfncnt - 1)) != 0) {

			/*
			 * at this point, node starts at an unaligned boundary
			 * and is contiguous with the previous node(s) to
			 * basenode. Check if there is an aligned contiguous
			 * range of length pfncnt that crosses this boundary.
			 */

			sa = P2ALIGN(lgrp_plat_memnode_info[prevnode].end,
			    pfncnt);
			ea = P2ROUNDUP((lgrp_plat_memnode_info[node].start),
			    pfncnt);

			ASSERT((ea - sa) == pfncnt);
			if (sa >= lgrp_plat_memnode_info[basenode].start &&
			    ea <= (lgrp_plat_memnode_info[node].end + 1)) {
				/*
				 * large page found to cross mnode boundary.
				 * Return Failure if workaround not enabled.
				 */
				if (mnode_xwa == 0)
					return (1);
				mnode_xwa++;
			}
		}
		prevnode = node;
	}
	return (0);
}


lgrp_handle_t
plat_mem_node_to_lgrphand(int mnode)
{
	if (max_mem_nodes == 1)
		return (LGRP_DEFAULT_HANDLE);

	ASSERT(0 <= mnode && mnode < lgrp_plat_max_mem_node);

	return ((lgrp_handle_t)(lgrp_plat_memnode_info[mnode].lgrphand));
}

int
plat_pfn_to_mem_node(pfn_t pfn)
{
	int	node;

	if (max_mem_nodes == 1)
		return (0);

	for (node = 0; node < lgrp_plat_max_mem_node; node++) {
		/*
		 * Skip nodes with no memory
		 */
		if (!lgrp_plat_memnode_info[node].exists)
			continue;

		membar_consumer();
		if (pfn >= lgrp_plat_memnode_info[node].start &&
		    pfn <= lgrp_plat_memnode_info[node].end)
			return (node);
	}

	/*
	 * Didn't find memnode where this PFN lives which should never happen
	 */
	ASSERT(node < lgrp_plat_max_mem_node);
	return (-1);
}


/*
 * LGROUP PLATFORM INTERFACE ROUTINES
 */

/*
 * Allocate additional space for an lgroup.
 */
lgrp_t *
lgrp_plat_alloc(lgrp_id_t lgrpid)
{
	lgrp_t *lgrp;

	lgrp = &lgrp_space[nlgrps_alloc++];
	if (lgrpid >= NLGRP || nlgrps_alloc > NLGRP)
		return (NULL);
	return (lgrp);
}


/*
 * Platform handling for (re)configuration changes
 *
 * Mechanism to protect lgrp_plat_cpu_node[] at CPU hotplug:
 * 1) Use cpu_lock to synchronize between lgrp_plat_config() and
 *    lgrp_plat_cpu_to_hand().
 * 2) Disable latency probing logic by making sure that the flag
 *    LGRP_PLAT_PROBE_ENABLE is cleared.
 *
 * Mechanism to protect lgrp_plat_memnode_info[] at memory hotplug:
 * 1) Only inserts into lgrp_plat_memnode_info at memory hotplug, no removal.
 * 2) Only expansion to existing entries, no shrinking.
 * 3) On writing side, DR framework ensures that lgrp_plat_config() is called
 *    in single-threaded context. And membar_producer() is used to ensure that
 *    all changes are visible to other CPUs before setting the "exists" flag.
 * 4) On reading side, membar_consumer() after checking the "exists" flag
 *    ensures that right values are retrieved.
 *
 * Mechanism to protect lgrp_plat_node_domain[] at hotplug:
 * 1) Only insertion into lgrp_plat_node_domain at hotplug, no removal.
 * 2) On writing side, it's single-threaded and membar_producer() is used to
 *    ensure all changes are visible to other CPUs before setting the "exists"
 *    flag.
 * 3) On reading side, membar_consumer() after checking the "exists" flag
 *    ensures that right values are retrieved.
 */
void
lgrp_plat_config(lgrp_config_flag_t flag, uintptr_t arg)
{
#ifdef	__xpv
	_NOTE(ARGUNUSED(flag, arg));
#else
	int	rc, node;
	cpu_t	*cp;
	void	*hdl = NULL;
	uchar_t	*sliptr = NULL;
	uint32_t domain, apicid, slicnt = 0;
	update_membounds_t *mp;

	extern int acpidev_dr_get_cpu_numa_info(cpu_t *, void **, uint32_t *,
	    uint32_t *, uint32_t *, uchar_t **);
	extern void acpidev_dr_free_cpu_numa_info(void *);

	/*
	 * This interface is used to support CPU/memory DR operations.
	 * Don't bother here if it's still during boot or only one lgrp node
	 * is supported.
	 */
	if (!lgrp_topo_initialized || lgrp_plat_node_cnt == 1)
		return;

	switch (flag) {
	case LGRP_CONFIG_CPU_ADD:
		cp = (cpu_t *)arg;
		ASSERT(cp != NULL);
		ASSERT(MUTEX_HELD(&cpu_lock));

		/* Check whether CPU already exists. */
		ASSERT(!lgrp_plat_cpu_node[cp->cpu_id].exists);
		if (lgrp_plat_cpu_node[cp->cpu_id].exists) {
			cmn_err(CE_WARN,
			    "!lgrp: CPU(%d) already exists in cpu_node map.",
			    cp->cpu_id);
			break;
		}

		/* Query CPU lgrp information. */
		rc = acpidev_dr_get_cpu_numa_info(cp, &hdl, &apicid, &domain,
		    &slicnt, &sliptr);
		ASSERT(rc == 0);
		if (rc != 0) {
			cmn_err(CE_WARN,
			    "!lgrp: failed to query lgrp info for CPU(%d).",
			    cp->cpu_id);
			break;
		}

		/* Update node to proximity domain mapping */
		node = lgrp_plat_domain_to_node(lgrp_plat_node_domain,
		    lgrp_plat_node_cnt, domain);
		if (node == -1) {
			node = lgrp_plat_node_domain_update(
			    lgrp_plat_node_domain, lgrp_plat_node_cnt, domain);
			ASSERT(node != -1);
			if (node == -1) {
				acpidev_dr_free_cpu_numa_info(hdl);
				cmn_err(CE_WARN, "!lgrp: failed to update "
				    "node_domain map for domain(%u).", domain);
				break;
			}
		}

		/* Update latency information among lgrps. */
		if (slicnt != 0 && sliptr != NULL) {
			if (lgrp_plat_process_sli(domain, sliptr, slicnt,
			    lgrp_plat_node_domain, lgrp_plat_node_cnt,
			    &lgrp_plat_lat_stats) != 0) {
				cmn_err(CE_WARN, "!lgrp: failed to update "
				    "latency information for domain (%u).",
				    domain);
			}
		}

		/* Update CPU to node mapping. */
		lgrp_plat_cpu_node[cp->cpu_id].prox_domain = domain;
		lgrp_plat_cpu_node[cp->cpu_id].node = node;
		lgrp_plat_cpu_node[cp->cpu_id].apicid = apicid;
		lgrp_plat_cpu_node[cp->cpu_id].exists = 1;
		lgrp_plat_apic_ncpus++;

		acpidev_dr_free_cpu_numa_info(hdl);
		break;

	case LGRP_CONFIG_CPU_DEL:
		cp = (cpu_t *)arg;
		ASSERT(cp != NULL);
		ASSERT(MUTEX_HELD(&cpu_lock));

		/* Check whether CPU exists. */
		ASSERT(lgrp_plat_cpu_node[cp->cpu_id].exists);
		if (!lgrp_plat_cpu_node[cp->cpu_id].exists) {
			cmn_err(CE_WARN,
			    "!lgrp: CPU(%d) doesn't exist in cpu_node map.",
			    cp->cpu_id);
			break;
		}

		/* Query CPU lgrp information. */
		rc = acpidev_dr_get_cpu_numa_info(cp, &hdl, &apicid, &domain,
		    NULL, NULL);
		ASSERT(rc == 0);
		if (rc != 0) {
			cmn_err(CE_WARN,
			    "!lgrp: failed to query lgrp info for CPU(%d).",
			    cp->cpu_id);
			break;
		}

		/* Update map. */
		ASSERT(lgrp_plat_cpu_node[cp->cpu_id].apicid == apicid);
		ASSERT(lgrp_plat_cpu_node[cp->cpu_id].prox_domain == domain);
		lgrp_plat_cpu_node[cp->cpu_id].exists = 0;
		lgrp_plat_cpu_node[cp->cpu_id].apicid = UINT32_MAX;
		lgrp_plat_cpu_node[cp->cpu_id].prox_domain = UINT32_MAX;
		lgrp_plat_cpu_node[cp->cpu_id].node = UINT_MAX;
		lgrp_plat_apic_ncpus--;

		acpidev_dr_free_cpu_numa_info(hdl);
		break;

	case LGRP_CONFIG_MEM_ADD:
		mp = (update_membounds_t *)arg;
		ASSERT(mp != NULL);

		/* Update latency information among lgrps. */
		if (mp->u_sli_cnt != 0 && mp->u_sli_ptr != NULL) {
			if (lgrp_plat_process_sli(mp->u_domain,
			    mp->u_sli_ptr, mp->u_sli_cnt,
			    lgrp_plat_node_domain, lgrp_plat_node_cnt,
			    &lgrp_plat_lat_stats) != 0) {
				cmn_err(CE_WARN, "!lgrp: failed to update "
				    "latency information for domain (%u).",
				    domain);
			}
		}

		if (lgrp_plat_memnode_info_update(lgrp_plat_node_domain,
		    lgrp_plat_node_cnt, lgrp_plat_memnode_info, max_mem_nodes,
		    mp->u_base, mp->u_base + mp->u_length,
		    mp->u_domain, mp->u_device_id) < 0) {
			cmn_err(CE_WARN,
			    "!lgrp: failed to update latency  information for "
			    "memory (0x%" PRIx64 " - 0x%" PRIx64 ").",
			    mp->u_base, mp->u_base + mp->u_length);
		}
		break;

	default:
		break;
	}
#endif	/* __xpv */
}


/*
 * Return the platform handle for the lgroup containing the given CPU
 */
lgrp_handle_t
lgrp_plat_cpu_to_hand(processorid_t id)
{
	lgrp_handle_t	hand;

	ASSERT(!lgrp_initialized || MUTEX_HELD(&cpu_lock));

	if (lgrp_plat_node_cnt == 1)
		return (LGRP_DEFAULT_HANDLE);

	hand = (lgrp_handle_t)lgrp_plat_cpu_to_node(cpu[id],
	    lgrp_plat_cpu_node, lgrp_plat_cpu_node_nentries);

	if (hand == (lgrp_handle_t)-1)
		return (LGRP_NULL_HANDLE);

	return (hand);
}


/*
 * Platform-specific initialization of lgroups
 */
void
lgrp_plat_init(lgrp_init_stages_t stage)
{
#if defined(__xpv)
#else	/* __xpv */
	u_longlong_t	value;
#endif	/* __xpv */

	switch (stage) {
	case LGRP_INIT_STAGE1:
#if defined(__xpv)
		/*
		 * XXPV	For now, the hypervisor treats all memory equally.
		 */
		lgrp_plat_node_cnt = max_mem_nodes = 1;
#else	/* __xpv */

		/*
		 * Get boot property for lgroup topology height limit
		 */
		if (bootprop_getval(BP_LGRP_TOPO_LEVELS, &value) == 0)
			(void) lgrp_topo_ht_limit_set((int)value);

		/*
		 * Get boot property for enabling/disabling SRAT
		 */
		if (bootprop_getval(BP_LGRP_SRAT_ENABLE, &value) == 0)
			lgrp_plat_srat_enable = (int)value;

		/*
		 * Get boot property for enabling/disabling SLIT
		 */
		if (bootprop_getval(BP_LGRP_SLIT_ENABLE, &value) == 0)
			lgrp_plat_slit_enable = (int)value;

		/*
		 * Get boot property for enabling/disabling MSCT
		 */
		if (bootprop_getval(BP_LGRP_MSCT_ENABLE, &value) == 0)
			lgrp_plat_msct_enable = (int)value;

		/*
		 * Initialize as a UMA machine
		 */
		if (lgrp_topo_ht_limit() == 1) {
			lgrp_plat_node_cnt = max_mem_nodes = 1;
			lgrp_plat_max_mem_node = 1;
			return;
		}

		lgrp_plat_get_numa_config();

		/*
		 * Each lgrp node needs MAX_MEM_NODES_PER_LGROUP memnodes
		 * to support memory DR operations if memory DR is enabled.
		 */
		lgrp_plat_max_mem_node = lgrp_plat_node_cnt;
		if (plat_dr_support_memory() && lgrp_plat_node_cnt != 1) {
			max_mem_nodes = MAX_MEM_NODES_PER_LGROUP *
			    lgrp_plat_node_cnt;
			ASSERT(max_mem_nodes <= MAX_MEM_NODES);
		}
#endif	/* __xpv */
		break;

	case LGRP_INIT_STAGE3:
		lgrp_plat_probe();
		lgrp_plat_release_bootstrap();
		break;

	case LGRP_INIT_STAGE4:
		lgrp_plat_main_init();
		break;

	default:
		break;
	}
}


/*
 * Return latency between "from" and "to" lgroups
 *
 * This latency number can only be used for relative comparison
 * between lgroups on the running system, cannot be used across platforms,
 * and may not reflect the actual latency.  It is platform and implementation
 * specific, so platform gets to decide its value.  It would be nice if the
 * number was at least proportional to make comparisons more meaningful though.
 */
int
lgrp_plat_latency(lgrp_handle_t from, lgrp_handle_t to)
{
	lgrp_handle_t	src, dest;
	int		node;

	if (max_mem_nodes == 1)
		return (0);

	/*
	 * Return max latency for root lgroup
	 */
	if (from == LGRP_DEFAULT_HANDLE || to == LGRP_DEFAULT_HANDLE)
		return (lgrp_plat_lat_stats.latency_max);

	src = from;
	dest = to;

	/*
	 * Return 0 for nodes (lgroup platform handles) out of range
	 */
	if (src >= MAX_NODES || dest >= MAX_NODES)
		return (0);

	/*
	 * Probe from current CPU if its lgroup latencies haven't been set yet
	 * and we are trying to get latency from current CPU to some node.
	 * Avoid probing if CPU/memory DR is enabled.
	 */
	if (lgrp_plat_lat_stats.latencies[src][src] == 0) {
		/*
		 * Latency information should be updated by lgrp_plat_config()
		 * for DR operations. Something is wrong if reaches here.
		 * For safety, flatten lgrp topology to two levels.
		 */
		if (plat_dr_support_cpu() || plat_dr_support_memory()) {
			ASSERT(lgrp_plat_lat_stats.latencies[src][src]);
			cmn_err(CE_WARN,
			    "lgrp: failed to get latency information, "
			    "fall back to two-level topology.");
			lgrp_plat_2level_setup(&lgrp_plat_lat_stats);
		} else {
			node = lgrp_plat_cpu_to_node(CPU, lgrp_plat_cpu_node,
			    lgrp_plat_cpu_node_nentries);
			ASSERT3U(node, <, lgrp_plat_node_cnt);
			if (node == (lgrp_handle_t)-1)
				return (0);
			if (node == src)
				lgrp_plat_probe();
		}
	}

	return (lgrp_plat_lat_stats.latencies[src][dest]);
}


/*
 * Return the maximum number of lgrps supported by the platform.
 * Before lgrp topology is known it returns an estimate based on the number of
 * nodes. Once topology is known it returns:
 * 1) the actual maximim number of lgrps created if CPU/memory DR operations
 *    are not suppported.
 * 2) the maximum possible number of lgrps if CPU/memory DR operations are
 *    supported.
 */
int
lgrp_plat_max_lgrps(void)
{
	if (!lgrp_topo_initialized || plat_dr_support_cpu() ||
	    plat_dr_support_memory()) {
		return (lgrp_plat_node_cnt * (lgrp_plat_node_cnt - 1) + 1);
	} else {
		return (lgrp_alloc_max + 1);
	}
}


/*
 * Count number of memory pages (_t) based on mnode id (_n) and query type (_t).
 */
#define	_LGRP_PLAT_MEM_SIZE(_n, _q, _t)					\
	if (mem_node_config[_n].exists) {				\
		switch (_q) {						\
		case LGRP_MEM_SIZE_FREE:				\
			_t += MNODE_PGCNT(_n);				\
			break;						\
		case LGRP_MEM_SIZE_AVAIL:				\
			_t += mem_node_memlist_pages(_n, phys_avail);	\
				break;					\
		case LGRP_MEM_SIZE_INSTALL:				\
			_t += mem_node_memlist_pages(_n, phys_install);	\
			break;						\
		default:						\
			break;						\
		}							\
	}

/*
 * Return the number of free pages in an lgroup.
 *
 * For query of LGRP_MEM_SIZE_FREE, return the number of base pagesize
 * pages on freelists.  For query of LGRP_MEM_SIZE_AVAIL, return the
 * number of allocatable base pagesize pages corresponding to the
 * lgroup (e.g. do not include page_t's, BOP_ALLOC()'ed memory, ..)
 * For query of LGRP_MEM_SIZE_INSTALL, return the amount of physical
 * memory installed, regardless of whether or not it's usable.
 */
pgcnt_t
lgrp_plat_mem_size(lgrp_handle_t plathand, lgrp_mem_query_t query)
{
	int	mnode;
	pgcnt_t npgs = (pgcnt_t)0;
	extern struct memlist *phys_avail;
	extern struct memlist *phys_install;


	if (plathand == LGRP_DEFAULT_HANDLE)
		return (lgrp_plat_mem_size_default(plathand, query));

	if (plathand != LGRP_NULL_HANDLE) {
		/* Count memory node present at boot. */
		mnode = (int)plathand;
		ASSERT(mnode < lgrp_plat_node_cnt);
		_LGRP_PLAT_MEM_SIZE(mnode, query, npgs);

		/* Count possible hot-added memory nodes. */
		for (mnode = lgrp_plat_node_cnt;
		    mnode < lgrp_plat_max_mem_node; mnode++) {
			if (lgrp_plat_memnode_info[mnode].lgrphand == plathand)
				_LGRP_PLAT_MEM_SIZE(mnode, query, npgs);
		}
	}

	return (npgs);
}


/*
 * Return the platform handle of the lgroup that contains the physical memory
 * corresponding to the given page frame number
 */
lgrp_handle_t
lgrp_plat_pfn_to_hand(pfn_t pfn)
{
	int	mnode;

	if (max_mem_nodes == 1)
		return (LGRP_DEFAULT_HANDLE);

	if (pfn > physmax)
		return (LGRP_NULL_HANDLE);

	mnode = plat_pfn_to_mem_node(pfn);
	if (mnode < 0)
		return (LGRP_NULL_HANDLE);

	return (MEM_NODE_2_LGRPHAND(mnode));
}


/*
 * Probe memory in each node from current CPU to determine latency topology
 *
 * The probing code will probe the vendor ID register on the Northbridge of
 * Opteron processors and probe memory for other processors by default.
 *
 * Since probing is inherently error prone, the code takes laps across all the
 * nodes probing from each node to each of the other nodes some number of
 * times.  Furthermore, each node is probed some number of times before moving
 * onto the next one during each lap.  The minimum latency gotten between nodes
 * is kept as the latency between the nodes.
 *
 * After all that,  the probe times are adjusted by normalizing values that are
 * close to each other and local latencies are made the same.  Lastly, the
 * latencies are verified to make sure that certain conditions are met (eg.
 * local < remote, latency(a, b) == latency(b, a), etc.).
 *
 * If any of the conditions aren't met, the code will export a NUMA
 * configuration with the local CPUs and memory given by the SRAT or PCI config
 * space registers and one remote memory latency since it can't tell exactly
 * how far each node is from each other.
 */
void
lgrp_plat_probe(void)
{
	int				from;
	int				i;
	lgrp_plat_latency_stats_t	*lat_stats;
	boolean_t			probed;
	hrtime_t			probe_time;
	int				to;

	if (!(lgrp_plat_probe_flags & LGRP_PLAT_PROBE_ENABLE) ||
	    max_mem_nodes == 1 || lgrp_topo_ht_limit() <= 2)
		return;

	/* SRAT and SLIT should be enabled if DR operations are enabled. */
	if (plat_dr_support_cpu() || plat_dr_support_memory())
		return;

	/*
	 * Determine ID of node containing current CPU
	 */
	from = lgrp_plat_cpu_to_node(CPU, lgrp_plat_cpu_node,
	    lgrp_plat_cpu_node_nentries);
	ASSERT3U(from, <, lgrp_plat_node_cnt);
	if (from == (lgrp_handle_t)-1)
		return;
	if (srat_ptr && lgrp_plat_srat_enable && !lgrp_plat_srat_error)
		ASSERT(lgrp_plat_node_domain[from].exists);

	/*
	 * Don't need to probe if got times already
	 */
	lat_stats = &lgrp_plat_lat_stats;
	if (lat_stats->latencies[from][from] != 0)
		return;

	/*
	 * Read vendor ID in Northbridge or read and write page(s)
	 * in each node from current CPU and remember how long it takes,
	 * so we can build latency topology of machine later.
	 * This should approximate the memory latency between each node.
	 */
	probed = B_FALSE;
	for (i = 0; i < lgrp_plat_probe_nrounds; i++) {
		for (to = 0; to < lgrp_plat_node_cnt; to++) {
			/*
			 * Get probe time and skip over any nodes that can't be
			 * probed yet or don't have memory
			 */
			probe_time = lgrp_plat_probe_time(to,
			    lgrp_plat_cpu_node, lgrp_plat_cpu_node_nentries,
			    &lgrp_plat_probe_mem_config, &lgrp_plat_lat_stats,
			    &lgrp_plat_probe_stats);
			if (probe_time == 0)
				continue;

			probed = B_TRUE;

			/*
			 * Keep lowest probe time as latency between nodes
			 */
			if (lat_stats->latencies[from][to] == 0 ||
			    probe_time < lat_stats->latencies[from][to])
				lat_stats->latencies[from][to] = probe_time;

			/*
			 * Update overall minimum and maximum probe times
			 * across all nodes
			 */
			if (probe_time < lat_stats->latency_min ||
			    lat_stats->latency_min == -1)
				lat_stats->latency_min = probe_time;
			if (probe_time > lat_stats->latency_max)
				lat_stats->latency_max = probe_time;
		}
	}

	/*
	 * Bail out if weren't able to probe any nodes from current CPU
	 */
	if (probed == B_FALSE)
		return;

	/*
	 * - Fix up latencies such that local latencies are same,
	 *   latency(i, j) == latency(j, i), etc. (if possible)
	 *
	 * - Verify that latencies look ok
	 *
	 * - Fallback to just optimizing for local and remote if
	 *   latencies didn't look right
	 */
	lgrp_plat_latency_adjust(lgrp_plat_memnode_info, &lgrp_plat_lat_stats,
	    &lgrp_plat_probe_stats);
	lgrp_plat_probe_stats.probe_error_code =
	    lgrp_plat_latency_verify(lgrp_plat_memnode_info,
	    &lgrp_plat_lat_stats);
	if (lgrp_plat_probe_stats.probe_error_code)
		lgrp_plat_2level_setup(&lgrp_plat_lat_stats);
}


/*
 * Return platform handle for root lgroup
 */
lgrp_handle_t
lgrp_plat_root_hand(void)
{
	return (LGRP_DEFAULT_HANDLE);
}


/*
 * INTERNAL ROUTINES
 */


/*
 * Update CPU to node mapping for given CPU and proximity domain.
 * Return values:
 *	- zero for success
 *	- positive numbers for warnings
 *	- negative numbers for errors
 */
static int
lgrp_plat_cpu_node_update(node_domain_map_t *node_domain, int node_cnt,
    cpu_node_map_t *cpu_node, int nentries, uint32_t apicid, uint32_t domain)
{
	uint_t	i;
	int	node;

	/*
	 * Get node number for proximity domain
	 */
	node = lgrp_plat_domain_to_node(node_domain, node_cnt, domain);
	if (node == -1) {
		node = lgrp_plat_node_domain_update(node_domain, node_cnt,
		    domain);
		if (node == -1)
			return (-1);
	}

	/*
	 * Search for entry with given APIC ID and fill in its node and
	 * proximity domain IDs (if they haven't been set already)
	 */
	for (i = 0; i < nentries; i++) {
		/*
		 * Skip nonexistent entries and ones without matching APIC ID
		 */
		if (!cpu_node[i].exists || cpu_node[i].apicid != apicid)
			continue;

		/*
		 * Just return if entry completely and correctly filled in
		 * already
		 */
		if (cpu_node[i].prox_domain == domain &&
		    cpu_node[i].node == node)
			return (1);

		/*
		 * It's invalid to have more than one entry with the same
		 * local APIC ID in SRAT table.
		 */
		if (cpu_node[i].node != UINT_MAX)
			return (-2);

		/*
		 * Fill in node and proximity domain IDs
		 */
		cpu_node[i].prox_domain = domain;
		cpu_node[i].node = node;

		return (0);
	}

	/*
	 * It's possible that an apicid doesn't exist in the cpu_node map due
	 * to user limits number of CPUs powered on at boot by specifying the
	 * boot_ncpus kernel option.
	 */
	return (2);
}


/*
 * Get node ID for given CPU
 */
static int
lgrp_plat_cpu_to_node(cpu_t *cp, cpu_node_map_t *cpu_node,
    int cpu_node_nentries)
{
	processorid_t	cpuid;

	if (cp == NULL)
		return (-1);

	cpuid = cp->cpu_id;
	if (cpuid < 0 || cpuid >= max_ncpus)
		return (-1);

	/*
	 * SRAT doesn't exist, isn't enabled, or there was an error processing
	 * it, so return node ID for Opteron and -1 otherwise.
	 */
	if (srat_ptr == NULL || !lgrp_plat_srat_enable ||
	    lgrp_plat_srat_error) {
		if (is_opteron())
			return (pg_plat_hw_instance_id(cp, PGHW_PROCNODE));
		return (-1);
	}

	/*
	 * Return -1 when CPU to node ID mapping entry doesn't exist for given
	 * CPU
	 */
	if (cpuid >= cpu_node_nentries || !cpu_node[cpuid].exists)
		return (-1);

	return (cpu_node[cpuid].node);
}


/*
 * Return node number for given proximity domain/system locality
 */
static int
lgrp_plat_domain_to_node(node_domain_map_t *node_domain, int node_cnt,
    uint32_t domain)
{
	uint_t	node;
	uint_t	start;

	/*
	 * Hash proximity domain ID into node to domain mapping table (array),
	 * search for entry with matching proximity domain ID, and return index
	 * of matching entry as node ID.
	 */
	node = start = NODE_DOMAIN_HASH(domain, node_cnt);
	do {
		if (node_domain[node].exists) {
			membar_consumer();
			if (node_domain[node].prox_domain == domain)
				return (node);
		}
		node = (node + 1) % node_cnt;
	} while (node != start);
	return (-1);
}


/*
 * Get NUMA configuration of machine
 */
static void
lgrp_plat_get_numa_config(void)
{
	uint_t		probe_op;

	/*
	 * Read boot property with CPU to APIC ID mapping table/array to
	 * determine number of CPUs
	 */
	lgrp_plat_apic_ncpus = lgrp_plat_process_cpu_apicids(NULL);

	/*
	 * Determine which CPUs and memory are local to each other and number
	 * of NUMA nodes by reading ACPI System Resource Affinity Table (SRAT)
	 */
	if (lgrp_plat_apic_ncpus > 0) {
		int	retval;

		/* Reserve enough resources if CPU DR is enabled. */
		if (plat_dr_support_cpu() && max_ncpus > lgrp_plat_apic_ncpus)
			lgrp_plat_cpu_node_nentries = max_ncpus;
		else
			lgrp_plat_cpu_node_nentries = lgrp_plat_apic_ncpus;

		/*
		 * Temporarily allocate boot memory to use for CPU to node
		 * mapping since kernel memory allocator isn't alive yet
		 */
		lgrp_plat_cpu_node = (cpu_node_map_t *)BOP_ALLOC(bootops,
		    NULL, lgrp_plat_cpu_node_nentries * sizeof (cpu_node_map_t),
		    sizeof (int));

		ASSERT(lgrp_plat_cpu_node != NULL);
		if (lgrp_plat_cpu_node) {
			bzero(lgrp_plat_cpu_node, lgrp_plat_cpu_node_nentries *
			    sizeof (cpu_node_map_t));
		} else {
			lgrp_plat_cpu_node_nentries = 0;
		}

		/*
		 * Fill in CPU to node ID mapping table with APIC ID for each
		 * CPU
		 */
		(void) lgrp_plat_process_cpu_apicids(lgrp_plat_cpu_node);

		retval = lgrp_plat_process_srat(srat_ptr, msct_ptr,
		    &lgrp_plat_prox_domain_min,
		    lgrp_plat_node_domain, lgrp_plat_cpu_node,
		    lgrp_plat_apic_ncpus, lgrp_plat_memnode_info);
		if (retval <= 0) {
			lgrp_plat_srat_error = retval;
			lgrp_plat_node_cnt = 1;
		} else {
			lgrp_plat_srat_error = 0;
			lgrp_plat_node_cnt = retval;
		}
	}

	/*
	 * Try to use PCI config space registers on Opteron if there's an error
	 * processing CPU to APIC ID mapping or SRAT
	 */
	if ((lgrp_plat_apic_ncpus <= 0 || lgrp_plat_srat_error != 0) &&
	    is_opteron())
		opt_get_numa_config(&lgrp_plat_node_cnt, &lgrp_plat_mem_intrlv,
		    lgrp_plat_memnode_info);

	/*
	 * Don't bother to setup system for multiple lgroups and only use one
	 * memory node when memory is interleaved between any nodes or there is
	 * only one NUMA node
	 */
	if (lgrp_plat_mem_intrlv || lgrp_plat_node_cnt == 1) {
		lgrp_plat_node_cnt = max_mem_nodes = 1;
		(void) lgrp_topo_ht_limit_set(1);
		return;
	}

	/*
	 * Leaf lgroups on x86/x64 architectures contain one physical
	 * processor chip. Tune lgrp_expand_proc_thresh and
	 * lgrp_expand_proc_diff so that lgrp_choose() will spread
	 * things out aggressively.
	 */
	lgrp_expand_proc_thresh = LGRP_LOADAVG_THREAD_MAX / 2;
	lgrp_expand_proc_diff = 0;

	/*
	 * There should be one memnode (physical page free list(s)) for
	 * each node if memory DR is disabled.
	 */
	max_mem_nodes = lgrp_plat_node_cnt;

	/*
	 * Initialize min and max latency before reading SLIT or probing
	 */
	lgrp_plat_lat_stats.latency_min = -1;
	lgrp_plat_lat_stats.latency_max = 0;

	/*
	 * Determine how far each NUMA node is from each other by
	 * reading ACPI System Locality Information Table (SLIT) if it
	 * exists
	 */
	lgrp_plat_slit_error = lgrp_plat_process_slit(slit_ptr,
	    lgrp_plat_node_domain, lgrp_plat_node_cnt, lgrp_plat_memnode_info,
	    &lgrp_plat_lat_stats);

	/*
	 * Disable support of CPU/memory DR operations if multiple locality
	 * domains exist in system and either of following is true.
	 * 1) Failed to process SLIT table.
	 * 2) Latency probing is enabled by user.
	 */
	if (lgrp_plat_node_cnt > 1 &&
	    (plat_dr_support_cpu() || plat_dr_support_memory())) {
		if (!lgrp_plat_slit_enable || lgrp_plat_slit_error != 0 ||
		    !lgrp_plat_srat_enable || lgrp_plat_srat_error != 0 ||
		    lgrp_plat_apic_ncpus <= 0) {
			cmn_err(CE_CONT,
			    "?lgrp: failed to process ACPI SRAT/SLIT table, "
			    "disable support of CPU/memory DR operations.");
			plat_dr_disable_cpu();
			plat_dr_disable_memory();
		} else if (lgrp_plat_probe_flags & LGRP_PLAT_PROBE_ENABLE) {
			cmn_err(CE_CONT,
			    "?lgrp: latency probing enabled by user, "
			    "disable support of CPU/memory DR operations.");
			plat_dr_disable_cpu();
			plat_dr_disable_memory();
		}
	}

	/* Done if succeeded to process SLIT table. */
	if (lgrp_plat_slit_error == 0)
		return;

	/*
	 * Probe to determine latency between NUMA nodes when SLIT
	 * doesn't exist or make sense
	 */
	lgrp_plat_probe_flags |= LGRP_PLAT_PROBE_ENABLE;

	/*
	 * Specify whether to probe using vendor ID register or page copy
	 * if hasn't been specified already or is overspecified
	 */
	probe_op = lgrp_plat_probe_flags &
	    (LGRP_PLAT_PROBE_PGCPY|LGRP_PLAT_PROBE_VENDOR);

	if (probe_op == 0 ||
	    probe_op == (LGRP_PLAT_PROBE_PGCPY|LGRP_PLAT_PROBE_VENDOR)) {
		lgrp_plat_probe_flags &=
		    ~(LGRP_PLAT_PROBE_PGCPY|LGRP_PLAT_PROBE_VENDOR);
		if (is_opteron())
			lgrp_plat_probe_flags |=
			    LGRP_PLAT_PROBE_VENDOR;
		else
			lgrp_plat_probe_flags |= LGRP_PLAT_PROBE_PGCPY;
	}

	/*
	 * Probing errors can mess up the lgroup topology and
	 * force us fall back to a 2 level lgroup topology.
	 * Here we bound how tall the lgroup topology can grow
	 * in hopes of avoiding any anamolies in probing from
	 * messing up the lgroup topology by limiting the
	 * accuracy of the latency topology.
	 *
	 * Assume that nodes will at least be configured in a
	 * ring, so limit height of lgroup topology to be less
	 * than number of nodes on a system with 4 or more
	 * nodes
	 */
	if (lgrp_plat_node_cnt >= 4 && lgrp_topo_ht_limit() ==
	    lgrp_topo_ht_limit_default())
		(void) lgrp_topo_ht_limit_set(lgrp_plat_node_cnt - 1);
}


/*
 * Latencies must be within 1/(2**LGRP_LAT_TOLERANCE_SHIFT) of each other to
 * be considered same
 */
#define	LGRP_LAT_TOLERANCE_SHIFT	4

int	lgrp_plat_probe_lt_shift = LGRP_LAT_TOLERANCE_SHIFT;


/*
 * Adjust latencies between nodes to be symmetric, normalize latencies between
 * any nodes that are within some tolerance to be same, and make local
 * latencies be same
 */
static void
lgrp_plat_latency_adjust(memnode_phys_addr_map_t *memnode_info,
    lgrp_plat_latency_stats_t *lat_stats, lgrp_plat_probe_stats_t *probe_stats)
{
	int				i;
	int				j;
	int				k;
	int				l;
	u_longlong_t			max;
	u_longlong_t			min;
	u_longlong_t			t;
	u_longlong_t			t1;
	u_longlong_t			t2;
	const lgrp_config_flag_t	cflag = LGRP_CONFIG_LAT_CHANGE_ALL;
	int				lat_corrected[MAX_NODES][MAX_NODES];

	t = 0;
	/*
	 * Nothing to do when this is an UMA machine or don't have args needed
	 */
	if (max_mem_nodes == 1)
		return;

	ASSERT(memnode_info != NULL && lat_stats != NULL &&
	    probe_stats != NULL);

	/*
	 * Make sure that latencies are symmetric between any two nodes
	 * (ie. latency(node0, node1) == latency(node1, node0))
	 */
	for (i = 0; i < lgrp_plat_node_cnt; i++) {
		if (!memnode_info[i].exists)
			continue;

		for (j = 0; j < lgrp_plat_node_cnt; j++) {
			if (!memnode_info[j].exists)
				continue;

			t1 = lat_stats->latencies[i][j];
			t2 = lat_stats->latencies[j][i];

			if (t1 == 0 || t2 == 0 || t1 == t2)
				continue;

			/*
			 * Latencies should be same
			 * - Use minimum of two latencies which should be same
			 * - Track suspect probe times not within tolerance of
			 *   min value
			 * - Remember how much values are corrected by
			 */
			if (t1 > t2) {
				t = t2;
				probe_stats->probe_errors[i][j] += t1 - t2;
				if (t1 - t2 > t2 >> lgrp_plat_probe_lt_shift) {
					probe_stats->probe_suspect[i][j]++;
					probe_stats->probe_suspect[j][i]++;
				}
			} else if (t2 > t1) {
				t = t1;
				probe_stats->probe_errors[j][i] += t2 - t1;
				if (t2 - t1 > t1 >> lgrp_plat_probe_lt_shift) {
					probe_stats->probe_suspect[i][j]++;
					probe_stats->probe_suspect[j][i]++;
				}
			}

			lat_stats->latencies[i][j] =
			    lat_stats->latencies[j][i] = t;
			lgrp_config(cflag, t1, t);
			lgrp_config(cflag, t2, t);
		}
	}

	/*
	 * Keep track of which latencies get corrected
	 */
	for (i = 0; i < MAX_NODES; i++)
		for (j = 0; j < MAX_NODES; j++)
			lat_corrected[i][j] = 0;

	/*
	 * For every two nodes, see whether there is another pair of nodes which
	 * are about the same distance apart and make the latencies be the same
	 * if they are close enough together
	 */
	for (i = 0; i < lgrp_plat_node_cnt; i++) {
		for (j = 0; j < lgrp_plat_node_cnt; j++) {
			if (!memnode_info[j].exists)
				continue;
			/*
			 * Pick one pair of nodes (i, j)
			 * and get latency between them
			 */
			t1 = lat_stats->latencies[i][j];

			/*
			 * Skip this pair of nodes if there isn't a latency
			 * for it yet
			 */
			if (t1 == 0)
				continue;

			for (k = 0; k < lgrp_plat_node_cnt; k++) {
				for (l = 0; l < lgrp_plat_node_cnt; l++) {
					if (!memnode_info[l].exists)
						continue;
					/*
					 * Pick another pair of nodes (k, l)
					 * not same as (i, j) and get latency
					 * between them
					 */
					if (k == i && l == j)
						continue;

					t2 = lat_stats->latencies[k][l];

					/*
					 * Skip this pair of nodes if there
					 * isn't a latency for it yet
					 */

					if (t2 == 0)
						continue;

					/*
					 * Skip nodes (k, l) if they already
					 * have same latency as (i, j) or
					 * their latency isn't close enough to
					 * be considered/made the same
					 */
					if (t1 == t2 || (t1 > t2 && t1 - t2 >
					    t1 >> lgrp_plat_probe_lt_shift) ||
					    (t2 > t1 && t2 - t1 >
					    t2 >> lgrp_plat_probe_lt_shift))
						continue;

					/*
					 * Make latency(i, j) same as
					 * latency(k, l), try to use latency
					 * that has been adjusted already to get
					 * more consistency (if possible), and
					 * remember which latencies were
					 * adjusted for next time
					 */
					if (lat_corrected[i][j]) {
						t = t1;
						lgrp_config(cflag, t2, t);
						t2 = t;
					} else if (lat_corrected[k][l]) {
						t = t2;
						lgrp_config(cflag, t1, t);
						t1 = t;
					} else {
						if (t1 > t2)
							t = t2;
						else
							t = t1;
						lgrp_config(cflag, t1, t);
						lgrp_config(cflag, t2, t);
						t1 = t2 = t;
					}

					lat_stats->latencies[i][j] =
					    lat_stats->latencies[k][l] = t;

					lat_corrected[i][j] =
					    lat_corrected[k][l] = 1;
				}
			}
		}
	}

	/*
	 * Local latencies should be same
	 * - Find min and max local latencies
	 * - Make all local latencies be minimum
	 */
	min = -1;
	max = 0;
	for (i = 0; i < lgrp_plat_node_cnt; i++) {
		if (!memnode_info[i].exists)
			continue;
		t = lat_stats->latencies[i][i];
		if (t == 0)
			continue;
		if (min == -1 || t < min)
			min = t;
		if (t > max)
			max = t;
	}
	if (min != max) {
		for (i = 0; i < lgrp_plat_node_cnt; i++) {
			int	local;

			if (!memnode_info[i].exists)
				continue;

			local = lat_stats->latencies[i][i];
			if (local == 0)
				continue;

			/*
			 * Track suspect probe times that aren't within
			 * tolerance of minimum local latency and how much
			 * probe times are corrected by
			 */
			if (local - min > min >> lgrp_plat_probe_lt_shift)
				probe_stats->probe_suspect[i][i]++;

			probe_stats->probe_errors[i][i] += local - min;

			/*
			 * Make local latencies be minimum
			 */
			lgrp_config(LGRP_CONFIG_LAT_CHANGE, i, min);
			lat_stats->latencies[i][i] = min;
		}
	}

	/*
	 * Determine max probe time again since just adjusted latencies
	 */
	lat_stats->latency_max = 0;
	for (i = 0; i < lgrp_plat_node_cnt; i++) {
		for (j = 0; j < lgrp_plat_node_cnt; j++) {
			if (!memnode_info[j].exists)
				continue;
			t = lat_stats->latencies[i][j];
			if (t > lat_stats->latency_max)
				lat_stats->latency_max = t;
		}
	}
}


/*
 * Verify following about latencies between nodes:
 *
 * - Latencies should be symmetric (ie. latency(a, b) == latency(b, a))
 * - Local latencies same
 * - Local < remote
 * - Number of latencies seen is reasonable
 * - Number of occurrences of a given latency should be more than 1
 *
 * Returns:
 *	0	Success
 *	-1	Not symmetric
 *	-2	Local latencies not same
 *	-3	Local >= remote
 */
static int
lgrp_plat_latency_verify(memnode_phys_addr_map_t *memnode_info,
    lgrp_plat_latency_stats_t *lat_stats)
{
	int				i;
	int				j;
	u_longlong_t			t1;
	u_longlong_t			t2;

	ASSERT(memnode_info != NULL && lat_stats != NULL);

	/*
	 * Nothing to do when this is an UMA machine, lgroup topology is
	 * limited to 2 levels, or there aren't any probe times yet
	 */
	if (max_mem_nodes == 1 || lgrp_topo_levels < 2 ||
	    lat_stats->latencies[0][0] == 0)
		return (0);

	/*
	 * Make sure that latencies are symmetric between any two nodes
	 * (ie. latency(node0, node1) == latency(node1, node0))
	 */
	for (i = 0; i < lgrp_plat_node_cnt; i++) {
		if (!memnode_info[i].exists)
			continue;
		for (j = 0; j < lgrp_plat_node_cnt; j++) {
			if (!memnode_info[j].exists)
				continue;
			t1 = lat_stats->latencies[i][j];
			t2 = lat_stats->latencies[j][i];

			if (t1 == 0 || t2 == 0 || t1 == t2)
				continue;

			return (-1);
		}
	}

	/*
	 * Local latencies should be same
	 */
	t1 = lat_stats->latencies[0][0];
	for (i = 1; i < lgrp_plat_node_cnt; i++) {
		if (!memnode_info[i].exists)
			continue;

		t2 = lat_stats->latencies[i][i];
		if (t2 == 0)
			continue;

		if (t1 == 0) {
			t1 = t2;
			continue;
		}

		if (t1 != t2)
			return (-2);
	}

	/*
	 * Local latencies should be less than remote
	 */
	if (t1) {
		for (i = 0; i < lgrp_plat_node_cnt; i++) {
			for (j = 0; j < lgrp_plat_node_cnt; j++) {
				if (!memnode_info[j].exists)
					continue;
				t2 = lat_stats->latencies[i][j];
				if (i == j || t2 == 0)
					continue;

				if (t1 >= t2)
					return (-3);
			}
		}
	}

	return (0);
}


/*
 * Platform-specific initialization
 */
static void
lgrp_plat_main_init(void)
{
	int	curnode;
	int	ht_limit;
	int	i;

	/*
	 * Print a notice that MPO is disabled when memory is interleaved
	 * across nodes....Would do this when it is discovered, but can't
	 * because it happens way too early during boot....
	 */
	if (lgrp_plat_mem_intrlv)
		cmn_err(CE_NOTE,
		    "MPO disabled because memory is interleaved\n");

	/*
	 * Don't bother to do any probing if it is disabled, there is only one
	 * node, or the height of the lgroup topology less than or equal to 2
	 */
	ht_limit = lgrp_topo_ht_limit();
	if (!(lgrp_plat_probe_flags & LGRP_PLAT_PROBE_ENABLE) ||
	    max_mem_nodes == 1 || ht_limit <= 2) {
		/*
		 * Setup lgroup latencies for 2 level lgroup topology
		 * (ie. local and remote only) if they haven't been set yet
		 */
		if (ht_limit == 2 && lgrp_plat_lat_stats.latency_min == -1 &&
		    lgrp_plat_lat_stats.latency_max == 0)
			lgrp_plat_2level_setup(&lgrp_plat_lat_stats);
		return;
	}

	if (lgrp_plat_probe_flags & LGRP_PLAT_PROBE_VENDOR) {
		/*
		 * Should have been able to probe from CPU 0 when it was added
		 * to lgroup hierarchy, but may not have been able to then
		 * because it happens so early in boot that gethrtime() hasn't
		 * been initialized.  (:-(
		 */
		curnode = lgrp_plat_cpu_to_node(CPU, lgrp_plat_cpu_node,
		    lgrp_plat_cpu_node_nentries);
		ASSERT3U(curnode, <, lgrp_plat_node_cnt);
		if (curnode == (lgrp_handle_t)-1)
			return;
		if (lgrp_plat_lat_stats.latencies[curnode][curnode] == 0)
			lgrp_plat_probe();

		return;
	}

	/*
	 * When probing memory, use one page for every sample to determine
	 * lgroup topology and taking multiple samples
	 */
	if (lgrp_plat_probe_mem_config.probe_memsize == 0)
		lgrp_plat_probe_mem_config.probe_memsize = PAGESIZE *
		    lgrp_plat_probe_nsamples;

	/*
	 * Map memory in each node needed for probing to determine latency
	 * topology
	 */
	for (i = 0; i < lgrp_plat_node_cnt; i++) {
		int	mnode;

		/*
		 * Skip this node and leave its probe page NULL
		 * if it doesn't have any memory
		 */
		mnode = i;
		if (!mem_node_config[mnode].exists) {
			lgrp_plat_probe_mem_config.probe_va[i] = NULL;
			continue;
		}

		/*
		 * Allocate one kernel virtual page
		 */
		lgrp_plat_probe_mem_config.probe_va[i] = vmem_alloc(heap_arena,
		    lgrp_plat_probe_mem_config.probe_memsize, VM_NOSLEEP);
		if (lgrp_plat_probe_mem_config.probe_va[i] == NULL) {
			cmn_err(CE_WARN,
			    "lgrp_plat_main_init: couldn't allocate memory");
			return;
		}

		/*
		 * Get PFN for first page in each node
		 */
		lgrp_plat_probe_mem_config.probe_pfn[i] =
		    mem_node_config[mnode].physbase;

		/*
		 * Map virtual page to first page in node
		 */
		hat_devload(kas.a_hat, lgrp_plat_probe_mem_config.probe_va[i],
		    lgrp_plat_probe_mem_config.probe_memsize,
		    lgrp_plat_probe_mem_config.probe_pfn[i],
		    PROT_READ | PROT_WRITE | HAT_PLAT_NOCACHE,
		    HAT_LOAD_NOCONSIST);
	}

	/*
	 * Probe from current CPU
	 */
	lgrp_plat_probe();
}


/*
 * Return the number of free, allocatable, or installed
 * pages in an lgroup
 * This is a copy of the MAX_MEM_NODES == 1 version of the routine
 * used when MPO is disabled (i.e. single lgroup) or this is the root lgroup
 */
static pgcnt_t
lgrp_plat_mem_size_default(lgrp_handle_t lgrphand, lgrp_mem_query_t query)
{
	_NOTE(ARGUNUSED(lgrphand));

	struct memlist *mlist;
	pgcnt_t npgs = 0;
	extern struct memlist *phys_avail;
	extern struct memlist *phys_install;

	switch (query) {
	case LGRP_MEM_SIZE_FREE:
		return ((pgcnt_t)freemem);
	case LGRP_MEM_SIZE_AVAIL:
		memlist_read_lock();
		for (mlist = phys_avail; mlist; mlist = mlist->ml_next)
			npgs += btop(mlist->ml_size);
		memlist_read_unlock();
		return (npgs);
	case LGRP_MEM_SIZE_INSTALL:
		memlist_read_lock();
		for (mlist = phys_install; mlist; mlist = mlist->ml_next)
			npgs += btop(mlist->ml_size);
		memlist_read_unlock();
		return (npgs);
	default:
		return ((pgcnt_t)0);
	}
}


/*
 * Update node to proximity domain mappings for given domain and return node ID
 */
static int
lgrp_plat_node_domain_update(node_domain_map_t *node_domain, int node_cnt,
    uint32_t domain)
{
	uint_t	node;
	uint_t	start;

	/*
	 * Hash proximity domain ID into node to domain mapping table (array)
	 * and add entry for it into first non-existent or matching entry found
	 */
	node = start = NODE_DOMAIN_HASH(domain, node_cnt);
	do {
		/*
		 * Entry doesn't exist yet, so create one for this proximity
		 * domain and return node ID which is index into mapping table.
		 */
		if (!node_domain[node].exists) {
			node_domain[node].prox_domain = domain;
			membar_producer();
			node_domain[node].exists = 1;
			return (node);
		}

		/*
		 * Entry exists for this proximity domain already, so just
		 * return node ID (index into table).
		 */
		if (node_domain[node].prox_domain == domain)
			return (node);
		node = NODE_DOMAIN_HASH(node + 1, node_cnt);
	} while (node != start);

	/*
	 * Ran out of supported number of entries which shouldn't happen....
	 */
	ASSERT(node != start);
	return (-1);
}

/*
 * Update node memory information for given proximity domain with specified
 * starting and ending physical address range (and return positive numbers for
 * success and negative ones for errors)
 */
static int
lgrp_plat_memnode_info_update(node_domain_map_t *node_domain, int node_cnt,
    memnode_phys_addr_map_t *memnode_info, int memnode_cnt, uint64_t start,
    uint64_t end, uint32_t domain, uint32_t device_id)
{
	int	node, mnode;

	/*
	 * Get node number for proximity domain
	 */
	node = lgrp_plat_domain_to_node(node_domain, node_cnt, domain);
	if (node == -1) {
		node = lgrp_plat_node_domain_update(node_domain, node_cnt,
		    domain);
		if (node == -1)
			return (-1);
	}

	/*
	 * This function is called during boot if device_id is
	 * ACPI_MEMNODE_DEVID_BOOT, otherwise it's called at runtime for
	 * memory DR operations.
	 */
	if (device_id != ACPI_MEMNODE_DEVID_BOOT) {
		ASSERT(lgrp_plat_max_mem_node <= memnode_cnt);

		for (mnode = lgrp_plat_node_cnt;
		    mnode < lgrp_plat_max_mem_node; mnode++) {
			if (memnode_info[mnode].exists &&
			    memnode_info[mnode].prox_domain == domain &&
			    memnode_info[mnode].device_id == device_id) {
				if (btop(start) < memnode_info[mnode].start)
					memnode_info[mnode].start = btop(start);
				if (btop(end) > memnode_info[mnode].end)
					memnode_info[mnode].end = btop(end);
				return (1);
			}
		}

		if (lgrp_plat_max_mem_node >= memnode_cnt) {
			return (-3);
		} else {
			lgrp_plat_max_mem_node++;
			memnode_info[mnode].start = btop(start);
			memnode_info[mnode].end = btop(end);
			memnode_info[mnode].prox_domain = domain;
			memnode_info[mnode].device_id = device_id;
			memnode_info[mnode].lgrphand = node;
			membar_producer();
			memnode_info[mnode].exists = 1;
			return (0);
		}
	}

	/*
	 * Create entry in table for node if it doesn't exist
	 */
	ASSERT(node < memnode_cnt);
	if (!memnode_info[node].exists) {
		memnode_info[node].start = btop(start);
		memnode_info[node].end = btop(end);
		memnode_info[node].prox_domain = domain;
		memnode_info[node].device_id = device_id;
		memnode_info[node].lgrphand = node;
		membar_producer();
		memnode_info[node].exists = 1;
		return (0);
	}

	/*
	 * Entry already exists for this proximity domain
	 *
	 * There may be more than one SRAT memory entry for a domain, so we may
	 * need to update existing start or end address for the node.
	 */
	if (memnode_info[node].prox_domain == domain) {
		if (btop(start) < memnode_info[node].start)
			memnode_info[node].start = btop(start);
		if (btop(end) > memnode_info[node].end)
			memnode_info[node].end = btop(end);
		return (1);
	}
	return (-2);
}


/*
 * Have to sort nodes by starting physical address because plat_mnode_xcheck()
 * assumes and expects memnodes to be sorted in ascending order by physical
 * address.
 */
static void
lgrp_plat_node_sort(node_domain_map_t *node_domain, int node_cnt,
    cpu_node_map_t *cpu_node, int cpu_count,
    memnode_phys_addr_map_t *memnode_info)
{
	boolean_t	found;
	int		i;
	int		j;
	int		n;
	boolean_t	sorted;
	boolean_t	swapped;

	if (!lgrp_plat_node_sort_enable || node_cnt <= 1 ||
	    node_domain == NULL || memnode_info == NULL)
		return;

	/*
	 * Sorted already?
	 */
	sorted = B_TRUE;
	for (i = 0; i < node_cnt - 1; i++) {
		/*
		 * Skip entries that don't exist
		 */
		if (!memnode_info[i].exists)
			continue;

		/*
		 * Try to find next existing entry to compare against
		 */
		found = B_FALSE;
		for (j = i + 1; j < node_cnt; j++) {
			if (memnode_info[j].exists) {
				found = B_TRUE;
				break;
			}
		}

		/*
		 * Done if no more existing entries to compare against
		 */
		if (found == B_FALSE)
			break;

		/*
		 * Not sorted if starting address of current entry is bigger
		 * than starting address of next existing entry
		 */
		if (memnode_info[i].start > memnode_info[j].start) {
			sorted = B_FALSE;
			break;
		}
	}

	/*
	 * Don't need to sort if sorted already
	 */
	if (sorted == B_TRUE)
		return;

	/*
	 * Just use bubble sort since number of nodes is small
	 */
	n = node_cnt;
	do {
		swapped = B_FALSE;
		n--;
		for (i = 0; i < n; i++) {
			/*
			 * Skip entries that don't exist
			 */
			if (!memnode_info[i].exists)
				continue;

			/*
			 * Try to find next existing entry to compare against
			 */
			found = B_FALSE;
			for (j = i + 1; j <= n; j++) {
				if (memnode_info[j].exists) {
					found = B_TRUE;
					break;
				}
			}

			/*
			 * Done if no more existing entries to compare against
			 */
			if (found == B_FALSE)
				break;

			if (memnode_info[i].start > memnode_info[j].start) {
				memnode_phys_addr_map_t	save_addr;
				node_domain_map_t	save_node;

				/*
				 * Swap node to proxmity domain ID assignments
				 */
				bcopy(&node_domain[i], &save_node,
				    sizeof (node_domain_map_t));
				bcopy(&node_domain[j], &node_domain[i],
				    sizeof (node_domain_map_t));
				bcopy(&save_node, &node_domain[j],
				    sizeof (node_domain_map_t));

				/*
				 * Swap node to physical memory assignments
				 */
				bcopy(&memnode_info[i], &save_addr,
				    sizeof (memnode_phys_addr_map_t));
				bcopy(&memnode_info[j], &memnode_info[i],
				    sizeof (memnode_phys_addr_map_t));
				bcopy(&save_addr, &memnode_info[j],
				    sizeof (memnode_phys_addr_map_t));
				swapped = B_TRUE;
			}
		}
	} while (swapped == B_TRUE);

	/*
	 * Check to make sure that CPUs assigned to correct node IDs now since
	 * node to proximity domain ID assignments may have been changed above
	 */
	if (n == node_cnt - 1 || cpu_node == NULL || cpu_count < 1)
		return;
	for (i = 0; i < cpu_count; i++) {
		int		node;

		node = lgrp_plat_domain_to_node(node_domain, node_cnt,
		    cpu_node[i].prox_domain);
		if (cpu_node[i].node != node)
			cpu_node[i].node = node;
	}

}


/*
 * Return time needed to probe from current CPU to memory in given node
 */
static hrtime_t
lgrp_plat_probe_time(int to, cpu_node_map_t *cpu_node, int cpu_node_nentries,
    lgrp_plat_probe_mem_config_t *probe_mem_config,
    lgrp_plat_latency_stats_t *lat_stats, lgrp_plat_probe_stats_t *probe_stats)
{
	caddr_t			buf;
	hrtime_t		elapsed;
	hrtime_t		end;
	int			from;
	int			i;
	int			ipl;
	hrtime_t		max;
	hrtime_t		min;
	hrtime_t		start;
	extern int		use_sse_pagecopy;

	/*
	 * Determine ID of node containing current CPU
	 */
	from = lgrp_plat_cpu_to_node(CPU, cpu_node, cpu_node_nentries);
	ASSERT3U(from, <, lgrp_plat_node_cnt);
	if (from == (lgrp_handle_t)-1)
		return (0);

	/*
	 * Do common work for probing main memory
	 */
	if (lgrp_plat_probe_flags & LGRP_PLAT_PROBE_PGCPY) {
		/*
		 * Skip probing any nodes without memory and
		 * set probe time to 0
		 */
		if (probe_mem_config->probe_va[to] == NULL) {
			lat_stats->latencies[from][to] = 0;
			return (0);
		}

		/*
		 * Invalidate caches once instead of once every sample
		 * which should cut cost of probing by a lot
		 */
		probe_stats->flush_cost = gethrtime();
		invalidate_cache();
		probe_stats->flush_cost = gethrtime() -
		    probe_stats->flush_cost;
		probe_stats->probe_cost_total += probe_stats->flush_cost;
	}

	/*
	 * Probe from current CPU to given memory using specified operation
	 * and take specified number of samples
	 */
	max = 0;
	min = -1;
	for (i = 0; i < lgrp_plat_probe_nsamples; i++) {
		probe_stats->probe_cost = gethrtime();

		/*
		 * Can't measure probe time if gethrtime() isn't working yet
		 */
		if (probe_stats->probe_cost == 0 && gethrtime() == 0)
			return (0);

		if (lgrp_plat_probe_flags & LGRP_PLAT_PROBE_VENDOR) {
			/*
			 * Measure how long it takes to read vendor ID from
			 * Northbridge
			 */
			elapsed = opt_probe_vendor(to, lgrp_plat_probe_nreads);
		} else {
			/*
			 * Measure how long it takes to copy page
			 * on top of itself
			 */
			buf = probe_mem_config->probe_va[to] + (i * PAGESIZE);

			kpreempt_disable();
			ipl = splhigh();
			start = gethrtime();
			if (use_sse_pagecopy)
				hwblkpagecopy(buf, buf);
			else
				bcopy(buf, buf, PAGESIZE);
			end = gethrtime();
			elapsed = end - start;
			splx(ipl);
			kpreempt_enable();
		}

		probe_stats->probe_cost = gethrtime() -
		    probe_stats->probe_cost;
		probe_stats->probe_cost_total += probe_stats->probe_cost;

		if (min == -1 || elapsed < min)
			min = elapsed;
		if (elapsed > max)
			max = elapsed;
	}

	/*
	 * Update minimum and maximum probe times between
	 * these two nodes
	 */
	if (min < probe_stats->probe_min[from][to] ||
	    probe_stats->probe_min[from][to] == 0)
		probe_stats->probe_min[from][to] = min;

	if (max > probe_stats->probe_max[from][to])
		probe_stats->probe_max[from][to] = max;

	return (min);
}


/*
 * Read boot property with CPU to APIC ID array, fill in CPU to node ID
 * mapping table with APIC ID for each CPU (if pointer to table isn't NULL),
 * and return number of CPU APIC IDs.
 *
 * NOTE: This code assumes that CPU IDs are assigned in order that they appear
 *       in in cpu_apicid_array boot property which is based on and follows
 *	 same ordering as processor list in ACPI MADT.  If the code in
 *	 usr/src/uts/i86pc/io/pcplusmp/apic.c that reads MADT and assigns
 *	 CPU IDs ever changes, then this code will need to change too....
 */
static int
lgrp_plat_process_cpu_apicids(cpu_node_map_t *cpu_node)
{
	int	boot_prop_len;
	char	*boot_prop_name = BP_CPU_APICID_ARRAY;
	uint32_t *cpu_apicid_array;
	int	i;
	int	n;

	/*
	 * Check length of property value
	 */
	boot_prop_len = BOP_GETPROPLEN(bootops, boot_prop_name);
	if (boot_prop_len <= 0)
		return (-1);

	/*
	 * Calculate number of entries in array and return when the system is
	 * not very interesting for NUMA. It's not interesting for NUMA if
	 * system has only one CPU and doesn't support CPU hotplug.
	 */
	n = boot_prop_len / sizeof (*cpu_apicid_array);
	if (n == 1 && !plat_dr_support_cpu())
		return (-2);

	cpu_apicid_array = (uint32_t *)BOP_ALLOC(bootops, NULL, boot_prop_len,
	    sizeof (*cpu_apicid_array));
	/*
	 * Get CPU to APIC ID property value
	 */
	if (cpu_apicid_array == NULL ||
	    BOP_GETPROP(bootops, boot_prop_name, cpu_apicid_array) < 0)
		return (-3);

	/*
	 * Just return number of CPU APIC IDs if CPU to node mapping table is
	 * NULL
	 */
	if (cpu_node == NULL) {
		if (plat_dr_support_cpu() && n >= boot_ncpus) {
			return (boot_ncpus);
		} else {
			return (n);
		}
	}

	/*
	 * Fill in CPU to node ID mapping table with APIC ID for each CPU
	 */
	for (i = 0; i < n; i++) {
		/* Only add boot CPUs into the map if CPU DR is enabled. */
		if (plat_dr_support_cpu() && i >= boot_ncpus)
			break;
		cpu_node[i].exists = 1;
		cpu_node[i].apicid = cpu_apicid_array[i];
		cpu_node[i].prox_domain = UINT32_MAX;
		cpu_node[i].node = UINT_MAX;
	}

	/*
	 * Return number of CPUs based on number of APIC IDs
	 */
	return (i);
}


/*
 * Read ACPI System Locality Information Table (SLIT) to determine how far each
 * NUMA node is from each other
 */
static int
lgrp_plat_process_slit(ACPI_TABLE_SLIT *tp,
    node_domain_map_t *node_domain, uint_t node_cnt,
    memnode_phys_addr_map_t *memnode_info, lgrp_plat_latency_stats_t *lat_stats)
{
	int		i;
	int		j;
	int		src;
	int		dst;
	int		localities;
	hrtime_t	max;
	hrtime_t	min;
	int		retval;
	uint8_t		*slit_entries;

	if (tp == NULL || !lgrp_plat_slit_enable)
		return (1);

	if (lat_stats == NULL)
		return (2);

	localities = tp->LocalityCount;

	min = lat_stats->latency_min;
	max = lat_stats->latency_max;

	/*
	 * Fill in latency matrix based on SLIT entries
	 */
	slit_entries = tp->Entry;
	for (i = 0; i < localities; i++) {
		src = lgrp_plat_domain_to_node(node_domain,
		    node_cnt, i);
		if (src == -1)
			continue;

		for (j = 0; j < localities; j++) {
			uint8_t	latency;

			dst = lgrp_plat_domain_to_node(node_domain,
			    node_cnt, j);
			if (dst == -1)
				continue;

			latency = slit_entries[(i * localities) + j];
			lat_stats->latencies[src][dst] = latency;
			if (latency < min || min == -1)
				min = latency;
			if (latency > max)
				max = latency;
		}
	}

	/*
	 * Verify that latencies/distances given in SLIT look reasonable
	 */
	retval = lgrp_plat_latency_verify(memnode_info, lat_stats);

	if (retval) {
		/*
		 * Reinitialize (zero) latency table since SLIT doesn't look
		 * right
		 */
		for (i = 0; i < localities; i++) {
			for (j = 0; j < localities; j++)
				lat_stats->latencies[i][j] = 0;
		}
	} else {
		/*
		 * Update min and max latencies seen since SLIT looks valid
		 */
		lat_stats->latency_min = min;
		lat_stats->latency_max = max;
	}

	return (retval);
}


/*
 * Update lgrp latencies according to information returned by ACPI _SLI method.
 */
static int
lgrp_plat_process_sli(uint32_t domain_id, uchar_t *sli_info,
    uint32_t sli_cnt, node_domain_map_t *node_domain, uint_t node_cnt,
    lgrp_plat_latency_stats_t *lat_stats)
{
	int		i;
	int		src, dst;
	uint8_t		latency;
	hrtime_t	max, min;

	if (lat_stats == NULL || sli_info == NULL ||
	    sli_cnt == 0 || domain_id >= sli_cnt)
		return (-1);

	src = lgrp_plat_domain_to_node(node_domain, node_cnt, domain_id);
	if (src == -1) {
		src = lgrp_plat_node_domain_update(node_domain, node_cnt,
		    domain_id);
		if (src == -1)
			return (-1);
	}

	/*
	 * Don't update latency info if topology has been flattened to 2 levels.
	 */
	if (lgrp_plat_topo_flatten != 0) {
		return (0);
	}

	/*
	 * Latency information for proximity domain is ready.
	 * TODO: support adjusting latency information at runtime.
	 */
	if (lat_stats->latencies[src][src] != 0) {
		return (0);
	}

	/* Validate latency information. */
	for (i = 0; i < sli_cnt; i++) {
		if (i == domain_id) {
			if (sli_info[i] != ACPI_SLIT_SELF_LATENCY ||
			    sli_info[sli_cnt + i] != ACPI_SLIT_SELF_LATENCY) {
				return (-1);
			}
		} else {
			if (sli_info[i] <= ACPI_SLIT_SELF_LATENCY ||
			    sli_info[sli_cnt + i] <= ACPI_SLIT_SELF_LATENCY ||
			    sli_info[i] != sli_info[sli_cnt + i]) {
				return (-1);
			}
		}
	}

	min = lat_stats->latency_min;
	max = lat_stats->latency_max;
	for (i = 0; i < sli_cnt; i++) {
		dst = lgrp_plat_domain_to_node(node_domain, node_cnt, i);
		if (dst == -1)
			continue;

		ASSERT(sli_info[i] == sli_info[sli_cnt + i]);

		/* Update row in latencies matrix. */
		latency = sli_info[i];
		lat_stats->latencies[src][dst] = latency;
		if (latency < min || min == -1)
			min = latency;
		if (latency > max)
			max = latency;

		/* Update column in latencies matrix. */
		latency = sli_info[sli_cnt + i];
		lat_stats->latencies[dst][src] = latency;
		if (latency < min || min == -1)
			min = latency;
		if (latency > max)
			max = latency;
	}
	lat_stats->latency_min = min;
	lat_stats->latency_max = max;

	return (0);
}


/*
 * Read ACPI System Resource Affinity Table (SRAT) to determine which CPUs
 * and memory are local to each other in the same NUMA node and return number
 * of nodes
 */
static int
lgrp_plat_process_srat(ACPI_TABLE_SRAT *tp, ACPI_TABLE_MSCT *mp,
    uint32_t *prox_domain_min, node_domain_map_t *node_domain,
    cpu_node_map_t *cpu_node, int cpu_count,
    memnode_phys_addr_map_t *memnode_info)
{
	ACPI_SUBTABLE_HEADER	*item, *srat_end;
	int			i;
	int			node_cnt;
	int			proc_entry_count;
	int			rc;

	/*
	 * Nothing to do when no SRAT or disabled
	 */
	if (tp == NULL || !lgrp_plat_srat_enable)
		return (-1);

	/*
	 * Try to get domain information from MSCT table.
	 * ACPI4.0: OSPM will use information provided by the MSCT only
	 * when the System Resource Affinity Table (SRAT) exists.
	 */
	node_cnt = lgrp_plat_msct_domains(mp, prox_domain_min);
	if (node_cnt <= 0) {
		/*
		 * Determine number of nodes by counting number of proximity
		 * domains in SRAT.
		 */
		node_cnt = lgrp_plat_srat_domains(tp, prox_domain_min);
	}
	/*
	 * Return if number of nodes is 1 or less since don't need to read SRAT.
	 */
	if (node_cnt == 1)
		return (1);
	else if (node_cnt <= 0)
		return (-2);

	/*
	 * Walk through SRAT, examining each CPU and memory entry to determine
	 * which CPUs and memory belong to which node.
	 */
	item = (ACPI_SUBTABLE_HEADER *)((uintptr_t)tp + sizeof (*tp));
	srat_end = (ACPI_SUBTABLE_HEADER *)(tp->Header.Length + (uintptr_t)tp);
	proc_entry_count = 0;
	while (item < srat_end) {
		uint32_t	apic_id;
		uint32_t	domain;
		uint64_t	end;
		uint64_t	length;
		uint64_t	start;

		switch (item->Type) {
		case ACPI_SRAT_TYPE_CPU_AFFINITY: {	/* CPU entry */
			ACPI_SRAT_CPU_AFFINITY *cpu =
			    (ACPI_SRAT_CPU_AFFINITY *) item;

			if (!(cpu->Flags & ACPI_SRAT_CPU_ENABLED) ||
			    cpu_node == NULL)
				break;

			/*
			 * Calculate domain (node) ID and fill in APIC ID to
			 * domain/node mapping table
			 */
			domain = cpu->ProximityDomainLo;
			for (i = 0; i < 3; i++) {
				domain += cpu->ProximityDomainHi[i] <<
				    ((i + 1) * 8);
			}
			apic_id = cpu->ApicId;

			rc = lgrp_plat_cpu_node_update(node_domain, node_cnt,
			    cpu_node, cpu_count, apic_id, domain);
			if (rc < 0)
				return (-3);
			else if (rc == 0)
				proc_entry_count++;
			break;
		}
		case ACPI_SRAT_TYPE_MEMORY_AFFINITY: {	/* memory entry */
			ACPI_SRAT_MEM_AFFINITY *mem =
			    (ACPI_SRAT_MEM_AFFINITY *)item;

			if (!(mem->Flags & ACPI_SRAT_MEM_ENABLED) ||
			    memnode_info == NULL)
				break;

			/*
			 * Get domain (node) ID and fill in domain/node
			 * to memory mapping table
			 */
			domain = mem->ProximityDomain;
			start = mem->BaseAddress;
			length = mem->Length;
			end = start + length - 1;

			/*
			 * According to ACPI 4.0, both ENABLE and HOTPLUG flags
			 * may be set for memory address range entries in SRAT
			 * table which are reserved for memory hot plug.
			 * We intersect memory address ranges in SRAT table
			 * with memory ranges in physinstalled to filter out
			 * memory address ranges reserved for hot plug.
			 */
			if (mem->Flags & ACPI_SRAT_MEM_HOT_PLUGGABLE) {
				uint64_t	rstart = UINT64_MAX;
				uint64_t	rend = 0;
				struct memlist	*ml;
				extern struct bootops	*bootops;

				memlist_read_lock();
				for (ml = bootops->boot_mem->physinstalled;
				    ml; ml = ml->ml_next) {
					uint64_t tstart = ml->ml_address;
					uint64_t tend;

					tend = ml->ml_address + ml->ml_size;
					if (tstart > end || tend < start)
						continue;
					if (start > tstart)
						tstart = start;
					if (rstart > tstart)
						rstart = tstart;
					if (end < tend)
						tend = end;
					if (rend < tend)
						rend = tend;
				}
				memlist_read_unlock();
				start = rstart;
				end = rend;
				/* Skip this entry if no memory installed. */
				if (start > end)
					break;
			}

			if (lgrp_plat_memnode_info_update(node_domain,
			    node_cnt, memnode_info, node_cnt,
			    start, end, domain, ACPI_MEMNODE_DEVID_BOOT) < 0)
				return (-4);
			break;
		}
		case ACPI_SRAT_TYPE_X2APIC_CPU_AFFINITY: {	/* x2apic CPU */
			ACPI_SRAT_X2APIC_CPU_AFFINITY *x2cpu =
			    (ACPI_SRAT_X2APIC_CPU_AFFINITY *) item;

			if (!(x2cpu->Flags & ACPI_SRAT_CPU_ENABLED) ||
			    cpu_node == NULL)
				break;

			/*
			 * Calculate domain (node) ID and fill in APIC ID to
			 * domain/node mapping table
			 */
			domain = x2cpu->ProximityDomain;
			apic_id = x2cpu->ApicId;

			rc = lgrp_plat_cpu_node_update(node_domain, node_cnt,
			    cpu_node, cpu_count, apic_id, domain);
			if (rc < 0)
				return (-3);
			else if (rc == 0)
				proc_entry_count++;
			break;
		}
		default:
			break;
		}

		item = (ACPI_SUBTABLE_HEADER *)((uintptr_t)item + item->Length);
	}

	/*
	 * Should have seen at least as many SRAT processor entries as CPUs
	 */
	if (proc_entry_count < cpu_count)
		return (-5);

	/*
	 * Need to sort nodes by starting physical address since VM system
	 * assumes and expects memnodes to be sorted in ascending order by
	 * physical address
	 */
	lgrp_plat_node_sort(node_domain, node_cnt, cpu_node, cpu_count,
	    memnode_info);

	return (node_cnt);
}


/*
 * Allocate permanent memory for any temporary memory that we needed to
 * allocate using BOP_ALLOC() before kmem_alloc() and VM system were
 * initialized and copy everything from temporary to permanent memory since
 * temporary boot memory will eventually be released during boot
 */
static void
lgrp_plat_release_bootstrap(void)
{
	void	*buf;
	size_t	size;

	if (lgrp_plat_cpu_node_nentries > 0) {
		size = lgrp_plat_cpu_node_nentries * sizeof (cpu_node_map_t);
		buf = kmem_alloc(size, KM_SLEEP);
		bcopy(lgrp_plat_cpu_node, buf, size);
		lgrp_plat_cpu_node = buf;
	}
}


/*
 * Return number of proximity domains given in ACPI SRAT
 */
static int
lgrp_plat_srat_domains(ACPI_TABLE_SRAT *tp, uint32_t *prox_domain_min)
{
	int			domain_cnt;
	uint32_t		domain_min;
	ACPI_SUBTABLE_HEADER	*item, *end;
	int			i;
	node_domain_map_t	node_domain[MAX_NODES];


	if (tp == NULL || !lgrp_plat_srat_enable)
		return (1);

	/*
	 * Walk through SRAT to find minimum proximity domain ID
	 */
	domain_min = UINT32_MAX;
	item = (ACPI_SUBTABLE_HEADER *)((uintptr_t)tp + sizeof (*tp));
	end = (ACPI_SUBTABLE_HEADER *)(tp->Header.Length + (uintptr_t)tp);
	while (item < end) {
		uint32_t	domain;

		switch (item->Type) {
		case ACPI_SRAT_TYPE_CPU_AFFINITY: {	/* CPU entry */
			ACPI_SRAT_CPU_AFFINITY *cpu =
			    (ACPI_SRAT_CPU_AFFINITY *) item;

			if (!(cpu->Flags & ACPI_SRAT_CPU_ENABLED)) {
				item = (ACPI_SUBTABLE_HEADER *)
				    ((uintptr_t)item + item->Length);
				continue;
			}
			domain = cpu->ProximityDomainLo;
			for (i = 0; i < 3; i++) {
				domain += cpu->ProximityDomainHi[i] <<
				    ((i + 1) * 8);
			}
			break;
		}
		case ACPI_SRAT_TYPE_MEMORY_AFFINITY: {	/* memory entry */
			ACPI_SRAT_MEM_AFFINITY *mem =
			    (ACPI_SRAT_MEM_AFFINITY *)item;

			if (!(mem->Flags & ACPI_SRAT_MEM_ENABLED)) {
				item = (ACPI_SUBTABLE_HEADER *)
				    ((uintptr_t)item + item->Length);
				continue;
			}
			domain = mem->ProximityDomain;
			break;
		}
		case ACPI_SRAT_TYPE_X2APIC_CPU_AFFINITY: {	/* x2apic CPU */
			ACPI_SRAT_X2APIC_CPU_AFFINITY *x2cpu =
			    (ACPI_SRAT_X2APIC_CPU_AFFINITY *) item;

			if (!(x2cpu->Flags & ACPI_SRAT_CPU_ENABLED)) {
				item = (ACPI_SUBTABLE_HEADER *)
				    ((uintptr_t)item + item->Length);
				continue;
			}
			domain = x2cpu->ProximityDomain;
			break;
		}
		default:
			item = (ACPI_SUBTABLE_HEADER *)((uintptr_t)item +
			    item->Length);
			continue;
		}

		/*
		 * Keep track of minimum proximity domain ID
		 */
		if (domain < domain_min)
			domain_min = domain;

		item = (ACPI_SUBTABLE_HEADER *)((uintptr_t)item + item->Length);
	}
	if (lgrp_plat_domain_min_enable && prox_domain_min != NULL)
		*prox_domain_min = domain_min;

	/*
	 * Walk through SRAT, examining each CPU and memory entry to determine
	 * proximity domain ID for each.
	 */
	domain_cnt = 0;
	item = (ACPI_SUBTABLE_HEADER *)((uintptr_t)tp + sizeof (*tp));
	end = (ACPI_SUBTABLE_HEADER *)(tp->Header.Length + (uintptr_t)tp);
	bzero(node_domain, MAX_NODES * sizeof (node_domain_map_t));
	while (item < end) {
		uint32_t	domain;
		boolean_t	overflow;
		uint_t		start;

		switch (item->Type) {
		case ACPI_SRAT_TYPE_CPU_AFFINITY: {	/* CPU entry */
			ACPI_SRAT_CPU_AFFINITY *cpu =
			    (ACPI_SRAT_CPU_AFFINITY *) item;

			if (!(cpu->Flags & ACPI_SRAT_CPU_ENABLED)) {
				item = (ACPI_SUBTABLE_HEADER *)
				    ((uintptr_t)item + item->Length);
				continue;
			}
			domain = cpu->ProximityDomainLo;
			for (i = 0; i < 3; i++) {
				domain += cpu->ProximityDomainHi[i] <<
				    ((i + 1) * 8);
			}
			break;
		}
		case ACPI_SRAT_TYPE_MEMORY_AFFINITY: {	/* memory entry */
			ACPI_SRAT_MEM_AFFINITY *mem =
			    (ACPI_SRAT_MEM_AFFINITY *)item;

			if (!(mem->Flags & ACPI_SRAT_MEM_ENABLED)) {
				item = (ACPI_SUBTABLE_HEADER *)
				    ((uintptr_t)item + item->Length);
				continue;
			}
			domain = mem->ProximityDomain;
			break;
		}
		case ACPI_SRAT_TYPE_X2APIC_CPU_AFFINITY: {	/* x2apic CPU */
			ACPI_SRAT_X2APIC_CPU_AFFINITY *x2cpu =
			    (ACPI_SRAT_X2APIC_CPU_AFFINITY *) item;

			if (!(x2cpu->Flags & ACPI_SRAT_CPU_ENABLED)) {
				item = (ACPI_SUBTABLE_HEADER *)
				    ((uintptr_t)item + item->Length);
				continue;
			}
			domain = x2cpu->ProximityDomain;
			break;
		}
		default:
			item = (ACPI_SUBTABLE_HEADER *)((uintptr_t)item +
			    item->Length);
			continue;
		}

		/*
		 * Count and keep track of which proximity domain IDs seen
		 */
		start = i = domain % MAX_NODES;
		overflow = B_TRUE;
		do {
			/*
			 * Create entry for proximity domain and increment
			 * count when no entry exists where proximity domain
			 * hashed
			 */
			if (!node_domain[i].exists) {
				node_domain[i].exists = 1;
				node_domain[i].prox_domain = domain;
				domain_cnt++;
				overflow = B_FALSE;
				break;
			}

			/*
			 * Nothing to do when proximity domain seen already
			 * and its entry exists
			 */
			if (node_domain[i].prox_domain == domain) {
				overflow = B_FALSE;
				break;
			}

			/*
			 * Entry exists where proximity domain hashed, but for
			 * different proximity domain so keep search for empty
			 * slot to put it or matching entry whichever comes
			 * first.
			 */
			i = (i + 1) % MAX_NODES;
		} while (i != start);

		/*
		 * Didn't find empty or matching entry which means have more
		 * proximity domains than supported nodes (:-(
		 */
		ASSERT(overflow != B_TRUE);
		if (overflow == B_TRUE)
			return (-1);

		item = (ACPI_SUBTABLE_HEADER *)((uintptr_t)item + item->Length);
	}
	return (domain_cnt);
}


/*
 * Parse domain information in ACPI Maximum System Capability Table (MSCT).
 * MSCT table has been verified in function process_msct() in fakebop.c.
 */
static int
lgrp_plat_msct_domains(ACPI_TABLE_MSCT *tp, uint32_t *prox_domain_min)
{
	int last_seen = 0;
	uint32_t proxmin = UINT32_MAX;
	ACPI_MSCT_PROXIMITY *item, *end;

	if (tp == NULL || lgrp_plat_msct_enable == 0)
		return (-1);

	if (tp->MaxProximityDomains >= MAX_NODES) {
		cmn_err(CE_CONT,
		    "?lgrp: too many proximity domains (%d), max %d supported, "
		    "disable support of CPU/memory DR operations.",
		    tp->MaxProximityDomains + 1, MAX_NODES);
		plat_dr_disable_cpu();
		plat_dr_disable_memory();
		return (-1);
	}

	if (prox_domain_min != NULL) {
		end = (void *)(tp->Header.Length + (uintptr_t)tp);
		for (item = (void *)((uintptr_t)tp +
		    tp->ProximityOffset); item < end;
		    item = (void *)(item->Length + (uintptr_t)item)) {
			if (item->RangeStart < proxmin) {
				proxmin = item->RangeStart;
			}

			last_seen = item->RangeEnd - item->RangeStart + 1;
			/*
			 * Break out if all proximity domains have been
			 * processed. Some BIOSes may have unused items
			 * at the end of MSCT table.
			 */
			if (last_seen > tp->MaxProximityDomains) {
				break;
			}
		}
		*prox_domain_min = proxmin;
	}

	return (tp->MaxProximityDomains + 1);
}


/*
 * Set lgroup latencies for 2 level lgroup topology
 */
static void
lgrp_plat_2level_setup(lgrp_plat_latency_stats_t *lat_stats)
{
	int	i, j;

	ASSERT(lat_stats != NULL);

	if (lgrp_plat_node_cnt >= 4)
		cmn_err(CE_NOTE,
		    "MPO only optimizing for local and remote\n");
	for (i = 0; i < lgrp_plat_node_cnt; i++) {
		for (j = 0; j < lgrp_plat_node_cnt; j++) {
			if (i == j)
				lat_stats->latencies[i][j] = 2;
			else
				lat_stats->latencies[i][j] = 3;
		}
	}
	lat_stats->latency_min = 2;
	lat_stats->latency_max = 3;
	/* TODO: check it. */
	lgrp_config(LGRP_CONFIG_FLATTEN, 2, 0);
	lgrp_plat_topo_flatten = 1;
}


/*
 * The following Opteron specific constants, macros, types, and routines define
 * PCI configuration space registers and how to read them to determine the NUMA
 * configuration of *supported* Opteron processors.  They provide the same
 * information that may be gotten from the ACPI System Resource Affinity Table
 * (SRAT) if it exists on the machine of interest.
 *
 * The AMD BIOS and Kernel Developer's Guide (BKDG) for the processor family
 * of interest describes all of these registers and their contents.  The main
 * registers used by this code to determine the NUMA configuration of the
 * machine are the node ID register for the number of NUMA nodes and the DRAM
 * address map registers for the physical address range of each node.
 *
 * NOTE: The format and how to determine the NUMA configuration using PCI
 *	 config space registers may change or may not be supported in future
 *	 Opteron processor families.
 */

/*
 * How many bits to shift Opteron DRAM Address Map base and limit registers
 * to get actual value
 */
#define	OPT_DRAMADDR_HI_LSHIFT_ADDR	40	/* shift left for address */
#define	OPT_DRAMADDR_LO_LSHIFT_ADDR	8	/* shift left for address */

#define	OPT_DRAMADDR_HI_MASK_ADDR	0x000000FF /* address bits 47-40 */
#define	OPT_DRAMADDR_LO_MASK_ADDR	0xFFFF0000 /* address bits 39-24 */

#define	OPT_DRAMADDR_LO_MASK_OFF	0xFFFFFF /* offset for address */

/*
 * Macros to derive addresses from Opteron DRAM Address Map registers
 */
#define	OPT_DRAMADDR_HI(reg) \
	(((u_longlong_t)reg & OPT_DRAMADDR_HI_MASK_ADDR) << \
	    OPT_DRAMADDR_HI_LSHIFT_ADDR)

#define	OPT_DRAMADDR_LO(reg) \
	(((u_longlong_t)reg & OPT_DRAMADDR_LO_MASK_ADDR) << \
	    OPT_DRAMADDR_LO_LSHIFT_ADDR)

#define	OPT_DRAMADDR(high, low) \
	(OPT_DRAMADDR_HI(high) | OPT_DRAMADDR_LO(low))

/*
 * Bit masks defining what's in Opteron DRAM Address Map base register
 */
#define	OPT_DRAMBASE_LO_MASK_RE		0x1	/* read enable */
#define	OPT_DRAMBASE_LO_MASK_WE		0x2	/* write enable */
#define	OPT_DRAMBASE_LO_MASK_INTRLVEN	0x700	/* interleave */

/*
 * Bit masks defining what's in Opteron DRAM Address Map limit register
 */
#define	OPT_DRAMLIMIT_LO_MASK_DSTNODE	0x7		/* destination node */
#define	OPT_DRAMLIMIT_LO_MASK_INTRLVSEL	0x700		/* interleave select */


/*
 * Opteron Node ID register in PCI configuration space contains
 * number of nodes in system, etc. for Opteron K8.  The following
 * constants and macros define its contents, structure, and access.
 */

/*
 * Bit masks defining what's in Opteron Node ID register
 */
#define	OPT_NODE_MASK_ID	0x7	/* node ID */
#define	OPT_NODE_MASK_CNT	0x70	/* node count */
#define	OPT_NODE_MASK_IONODE	0x700	/* Hypertransport I/O hub node ID */
#define	OPT_NODE_MASK_LCKNODE	0x7000	/* lock controller node ID */
#define	OPT_NODE_MASK_CPUCNT	0xF0000	/* CPUs in system (0 means 1 CPU)  */

/*
 * How many bits in Opteron Node ID register to shift right to get actual value
 */
#define	OPT_NODE_RSHIFT_CNT	0x4	/* shift right for node count value */

/*
 * Macros to get values from Opteron Node ID register
 */
#define	OPT_NODE_CNT(reg) \
	((reg & OPT_NODE_MASK_CNT) >> OPT_NODE_RSHIFT_CNT)

/*
 * Macro to setup PCI Extended Configuration Space (ECS) address to give to
 * "in/out" instructions
 *
 * NOTE: Should only be used in lgrp_plat_init() before MMIO setup because any
 *	 other uses should just do MMIO to access PCI ECS.
 *	 Must enable special bit in Northbridge Configuration Register on
 *	 Greyhound for extended CF8 space access to be able to access PCI ECS
 *	 using "in/out" instructions and restore special bit after done
 *	 accessing PCI ECS.
 */
#define	OPT_PCI_ECS_ADDR(bus, device, function, reg) \
	(PCI_CONE | (((bus) & 0xff) << 16) | (((device & 0x1f)) << 11)  | \
	    (((function) & 0x7) << 8) | ((reg) & 0xfc) | \
	    ((((reg) >> 8) & 0xf) << 24))

/*
 * PCI configuration space registers accessed by specifying
 * a bus, device, function, and offset.  The following constants
 * define the values needed to access Opteron K8 configuration
 * info to determine its node topology
 */

#define	OPT_PCS_BUS_CONFIG	0	/* Hypertransport config space bus */

/*
 * Opteron PCI configuration space register function values
 */
#define	OPT_PCS_FUNC_HT		0	/* Hypertransport configuration */
#define	OPT_PCS_FUNC_ADDRMAP	1	/* Address map configuration */
#define	OPT_PCS_FUNC_DRAM	2	/* DRAM configuration */
#define	OPT_PCS_FUNC_MISC	3	/* Miscellaneous configuration */

/*
 * PCI Configuration Space register offsets
 */
#define	OPT_PCS_OFF_VENDOR	0x0	/* device/vendor ID register */
#define	OPT_PCS_OFF_DRAMBASE_HI	0x140	/* DRAM Base register (node 0) */
#define	OPT_PCS_OFF_DRAMBASE_LO	0x40	/* DRAM Base register (node 0) */
#define	OPT_PCS_OFF_NODEID	0x60	/* Node ID register */

/*
 * Opteron PCI Configuration Space device IDs for nodes
 */
#define	OPT_PCS_DEV_NODE0		24	/* device number for node 0 */


/*
 * Opteron DRAM address map gives base and limit for physical memory in a node
 */
typedef	struct opt_dram_addr_map {
	uint32_t	base_hi;
	uint32_t	base_lo;
	uint32_t	limit_hi;
	uint32_t	limit_lo;
} opt_dram_addr_map_t;


/*
 * Supported AMD processor families
 */
#define	AMD_FAMILY_HAMMER	15
#define	AMD_FAMILY_GREYHOUND	16

/*
 * Whether to have is_opteron() return 1 even when processor isn't supported
 */
uint_t	is_opteron_override = 0;

/*
 * AMD processor family for current CPU
 */
uint_t	opt_family = 0;


/*
 * Determine whether we're running on a supported AMD Opteron since reading
 * node count and DRAM address map registers may have different format or
 * may not be supported across processor families
 */
static int
is_opteron(void)
{

	if (x86_vendor != X86_VENDOR_AMD)
		return (0);

	opt_family = cpuid_getfamily(CPU);
	if (opt_family == AMD_FAMILY_HAMMER ||
	    opt_family == AMD_FAMILY_GREYHOUND || is_opteron_override)
		return (1);
	else
		return (0);
}


/*
 * Determine NUMA configuration for Opteron from registers that live in PCI
 * configuration space
 */
static void
opt_get_numa_config(uint_t *node_cnt, int *mem_intrlv,
    memnode_phys_addr_map_t *memnode_info)
{
	uint_t				bus;
	uint_t				dev;
	struct opt_dram_addr_map	dram_map[MAX_NODES];
	uint_t				node;
	uint_t				node_info[MAX_NODES];
	uint_t				off_hi;
	uint_t				off_lo;
	uint64_t nb_cfg_reg;

	/*
	 * Read configuration registers from PCI configuration space to
	 * determine node information, which memory is in each node, etc.
	 *
	 * Write to PCI configuration space address register to specify
	 * which configuration register to read and read/write PCI
	 * configuration space data register to get/set contents
	 */
	bus = OPT_PCS_BUS_CONFIG;
	dev = OPT_PCS_DEV_NODE0;
	off_hi = OPT_PCS_OFF_DRAMBASE_HI;
	off_lo = OPT_PCS_OFF_DRAMBASE_LO;

	/*
	 * Read node ID register for node 0 to get node count
	 */
	node_info[0] = pci_getl_func(bus, dev, OPT_PCS_FUNC_HT,
	    OPT_PCS_OFF_NODEID);
	*node_cnt = OPT_NODE_CNT(node_info[0]) + 1;

	/*
	 * If number of nodes is more than maximum supported, then set node
	 * count to 1 and treat system as UMA instead of NUMA.
	 */
	if (*node_cnt > MAX_NODES) {
		*node_cnt = 1;
		return;
	}

	/*
	 * For Greyhound, PCI Extended Configuration Space must be enabled to
	 * read high DRAM address map base and limit registers
	 */
	nb_cfg_reg = 0;
	if (opt_family == AMD_FAMILY_GREYHOUND) {
		nb_cfg_reg = rdmsr(MSR_AMD_NB_CFG);
		if ((nb_cfg_reg & AMD_GH_NB_CFG_EN_ECS) == 0)
			wrmsr(MSR_AMD_NB_CFG,
			    nb_cfg_reg | AMD_GH_NB_CFG_EN_ECS);
	}

	for (node = 0; node < *node_cnt; node++) {
		uint32_t	base_hi;
		uint32_t	base_lo;
		uint32_t	limit_hi;
		uint32_t	limit_lo;

		/*
		 * Read node ID register (except for node 0 which we just read)
		 */
		if (node > 0) {
			node_info[node] = pci_getl_func(bus, dev,
			    OPT_PCS_FUNC_HT, OPT_PCS_OFF_NODEID);
		}

		/*
		 * Read DRAM base and limit registers which specify
		 * physical memory range of each node
		 */
		if (opt_family != AMD_FAMILY_GREYHOUND)
			base_hi = 0;
		else {
			outl(PCI_CONFADD, OPT_PCI_ECS_ADDR(bus, dev,
			    OPT_PCS_FUNC_ADDRMAP, off_hi));
			base_hi = dram_map[node].base_hi =
			    inl(PCI_CONFDATA);
		}
		base_lo = dram_map[node].base_lo = pci_getl_func(bus, dev,
		    OPT_PCS_FUNC_ADDRMAP, off_lo);

		if ((dram_map[node].base_lo & OPT_DRAMBASE_LO_MASK_INTRLVEN) &&
		    mem_intrlv)
			*mem_intrlv = *mem_intrlv + 1;

		off_hi += 4;	/* high limit register offset */
		if (opt_family != AMD_FAMILY_GREYHOUND)
			limit_hi = 0;
		else {
			outl(PCI_CONFADD, OPT_PCI_ECS_ADDR(bus, dev,
			    OPT_PCS_FUNC_ADDRMAP, off_hi));
			limit_hi = dram_map[node].limit_hi =
			    inl(PCI_CONFDATA);
		}

		off_lo += 4;	/* low limit register offset */
		limit_lo = dram_map[node].limit_lo = pci_getl_func(bus,
		    dev, OPT_PCS_FUNC_ADDRMAP, off_lo);

		/*
		 * Increment device number to next node and register offsets
		 * for DRAM base register of next node
		 */
		off_hi += 4;
		off_lo += 4;
		dev++;

		/*
		 * Both read and write enable bits must be enabled in DRAM
		 * address map base register for physical memory to exist in
		 * node
		 */
		if ((base_lo & OPT_DRAMBASE_LO_MASK_RE) == 0 ||
		    (base_lo & OPT_DRAMBASE_LO_MASK_WE) == 0) {
			/*
			 * Mark node memory as non-existent and set start and
			 * end addresses to be same in memnode_info[]
			 */
			memnode_info[node].exists = 0;
			memnode_info[node].start = memnode_info[node].end =
			    (pfn_t)-1;
			continue;
		}

		/*
		 * Mark node memory as existing and remember physical address
		 * range of each node for use later
		 */
		memnode_info[node].exists = 1;

		memnode_info[node].start = btop(OPT_DRAMADDR(base_hi, base_lo));

		memnode_info[node].end = btop(OPT_DRAMADDR(limit_hi, limit_lo) |
		    OPT_DRAMADDR_LO_MASK_OFF);
	}

	/*
	 * Restore PCI Extended Configuration Space enable bit
	 */
	if (opt_family == AMD_FAMILY_GREYHOUND) {
		if ((nb_cfg_reg & AMD_GH_NB_CFG_EN_ECS) == 0)
			wrmsr(MSR_AMD_NB_CFG, nb_cfg_reg);
	}
}


/*
 * Return average amount of time to read vendor ID register on Northbridge
 * N times on specified destination node from current CPU
 */
static hrtime_t
opt_probe_vendor(int dest_node, int nreads)
{
	int		cnt;
	uint_t		dev;
	/* LINTED: set but not used in function */
	volatile uint_t	dev_vendor __unused;
	hrtime_t	elapsed;
	hrtime_t	end;
	int		ipl;
	hrtime_t	start;

	dev = OPT_PCS_DEV_NODE0 + dest_node;
	kpreempt_disable();
	ipl = spl8();
	outl(PCI_CONFADD, PCI_CADDR1(0, dev, OPT_PCS_FUNC_DRAM,
	    OPT_PCS_OFF_VENDOR));
	start = gethrtime();
	for (cnt = 0; cnt < nreads; cnt++)
		dev_vendor = inl(PCI_CONFDATA);
	end = gethrtime();
	elapsed = (end - start) / nreads;
	splx(ipl);
	kpreempt_enable();
	return (elapsed);
}