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

/*
 * Copyright 2019 Joyent, Inc.
 */

#include <sys/segments.h>
#include <sys/controlregs.h>

/*
 * Do a call into BIOS.  This goes down to 16 bit real mode and back again.
 */

/*
 * instruction prefix to change operand size in instruction
 */
#define DATASZ	.byte 0x66;

	.globl	_start
_start:

	/*
	 * Save caller registers
	 */
	movq	%rbp, save_rbp
	movq	%rsp, save_rsp
	movq	%rbx, save_rbx
	movq	%rsi, save_rsi
	movq	%r12, save_r12
	movq	%r13, save_r13
	movq	%r14, save_r14
	movq	%r15, save_r15

	/* Switch to a low memory stack */
	movq	$_start, %rsp

	/* put interrupt number in %bl */
	movq	%rdi, %rbx

	/* allocate space for args on stack */
	subq	$18, %rsp
	movq	%rsp, %rdi

	/* copy args from high memory to stack in low memory */
	cld
	movl	$18, %ecx
	rep
	movsb

	/*
	 * Save system registers
	 */
	sidt	save_idt
	sgdt	save_gdt
	str	save_tr
	movw	%cs, save_cs
	movw	%ds, save_ds
	movw	%ss, save_ss
	movw	%es, save_es
	movw	%fs, save_fs
	movw	%gs, save_gs
	movq	%cr4, %rax
	movq	%rax, save_cr4
	movq	%cr3, %rax
	movq	%rax, save_cr3
	movq	%cr0, %rax
	movq	%rax, save_cr0

	/*
	 * save/clear the extension parts of the fs/gs base registers and cr8
	 */
	movl	$MSR_AMD_FSBASE, %ecx
	rdmsr
	movl	%eax, save_fsbase
	movl	%edx, save_fsbase + 4
	xorl	%eax, %eax
	xorl	%edx, %edx
	wrmsr

	movl	$MSR_AMD_GSBASE, %ecx
	rdmsr
	movl	%eax, save_gsbase
	movl	%edx, save_gsbase + 4
	xorl	%eax, %eax
	xorl	%edx, %edx
	wrmsr

	movl	$MSR_AMD_KGSBASE, %ecx
	rdmsr
	movl	%eax, save_kgsbase
	movl	%edx, save_kgsbase + 4
	xorl	%eax, %eax
	xorl	%edx, %edx
	wrmsr

	movq	%cr8, %rax
	movq	%rax, save_cr8

	/*
	 * set offsets in 16 bit ljmp instructions below
	 */
	leaq	enter_real, %rax
	movw	%ax, enter_real_ljmp

	leaq	enter_protected, %rax
	movw	%ax, enter_protected_ljmp

	leaq	gdt_info, %rax
	movw	%ax, gdt_info_load

	/*
	 * insert BIOS interrupt number into later instruction
	 */
	movb    %bl, int_instr+1
	jmp     1f
1:

	/*
	 * zero out all the registers to make sure they're 16 bit clean
	 */
	xorq	%r8, %r8
	xorq	%r9, %r9
	xorq	%r10, %r10
	xorq	%r11, %r11
	xorq	%r12, %r12
	xorq	%r13, %r13
	xorq	%r14, %r14
	xorq	%r15, %r15
	xorl	%eax, %eax
	xorl	%ebx, %ebx
	xorl	%ecx, %ecx
	xorl	%edx, %edx
	xorl	%ebp, %ebp
	xorl	%esi, %esi
	xorl	%edi, %edi

	/*
	 * Load our own GDT/IDT
	 */
	lgdt	gdt_info
	lidt	idt_info

	/*
	 * Shut down 64 bit mode. First get into compatibility mode.
	 */
	movq	%rsp, %rax
	pushq	$B32DATA_SEL
	pushq	%rax
	pushf
	pushq	$B32CODE_SEL
	pushq	$1f
	iretq
1:
	.code32

	/*
	 * disable long mode by:
	 * - shutting down paging (bit 31 of cr0)
	 * - flushing the TLB
	 * - disabling LME (long made enable) in EFER (extended feature reg)
	 */
	movl	%cr0, %eax
	btcl	$31, %eax		/* disable paging */
	movl	%eax, %cr0
	ljmp	$B32CODE_SEL, $1f
1:

	xorl	%eax, %eax
	movl	%eax, %cr3		/* flushes TLB */

	movl	$MSR_AMD_EFER, %ecx	/* Extended Feature Enable */
	rdmsr
	btcl	$8, %eax		/* bit 8 Long Mode Enable bit */
	wrmsr

	/*
	 * ok.. now enter 16 bit mode, so we can shut down protected mode
	 *
	 * We'll have to act like we're still in a 32 bit section.
	 * So the code from this point has DATASZ in front of it to get 32 bit
	 * operands. If DATASZ is missing the operands will be 16 bit.
	 *
	 * Now shut down paging and protected (ie. segmentation) modes.
	 */
	ljmp	$B16CODE_SEL, $enter_16_bit
enter_16_bit:

	/*
	 * Make sure hidden parts of segment registers are 16 bit clean
	 */
	DATASZ	movl	$B16DATA_SEL, %eax
		movw    %ax, %ss
		movw    %ax, %ds
		movw    %ax, %es
		movw    %ax, %fs
		movw    %ax, %gs


	DATASZ	movl	$0x0, %eax	/* put us in real mode */
	DATASZ	movl	%eax, %cr0
	.byte	0xea			/* ljmp */
enter_real_ljmp:
	.value	0			/* addr (16 bit) */
	.value	0x0			/* value for %cs */
enter_real:

	/*
	 * zero out the remaining segment registers
	 */
	DATASZ	xorl	%eax, %eax
		movw    %ax, %ss
		movw    %ax, %ds
		movw    %ax, %es
		movw    %ax, %fs
		movw    %ax, %gs

	/*
	 * load the arguments to the BIOS call from the stack
	 */
	popl	%eax	/* really executes a 16 bit pop */
	popl	%ebx
	popl	%ecx
	popl	%edx
	popl	%esi
	popl	%edi
	popl	%ebp
	pop	%es
	pop	%ds

	/*
	 * do the actual BIOS call
	 */
	sti
int_instr:
	int	$0x10		/* this int number is overwritten */
	cli			/* ensure interrupts remain disabled */

	/*
	 * save results of the BIOS call
	 */
	pushf
	push	%ds
	push	%es
	pushl	%ebp		/* still executes as 16 bit */
	pushl	%edi
	pushl	%esi
	pushl	%edx
	pushl	%ecx
	pushl	%ebx
	pushl	%eax

	/*
	 * Restore protected mode and 32 bit execution
	 */
	push	$0			/* make sure %ds is zero before lgdt */
	pop	%ds
	.byte	0x0f, 0x01, 0x16	/* lgdt */
gdt_info_load:
	.value	0	/* temp GDT in currently addressible mem */

	DATASZ	movl	$0x1, %eax
	DATASZ	movl	%eax, %cr0

	.byte	0xea			/* ljmp */
enter_protected_ljmp:
	.value	0			/* addr (still in 16 bit) */
	.value	B32CODE_SEL		/* %cs value */
enter_protected:

	/*
	 * We are now back in a 32 bit code section, fix data/stack segments
	 */
	.code32
	movw	$B32DATA_SEL, %ax
	movw	%ax, %ds
	movw	%ax, %ss

	/*
	 * Re-enable paging. Note we only use 32 bit mov's to restore these
	 * control registers. That's OK as the upper 32 bits are always zero.
	 */
	movl	save_cr4, %eax
	movl	%eax, %cr4
	movl	save_cr3, %eax
	movl	%eax, %cr3

	/*
	 * re-enable long mode
	 */
	movl	$MSR_AMD_EFER, %ecx
	rdmsr
	btsl	$8, %eax
	wrmsr

	movl	save_cr0, %eax
	movl	%eax, %cr0
	jmp	enter_paging
enter_paging:


	/*
	 * transition back to 64 bit mode
	 */
	pushl	$B64CODE_SEL
	pushl	$longmode
	lret
longmode:
	.code64
	/*
	 * restore caller frame pointer and segment registers
	 */
	lgdt	save_gdt
	lidt	save_idt

	/*
	 * Before loading the task register we need to reset the busy bit
	 * in its corresponding GDT selector. The busy bit is the 2nd bit in
	 * the 5th byte of the selector.
	 */
	movzwq	save_tr, %rax
	addq	save_gdt+2, %rax
	btcl	$1, 5(%rax)
	ltr	save_tr
	movw	save_ds, %ds
	movw	save_ss, %ss
	movw	save_es, %es
	movw	save_fs, %fs
	movw	save_gs, %gs

	pushq	save_cs
	pushq	$.newcs
	lretq
.newcs:

	/*
	 * restore the hidden kernel segment base register values
	 */
	movl	save_fsbase, %eax
	movl	save_fsbase + 4, %edx
	movl	$MSR_AMD_FSBASE, %ecx
	wrmsr

	movl	save_gsbase, %eax
	movl	save_gsbase + 4, %edx
	movl	$MSR_AMD_GSBASE, %ecx
	wrmsr

	movl	save_kgsbase, %eax
	movl	save_kgsbase + 4, %edx
	movl	$MSR_AMD_KGSBASE, %ecx
	wrmsr

	movq	save_cr8, %rax
	cmpq	$0, %rax
	je	1f
	movq	%rax, %cr8
1:

	/*
	 * copy results to caller's location, then restore remaining registers
	 */
	movq    save_rsi, %rdi
	movq	%rsp, %rsi
	movq	$18, %rcx
	rep
	movsb
	movw	18(%rsp), %ax
	andq	$0xffff, %rax
	movq    save_r12, %r12
	movq    save_r13, %r13
	movq    save_r14, %r14
	movq    save_r15, %r15
	movq    save_rbx, %rbx
	movq    save_rbp, %rbp
	movq    save_rsp, %rsp
	ret


/*
 * Caller's registers to restore
 */
	.align 4
save_esi:
	.long	0
save_edi:
	.long	0
save_ebx:
	.long	0
save_ebp:
	.long	0
save_esp:
	.long	0

	.align 8
save_rsi:
	.quad	0
save_rbx:
	.quad	0
save_rbp:
	.quad	0
save_rsp:
	.quad	0
save_r12:
	.quad	0
save_r13:
	.quad	0
save_r14:
	.quad	0
save_r15:
	.quad	0
save_kgsbase:
	.quad	0
save_gsbase:
	.quad	0
save_fsbase:
	.quad	0
save_cr8:
	.quad	0

save_idt:
	.quad	0
	.quad	0

save_gdt:
	.quad	0
	.quad	0

save_cr0:
	.quad	0
save_cr3:
	.quad	0
save_cr4:
	.quad	0
save_cs:
	.quad	0
save_ss:
	.value	0
save_ds:
	.value	0
save_es:
	.value	0
save_fs:
	.value	0
save_gs:
	.value	0
save_tr:
	.value	0

idt_info:
	.value 0x3ff
	.quad 0


/*
 * We need to trampoline thru a gdt we have in low memory.
 */
#include "../boot/boot_gdt.s"

/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright 2016 Joyent, Inc.
 * Copyright 2025 Oxide Computer Company
 */

#include <sys/asm_linkage.h>
#include <sys/asm_misc.h>
#include <sys/param.h>
#include <sys/comm_page.h>
#include <sys/tsc.h>

#if defined(_GENCTF)

hrtime_t tsc_last;
hrtime_t tsc_resume_cap;
hrtime_t tsc_hrtime_base;
uint32_t tsc_max_delta;
volatile uint32_t hres_lock;
uint32_t tsc_type;
uint32_t nsec_scale;
int64_t hrestime_adj;
hrtime_t hres_last_tick;
uint32_t tsc_ncpu;
volatile timestruc_t hrestime;
hrtime_t tsc_sync_tick_delta[NCPU];

comm_page_t comm_page;

#else /* defined(_GENCTF) */

#include "assym.h"

/*
 * x86 Comm Page
 *
 * This is the definition for the comm page on x86.  The purpose of this struct
 * is to consolidate certain pieces of kernel state into one contiguous section
 * of memory in order for it to be exposed (read-only) to userspace.  The
 * struct contents are defined by hand so that member variables will maintain
 * their original symbols for use throughout the rest of the kernel.  This
 * layout must exactly match the C definition of comm_page_t.
 * See: "uts/i86pc/sys/comm_page.h"
 */

	.data
	DGDEF3(comm_page, COMM_PAGE_S_SIZE, 4096)
	DGDEF2(tsc_last, 8)
	.fill	1, 8, 0
	DGDEF2(tsc_hrtime_base, 8)
	.fill	1, 8, 0
	DGDEF2(tsc_resume_cap, 8)
	.fill	1, 8, 0
	DGDEF2(tsc_type, 4);
	.fill	1, 4, _CONST(TSC_RDTSC_CPUID)
	DGDEF2(tsc_max_delta, 4);
	.fill	1, 4, 0
	DGDEF2(hres_lock, 4);
	.fill	1, 4, 0
	DGDEF2(nsec_scale, 4);
	.fill	1, 4, 0
	DGDEF2(hrestime_adj, 8)
	.fill	1, 8, 0
	DGDEF2(hres_last_tick, 8)
	.fill	1, 8, 0
	DGDEF2(tsc_ncpu, 4)
	.fill	1, 4, 0
	/* _cp_pad0 */
	.fill	1, 4, 0
	DGDEF2(hrestime, _MUL(2, 8))
	.fill	2, 8, 0
	/* _cp_pad1 */
	.fill	502, 8, 0
	DGDEF2(tsc_sync_tick_delta, _MUL(NCPU, 8))
	.fill	_CONST(NCPU), 8, 0
	/* _cp_pad2 */
	.fill	_CONST(COMM_PAGE_S_SIZE - COMM_PAGE_PAD2), 1, 0

#endif /* defined(_GENCTF) */
/*
 * 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) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright 2019 Joyent, Inc.
 * Copyright 2020 OmniOS Community Edition (OmniOSce) Association.
 */

#include <sys/asm_linkage.h>
#include <sys/asm_misc.h>
#include <sys/regset.h>
#include <sys/privregs.h>
#include <sys/x86_archext.h>
#include <sys/cpr_wakecode.h>

#include <sys/segments.h>
#include "assym.h"

#ifdef  DEBUG
#define LED     1
#define SERIAL  1
#endif	/*	DEBUG	*/

#ifdef	DEBUG
#define	COM1	0x3f8
#define	COM2	0x2f8
#define	WC_COM	COM2	/* either COM1 or COM2			*/
#define	WC_LED	0x80    /* diagnostic led port ON motherboard	*/

/*
 * defined as offsets from the data register
 */
#define	DLL	0	/* divisor latch (lsb) */
#define	DLH	1	/* divisor latch (msb) */
#define	LCR	3	/* line control register		*/
#define	MCR	4	/* modem control register		*/


#define	DLAB	0x80    /* divisor latch access bit		*/
#define	B9600L	0X0c	/* lsb bit pattern for 9600 baud	*/
#define	B9600H	0X0	/* hsb bit pattern for 9600 baud	*/
#define	DTR	0x01    /* Data Terminal Ready			*/
#define	RTS	0x02    /* Request To Send			*/
#define	STOP1	0x00	/* 1 stop bit				*/
#define	BITS8	0x03    /* 8 bits per char			*/

#endif	/*	DEBUG	*/

/*
 *	This file contains the low level routines involved in getting
 *	into and out of ACPI S3, including those needed for restarting
 *	the non-boot cpus.
 *
 *	Our assumptions:
 *
 *	Our actions:
 *
 */

	ENTRY_NP(wc_save_context)

	movq	(%rsp), %rdx		/ return address
	movq	%rdx, WC_RETADDR(%rdi)
	pushq	%rbp
	movq	%rsp,%rbp

	movq    %rdi, WC_VIRTADDR(%rdi)
	movq    %rdi, WC_RDI(%rdi)

	movq    %rdx, WC_RDX(%rdi)

/ stash everything else we need
	sgdt	WC_GDT(%rdi)
	sidt	WC_IDT(%rdi)
	sldt	WC_LDT(%rdi)
	str	WC_TR(%rdi)

	movq	%cr0, %rdx
	movq	%rdx, WC_CR0(%rdi)
	movq	%cr3, %rdx
	movq	%rdx, WC_CR3(%rdi)
	movq	%cr4, %rdx
	movq	%rdx, WC_CR4(%rdi)
	movq	%cr8, %rdx
	movq	%rdx, WC_CR8(%rdi)

	movq    %r8, WC_R8(%rdi)
	movq    %r9, WC_R9(%rdi)
	movq    %r10, WC_R10(%rdi)
	movq    %r11, WC_R11(%rdi)
	movq    %r12, WC_R12(%rdi)
	movq    %r13, WC_R13(%rdi)
	movq    %r14, WC_R14(%rdi)
	movq    %r15, WC_R15(%rdi)
	movq    %rax, WC_RAX(%rdi)
	movq    %rbp, WC_RBP(%rdi)
	movq    %rbx, WC_RBX(%rdi)
	movq    %rcx, WC_RCX(%rdi)
	movq    %rsi, WC_RSI(%rdi)
	movq    %rsp, WC_RSP(%rdi)

	movw	%ss, WC_SS(%rdi)
	movw	%cs, WC_CS(%rdi)
	movw	%ds, WC_DS(%rdi)
	movw	%es, WC_ES(%rdi)

	movq	$0, %rcx		/ save %fs register
	movw    %fs, %cx
	movq    %rcx, WC_FS(%rdi)

	movl    $MSR_AMD_FSBASE, %ecx
	rdmsr
	movl    %eax, WC_FSBASE(%rdi)
	movl    %edx, WC_FSBASE+4(%rdi)

	movq	$0, %rcx		/ save %gs register
	movw    %gs, %cx
	movq    %rcx, WC_GS(%rdi)

	movl    $MSR_AMD_GSBASE, %ecx	/ save gsbase msr
	rdmsr
	movl    %eax, WC_GSBASE(%rdi)
	movl    %edx, WC_GSBASE+4(%rdi)

	movl    $MSR_AMD_KGSBASE, %ecx	/ save kgsbase msr
	rdmsr
	movl    %eax, WC_KGSBASE(%rdi)
	movl    %edx, WC_KGSBASE+4(%rdi)

	movq	%gs:CPU_ID, %rax	/ save current cpu id
	movq	%rax, WC_CPU_ID(%rdi)

	pushfq
	popq	WC_EFLAGS(%rdi)

	wbinvd				/ flush the cache
	mfence

	movq	$1, %rax		/ at suspend return 1

	leave

	ret

	SET_SIZE(wc_save_context)


/*
 *	Our assumptions:
 *		- We are running in real mode.
 *		- Interrupts are disabled.
 *
 *	Our actions:
 *		- We start using our GDT by loading correct values in the
 *		  selector registers (cs=KCS_SEL, ds=es=ss=KDS_SEL, fs=KFS_SEL,
 *		  gs=KGS_SEL).
 *		- We change over to using our IDT.
 *		- We load the default LDT into the hardware LDT register.
 *		- We load the default TSS into the hardware task register.
 *		- We restore registers
 *		- We return to original caller (a la setjmp)
 */

	ENTRY_NP(wc_rm_start)

	/*
	 * For the Sun Studio 10 assembler we needed to do a .code32 and
	 * mentally invert the meaning of the addr16 and data16 prefixes to
	 * get 32-bit access when generating code to be executed in 16-bit
	 * mode (sigh...)
	 *
	 * This code, despite always being built with GNU as, has inherited
	 * the conceptual damage.
	 */

	.code32

	cli
	movw		%cs, %ax
	movw		%ax, %ds		/ establish ds ...
	movw		%ax, %ss		/ ... and ss:esp
	D16 movl	$WC_STKSTART, %esp
/ using the following value blows up machines! - DO NOT USE
/	D16 movl	0xffc, %esp


#if     LED
	D16 movl        $WC_LED, %edx
	D16 movb        $0xd1, %al
	outb    (%dx)
#endif

#if     SERIAL
	D16 movl        $WC_COM, %edx
	D16 movb        $0x61, %al
	outb    (%dx)
#endif

	D16 call	cominit

	/*
	 * Enable protected-mode, write protect, and alignment mask
	 * %cr0 has already been initialsed to zero
	 */
	movl		%cr0, %eax
	D16 orl		$_CONST(CR0_PE|CR0_WP|CR0_AM), %eax
	movl		%eax, %cr0

	/*
	 * Do a jmp immediately after writing to cr0 when enabling protected
	 * mode to clear the real mode prefetch queue (per Intel's docs)
	 */
	jmp		pestart
pestart:

#if     LED
	D16 movl        $WC_LED, %edx
	D16 movb        $0xd2, %al
	outb    (%dx)
#endif

#if     SERIAL
	D16 movl        $WC_COM, %edx
	D16 movb        $0x62, %al
	outb    (%dx)
#endif

	/*
	 * 16-bit protected mode is now active, so prepare to turn on long
	 * mode
	 */

#if     LED
	D16 movl        $WC_LED, %edx
	D16 movb        $0xd3, %al
	outb    (%dx)
#endif

#if     SERIAL
	D16 movl        $WC_COM, %edx
	D16 movb        $0x63, %al
	outb    (%dx)
#endif

	/*
	 * Add any initial cr4 bits
	 */
	movl		%cr4, %eax
	A16 D16 orl	CR4OFF, %eax

	/*
	 * Enable PAE mode (CR4.PAE)
	 */
	D16 orl		$CR4_PAE, %eax
	movl		%eax, %cr4

#if     LED
	D16 movl        $WC_LED, %edx
	D16 movb        $0xd4, %al
	outb    (%dx)
#endif

#if     SERIAL
	D16 movl        $WC_COM, %edx
	D16 movb        $0x64, %al
	outb    (%dx)
#endif

	/*
	 * Point cr3 to the 64-bit long mode page tables.
	 *
	 * Note that these MUST exist in 32-bit space, as we don't have
	 * a way to load %cr3 with a 64-bit base address for the page tables
	 * until the CPU is actually executing in 64-bit long mode.
	 */
	A16 D16 movl	CR3OFF, %eax
	movl		%eax, %cr3

	/*
	 * Set long mode enable in EFER (EFER.LME = 1)
	 */
	D16 movl	$MSR_AMD_EFER, %ecx
	rdmsr

	D16 orl		$AMD_EFER_LME, %eax
	wrmsr

#if     LED
	D16 movl        $WC_LED, %edx
	D16 movb        $0xd5, %al
	outb    (%dx)
#endif

#if     SERIAL
	D16 movl        $WC_COM, %edx
	D16 movb        $0x65, %al
	outb    (%dx)
#endif

	/*
	 * Finally, turn on paging (CR0.PG = 1) to activate long mode.
	 */
	movl		%cr0, %eax
	D16 orl		$CR0_PG, %eax
	movl		%eax, %cr0

	/*
	 * The instruction after enabling paging in CR0 MUST be a branch.
	 */
	jmp		long_mode_active

long_mode_active:

#if     LED
	D16 movl        $WC_LED, %edx
	D16 movb        $0xd6, %al
	outb    (%dx)
#endif

#if     SERIAL
	D16 movl        $WC_COM, %edx
	D16 movb        $0x66, %al
	outb    (%dx)
#endif

	/*
	 * Long mode is now active but since we're still running with the
	 * original 16-bit CS we're actually in 16-bit compatability mode.
	 *
	 * We have to load an intermediate GDT and IDT here that we know are
	 * in 32-bit space before we can use the kernel's GDT and IDT, which
	 * may be in the 64-bit address space, and since we're in compatability
	 * mode, we only have access to 16 and 32-bit instructions at the
	 * moment.
	 */
	A16 D16 lgdt	TEMPGDTOFF	/* load temporary GDT */
	A16 D16 lidt	TEMPIDTOFF	/* load temporary IDT */


	/*
	 * Do a far transfer to 64-bit mode.  Set the CS selector to a 64-bit
	 * long mode selector (CS.L=1) in the temporary 32-bit GDT and jump
	 * to the real mode platter address of wc_long_mode_64 as until the
	 * 64-bit CS is in place we don't have access to 64-bit instructions
	 * and thus can't reference a 64-bit %rip.
	 */

#if     LED
	D16 movl        $WC_LED, %edx
	D16 movb        $0xd7, %al
	outb    (%dx)
#endif

#if     SERIAL
	D16 movl        $WC_COM, %edx
	D16 movb        $0x67, %al
	outb    (%dx)
#endif

	D16	pushl	$TEMP_CS64_SEL
	A16 D16 pushl	LM64OFF

	D16 lret


/*
 * Support routine to re-initialize VGA subsystem
 */
vgainit:
	D16 ret

/*
 * Support routine to re-initialize keyboard (which is USB - help!)
 */
kbdinit:
	D16 ret

/*
 * Support routine to re-initialize COM ports to something sane
 */
cominit:
	/ init COM1 & COM2

#if     DEBUG
/*
 * on debug kernels we need to initialize COM1 & COM2 here, so that
 * we can get debug output before the asy driver has resumed
 */

/ select COM1
	D16 movl	$_CONST(COM1+LCR), %edx
	D16 movb	$DLAB, %al		/ divisor latch
	outb	(%dx)

	D16 movl	$_CONST(COM1+DLL), %edx	/ divisor latch lsb
	D16 movb	$B9600L, %al		/ divisor latch
	outb	(%dx)

	D16 movl	$_CONST(COM1+DLH), %edx	/ divisor latch hsb
	D16 movb	$B9600H, %al		/ divisor latch
	outb	(%dx)

	D16 movl	$_CONST(COM1+LCR), %edx	/ select COM1
	D16 movb	$_CONST(STOP1|BITS8), %al	/ 1 stop bit, 8bit word len
	outb	(%dx)

	D16 movl	$_CONST(COM1+MCR), %edx	/ select COM1
	D16 movb	$_CONST(RTS|DTR), %al		/ data term ready & req to send
	outb	(%dx)

/ select COM2
	D16 movl	$_CONST(COM2+LCR), %edx
	D16 movb	$DLAB, %al		/ divisor latch
	outb	(%dx)

	D16 movl	$_CONST(COM2+DLL), %edx	/ divisor latch lsb
	D16 movb	$B9600L, %al		/ divisor latch
	outb	(%dx)

	D16 movl	$_CONST(COM2+DLH), %edx	/ divisor latch hsb
	D16 movb	$B9600H, %al		/ divisor latch
	outb	(%dx)

	D16 movl	$_CONST(COM2+LCR), %edx	/ select COM1
	D16 movb	$_CONST(STOP1|BITS8), %al	/ 1 stop bit, 8bit word len
	outb	(%dx)

	D16 movl	$_CONST(COM2+MCR), %edx	/ select COM1
	D16 movb	$_CONST(RTS|DTR), %al		/ data term ready & req to send
	outb	(%dx)
#endif	/*	DEBUG	*/

	D16 ret

	.code64

	.globl wc_long_mode_64
wc_long_mode_64:

#if     LED
	movw        $WC_LED, %dx
	movb        $0xd8, %al
	outb    (%dx)
#endif

#if     SERIAL
	movw        $WC_COM, %dx
	movb        $0x68, %al
	outb    (%dx)
#endif

	/*
	 * We are now running in long mode with a 64-bit CS (EFER.LMA=1,
	 * CS.L=1) so we now have access to 64-bit instructions.
	 *
	 * First, set the 64-bit GDT base.
	 */
	.globl	rm_platter_pa
	movl	rm_platter_pa, %eax

	lgdtq	GDTROFF(%rax)		/* load 64-bit GDT */

	/*
	 * Save the CPU number in %r11; get the value here since it's saved in
	 * the real mode platter.
	 */
/ JAN
/ the following is wrong! need to figure out MP systems
/	movl	CPUNOFF(%rax), %r11d

	/*
	 * Add rm_platter_pa to %rsp to point it to the same location as seen
	 * from 64-bit mode.
	 */
	addq	%rax, %rsp

	/*
	 * Now do an lretq to load CS with the appropriate selector for the
	 * kernel's 64-bit GDT and to start executing 64-bit setup code at the
	 * virtual address where boot originally loaded this code rather than
	 * the copy in the real mode platter's rm_code array as we've been
	 * doing so far.
	 */

#if     LED
	movw        $WC_LED, %dx
	movb        $0xd9, %al
	outb    (%dx)
#endif

/ JAN this should produce 'i' but we get 'g' instead ???
#if     SERIAL
	movw        $WC_COM, %dx
	movb        $0x69, %al
	outb    (%dx)
#endif

	pushq	$KCS_SEL
	pushq	$kernel_wc_code
	lretq

	.globl kernel_wc_code
kernel_wc_code:

#if     LED
	movw        $WC_LED, %dx
	movb        $0xda, %al
	outb    (%dx)
#endif

/ JAN this should produce 'j' but we get 'g' instead ???
#if     SERIAL
	movw        $WC_COM, %dx
	movb        $0x6a, %al
	outb    (%dx)
#endif

	/*
	 * Complete the balance of the setup we need to before executing
	 * 64-bit kernel code (namely init rsp, TSS, LGDT, FS and GS).
	 */
	.globl  rm_platter_va
	movq    rm_platter_va, %rbx
	addq	$WC_CPU, %rbx

#if     LED
	movw        $WC_LED, %dx
	movb        $0xdb, %al
	outb    (%dx)
#endif

#if     SERIAL
	movw        $WC_COM, %dx
	movw        $0x6b, %ax
	outb    (%dx)
#endif

	/*
	 * restore the rest of the registers
	 */

	lidtq	WC_IDT(%rbx)

#if     LED
	movw        $WC_LED, %dx
	movb        $0xdc, %al
	outb    (%dx)
#endif

#if     SERIAL
	movw        $WC_COM, %dx
	movw        $0x6c, %ax
	outb    (%dx)
#endif

	/*
	 * restore the rest of the registers
	 */

	movw    $KDS_SEL, %ax
	movw    %ax, %ds
	movw    %ax, %es
	movw    %ax, %ss

	/*
	 * Before proceeding, enable usage of the page table NX bit if
	 * that's how the page tables are set up.
	 */
	btl     $X86FSET_NX, x86_featureset(%rip)
	jnc     1f
	movl    $MSR_AMD_EFER, %ecx
	rdmsr
	orl     $AMD_EFER_NXE, %eax
	wrmsr
1:

	movq	WC_CR4(%rbx), %rax	/ restore full cr4 (with Global Enable)
	movq	%rax, %cr4

	lldt	WC_LDT(%rbx)
	movzwq	WC_TR(%rbx), %rax	/ clear TSS busy bit
	addq	WC_GDT+2(%rbx), %rax
	andl	$0xfffffdff, 4(%rax)
	movq	4(%rax), %rcx
	ltr	WC_TR(%rbx)

#if     LED
	movw        $WC_LED, %dx
	movb        $0xdd, %al
	outb    (%dx)
#endif

#if     SERIAL
	movw        $WC_COM, %dx
	movw        $0x6d, %ax
	outb    (%dx)
#endif

/ restore %fsbase %gsbase %kgbase registers using wrmsr instruction

	movq    WC_FS(%rbx), %rcx	/ restore fs register
	movw    %cx, %fs

	movl    $MSR_AMD_FSBASE, %ecx
	movl    WC_FSBASE(%rbx), %eax
	movl    WC_FSBASE+4(%rbx), %edx
	wrmsr

	movq    WC_GS(%rbx), %rcx	/ restore gs register
	movw    %cx, %gs

	movl    $MSR_AMD_GSBASE, %ecx	/ restore gsbase msr
	movl    WC_GSBASE(%rbx), %eax
	movl    WC_GSBASE+4(%rbx), %edx
	wrmsr

	movl    $MSR_AMD_KGSBASE, %ecx	/ restore kgsbase msr
	movl    WC_KGSBASE(%rbx), %eax
	movl    WC_KGSBASE+4(%rbx), %edx
	wrmsr

	movq	WC_CR0(%rbx), %rdx
	movq	%rdx, %cr0
	movq	WC_CR3(%rbx), %rdx
	movq	%rdx, %cr3
	movq	WC_CR8(%rbx), %rdx
	movq	%rdx, %cr8

#if     LED
	movw        $WC_LED, %dx
	movb        $0xde, %al
	outb    (%dx)
#endif

#if     SERIAL
	movw        $WC_COM, %dx
	movb        $0x6e, %al
	outb    (%dx)
#endif

	/*
	 * if we are not running on the boot CPU restore stack contents by
	 * calling i_cpr_restore_stack(curthread, save_stack);
	 */
	movq    %rsp, %rbp
	call	i_cpr_bootcpuid
	cmpl	%eax, WC_CPU_ID(%rbx)
	je	2f

	movq	%gs:CPU_THREAD, %rdi
	movq	WC_SAVED_STACK(%rbx), %rsi
	call	i_cpr_restore_stack
2:

	movq    WC_RSP(%rbx), %rsp	/ restore stack pointer

	/*
	 * APIC initialization
	 */
	movq    %rsp, %rbp

	/*
	 * skip iff function pointer is NULL
	 */
	cmpq	$0, ap_mlsetup
	je	3f
	leaq	ap_mlsetup, %rax
	INDIRECT_CALL_REG(rax)
3:

	leaq	cpr_start_cpu_func, %rax
	INDIRECT_CALL_REG(rax)

/ restore %rbx to the value it ahd before we called the functions above
	movq    rm_platter_va, %rbx
	addq	$WC_CPU, %rbx

	movq    WC_R8(%rbx), %r8
	movq    WC_R9(%rbx), %r9
	movq    WC_R10(%rbx), %r10
	movq    WC_R11(%rbx), %r11
	movq    WC_R12(%rbx), %r12
	movq    WC_R13(%rbx), %r13
	movq    WC_R14(%rbx), %r14
	movq    WC_R15(%rbx), %r15
/	movq    WC_RAX(%rbx), %rax
	movq    WC_RBP(%rbx), %rbp
	movq    WC_RCX(%rbx), %rcx
/	movq    WC_RDX(%rbx), %rdx
	movq    WC_RDI(%rbx), %rdi
	movq    WC_RSI(%rbx), %rsi


/ assume that %cs does not need to be restored
/ %ds, %es & %ss are ignored in 64bit mode
	movw	WC_SS(%rbx), %ss
	movw	WC_DS(%rbx), %ds
	movw	WC_ES(%rbx), %es

#if     LED
	movw        $WC_LED, %dx
	movb        $0xdf, %al
	outb    (%dx)
#endif

#if     SERIAL
	movw        $WC_COM, %dx
	movb        $0x6f, %al
	outb    (%dx)
#endif


	movq    WC_RBP(%rbx), %rbp
	movq    WC_RSP(%rbx), %rsp

#if     LED
	movw        $WC_LED, %dx
	movb        $0xe0, %al
	outb    (%dx)
#endif

#if     SERIAL
	movw        $WC_COM, %dx
	movb        $0x70, %al
	outb    (%dx)
#endif


	movq    WC_RCX(%rbx), %rcx

	pushq	WC_EFLAGS(%rbx)			/ restore flags
	popfq

#if     LED
	movw        $WC_LED, %dx
	movb        $0xe1, %al
	outb    (%dx)
#endif

#if     SERIAL
	movw        $WC_COM, %dx
	movb        $0x71, %al
	outb    (%dx)
#endif

/*
 * can not use outb after this point, because doing so would mean using
 * %dx which would modify %rdx which is restored here
 */

	movq	%rbx, %rax
	movq    WC_RDX(%rax), %rdx
	movq    WC_RBX(%rax), %rbx

	leave

	movq	WC_RETADDR(%rax), %rax
	movq	%rax, (%rsp)		/ return to caller of wc_save_context

	xorl	%eax, %eax			/ at wakeup return 0
	ret


	SET_SIZE(wc_rm_start)

	ENTRY_NP(asmspin)

	movl	%edi, %ecx
A1:
	loop	A1

	SET_SIZE(asmspin)

	.globl wc_rm_end
wc_rm_end:
	nop

/*
 * 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 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright 2019 Joyent, Inc.
 */

#include <sys/asm_linkage.h>
#include <sys/asm_misc.h>
#include <sys/regset.h>
#include <sys/psw.h>

#include <sys/pcb.h>
#include <sys/trap.h>
#include <sys/ftrace.h>
#include <sys/traptrace.h>
#include <sys/clock.h>
#include <sys/panic.h>
#include <sys/privregs.h>

#include "assym.h"


/*
 * XX64: We are assuming that libc continues to expect the 64-bit value being
 * returned in %edx:%eax.  We further assume that it is safe to leave
 * the top 32-bit intact in %rax as they will be ignored by libc.  In
 * other words, if the 64-bit value is already in %rax, while we manually
 * manufacture a 64-bit value in %edx:%eax by setting %edx to be the high
 * 32 bits of %rax, we don't zero them out in %rax.
 * The following amd64 versions will need to be changed if the above
 * assumptions are not true.
 */

	.globl	gethrtimef
	ENTRY_NP(get_hrtime)
	FAST_INTR_PUSH
	movq	gethrtimef(%rip), %rax
	INDIRECT_CALL_REG(rax)
	movq	%rax, %rdx
	shrq	$32, %rdx			/* high 32-bit in %edx */
	FAST_INTR_POP
	FAST_INTR_RETURN
	SET_SIZE(get_hrtime)

	.globl	gethrestimef
	ENTRY_NP(get_hrestime)
	FAST_INTR_PUSH
	subq	$TIMESPEC_SIZE, %rsp
	movq	%rsp, %rdi
	movq	gethrestimef(%rip), %rax
	INDIRECT_CALL_REG(rax)
	movl	(%rsp), %eax
	movl	CLONGSIZE(%rsp), %edx
	addq	$TIMESPEC_SIZE, %rsp
	FAST_INTR_POP
	FAST_INTR_RETURN
	SET_SIZE(get_hrestime)

	/*
	 * In C this is
	 *
	 * klwp_t *lwp = ttolwp(curthread);
	 * struct mstate *ms = &lwp->lwp_mstate;
	 * return (gethrtime() - ms->ms_state_start + ms->ms_acct[LMS_USER]);
	 */
	ENTRY_NP(gethrvtime)
	FAST_INTR_PUSH
	call	gethrtime_unscaled		/* get time since boot */
	movq	%gs:CPU_LWP, %rcx		/* current lwp */
	subq	LWP_MS_STATE_START(%rcx), %rax	/* - ms->ms_state_start */
	addq	LWP_ACCT_USER(%rcx), %rax	/* add ms->ms_acct[LMS_USER] */
	subq	$16, %rsp
	movq	%rax, (%rsp)
	movq	%rsp, %rdi
	call	scalehrtime
	movq	(%rsp), %rax
	addq	$16, %rsp
	movq	%rax, %rdx
	shrq	$32, %rdx			/* high 32-bit in %rdx */
	FAST_INTR_POP
	FAST_INTR_RETURN
	SET_SIZE(gethrvtime)

	/*
	 * In C this is:
	 *
	 * return (((uint64_t)(curthread->t_lpl->lpl_lgrpid) << 32) |
	 *     curthread->t_cpu->cpu_id);
	 */
	ENTRY_NP(getlgrp)
	FAST_INTR_PUSH
	movq	%gs:CPU_THREAD, %rcx
	movq	T_LPL(%rcx), %rcx
	movl	LPL_LGRPID(%rcx), %edx
	movl	%gs:CPU_ID, %eax
	FAST_INTR_POP
	FAST_INTR_RETURN
	SET_SIZE(getlgrp)

/*
 * 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 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright 2018 Joyent, Inc.
 */


#include <sys/asm_linkage.h>
#include <sys/segments.h>
#include <sys/controlregs.h>
#include <sys/machparam.h>
#include <sys/multiboot.h>
#include <sys/fastboot.h>
#include "assym.h"

/*
 * This code is to switch from 64-bit or 32-bit to protected mode.
 */

/*
 * For debugging with LEDs
 */
#define	FB_OUTB_ASM(val)	\
    movb	val, %al;	\
    outb	$0x80;


#define	DISABLE_PAGING							\
	movl	%cr4, %eax						;\
	btrl	$17, %eax	/* clear PCIDE bit */			;\
	movl	%eax, %cr4						;\
	movl	%cr0, %eax						;\
	btrl	$31, %eax	/* clear PG bit */			;\
	movl	%eax, %cr0

/*
 * This macro contains common code for 64/32-bit versions of copy_sections().
 * On entry:
 *	fbf points to the fboot_file_t
 *	snum contains the number of sections
 * Registers that would be clobbered:
 *	fbs, snum, %eax, %ecx, %edi, %esi.
 * NOTE: fb_dest_pa is supposed to be in the first 1GB,
 * therefore it is safe to use 32-bit register to hold it's value
 * even for 64-bit code.
 */

#define	COPY_SECT(fbf, fbs, snum)		\
	lea	FB_SECTIONS(fbf), fbs;		\
	xorl	%eax, %eax;			\
1:	movl	FB_DEST_PA(fbf), %esi;		\
	addl	FB_SEC_OFFSET(fbs), %esi;	\
	movl	FB_SEC_PADDR(fbs), %edi;	\
	movl	FB_SEC_SIZE(fbs), %ecx;		\
	rep					\
	  movsb;				\
	/* Zero BSS */				\
	movl	FB_SEC_BSS_SIZE(fbs), %ecx;	\
	rep					\
	  stosb;				\
	add	$FB_SECTIONS_INCR, fbs;		\
	dec	snum;				\
	jnz	1b


	.globl	_start
_start:

	/* Disable interrupts */
	cli

	/* Switch to a low memory stack */
	movq	$_start, %rsp
	addq	$FASTBOOT_STACK_OFFSET, %rsp

	/*
	 * Copy from old stack to new stack
	 * If the content before fi_valid gets bigger than 0x200 bytes,
	 * the reserved stack size above will need to be changed.
	 */
	movq	%rdi, %rsi	/* source from old stack */
	movq	%rsp, %rdi	/* destination on the new stack */
	movq	$FI_VALID, %rcx	/* size to copy */
	rep
	  smovb

	xorl	%eax, %eax
	xorl	%edx, %edx

	movl	$MSR_AMD_FSBASE, %ecx
	wrmsr

	movl	$MSR_AMD_GSBASE, %ecx
	wrmsr

	movl	$MSR_AMD_KGSBASE, %ecx
	wrmsr

	/*
	 * zero out all the registers to make sure they're 16 bit clean
	 */
	xorq	%r8, %r8
	xorq	%r9, %r9
	xorq	%r10, %r10
	xorq	%r11, %r11
	xorq	%r12, %r12
	xorq	%r13, %r13
	xorq	%r14, %r14
	xorq	%r15, %r15
	xorl	%eax, %eax
	xorl	%ebx, %ebx
	xorl	%ecx, %ecx
	xorl	%edx, %edx
	xorl	%ebp, %ebp

	/*
	 * Load our own GDT
	 */
	lgdt	gdt_info
	/*
	 * Load our own IDT
	 */
	lidt	idt_info

	/*
	 * Invalidate all TLB entries.
	 * Load temporary pagetables to copy kernel and boot-archive
	 */
	movq	%cr4, %rax
	andq	$_BITNOT(CR4_PGE), %rax
	movq	%rax, %cr4
	movq	FI_PAGETABLE_PA(%rsp), %rax
	movq	%rax, %cr3

	leaq	FI_FILES(%rsp), %rbx	/* offset to the files */

	/* copy unix to final destination */
	movq	FI_LAST_TABLE_PA(%rsp), %rsi	/* page table PA */
	leaq	_MUL(FASTBOOT_UNIX, FI_FILES_INCR)(%rbx), %rdi
	call	map_copy

	/* copy boot archive to final destination */
	movq	FI_LAST_TABLE_PA(%rsp), %rsi	/* page table PA */
	leaq	_MUL(FASTBOOT_BOOTARCHIVE, FI_FILES_INCR)(%rbx), %rdi
	call	map_copy

	/* Copy sections if there are any */
	leaq	_MUL(FASTBOOT_UNIX, FI_FILES_INCR)(%rbx), %rdi
	movl	FB_SECTCNT(%rdi), %esi
	cmpl	$0, %esi
	je	1f
	call	copy_sections
1:
	/*
	 * Shut down 64 bit mode. First get into compatiblity mode.
	 */
	movq	%rsp, %rax
	pushq	$B32DATA_SEL
	pushq	%rax
	pushf
	pushq	$B32CODE_SEL
	pushq	$1f
	iretq

	.code32
1:
	movl	$B32DATA_SEL, %eax
	movw	%ax, %ss
	movw	%ax, %ds
	movw	%ax, %es
	movw	%ax, %fs
	movw	%ax, %gs

	/*
	 * Disable long mode by:
	 * - shutting down paging (bit 31 of cr0).  This will flush the
	 *   TLBs.
	 * - turning off PCID in cr4
	 * - disabling LME (long mode enable) in EFER (extended feature reg)
	 */
	DISABLE_PAGING		/* clobbers %eax */

	ljmp	$B32CODE_SEL, $1f
1:

	/*
	 * Clear PGE, PAE and PSE flags as dboot expects them to be
	 * cleared.
	 */
	movl	%cr4, %eax
	andl	$_BITNOT(CR4_PGE | CR4_PAE | CR4_PSE), %eax
	movl	%eax, %cr4

	movl	$MSR_AMD_EFER, %ecx	/* Extended Feature Enable */
	rdmsr
	btcl	$8, %eax		/* bit 8 Long Mode Enable bit */
	wrmsr

dboot_jump:
	/* Jump to dboot */
	movl	$DBOOT_ENTRY_ADDRESS, %edi
	movl	FI_NEW_MBI_PA(%esp), %ebx
	movl	$MB_BOOTLOADER_MAGIC, %eax
	jmp	*%edi

	.code64
	ENTRY_NP(copy_sections)
	/*
	 * On entry
	 *	%rdi points to the fboot_file_t
	 *	%rsi contains number of sections
	 */
	movq	%rdi, %rdx
	movq	%rsi, %r9

	COPY_SECT(%rdx, %r8, %r9)
	ret
	SET_SIZE(copy_sections)

	ENTRY_NP(map_copy)
	/*
	 * On entry
	 *	%rdi points to the fboot_file_t
	 *	%rsi has FI_LAST_TABLE_PA(%rsp)
	 */

	movq	%rdi, %rdx
	movq	%rsi, %r8
	movq	FB_PTE_LIST_PA(%rdx), %rax	/* PA list of the source */
	movq	FB_DEST_PA(%rdx), %rdi		/* PA of the destination */

2:
	movq	(%rax), %rcx			/* Are we done? */
	cmpl	$FASTBOOT_TERMINATE, %ecx
	je	1f

	movq	%rcx, (%r8)
	movq	%cr3, %rsi		/* Reload cr3 */
	movq	%rsi, %cr3
	movq	FB_VA(%rdx), %rsi	/* Load from VA */
	movq	$PAGESIZE, %rcx
	shrq	$3, %rcx		/* 8-byte at a time */
	rep
	  smovq
	addq	$8, %rax 		/* Go to next PTE */
	jmp	2b
1:
	ret
	SET_SIZE(map_copy)

idt_info:
	.value	0x3ff
	.quad	0

/*
 * We need to trampoline thru a gdt we have in low memory.
 */
#include "../boot/boot_gdt.s"
/*
 * 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) 1992, 2010, Oracle and/or its affiliates. All rights reserved.
 *
 * Copyright 2018 Joyent, Inc.
 */

#ifndef	_GENASSYM
#define	_GENASSYM
#endif

#define	exit	kern_exit

#include <sys/types.h>
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/elf_notes.h>
#include <sys/thread.h>
#include <sys/rwlock.h>
#include <sys/proc.h>
#include <sys/cpuvar.h>
#include <sys/clock.h>
#include <sys/trap.h>
#include <sys/modctl.h>
#include <sys/traptrace.h>
#include <vm/seg.h>
#include <sys/avintr.h>
#include <sys/pic.h>
#include <sys/pit.h>
#include <sys/fp.h>
#include <sys/disp.h>
#include <sys/archsystm.h>
#include <sys/x86_archext.h>
#include <sys/sunddi.h>
#include <sys/mach_mmu.h>

#if defined(__xpv)
#include <sys/hypervisor.h>
#endif

#undef	exit		/* unhide exit, see comment above */
extern void exit(int);

/*
 * Proactively discourage anyone from referring to structures or
 * member offsets in this program.
 */
#define	struct	struct...
#define	OFFSET	OFFSET...

int
main(int argc, char *argv[])
{
	printf("#define\tLOCK_LEVEL 0x%x\n", LOCK_LEVEL);
	printf("#define\tCLOCK_LEVEL 0x%x\n", CLOCK_LEVEL);
	printf("#define\tDISP_LEVEL 0x%x\n", DISP_LEVEL);
	printf("#define\tPIL_MAX 0x%x\n", PIL_MAX);
	printf("#define\tHIGH_LEVELS 0x%x\n", HIGH_LEVELS);
	printf("#define\tCPU_INTR_ACTV_HIGH_LEVEL_MASK 0x%x\n",
	    CPU_INTR_ACTV_HIGH_LEVEL_MASK);

	printf("#define\tPIC_NSEOI 0x%x\n", PIC_NSEOI);
	printf("#define\tPIC_SEOI_LVL7 0x%x\n", PIC_SEOI_LVL7);

	printf("#define\tNANOSEC 0x%llx\n", NANOSEC);
	printf("#define\tADJ_SHIFT 0x%x\n", ADJ_SHIFT);

	printf("#define\tSSLEEP 0x%x\n", SSLEEP);
	printf("#define\tSRUN 0x%x\n", SRUN);
	printf("#define\tSONPROC 0x%x\n", SONPROC);

	printf("#define\tT_INTR_THREAD 0x%x\n", T_INTR_THREAD);
	printf("#define\tFREE_THREAD 0x%x\n", TS_FREE);
	printf("#define\tTS_FREE 0x%x\n", TS_FREE);
	printf("#define\tTS_ZOMB 0x%x\n", TS_ZOMB);
	printf("#define\tTP_MSACCT 0x%x\n", TP_MSACCT);
	printf("#define\tTP_WATCHPT 0x%x\n", TP_WATCHPT);
	printf("#define\tONPROC_THREAD 0x%x\n", TS_ONPROC);

	printf("#define\tS_READ 0x%x\n", (int)S_READ);
	printf("#define\tS_WRITE 0x%x\n", (int)S_WRITE);
	printf("#define\tS_EXEC 0x%x\n", (int)S_EXEC);
	printf("#define\tS_OTHER 0x%x\n", (int)S_OTHER);

	printf("#define\tNORMALRETURN 0x%x\n", (int)NORMALRETURN);
	printf("#define\tLWP_USER 0x%x\n", LWP_USER);
	printf("#define\tLWP_SYS 0x%x\n", LWP_SYS);
	printf("#define\tLMS_USER 0x%x\n", LMS_USER);
	printf("#define\tLMS_SYSTEM 0x%x\n", LMS_SYSTEM);

	printf("#define\tSSE_MXCSR_EFLAGS 0x%x\n", SSE_MXCSR_EFLAGS);

	printf("#define\tFP_FXSAVE 0x%x\n", FP_FXSAVE);
	printf("#define\tFP_XSAVE 0x%x\n", FP_XSAVE);

	printf("#define\tAV_INT_SPURIOUS 0x%x\n", AV_INT_SPURIOUS);

	printf("#define\tCPU_READY 0x%x\n", CPU_READY);
	printf("#define\tCPU_QUIESCED 0x%x\n", CPU_QUIESCED);

	printf("#define\tMCMD_PORT 0x%x\n", MCMD_PORT);
	printf("#define\tSCMD_PORT 0x%x\n", SCMD_PORT);
	printf("#define\tMIMR_PORT 0x%x\n", MIMR_PORT);
	printf("#define\tSIMR_PORT 0x%x\n", SIMR_PORT);

	printf("#define\tDMP_NOSYNC 0x%x\n", DMP_NOSYNC);

	printf("#define\tRW_WRITER\t0x%x\n", RW_WRITER);
	printf("#define\tRW_READER\t0x%x\n", RW_READER);

	printf("#define\tNSYSCALL 0x%x\n", NSYSCALL);

	printf("#define\tSE_32RVAL1 0x%x\n", SE_32RVAL1);
	printf("#define\tSE_32RVAL2 0x%x\n", SE_32RVAL2);
	printf("#define\tSE_64RVAL 0x%x\n", SE_64RVAL);

	printf("#define\tMAXSYSARGS 0x%x\n", MAXSYSARGS);

	/* Hack value just to allow clock to be kicked */
	printf("#define\tNSEC_PER_CLOCK_TICK 0x%llx\n", NANOSEC / 100);

	printf("#define\tNSEC_PER_COUNTER_TICK 0x%llx\n", NANOSEC / PIT_HZ);

	printf("#define\tNBPW 0x%x\n", (uint_t)NBPW);

	printf("#define\tDDI_ACCATTR_IO_SPACE 0x%x\n", DDI_ACCATTR_IO_SPACE);
	printf("#define\tDDI_ACCATTR_DIRECT 0x%x\n", DDI_ACCATTR_DIRECT);
	printf("#define\tDDI_ACCATTR_CPU_VADDR 0x%x\n", DDI_ACCATTR_CPU_VADDR);
	printf("#define\tDDI_DEV_AUTOINCR 0x%x\n", DDI_DEV_AUTOINCR);

	printf("#define\tMMU_STD_PAGESIZE 0x%x\n", (uint_t)MMU_STD_PAGESIZE);
	printf("#define\tMMU_STD_PAGEMASK 0x%x\n", (uint_t)MMU_STD_PAGEMASK);
	printf("#define\tFOUR_MEG 0x%x\n", (uint_t)FOUR_MEG);

	printf("#define\tTRAPTR_NENT 0x%x\n", TRAPTR_NENT);

	printf("#define\tCPU_DTRACE_NOFAULT 0x%x\n", CPU_DTRACE_NOFAULT);
	printf("#define\tCPU_DTRACE_BADADDR 0x%x\n", CPU_DTRACE_BADADDR);
	printf("#define\tCPU_DTRACE_DIVZERO 0x%x\n", CPU_DTRACE_DIVZERO);
	printf("#define\tCPU_DTRACE_ILLOP 0x%x\n", CPU_DTRACE_ILLOP);

	printf("#define\tMODS_NOUNLOAD 0x%x\n", MODS_NOUNLOAD);
	printf("#define\tMODS_WEAK 0x%x\n", MODS_WEAK);
	printf("#define\tMODS_INSTALLED 0x%x\n", MODS_INSTALLED);

	printf("#define\tKPREEMPT_SYNC 0x%x\n", KPREEMPT_SYNC);

#if defined(__xpv)
	printf("#define\tSHUTDOWN_reboot 0x%x\n", SHUTDOWN_reboot);
	printf("#define\tSCHEDOP_block 0x%x\n", SCHEDOP_block);
	printf("#define\tVGCF_IN_KERNEL 0x%x\n", VGCF_IN_KERNEL);
#endif
	return (0);
}
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright 2019 Joyent, Inc.
 */


#include <sys/asm_linkage.h>

	ENTRY_NP(hma_vmx_vmxon)
	push	%rbp
	movq	%rsp, %rbp
	pushq	%rdi

	xorl	%eax, %eax
	vmxon	-0x8(%rbp)
	ja	1f	/* CF=0, ZF=0 (success) */
	incl	%eax
1:

	leave
	ret
	SET_SIZE(hma_vmx_vmxon)

	ENTRY_NP(hma_vmx_do_invept)
	push	%rbp
	movq	%rsp, %rbp
	pushq	%rdi
	pushq	%rsi

	/* build INVEPT descriptor on stack */
	xorl	%eax, %eax
	pushq	%rax;
	pushq	%rsi

	invept	(%rsp), %rdi
	ja	1f	/* CF=0, ZF=0 (success) */
	incl	%eax
1:

	leave
	ret
	SET_SIZE(hma_vmx_do_invept)
/*
 * 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 2019 Joyent, Inc.
 */

/*	Copyright (c) 1990, 1991 UNIX System Laboratories, Inc.	*/
/*	Copyright (c) 1984, 1986, 1987, 1988, 1989, 1990 AT&T	*/
/*	  All Rights Reserved					*/

/*	Copyright (c) 1987, 1988 Microsoft Corporation		*/
/*	  All Rights Reserved					*/

#include <sys/asm_linkage.h>
#include <sys/asm_misc.h>
#include <sys/regset.h>
#include <sys/psw.h>
#include <sys/x86_archext.h>

#include <sys/segments.h>
#include <sys/pcb.h>
#include <sys/trap.h>
#include <sys/ftrace.h>
#include <sys/traptrace.h>
#include <sys/clock.h>
#include <sys/panic.h>
#include "assym.h"

	/*
	 * Common register usage:
	 *
	 * %r12		trap trace pointer
	 */
	ENTRY_NP2(cmnint, _interrupt)

	INTR_PUSH
	INTGATE_INIT_KERNEL_FLAGS	/* (set kernel rflags values) */

	/*
	 * At the end of TRACE_PTR %r12 points to the current TRAPTRACE entry
	 */
	TRACE_PTR(%r12, %rax, %eax, %rdx, $TT_INTERRUPT)
						/* Uses labels 8 and 9 */
	TRACE_REGS(%r12, %rsp, %rax, %rbx)	/* Uses label 9 */
	TRACE_STAMP(%r12)		/* Clobbers %eax, %edx, uses 9 */

	movq	%rsp, %rbp

	TRACE_STACK(%r12)

#ifdef TRAPTRACE
	LOADCPU(%rbx)				/* &cpu */
	movl	CPU_PRI(%rbx), %r14d		/* old ipl */
	movl	$255, TTR_IPL(%r12)
	movl	%r14d, %edi
	movb	%dil, TTR_PRI(%r12)
	movl	CPU_BASE_SPL(%rbx), %edi
	movb	%dil, TTR_SPL(%r12)
	movb	$255, TTR_VECTOR(%r12)
	movq	%r12, %rsi		/* pass traptrace record pointer */
#endif

	movq	%rsp, %rdi		/* pass struct regs pointer */
	movq	do_interrupt_common, %rax
	INDIRECT_CALL_REG(rax)

	jmp	_sys_rtt_ints_disabled
	/*NOTREACHED*/

	SET_SIZE(cmnint)
	SET_SIZE(_interrupt)

/*
 * Declare a uintptr_t which has the size of _interrupt to enable stack
 * traceback code to know when a regs structure is on the stack.
 */
	.globl	_interrupt_size
	.align	CLONGSIZE
_interrupt_size:
	.NWORD	. - _interrupt
	.type	_interrupt_size, @object

	/*
	 * If we're here, we're being called from splx() to fake a soft
	 * interrupt (note that interrupts are still disabled from
	 * splx()).  We execute this code when a soft interrupt is
	 * posted at level higher than the CPU's current spl; when spl
	 * is lowered in splx(), it will see the softint and jump here.
	 * We'll do exactly what a trap would do:  push our flags, %cs,
	 * %rip, error code and trap number (T_SOFTINT).  The cmnint()
	 * code will see T_SOFTINT and branch to the dosoftint() code.
	 *
	 * iretq -always- pops all five regs. Imitate the 16-byte
	 * auto-align of the stack, and the zero-ed out %ss value.
	 */

	ENTRY_NP(fakesoftint)
	movq	%rsp, %r11
	andq	$-16, %rsp
	pushq	$KDS_SEL	/* %ss */
	pushq	%r11		/* %rsp */
	pushf			/* rflags */
#if defined(__xpv)
	popq	%r11
	EVENT_MASK_TO_IE(%rdi, %r11)
	pushq	%r11
#endif
	pushq	$KCS_SEL	/* %cs */
	leaq	fakesoftint_return(%rip), %r11
	pushq	%r11		/* %rip */
	pushq	$0		/* err */
	pushq	$T_SOFTINT	/* trap */
	jmp	cmnint
	ALTENTRY(fakesoftint_return)
	ret
	SET_SIZE(fakesoftint_return)
	SET_SIZE(fakesoftint)

/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */
/*
 * Copyright 2019 Joyent, Inc.
 * Copyright 2020 OmniOS Community Edition (OmniOSce) Association.
 */

/*
 * This file contains the trampolines that are used by KPTI in order to be
 * able to take interrupts/trap/etc while on the "user" page table.
 *
 * We don't map the full kernel text into the user page table: instead we
 * map this one small section of trampolines (which compiles to ~13 pages).
 * These trampolines are set in the IDT always (so they will run no matter
 * whether we're on the kernel or user page table), and their primary job is to
 * pivot us to the kernel %cr3 and %rsp without ruining everything.
 *
 * All of these interrupts use the amd64 IST feature when we have KPTI enabled,
 * meaning that they will execute with their %rsp set to a known location, even
 * if we take them in the kernel.
 *
 * Over in desctbls.c (for cpu0) and mp_pc.c (other cpus) we set up the IST
 * stack to point at &cpu->cpu_m.mcpu_kpti.kf_tr_rsp. You can see the mcpu_kpti
 * (a struct kpti_frame) defined in machcpuvar.h. This struct is set up to be
 * page-aligned, and we map the page it's on into both page tables. Using a
 * struct attached to the cpu_t also means that we can use %rsp-relative
 * addressing to find anything on the cpu_t, so we don't have to touch %gs or
 * GSBASE at all on incoming interrupt trampolines (which can get pretty hairy).
 *
 * This little struct is where the CPU will push the actual interrupt frame.
 * Then, in the trampoline, we change %cr3, then figure out our destination
 * stack pointer and "pivot" to it (set %rsp and re-push the CPU's interrupt
 * frame). Then we jump to the regular ISR in the kernel text and carry on as
 * normal.
 *
 * We leave the original frame and any spilled regs behind in the kpti_frame
 * lazily until we want to return to userland. Then, we clear any spilled
 * regs from it, and overwrite the rest with our iret frame. When switching
 * this cpu to a different process (in hat_switch), we bzero the whole region to
 * make sure nothing can leak between processes.
 *
 * When we're returning back to the original place we took the interrupt later
 * (especially if it was in userland), we have to jmp back to the "return
 * trampolines" here, since when we set %cr3 back to the user value, we need to
 * be executing from code here in these shared pages and not the main kernel
 * text again. Even though it should be fine to iret directly from kernel text
 * when returning to kernel code, we make things jmp to a trampoline here just
 * for consistency.
 *
 * Note that with IST, it's very important that we always must have pivoted
 * away from the IST stack before we could possibly take any other interrupt
 * on the same IST (unless it's an end-of-the-world fault and we don't care
 * about coming back from it ever).
 *
 * This is particularly relevant to the dbgtrap/brktrap trampolines, as they
 * regularly have to happen from within trampoline code (e.g. in the sysenter
 * single-step case) and then return to the world normally. As a result, these
 * two are IST'd to their own kpti_frame right above the normal one (in the same
 * page), so they don't clobber their parent interrupt.
 *
 * To aid with debugging, we also IST the page fault (#PF/pftrap), general
 * protection fault (#GP/gptrap) and stack fault (#SS/stktrap) interrupts to
 * their own separate kpti_frame. This ensures that if we take one of these
 * due to a bug in trampoline code, we preserve the original trampoline
 * state that caused the trap.
 *
 * NMI, MCE and dblfault interrupts also are taken on their own dedicated IST
 * stacks, since they can interrupt another ISR at any time. These stacks are
 * full-sized, however, and not a little kpti_frame struct. We only set %cr3 in
 * their trampolines (and do it unconditionally), and don't bother pivoting
 * away. We're either going into the panic() path, or we're going to return
 * straight away without rescheduling, so it's fine to not be on our real
 * kthread stack (and some of the state we want to go find it with might be
 * corrupt!)
 *
 * Finally, for these "special" interrupts (NMI/MCE/double fault) we use a
 * special %cr3 value we stash here in the text (kpti_safe_cr3). We set this to
 * point at the PML4 for kas early in boot and never touch it again. Hopefully
 * it survives whatever corruption brings down the rest of the kernel!
 *
 * Syscalls are different to interrupts (at least in the SYSENTER/SYSCALL64
 * cases) in that they do not push an interrupt frame (and also have some other
 * effects). In the syscall trampolines, we assume that we can only be taking
 * the call from userland and use swapgs and an unconditional overwrite of %cr3.
 * We do not do any stack pivoting for syscalls (and we leave SYSENTER's
 * existing %rsp pivot untouched) -- instead we spill registers into
 * %gs:CPU_KPTI_* as we need to.
 *
 * Note that the normal %cr3 values do not cause invalidations with PCIDE - see
 * hat_switch().
 */

/*
 * The macros here mostly line up with what's in kdi_idthdl.s, too, so if you
 * fix bugs here check to see if they should be fixed there as well.
 */

#include <sys/asm_linkage.h>
#include <sys/asm_misc.h>
#include <sys/regset.h>
#include <sys/privregs.h>
#include <sys/psw.h>
#include <sys/machbrand.h>
#include <sys/param.h>

#include <sys/segments.h>
#include <sys/pcb.h>
#include <sys/trap.h>
#include <sys/ftrace.h>
#include <sys/traptrace.h>
#include <sys/clock.h>
#include <sys/model.h>
#include <sys/panic.h>

#if defined(__xpv)
#include <sys/hypervisor.h>
#endif

#include "assym.h"

	.data
	DGDEF3(kpti_enable, 8, 8)
	.fill	1, 8, 1

#if DEBUG
	.data
_bad_ts_panic_msg:
	.string "kpti_trampolines.s: tr_iret_user but CR0.TS set"
#endif

.section ".text";
.align MMU_PAGESIZE

.global kpti_tramp_start
kpti_tramp_start:
	nop

/* This will be set by mlsetup, and then double-checked later */
.global kpti_safe_cr3
kpti_safe_cr3:
	.quad 0
	SET_SIZE(kpti_safe_cr3)

/* startup_kmem() will overwrite this */
.global kpti_kbase
kpti_kbase:
	.quad KERNELBASE
	SET_SIZE(kpti_kbase)

#define	SET_KERNEL_CR3(spillreg)		\
	mov	%cr3, spillreg;			\
	mov	spillreg, %gs:CPU_KPTI_TR_CR3;	\
	mov	%gs:CPU_KPTI_KCR3, spillreg;	\
	cmp	$0, spillreg;			\
	je	2f;				\
	mov	spillreg, %cr3;			\
2:

#if DEBUG
#define	SET_USER_CR3(spillreg)			\
	mov	%cr3, spillreg;			\
	mov	spillreg, %gs:CPU_KPTI_TR_CR3;	\
	mov	%gs:CPU_KPTI_UCR3, spillreg;	\
	mov	spillreg, %cr3
#else
#define	SET_USER_CR3(spillreg)			\
	mov	%gs:CPU_KPTI_UCR3, spillreg;	\
	mov	spillreg, %cr3
#endif

#define	PIVOT_KPTI_STK(spillreg)		\
	mov	%rsp, spillreg;			\
	mov	%gs:CPU_KPTI_RET_RSP, %rsp;	\
	pushq	T_FRAMERET_SS(spillreg);	\
	pushq	T_FRAMERET_RSP(spillreg);	\
	pushq	T_FRAMERET_RFLAGS(spillreg);	\
	pushq	T_FRAMERET_CS(spillreg);	\
	pushq	T_FRAMERET_RIP(spillreg)


#define	INTERRUPT_TRAMPOLINE_P(errpush)	\
	pushq	%r13;				\
	pushq	%r14;				\
	subq	$KPTI_R14, %rsp;		\
	/* Save current %cr3. */		\
	mov	%cr3, %r14;			\
	mov	%r14, KPTI_TR_CR3(%rsp);	\
						\
	cmpw	$KCS_SEL, KPTI_CS(%rsp);	\
	je	3f;				\
1:						\
	/* Change to the "kernel" %cr3 */	\
	mov	KPTI_KCR3(%rsp), %r14;		\
	cmp	$0, %r14;			\
	je	2f;				\
	mov	%r14, %cr3;			\
2:						\
	/* Get our cpu_t in %r13 */		\
	mov	%rsp, %r13;			\
	and	$(~(MMU_PAGESIZE - 1)), %r13;	\
	subq	$CPU_KPTI_START, %r13;		\
	/* Use top of the kthread stk */	\
	mov	CPU_THREAD(%r13), %r14;		\
	mov	T_STACK(%r14), %r14;		\
	addq	$REGSIZE+MINFRAME, %r14;	\
	jmp	4f;				\
3:						\
	/* Check the %rsp in the frame. */	\
	/* Is it above kernel base? */		\
	mov	kpti_kbase, %r14;		\
	cmp	%r14, KPTI_RSP(%rsp);		\
	jb	1b;				\
	/* Use the %rsp from the trap frame */	\
	mov	KPTI_RSP(%rsp), %r14;		\
	and	$(~0xf), %r14;			\
4:						\
	mov	%rsp, %r13;			\
	/* %r14 contains our destination stk */	\
	mov	%r14, %rsp;			\
	pushq	KPTI_SS(%r13);			\
	pushq	KPTI_RSP(%r13);			\
	pushq	KPTI_RFLAGS(%r13);		\
	pushq	KPTI_CS(%r13);			\
	pushq	KPTI_RIP(%r13);			\
	errpush;				\
	mov	KPTI_R14(%r13), %r14;		\
	mov	KPTI_R13(%r13), %r13

#define	INTERRUPT_TRAMPOLINE_NOERR		\
	INTERRUPT_TRAMPOLINE_P(/**/)

#define	INTERRUPT_TRAMPOLINE			\
	INTERRUPT_TRAMPOLINE_P(pushq KPTI_ERR(%r13))

/*
 * This is used for all interrupts that can plausibly be taken inside another
 * interrupt and are using a kpti_frame stack (so #BP, #DB, #GP, #PF, #SS).
 *
 * We also use this for #NP, even though it uses the standard IST: the
 * additional %rsp checks below will catch when we get an exception doing an
 * iret to userspace with a bad %cs/%ss.  This appears as a kernel trap, and
 * only later gets redirected via kern_gpfault().
 *
 * We check for whether we took the interrupt while in another trampoline, in
 * which case we need to use the kthread stack.
 */
#define	DBG_INTERRUPT_TRAMPOLINE_P(errpush)	\
	pushq	%r13;				\
	pushq	%r14;				\
	subq	$KPTI_R14, %rsp;		\
	/* Check for clobbering */		\
	cmpq	$0, KPTI_FLAG(%rsp);		\
	je	1f;				\
	/* Don't worry, this totally works */	\
	int	$8;				\
1:						\
	movq	$1, KPTI_FLAG(%rsp);		\
	/* Save current %cr3. */		\
	mov	%cr3, %r14;			\
	mov	%r14, KPTI_TR_CR3(%rsp);	\
						\
	cmpw	$KCS_SEL, KPTI_CS(%rsp);	\
	je	4f;				\
2:						\
	/* Change to the "kernel" %cr3 */	\
	mov	KPTI_KCR3(%rsp), %r14;		\
	cmp	$0, %r14;			\
	je	3f;				\
	mov	%r14, %cr3;			\
3:						\
	/* Get our cpu_t in %r13 */		\
	mov	%rsp, %r13;			\
	and	$(~(MMU_PAGESIZE - 1)), %r13;	\
	subq	$CPU_KPTI_START, %r13;		\
	/* Use top of the kthread stk */	\
	mov	CPU_THREAD(%r13), %r14;		\
	mov	T_STACK(%r14), %r14;		\
	addq	$REGSIZE+MINFRAME, %r14;	\
	jmp	6f;				\
4:						\
	/* Check the %rsp in the frame. */	\
	/* Is it above kernel base? */		\
	/* If not, treat as user. */		\
	mov	kpti_kbase, %r14;		\
	cmp	%r14, KPTI_RSP(%rsp);		\
	jb	2b;				\
	/* Is it within the kpti_frame page? */	\
	/* If it is, treat as user interrupt */	\
	mov	%rsp, %r13;			\
	and	$(~(MMU_PAGESIZE - 1)), %r13;	\
	mov	KPTI_RSP(%rsp), %r14;		\
	and	$(~(MMU_PAGESIZE - 1)), %r14;	\
	cmp	%r13, %r14;			\
	je	2b;				\
	/* Were we in trampoline code? */	\
	leaq	kpti_tramp_start, %r14;		\
	cmp	%r14, KPTI_RIP(%rsp);		\
	jb	5f;				\
	leaq	kpti_tramp_end, %r14;		\
	cmp	%r14, KPTI_RIP(%rsp);		\
	ja	5f;				\
	/* If we were, change %cr3: we might */	\
	/* have interrupted before it did. */	\
	mov	KPTI_KCR3(%rsp), %r14;		\
	mov	%r14, %cr3;			\
5:						\
	/* Use the %rsp from the trap frame */	\
	mov	KPTI_RSP(%rsp), %r14;		\
	and	$(~0xf), %r14;			\
6:						\
	mov	%rsp, %r13;			\
	/* %r14 contains our destination stk */	\
	mov	%r14, %rsp;			\
	pushq	KPTI_SS(%r13);			\
	pushq	KPTI_RSP(%r13);			\
	pushq	KPTI_RFLAGS(%r13);		\
	pushq	KPTI_CS(%r13);			\
	pushq	KPTI_RIP(%r13);			\
	errpush;				\
	mov	KPTI_R14(%r13), %r14;		\
	movq	$0, KPTI_FLAG(%r13);		\
	mov	KPTI_R13(%r13), %r13

#define	DBG_INTERRUPT_TRAMPOLINE_NOERR		\
	DBG_INTERRUPT_TRAMPOLINE_P(/**/)

#define	DBG_INTERRUPT_TRAMPOLINE		\
	DBG_INTERRUPT_TRAMPOLINE_P(pushq KPTI_ERR(%r13))

	/*
	 * These labels (_start and _end) are used by trap.c to determine if
	 * we took an interrupt like an NMI during the return process.
	 */
.global	tr_sysc_ret_start
tr_sysc_ret_start:

	/*
	 * Syscall return trampolines.
	 *
	 * These are expected to be called on the kernel %gs. tr_sysret[ql] are
	 * called after %rsp is changed back to the user value, so we have no
	 * stack to work with. tr_sysexit has a kernel stack (but has to
	 * preserve rflags, soooo).
	 */
	ENTRY_NP(tr_sysretq)
	cmpq	$1, kpti_enable
	jne	1f

	mov	%r13, %gs:CPU_KPTI_R13
	SET_USER_CR3(%r13)
	mov	%gs:CPU_KPTI_R13, %r13
	/* Zero these to make sure they didn't leak from a kernel trap */
	movq	$0, %gs:CPU_KPTI_R13
	movq	$0, %gs:CPU_KPTI_R14
1:
	swapgs
	sysretq
	SET_SIZE(tr_sysretq)

	ENTRY_NP(tr_sysretl)
	cmpq	$1, kpti_enable
	jne	1f

	mov	%r13, %gs:CPU_KPTI_R13
	SET_USER_CR3(%r13)
	mov	%gs:CPU_KPTI_R13, %r13
	/* Zero these to make sure they didn't leak from a kernel trap */
	movq	$0, %gs:CPU_KPTI_R13
	movq	$0, %gs:CPU_KPTI_R14
1:
	SWAPGS
	SYSRETL
	SET_SIZE(tr_sysretl)

	ENTRY_NP(tr_sysexit)
	/*
	 * Note: we want to preserve RFLAGS across this branch, since sysexit
	 * (unlike sysret above) does not restore RFLAGS for us.
	 *
	 * We still have the real kernel stack (sysexit does restore that), so
	 * we can use pushfq/popfq.
	 */
	pushfq

	cmpq	$1, kpti_enable
	jne	1f

	/* Have to pop it back off now before we change %cr3! */
	popfq
	mov	%r13, %gs:CPU_KPTI_R13
	SET_USER_CR3(%r13)
	mov	%gs:CPU_KPTI_R13, %r13
	/* Zero these to make sure they didn't leak from a kernel trap */
	movq	$0, %gs:CPU_KPTI_R13
	movq	$0, %gs:CPU_KPTI_R14
	jmp	2f
1:
	popfq
2:
	swapgs
	sti
	SYSEXITL
	SET_SIZE(tr_sysexit)

.global	tr_sysc_ret_end
tr_sysc_ret_end:

	/*
	 * Syscall entry trampolines.
	 */

#if DEBUG
#define	MK_SYSCALL_TRAMPOLINE(isr)		\
	ENTRY_NP(tr_##isr);			\
	swapgs;					\
	mov	%r13, %gs:CPU_KPTI_R13;		\
	mov	%cr3, %r13;			\
	mov	%r13, %gs:CPU_KPTI_TR_CR3;	\
	mov	%gs:CPU_KPTI_KCR3, %r13;	\
	mov	%r13, %cr3;			\
	mov	%gs:CPU_KPTI_R13, %r13;		\
	swapgs;					\
	jmp	isr;				\
	SET_SIZE(tr_##isr)
#else
#define	MK_SYSCALL_TRAMPOLINE(isr)		\
	ENTRY_NP(tr_##isr);			\
	swapgs;					\
	mov	%r13, %gs:CPU_KPTI_R13;		\
	mov	%gs:CPU_KPTI_KCR3, %r13;	\
	mov	%r13, %cr3;			\
	mov	%gs:CPU_KPTI_R13, %r13;		\
	swapgs;					\
	jmp	isr;				\
	SET_SIZE(tr_##isr)
#endif

	MK_SYSCALL_TRAMPOLINE(sys_syscall)
	MK_SYSCALL_TRAMPOLINE(sys_syscall32)
	MK_SYSCALL_TRAMPOLINE(brand_sys_syscall)
	MK_SYSCALL_TRAMPOLINE(brand_sys_syscall32)

	/*
	 * SYSENTER is special. The CPU is really not very helpful when it
	 * comes to preserving and restoring state with it, and as a result
	 * we have to do all of it by hand. So, since we want to preserve
	 * RFLAGS, we have to be very careful in these trampolines to not
	 * clobber any bits in it. That means no cmpqs or branches!
	 */
	ENTRY_NP(tr_sys_sysenter)
	swapgs
	mov	%r13, %gs:CPU_KPTI_R13
#if DEBUG
	mov	%cr3, %r13
	mov	%r13, %gs:CPU_KPTI_TR_CR3
#endif
	mov	%gs:CPU_KPTI_KCR3, %r13
	mov	%r13, %cr3
	mov	%gs:CPU_KPTI_R13, %r13
	jmp	_sys_sysenter_post_swapgs
	SET_SIZE(tr_sys_sysenter)

	ENTRY_NP(tr_brand_sys_sysenter)
	swapgs
	mov	%r13, %gs:CPU_KPTI_R13
#if DEBUG
	mov	%cr3, %r13
	mov	%r13, %gs:CPU_KPTI_TR_CR3
#endif
	mov	%gs:CPU_KPTI_KCR3, %r13
	mov	%r13, %cr3
	mov	%gs:CPU_KPTI_R13, %r13
	jmp	_brand_sys_sysenter_post_swapgs
	SET_SIZE(tr_brand_sys_sysenter)

#define	MK_SYSCALL_INT_TRAMPOLINE(isr)		\
	ENTRY_NP(tr_##isr);			\
	swapgs;					\
	mov	%r13, %gs:CPU_KPTI_R13;		\
	SET_KERNEL_CR3(%r13);			\
	mov	%gs:CPU_THREAD, %r13;		\
	mov	T_STACK(%r13), %r13;		\
	addq	$REGSIZE+MINFRAME, %r13;	\
	mov	%r13, %rsp;			\
	pushq	%gs:CPU_KPTI_SS;		\
	pushq	%gs:CPU_KPTI_RSP;		\
	pushq	%gs:CPU_KPTI_RFLAGS;		\
	pushq	%gs:CPU_KPTI_CS;		\
	pushq	%gs:CPU_KPTI_RIP;		\
	mov	%gs:CPU_KPTI_R13, %r13;		\
	swapgs;					\
	jmp	isr;				\
	SET_SIZE(tr_##isr)

	MK_SYSCALL_INT_TRAMPOLINE(brand_sys_syscall_int)
	MK_SYSCALL_INT_TRAMPOLINE(sys_syscall_int)

	/*
	 * Interrupt/trap return trampolines
	 */

.global	tr_intr_ret_start
tr_intr_ret_start:

	ENTRY_NP(tr_iret_auto)
	cmpq	$1, kpti_enable
	jne	tr_iret_kernel
	cmpw	$KCS_SEL, T_FRAMERET_CS(%rsp)
	je	tr_iret_kernel
	jmp	tr_iret_user
	SET_SIZE(tr_iret_auto)

	ENTRY_NP(tr_iret_kernel)
	/*
	 * Yes, this does nothing extra. But this way we know if we see iret
	 * elsewhere, then we've failed to properly consider trampolines there.
	 */
	iretq
	SET_SIZE(tr_iret_kernel)

	ENTRY_NP(tr_iret_user)
#if DEBUG
	/*
	 * Panic if we find CR0.TS set. We're still on the kernel stack and
	 * %cr3, but we do need to swap back to the kernel gs. (We don't worry
	 * about swapgs speculation here.)
	 */
	pushq	%rax
	mov	%cr0, %rax
	testq	$CR0_TS, %rax
	jz	1f
	swapgs
	popq	%rax
	leaq	_bad_ts_panic_msg(%rip), %rdi
	xorl	%eax, %eax
	pushq	%rbp
	movq	%rsp, %rbp
	call	panic
1:
	popq	%rax
#endif

	cmpq	$1, kpti_enable
	jne	1f

	/*
	 * KPTI enabled: we're on the user gsbase at this point, so we
	 * need to swap back so we can pivot stacks.
	 *
	 * The swapgs lfence mitigation is probably not needed here
	 * since a mis-speculation of the above branch would imply KPTI
	 * is disabled, but we'll do so anyway.
	 */
	swapgs
	lfence
	mov	%r13, %gs:CPU_KPTI_R13
	PIVOT_KPTI_STK(%r13)
	SET_USER_CR3(%r13)
	mov	%gs:CPU_KPTI_R13, %r13
	/* Zero these to make sure they didn't leak from a kernel trap. */
	movq	$0, %gs:CPU_KPTI_R13
	movq	$0, %gs:CPU_KPTI_R14
	/* And back to user gsbase again. */
	swapgs
1:
	iretq
	SET_SIZE(tr_iret_user)

	/*
	 * This special return trampoline is for KDI's use only (with kmdb).
	 *
	 * KDI/kmdb do not use swapgs -- they directly write the GSBASE MSR
	 * instead. This trampoline runs after GSBASE has already been changed
	 * back to the userland value (so we can't use %gs).
	 *
	 * Instead, the caller gives us a pointer to the kpti_dbg frame in %r13.
	 * The KPTI_R13 member in the kpti_dbg has already been set to what the
	 * real %r13 should be before we IRET.
	 *
	 * Additionally, KDI keeps a copy of the incoming %cr3 value when it
	 * took an interrupt, and has put that back in the kpti_dbg area for us
	 * to use, so we don't do any sniffing of %cs here. This is important
	 * so that debugging code that changes %cr3 is possible.
	 */
	ENTRY_NP(tr_iret_kdi)
	movq	%r14, KPTI_R14(%r13)	/* %r14 has to be preserved by us */

	movq	%rsp, %r14	/* original %rsp is pointing at IRET frame */
	leaq	KPTI_TOP(%r13), %rsp
	pushq	T_FRAMERET_SS(%r14)
	pushq	T_FRAMERET_RSP(%r14)
	pushq	T_FRAMERET_RFLAGS(%r14)
	pushq	T_FRAMERET_CS(%r14)
	pushq	T_FRAMERET_RIP(%r14)

	movq	KPTI_TR_CR3(%r13), %r14
	movq	%r14, %cr3

	movq	KPTI_R14(%r13), %r14
	movq	KPTI_R13(%r13), %r13	/* preserved by our caller */

	iretq
	SET_SIZE(tr_iret_kdi)

.global	tr_intr_ret_end
tr_intr_ret_end:

	/*
	 * Interrupt/trap entry trampolines
	 */

	/* CPU pushed an error code, and ISR wants one */
#define	MK_INTR_TRAMPOLINE(isr)			\
	ENTRY_NP(tr_##isr);			\
	INTERRUPT_TRAMPOLINE;			\
	jmp	isr;				\
	SET_SIZE(tr_##isr)

	/* CPU didn't push an error code, and ISR doesn't want one */
#define	MK_INTR_TRAMPOLINE_NOERR(isr)		\
	ENTRY_NP(tr_##isr);			\
	push	$0;				\
	INTERRUPT_TRAMPOLINE_NOERR;		\
	jmp	isr;				\
	SET_SIZE(tr_##isr)

	/* CPU pushed an error code, and ISR wants one */
#define	MK_DBG_INTR_TRAMPOLINE(isr)	\
	ENTRY_NP(tr_##isr);			\
	DBG_INTERRUPT_TRAMPOLINE;		\
	jmp	isr;				\
	SET_SIZE(tr_##isr)

	/* CPU didn't push an error code, and ISR doesn't want one */
#define	MK_DBG_INTR_TRAMPOLINE_NOERR(isr)	\
	ENTRY_NP(tr_##isr);			\
	push	$0;				\
	DBG_INTERRUPT_TRAMPOLINE_NOERR;		\
	jmp	isr;				\
	SET_SIZE(tr_##isr)


	MK_INTR_TRAMPOLINE_NOERR(div0trap)
	MK_DBG_INTR_TRAMPOLINE_NOERR(dbgtrap)
	MK_DBG_INTR_TRAMPOLINE_NOERR(brktrap)
	MK_INTR_TRAMPOLINE_NOERR(ovflotrap)
	MK_INTR_TRAMPOLINE_NOERR(boundstrap)
	MK_INTR_TRAMPOLINE_NOERR(invoptrap)
	MK_INTR_TRAMPOLINE_NOERR(ndptrap)
	MK_INTR_TRAMPOLINE(invtsstrap)
	MK_DBG_INTR_TRAMPOLINE(segnptrap)
	MK_DBG_INTR_TRAMPOLINE(stktrap)
	MK_DBG_INTR_TRAMPOLINE(gptrap)
	MK_DBG_INTR_TRAMPOLINE(pftrap)
	MK_INTR_TRAMPOLINE_NOERR(resvtrap)
	MK_INTR_TRAMPOLINE_NOERR(ndperr)
	MK_INTR_TRAMPOLINE(achktrap)
	MK_INTR_TRAMPOLINE_NOERR(xmtrap)
	MK_INTR_TRAMPOLINE_NOERR(invaltrap)
	MK_INTR_TRAMPOLINE_NOERR(fasttrap)
	MK_INTR_TRAMPOLINE_NOERR(dtrace_ret)

	/*
	 * These are special because they can interrupt other traps, and
	 * each other. We don't need to pivot their stacks, because they have
	 * dedicated IST stack space, but we need to change %cr3.
	 */
	ENTRY_NP(tr_nmiint)
	pushq	%r13
	mov	kpti_safe_cr3, %r13
	mov	%r13, %cr3
	popq	%r13
	jmp	nmiint
	SET_SIZE(tr_nmiint)

#if !defined(__xpv)
	ENTRY_NP(tr_syserrtrap)
	/*
	 * If we got here we should always have a zero error code pushed.
	 * The INT $0x8 instr doesn't seem to push one, though, which we use
	 * as an emergency panic in the other trampolines. So adjust things
	 * here.
	 */
	cmpq	$0, (%rsp)
	je	1f
	pushq	$0
1:
	pushq	%r13
	mov	kpti_safe_cr3, %r13
	mov	%r13, %cr3
	popq	%r13
	jmp	syserrtrap
	SET_SIZE(tr_syserrtrap)
#endif

	ENTRY_NP(tr_mcetrap)
	pushq	%r13
	mov	kpti_safe_cr3, %r13
	mov	%r13, %cr3
	popq	%r13
	jmp	mcetrap
	SET_SIZE(tr_mcetrap)

	/*
	 * Interrupts start at 32
	 */
#define MKIVCT(n)			\
	ENTRY_NP(tr_ivct##n)		\
	push	$0;			\
	INTERRUPT_TRAMPOLINE;		\
	push	$n - 0x20;		\
	jmp	cmnint;			\
	SET_SIZE(tr_ivct##n)

	MKIVCT(32);	MKIVCT(33);	MKIVCT(34);	MKIVCT(35);
	MKIVCT(36);	MKIVCT(37);	MKIVCT(38);	MKIVCT(39);
	MKIVCT(40);	MKIVCT(41);	MKIVCT(42);	MKIVCT(43);
	MKIVCT(44);	MKIVCT(45);	MKIVCT(46);	MKIVCT(47);
	MKIVCT(48);	MKIVCT(49);	MKIVCT(50);	MKIVCT(51);
	MKIVCT(52);	MKIVCT(53);	MKIVCT(54);	MKIVCT(55);
	MKIVCT(56);	MKIVCT(57);	MKIVCT(58);	MKIVCT(59);
	MKIVCT(60);	MKIVCT(61);	MKIVCT(62);	MKIVCT(63);
	MKIVCT(64);	MKIVCT(65);	MKIVCT(66);	MKIVCT(67);
	MKIVCT(68);	MKIVCT(69);	MKIVCT(70);	MKIVCT(71);
	MKIVCT(72);	MKIVCT(73);	MKIVCT(74);	MKIVCT(75);
	MKIVCT(76);	MKIVCT(77);	MKIVCT(78);	MKIVCT(79);
	MKIVCT(80);	MKIVCT(81);	MKIVCT(82);	MKIVCT(83);
	MKIVCT(84);	MKIVCT(85);	MKIVCT(86);	MKIVCT(87);
	MKIVCT(88);	MKIVCT(89);	MKIVCT(90);	MKIVCT(91);
	MKIVCT(92);	MKIVCT(93);	MKIVCT(94);	MKIVCT(95);
	MKIVCT(96);	MKIVCT(97);	MKIVCT(98);	MKIVCT(99);
	MKIVCT(100);	MKIVCT(101);	MKIVCT(102);	MKIVCT(103);
	MKIVCT(104);	MKIVCT(105);	MKIVCT(106);	MKIVCT(107);
	MKIVCT(108);	MKIVCT(109);	MKIVCT(110);	MKIVCT(111);
	MKIVCT(112);	MKIVCT(113);	MKIVCT(114);	MKIVCT(115);
	MKIVCT(116);	MKIVCT(117);	MKIVCT(118);	MKIVCT(119);
	MKIVCT(120);	MKIVCT(121);	MKIVCT(122);	MKIVCT(123);
	MKIVCT(124);	MKIVCT(125);	MKIVCT(126);	MKIVCT(127);
	MKIVCT(128);	MKIVCT(129);	MKIVCT(130);	MKIVCT(131);
	MKIVCT(132);	MKIVCT(133);	MKIVCT(134);	MKIVCT(135);
	MKIVCT(136);	MKIVCT(137);	MKIVCT(138);	MKIVCT(139);
	MKIVCT(140);	MKIVCT(141);	MKIVCT(142);	MKIVCT(143);
	MKIVCT(144);	MKIVCT(145);	MKIVCT(146);	MKIVCT(147);
	MKIVCT(148);	MKIVCT(149);	MKIVCT(150);	MKIVCT(151);
	MKIVCT(152);	MKIVCT(153);	MKIVCT(154);	MKIVCT(155);
	MKIVCT(156);	MKIVCT(157);	MKIVCT(158);	MKIVCT(159);
	MKIVCT(160);	MKIVCT(161);	MKIVCT(162);	MKIVCT(163);
	MKIVCT(164);	MKIVCT(165);	MKIVCT(166);	MKIVCT(167);
	MKIVCT(168);	MKIVCT(169);	MKIVCT(170);	MKIVCT(171);
	MKIVCT(172);	MKIVCT(173);	MKIVCT(174);	MKIVCT(175);
	MKIVCT(176);	MKIVCT(177);	MKIVCT(178);	MKIVCT(179);
	MKIVCT(180);	MKIVCT(181);	MKIVCT(182);	MKIVCT(183);
	MKIVCT(184);	MKIVCT(185);	MKIVCT(186);	MKIVCT(187);
	MKIVCT(188);	MKIVCT(189);	MKIVCT(190);	MKIVCT(191);
	MKIVCT(192);	MKIVCT(193);	MKIVCT(194);	MKIVCT(195);
	MKIVCT(196);	MKIVCT(197);	MKIVCT(198);	MKIVCT(199);
	MKIVCT(200);	MKIVCT(201);	MKIVCT(202);	MKIVCT(203);
	MKIVCT(204);	MKIVCT(205);	MKIVCT(206);	MKIVCT(207);
	MKIVCT(208);	MKIVCT(209);	MKIVCT(210);	MKIVCT(211);
	MKIVCT(212);	MKIVCT(213);	MKIVCT(214);	MKIVCT(215);
	MKIVCT(216);	MKIVCT(217);	MKIVCT(218);	MKIVCT(219);
	MKIVCT(220);	MKIVCT(221);	MKIVCT(222);	MKIVCT(223);
	MKIVCT(224);	MKIVCT(225);	MKIVCT(226);	MKIVCT(227);
	MKIVCT(228);	MKIVCT(229);	MKIVCT(230);	MKIVCT(231);
	MKIVCT(232);	MKIVCT(233);	MKIVCT(234);	MKIVCT(235);
	MKIVCT(236);	MKIVCT(237);	MKIVCT(238);	MKIVCT(239);
	MKIVCT(240);	MKIVCT(241);	MKIVCT(242);	MKIVCT(243);
	MKIVCT(244);	MKIVCT(245);	MKIVCT(246);	MKIVCT(247);
	MKIVCT(248);	MKIVCT(249);	MKIVCT(250);	MKIVCT(251);
	MKIVCT(252);	MKIVCT(253);	MKIVCT(254);	MKIVCT(255);

	/*
	 * We're PCIDE, but we don't have INVPCID.  The only way to invalidate a
	 * PCID other than the current one, then, is to load its cr3 then
	 * invlpg.  But loading kf_user_cr3 means we can longer access our
	 * caller's text mapping (or indeed, its stack).  So this little helper
	 * has to live within our trampoline text region.
	 *
	 * Called as tr_mmu_flush_user_range(addr, len, pgsz, cr3)
	 */
	ENTRY_NP(tr_mmu_flush_user_range)
	push	%rbx
	/* When we read cr3, it never has the NOINVL bit set. */
	mov	%cr3, %rax
	movq	$CR3_NOINVL_BIT, %rbx
	orq	%rbx, %rax

	mov	%rcx, %cr3
	add	%rdi, %rsi
.align	ASM_ENTRY_ALIGN
1:
	invlpg	(%rdi)
	add	%rdx, %rdi
	cmp	%rsi, %rdi
	jb	1b
	mov	%rax, %cr3
	pop	%rbx
	retq
	SET_SIZE(tr_mmu_flush_user_range)

.align MMU_PAGESIZE
.global kpti_tramp_end
kpti_tramp_end:
	nop
/*
 * 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) 1992, 2010, Oracle and/or its affiliates. All rights reserved.
 */
/*
 * Copyright 2020 Joyent, Inc.
 * Copyright 2020 OmniOS Community Edition (OmniOSce) Association.
 */

/*	Copyright (c) 1990, 1991 UNIX System Laboratories, Inc.	*/
/*	Copyright (c) 1984, 1986, 1987, 1988, 1989, 1990 AT&T	*/
/*	  All Rights Reserved					*/

/*	Copyright (c) 1987, 1988 Microsoft Corporation		*/
/*	  All Rights Reserved					*/


#include <sys/asm_linkage.h>
#include <sys/asm_misc.h>
#include <sys/regset.h>
#include <sys/privregs.h>
#include <sys/psw.h>
#include <sys/reboot.h>
#include <sys/machparam.h>

#include <sys/segments.h>
#include <sys/pcb.h>
#include <sys/trap.h>
#include <sys/ftrace.h>
#include <sys/traptrace.h>
#include <sys/clock.h>
#include <sys/cmn_err.h>
#include <sys/pit.h>
#include <sys/panic.h>

#if defined(__xpv)
#include <sys/hypervisor.h>
#endif

#include "assym.h"

/*
 * Our assumptions:
 *	- We are running in protected-paged mode.
 *	- Interrupts are disabled.
 *	- The GDT and IDT are the callers; we need our copies.
 *	- The kernel's text, initialized data and bss are mapped.
 *
 * Our actions:
 *	- Save arguments
 *	- Initialize our stack pointer to the thread 0 stack (t0stack)
 *	  and leave room for a phony "struct regs".
 *	- Our GDT and IDT need to get munged.
 *	- Since we are using the boot's GDT descriptors, we need
 *	  to copy them into our GDT before we switch to ours.
 *	- We start using our GDT by loading correct values in the
 *	  selector registers (cs=KCS_SEL, ds=es=ss=KDS_SEL, fs=KFS_SEL,
 *	  gs=KGS_SEL).
 *	- The default LDT entry for syscall is set.
 *	- We load the default LDT into the hardware LDT register.
 *	- We load the default TSS into the hardware task register.
 *	- Check for cpu type, i.e. 486 vs. P5 vs. P6 etc.
 *	- mlsetup(%esp) gets called.
 *	- We change our appearance to look like the real thread 0.
 *	  (NOTE: making ourselves to be a real thread may be a noop)
 *	- main() gets called.  (NOTE: main() never returns).
 *
 * NOW, the real code!
 */
	/*
	 * The very first thing in the kernel's text segment must be a jump
	 * to the os/fakebop.c startup code.
	 */
	.text
	jmp     _start

	/*
	 * Globals:
	 */
	.globl	_locore_start
	.globl	mlsetup
	.globl	main
	.globl	panic
	.globl	t0stack
	.globl	t0
	.globl	sysp
	.globl	edata

	/*
	 * call back into boot - sysp (bootsvcs.h) and bootops (bootconf.h)
	 */
	.globl	bootops
	.globl	bootopsp

	/*
	 * NOTE: t0stack should be the first thing in the data section so that
	 * if it ever overflows, it will fault on the last kernel text page.
	 */
	.data
	.comm	t0stack, DEFAULTSTKSZ, 32
	.comm	t0, 4094, 32


	/*
	 * kobj_init() vectors us back to here with (note) a slightly different
	 * set of arguments than _start is given (see lint prototypes above).
	 *
	 * XXX	Make this less vile, please.
	 */
	ENTRY_NP(_locore_start)

	/*
	 * %rdi = boot services (should die someday)
	 * %rdx = bootops
	 * end
	 */

	leaq	edata(%rip), %rbp	/* reference edata for ksyms */
	movq	$0, (%rbp)		/* limit stack back trace */

	/*
	 * Initialize our stack pointer to the thread 0 stack (t0stack)
	 * and leave room for a "struct regs" for lwp0.  Note that the
	 * stack doesn't actually align to a 16-byte boundary until just
	 * before we call mlsetup because we want to use %rsp to point at
	 * our regs structure.
	 */
	leaq	t0stack(%rip), %rsp
	addq	$_CONST(DEFAULTSTKSZ - REGSIZE), %rsp
#if (REGSIZE & 15) == 0
	subq	$8, %rsp
#endif
	/*
	 * Save call back for special x86 boot services vector
	 */
	movq	%rdi, sysp(%rip)

	movq	%rdx, bootops(%rip)		/* save bootops */
	movq	$bootops, bootopsp(%rip)

	/*
	 * Save arguments and flags, if only for debugging ..
	 */
	movq	%rdi, REGOFF_RDI(%rsp)
	movq	%rsi, REGOFF_RSI(%rsp)
	movq	%rdx, REGOFF_RDX(%rsp)
	movq	%rcx, REGOFF_RCX(%rsp)
	movq	%r8, REGOFF_R8(%rsp)
	movq	%r9, REGOFF_R9(%rsp)
	pushf
	popq	%r11
	movq	%r11, REGOFF_RFL(%rsp)

#if !defined(__xpv)
	/*
	 * Enable write protect and alignment check faults.
	 */
	movq	%cr0, %rax
	orq	$_CONST(CR0_WP|CR0_AM), %rax
	andq	$_BITNOT(CR0_WT|CR0_CE), %rax
	movq	%rax, %cr0
#endif	/* __xpv */

	/*
	 * mlsetup() gets called with a struct regs as argument, while
	 * main takes no args and should never return.
	 */
	xorl	%ebp, %ebp
	movq	%rsp, %rdi
	pushq	%rbp
	/* (stack pointer now aligned on 16-byte boundary right here) */
	movq	%rsp, %rbp
	call	mlsetup
	call	main
	/* NOTREACHED */
	leaq	__return_from_main(%rip), %rdi
	xorl	%eax, %eax
	call	panic
	SET_SIZE(_locore_start)

__return_from_main:
	.string	"main() returned"
__unsupported_cpu:
	.string	"486 style cpu detected - no longer supported!"

#if defined(DEBUG)
_no_pending_updates:
	.string	"locore.s:%d lwp_rtt(lwp %p) but pcb_rupdate != 1"
#endif

/*
 *  For stack layout, see privregs.h
 *  When cmntrap gets called, the error code and trap number have been pushed.
 *  When cmntrap_pushed gets called, the entire struct regs has been pushed.
 */

	.globl	trap		/* C handler called below */

	ENTRY_NP2(cmntrap, _cmntrap)

	INTR_PUSH

	ALTENTRY(cmntrap_pushed)

	movq	%rsp, %rbp

	/*
	 * - if this is a #pf i.e. T_PGFLT, %r15 is live
	 *   and contains the faulting address i.e. a copy of %cr2
	 *
	 * - if this is a #db i.e. T_SGLSTP, %r15 is live
	 *   and contains the value of %db6
	 */

	TRACE_PTR(%rdi, %rbx, %ebx, %rcx, $TT_TRAP) /* Uses labels 8 and 9 */
	TRACE_REGS(%rdi, %rsp, %rbx, %rcx)	/* Uses label 9 */
	TRACE_STAMP(%rdi)		/* Clobbers %eax, %edx, uses 9 */

	/*
	 * We must first check if DTrace has set its NOFAULT bit.  This
	 * regrettably must happen before the trap stack is recorded, because
	 * this requires a call to getpcstack() and may induce recursion if an
	 * fbt::getpcstack: enabling is inducing the bad load.
	 */
	movl	%gs:CPU_ID, %eax
	shlq	$CPU_CORE_SHIFT, %rax
	leaq	cpu_core(%rip), %r8
	addq	%r8, %rax
	movw	CPUC_DTRACE_FLAGS(%rax), %cx
	testw	$CPU_DTRACE_NOFAULT, %cx
	jnz	.dtrace_induced

	TRACE_STACK(%rdi)

	movq	%rbp, %rdi
	movq	%r15, %rsi
	movl	%gs:CPU_ID, %edx

	/*
	 * We know that this isn't a DTrace non-faulting load; we can now safely
	 * reenable interrupts.  (In the case of pagefaults, we enter through an
	 * interrupt gate.)
	 */
	ENABLE_INTR_FLAGS

	call	trap		/* trap(rp, addr, cpuid) handles all traps */
	jmp	_sys_rtt

.dtrace_induced:
	cmpw	$KCS_SEL, REGOFF_CS(%rbp)	/* test CS for user-mode trap */
	jne	3f				/* if from user, panic */

	cmpl	$T_PGFLT, REGOFF_TRAPNO(%rbp)
	je	1f

	cmpl	$T_GPFLT, REGOFF_TRAPNO(%rbp)
	je	0f

	cmpl	$T_ILLINST, REGOFF_TRAPNO(%rbp)
	je	0f

	cmpl	$T_ZERODIV, REGOFF_TRAPNO(%rbp)
	jne	4f				/* if not PF/GP/UD/DE, panic */

	orw	$CPU_DTRACE_DIVZERO, %cx
	movw	%cx, CPUC_DTRACE_FLAGS(%rax)
	jmp	2f

	/*
	 * If we've taken a GPF, we don't (unfortunately) have the address that
	 * induced the fault.  So instead of setting the fault to BADADDR,
	 * we'll set the fault to ILLOP.
	 */
0:
	orw	$CPU_DTRACE_ILLOP, %cx
	movw	%cx, CPUC_DTRACE_FLAGS(%rax)
	jmp	2f
1:
	orw	$CPU_DTRACE_BADADDR, %cx
	movw	%cx, CPUC_DTRACE_FLAGS(%rax)	/* set fault to bad addr */
	movq	%r15, CPUC_DTRACE_ILLVAL(%rax)
					    /* fault addr is illegal value */
2:
	movq	REGOFF_RIP(%rbp), %rdi
	movq	%rdi, %r12
	call	dtrace_instr_size
	addq	%rax, %r12
	movq	%r12, REGOFF_RIP(%rbp)
	INTR_POP
	call	x86_md_clear
	jmp	tr_iret_auto
	/*NOTREACHED*/
3:
	leaq	dtrace_badflags(%rip), %rdi
	xorl	%eax, %eax
	call	panic
4:
	leaq	dtrace_badtrap(%rip), %rdi
	xorl	%eax, %eax
	call	panic
	SET_SIZE(cmntrap_pushed)
	SET_SIZE(cmntrap)
	SET_SIZE(_cmntrap)

/*
 * Declare a uintptr_t which has the size of _cmntrap to enable stack
 * traceback code to know when a regs structure is on the stack.
 */
	.globl	_cmntrap_size
	.align	CLONGSIZE
_cmntrap_size:
	.NWORD	. - _cmntrap
	.type	_cmntrap_size, @object

dtrace_badflags:
	.string "bad DTrace flags"

dtrace_badtrap:
	.string "bad DTrace trap"

	.globl	trap		/* C handler called below */

	ENTRY_NP(cmninttrap)

	INTR_PUSH
	INTGATE_INIT_KERNEL_FLAGS

	TRACE_PTR(%rdi, %rbx, %ebx, %rcx, $TT_TRAP) /* Uses labels 8 and 9 */
	TRACE_REGS(%rdi, %rsp, %rbx, %rcx)	/* Uses label 9 */
	TRACE_STAMP(%rdi)		/* Clobbers %eax, %edx, uses 9 */

	movq	%rsp, %rbp

	movl	%gs:CPU_ID, %edx
	xorl	%esi, %esi
	movq	%rsp, %rdi
	call	trap		/* trap(rp, addr, cpuid) handles all traps */
	jmp	_sys_rtt
	SET_SIZE(cmninttrap)

#if !defined(__xpv)
	/*
	 * Handle traps early in boot. Just revectors into C quickly as
	 * these are always fatal errors.
	 *
	 * Adjust %rsp to get same stack layout as in 32bit mode for bop_trap().
	 */
	ENTRY(bop_trap_handler)
	movq	%rsp, %rdi
	sub	$8, %rsp
	call	bop_trap
	SET_SIZE(bop_trap_handler)
#endif

	.globl	dtrace_user_probe

	ENTRY_NP(dtrace_trap)

	INTR_PUSH

	TRACE_PTR(%rdi, %rbx, %ebx, %rcx, $TT_TRAP) /* Uses labels 8 and 9 */
	TRACE_REGS(%rdi, %rsp, %rbx, %rcx)	/* Uses label 9 */
	TRACE_STAMP(%rdi)		/* Clobbers %eax, %edx, uses 9 */

	movq	%rsp, %rbp

	movl	%gs:CPU_ID, %edx
#if defined(__xpv)
	movq	%gs:CPU_VCPU_INFO, %rsi
	movq	VCPU_INFO_ARCH_CR2(%rsi), %rsi
#else
	movq	%cr2, %rsi
#endif
	movq	%rsp, %rdi

	ENABLE_INTR_FLAGS

	call	dtrace_user_probe /* dtrace_user_probe(rp, addr, cpuid) */
	jmp	_sys_rtt

	SET_SIZE(dtrace_trap)

/*
 * Return from _sys_trap routine.
 */

	ENTRY_NP(lwp_rtt_initial)
	movq	%gs:CPU_THREAD, %r15
	movq	T_STACK(%r15), %rsp	/* switch to the thread stack */
	movq	%rsp, %rbp
	call	__dtrace_probe___proc_start
	jmp	_lwp_rtt

	ENTRY_NP(lwp_rtt)

	/*
	 * r14	lwp
	 * rdx	lwp->lwp_procp
	 * r15	curthread
	 */

	movq	%gs:CPU_THREAD, %r15
	movq	T_STACK(%r15), %rsp	/* switch to the thread stack */
	movq	%rsp, %rbp
_lwp_rtt:
	call	__dtrace_probe___proc_lwp__start
	movq	%gs:CPU_LWP, %r14
	movq	LWP_PROCP(%r14), %rdx

	/*
	 * XX64	Is the stack misaligned correctly at this point?
	 *	If not, we need to do a push before calling anything ..
	 */

#if defined(DEBUG)
	/*
	 * If we were to run lwp_savectx at this point -without-
	 * pcb_rupdate being set to 1, we'd end up sampling the hardware
	 * state left by the previous running lwp, rather than setting
	 * the values requested by the lwp creator.  Bad.
	 */
	testb	$0x1, PCB_RUPDATE(%r14)
	jne	1f
	leaq	_no_pending_updates(%rip), %rdi
	movl	$__LINE__, %esi
	movq	%r14, %rdx
	xorl	%eax, %eax
	call	panic
1:
#endif

	/*
	 * If agent lwp, clear %fs and %gs
	 */
	cmpq	%r15, P_AGENTTP(%rdx)
	jne	1f
	xorl	%ecx, %ecx
	movq	%rcx, REGOFF_FS(%rsp)
	movq	%rcx, REGOFF_GS(%rsp)
	movw	%cx, LWP_PCB_FS(%r14)
	movw	%cx, LWP_PCB_GS(%r14)
1:
	call	dtrace_systrace_rtt
	movq	REGOFF_RDX(%rsp), %rsi
	movq	REGOFF_RAX(%rsp), %rdi
	call	post_syscall		/* post_syscall(rval1, rval2) */

	/*
	 * XXX - may want a fast path that avoids sys_rtt_common in the
	 * most common case.
	 */
	ALTENTRY(_sys_rtt)
	CLI(%rax)			/* disable interrupts */
	ALTENTRY(_sys_rtt_ints_disabled)
	movq	%rsp, %rdi		/* pass rp to sys_rtt_common */
	call	sys_rtt_common		/* do common sys_rtt tasks */
	testq	%rax, %rax		/* returning to userland? */
	jz	sr_sup

	/*
	 * Return to user
	 */
	ASSERT_UPCALL_MASK_IS_SET
	cmpw	$UCS_SEL, REGOFF_CS(%rsp) /* test for native (64-bit) lwp? */
	je	sys_rtt_syscall

	/*
	 * Return to 32-bit userland
	 */
	ALTENTRY(sys_rtt_syscall32)
	USER32_POP
	call	x86_md_clear
	jmp	tr_iret_user
	/*NOTREACHED*/

	ALTENTRY(sys_rtt_syscall)
	/*
	 * Return to 64-bit userland
	 */
	USER_POP
	ALTENTRY(nopop_sys_rtt_syscall)
	call	x86_md_clear
	jmp	tr_iret_user
	/*NOTREACHED*/
	SET_SIZE(nopop_sys_rtt_syscall)

	/*
	 * Return to supervisor
	 * NOTE: to make the check in trap() that tests if we are executing
	 * segment register fixup/restore code work properly, sr_sup MUST be
	 * after _sys_rtt .
	 */
	ALTENTRY(sr_sup)
	/*
	 * Restore regs before doing iretq to kernel mode
	 */
	INTR_POP
	jmp	tr_iret_kernel
	.globl	_sys_rtt_end
_sys_rtt_end:
	/*NOTREACHED*/
	SET_SIZE(sr_sup)
	SET_SIZE(_sys_rtt_end)
	SET_SIZE(lwp_rtt)
	SET_SIZE(lwp_rtt_initial)
	SET_SIZE(_sys_rtt_ints_disabled)
	SET_SIZE(_sys_rtt)
	SET_SIZE(sys_rtt_syscall)
	SET_SIZE(sys_rtt_syscall32)

	/*
	 * XX64 quick and dirty port from the i386 version. Since we
	 * believe the amd64 tsc is more reliable, could this code be
	 * simpler?
	 */
	ENTRY_NP(freq_tsc_pit)
	pushq	%rbp
	movq	%rsp, %rbp
	movq	%rdi, %r9	/* save pit_counter */
	pushq	%rbx

/ We have a TSC, but we have no way in general to know how reliable it is.
/ Usually a marginal TSC behaves appropriately unless not enough time
/ elapses between reads. A reliable TSC can be read as often and as rapidly
/ as desired. The simplistic approach of reading the TSC counter and
/ correlating to the PIT counter cannot be naively followed. Instead estimates
/ have to be taken to successively refine a guess at the speed of the cpu
/ and then the TSC and PIT counter are correlated. In practice very rarely
/ is more than one quick loop required for an estimate. Measures have to be
/ taken to prevent the PIT counter from wrapping beyond its resolution and for
/ measuring the clock rate of very fast processors.
/
/ The following constant can be tuned. It should be such that the loop does
/ not take too many nor too few PIT counts to execute. If this value is too
/ large, then on slow machines the loop will take a long time, or the PIT
/ counter may even wrap. If this value is too small, then on fast machines
/ the PIT counter may count so few ticks that the resolution of the PIT
/ itself causes a bad guess. Because this code is used in machines with
/ marginal TSC's and/or IO, if this value is too small on those, it may
/ cause the calculated cpu frequency to vary slightly from boot to boot.
/
/ In all cases even if this constant is set inappropriately, the algorithm
/ will still work and the caller should be able to handle variances in the
/ calculation of cpu frequency, but the calculation will be inefficient and
/ take a disproportionate amount of time relative to a well selected value.
/ As the slowest supported cpu becomes faster, this constant should be
/ carefully increased.

	movl	$0x8000, %ecx

	/ to make sure the instruction cache has been warmed
	clc

	jmp	freq_tsc_loop

/ The following block of code up to and including the latching of the PIT
/ counter after freq_tsc_perf_loop is very critical and very carefully
/ written, it should only be modified with great care. freq_tsc_loop to
/ freq_tsc_perf_loop fits exactly in 16 bytes as do the instructions in
/ freq_tsc_perf_loop up to the unlatching of the PIT counter.

	.align	32
freq_tsc_loop:
	/ save the loop count in %ebx
	movl	%ecx, %ebx

	/ initialize the PIT counter and start a count down
	movb	$PIT_LOADMODE, %al
	outb	$PITCTL_PORT
	movb	$0xff, %al
	outb	$PITCTR0_PORT
	outb	$PITCTR0_PORT

	/ read the TSC and store the TS in %edi:%esi
	rdtsc
	movl	%eax, %esi

freq_tsc_perf_loop:
	movl	%edx, %edi
	movl	%eax, %esi
	movl	%edx, %edi
	loop	freq_tsc_perf_loop

	/ read the TSC and store the LSW in %ecx
	rdtsc
	movl	%eax, %ecx

	/ latch the PIT counter and status
	movb	$_CONST(PIT_READBACK|PIT_READBACKC0), %al
	outb	$PITCTL_PORT

	/ remember if the icache has been warmed
	setc	%ah

	/ read the PIT status
	inb	$PITCTR0_PORT
	shll	$8, %eax

	/ read PIT count
	inb	$PITCTR0_PORT
	shll	$8, %eax
	inb	$PITCTR0_PORT
	bswap	%eax

	/ check to see if the PIT count was loaded into the CE
	btw	$_CONST(PITSTAT_NULLCNT+8), %ax
	jc	freq_tsc_increase_count

	/ check to see if PIT counter wrapped
	btw	$_CONST(PITSTAT_OUTPUT+8), %ax
	jnc	freq_tsc_pit_did_not_wrap

	/ halve count
	shrl	$1, %ebx
	movl	%ebx, %ecx

	/ the instruction cache has been warmed
	stc

	jmp	freq_tsc_loop

freq_tsc_increase_count:
	shll	$1, %ebx
	jc	freq_tsc_too_fast

	movl	%ebx, %ecx

	/ the instruction cache has been warmed
	stc

	jmp	freq_tsc_loop

freq_tsc_pit_did_not_wrap:
	roll	$16, %eax

	cmpw	$0x2000, %ax
	notw	%ax
	jb	freq_tsc_sufficient_duration

freq_tsc_calculate:
	/ in mode 0, the PIT loads the count into the CE on the first CLK pulse,
	/ then on the second CLK pulse the CE is decremented, therefore mode 0
	/ is really a (count + 1) counter, ugh
	xorl	%esi, %esi
	movw	%ax, %si
	incl	%esi

	movl	$0xf000, %eax
	mull	%ebx

	/ tuck away (target_pit_count * loop_count)
	movl	%edx, %ecx
	movl	%eax, %ebx

	movl	%esi, %eax
	movl	$0xffffffff, %edx
	mull	%edx

	addl	%esi, %eax
	adcl	$0, %edx

	cmpl	%ecx, %edx
	ja	freq_tsc_div_safe
	jb	freq_tsc_too_fast

	cmpl	%ebx, %eax
	jbe	freq_tsc_too_fast

freq_tsc_div_safe:
	movl	%ecx, %edx
	movl	%ebx, %eax

	movl	%esi, %ecx
	divl	%ecx

	movl	%eax, %ecx

	/ the instruction cache has been warmed
	stc

	jmp	freq_tsc_loop

freq_tsc_sufficient_duration:
	/ test to see if the icache has been warmed
	btl	$16, %eax
	jnc	freq_tsc_calculate

	/ recall mode 0 is a (count + 1) counter
	andl	$0xffff, %eax
	incl	%eax

	/ save the number of PIT counts
	movl	%eax, (%r9)

	/ calculate the number of TS's that elapsed
	movl	%ecx, %eax
	subl	%esi, %eax
	sbbl	%edi, %edx

	jmp	freq_tsc_end

freq_tsc_too_fast:
	/ return 0 as a 64 bit quantity
	xorl	%eax, %eax
	xorl	%edx, %edx

freq_tsc_end:
	shlq	$32, %rdx
	orq	%rdx, %rax

	popq	%rbx
	leaveq
	ret
	SET_SIZE(freq_tsc_pit)

/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright 2019 Joyent, Inc.
 */

#include <sys/asm_linkage.h>

/*
 * This ASM file contains various routines that are designed to flush
 * microarchitectural buffer state as part of dealing with the
 * microarchitectural data sampling (MDS) vulnerabilities.
 *
 * These are called from various points in the system ranging from interrupts,
 * before going idle, to returning from system calls. This means the following
 * is true about the state of the system:
 *
 *  o All register state is precious, we must not change register state upon
 *    entry or return from these functions.
 *
 *  o %ds is valid.
 *
 *  o %gs is arbitrary, it may be kernel or user. You cannot rely on it.
 *
 *  o Interrupts should be disabled by the caller.
 *
 *  o %cr3 is on the kernel-side and therefore we still have access to kernel
 *    text. In other words, we haven't switched back to the user page table.
 *
 *  o It is up to the caller to insure that a sufficient serializing instruction
 *    has been executed after this to make sure any pending speculations are
 *    captured. In general, this should be handled by the fact that callers of
 *    this are either going to change privilege levels or halt, which makes
 *    these operations safer.
 */

	/*
	 * By default, x86_md_clear is disabled until the system determines that
	 * it both needs MDS related mitigations and we have microcode that
	 * provides the needed functionality.
	 *
	 * The VERW instruction clobbers flags which is why it's important that
	 * we save and restore them here.
	 */
	ENTRY_NP(x86_md_clear)
	ret
	pushfq
	subq	$8, %rsp
	mov	%ds, (%rsp)
	verw	(%rsp)
	addq	$8, %rsp
	popfq
	ret
	SET_SIZE(x86_md_clear)
/*
 * 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) 1992, 2010, Oracle and/or its affiliates. All rights reserved.
 */
/*
 * Copyright (c) 2010, Intel Corporation.
 * All rights reserved.
 *
 * Copyright 2019 Joyent, Inc.
 * Copyright 2020 OmniOS Community Edition (OmniOSce) Association.
 * Copyright 2023 Oxide Computer Co.
 */

#include <sys/asm_linkage.h>
#include <sys/asm_misc.h>
#include <sys/regset.h>
#include <sys/privregs.h>
#include <sys/x86_archext.h>

#include <sys/segments.h>
#include "assym.h"

/*
 *	Our assumptions:
 *		- We are running in real mode.
 *		- Interrupts are disabled.
 *		- Selectors are equal (cs == ds == ss) for all real mode code
 *		- The GDT, IDT, ktss and page directory has been built for us
 *
 *	Our actions:
 *	Start CPU:
 *		- We start using our GDT by loading correct values in the
 *		  selector registers (cs=KCS_SEL, ds=es=ss=KDS_SEL, fs=KFS_SEL,
 *		  gs=KGS_SEL).
 *		- We change over to using our IDT.
 *		- We load the default LDT into the hardware LDT register.
 *		- We load the default TSS into the hardware task register.
 *		- call mp_startup(void) indirectly through the T_PC
 *	Stop CPU:
 *		- Put CPU into halted state with interrupts disabled
 *
 */

	ENTRY_NP(real_mode_start_cpu)

	/*
	 * NOTE:  The GNU assembler automatically does the right thing to
	 *	  generate data size operand prefixes based on the code size
	 *	  generation mode (e.g. .code16, .code32, .code64) and as such
	 *	  prefixes need not be used on instructions EXCEPT in the case
	 *	  of address prefixes for code for which the reference is not
	 *	  automatically of the default operand size.
	 */
	.code16
	cli
	movw		%cs, %ax
	movw		%ax, %ds	/* load cs into ds */
	movw		%ax, %ss	/* and into ss */

	/*
	 * Helps in debugging by giving us the fault address.
	 *
	 * Remember to patch a hlt (0xf4) at cmntrap to get a good stack.
	 */
	movl		$0xffc, %esp
	movl		%cr0, %eax

	/*
	 * Enable protected-mode, write protect, and alignment mask
	 */
	orl		$(CR0_PE|CR0_WP|CR0_AM), %eax
	movl		%eax, %cr0

	/*
	 * Do a jmp immediately after writing to cr0 when enabling protected
	 * mode to clear the real mode prefetch queue (per Intel's docs)
	 */
	jmp		pestart

pestart:
	/*
	 * 16-bit protected mode is now active, so prepare to turn on long
	 * mode.
	 */

	/*
	 * Add any initial cr4 bits
	 */
	movl		%cr4, %eax
	addr32 orl	CR4OFF, %eax

	/*
	 * Enable PAE mode (CR4.PAE)
	 */
	orl		$CR4_PAE, %eax
	movl		%eax, %cr4

	/*
	 * Point cr3 to the 64-bit long mode page tables.
	 *
	 * Note that these MUST exist in 32-bit space, as we don't have
	 * a way to load %cr3 with a 64-bit base address for the page tables
	 * until the CPU is actually executing in 64-bit long mode.
	 */
	addr32 movl	CR3OFF, %eax
	movl		%eax, %cr3

	/*
	 * Set long mode enable in EFER (EFER.LME = 1)
	 */
	movl	$MSR_AMD_EFER, %ecx
	rdmsr
	orl	$AMD_EFER_LME, %eax
	wrmsr

	/*
	 * Finally, turn on paging (CR0.PG = 1) to activate long mode.
	 */
	movl	%cr0, %eax
	orl	$CR0_PG, %eax
	movl	%eax, %cr0

	/*
	 * The instruction after enabling paging in CR0 MUST be a branch.
	 */
	jmp	long_mode_active

long_mode_active:
	/*
	 * Long mode is now active but since we're still running with the
	 * original 16-bit CS we're actually in 16-bit compatability mode.
	 *
	 * We have to load an intermediate GDT and IDT here that we know are
	 * in 32-bit space before we can use the kernel's GDT and IDT, which
	 * may be in the 64-bit address space, and since we're in compatability
	 * mode, we only have access to 16 and 32-bit instructions at the
	 * moment.
	 */
	addr32 lgdtl	TEMPGDTOFF	/* load temporary GDT */
	addr32 lidtl	TEMPIDTOFF	/* load temporary IDT */

	/*
	 * Do a far transfer to 64-bit mode.  Set the CS selector to a 64-bit
	 * long mode selector (CS.L=1) in the temporary 32-bit GDT and jump
	 * to the real mode platter address of long_mode 64 as until the 64-bit
	 * CS is in place we don't have access to 64-bit instructions and thus
	 * can't reference a 64-bit %rip.
	 */
	pushl		$TEMP_CS64_SEL
	addr32 pushl	LM64OFF
	lretl

	.globl	long_mode_64
long_mode_64:
	.code64
	/*
	 * We are now running in long mode with a 64-bit CS (EFER.LMA=1,
	 * CS.L=1) so we now have access to 64-bit instructions.
	 *
	 * First, set the 64-bit GDT base.
	 */
	.globl	rm_platter_pa
	movl	rm_platter_pa, %eax
	lgdtq	GDTROFF(%rax)		/* load 64-bit GDT */

	/*
	 * Save the CPU number in %r11; get the value here since it's saved in
	 * the real mode platter.
	 */
	movl	CPUNOFF(%rax), %r11d

	/*
	 * Add rm_platter_pa to %rsp to point it to the same location as seen
	 * from 64-bit mode.
	 */
	addq	%rax, %rsp

	/*
	 * Now do an lretq to load CS with the appropriate selector for the
	 * kernel's 64-bit GDT and to start executing 64-bit setup code at the
	 * virtual address where boot originally loaded this code rather than
	 * the copy in the real mode platter's rm_code array as we've been
	 * doing so far.
	 */
	pushq	$KCS_SEL
	pushq	$kernel_cs_code
	lretq
	.globl real_mode_start_cpu_end
real_mode_start_cpu_end:
	nop

kernel_cs_code:
	/*
	 * Complete the balance of the setup we need to before executing
	 * 64-bit kernel code (namely init rsp, TSS, LGDT, FS and GS).
	 */
	.globl	rm_platter_va
	movq	rm_platter_va, %rax
	lidtq	IDTROFF(%rax)

	movw	$KDS_SEL, %ax
	movw	%ax, %ds
	movw	%ax, %es
	movw	%ax, %ss

	movw	$KTSS_SEL, %ax		/* setup kernel TSS */
	ltr	%ax

	xorw	%ax, %ax		/* clear LDTR */
	lldt	%ax

	/*
	 * Set GS to the address of the per-cpu structure as contained in
	 * cpu[cpu_number].
	 *
	 * Unfortunately there's no way to set the 64-bit gsbase with a mov,
	 * so we have to stuff the low 32 bits in %eax and the high 32 bits in
	 * %edx, then call wrmsr.
	 */
	leaq	cpu(%rip), %rdi
	movl	(%rdi, %r11, 8), %eax
	movl	4(%rdi, %r11, 8), %edx
	movl	$MSR_AMD_GSBASE, %ecx
	wrmsr

	/*
	 * Init FS and KernelGSBase.
	 *
	 * Based on code in mlsetup(), set them both to 8G (which shouldn't be
	 * valid until some 64-bit processes run); this will then cause an
	 * exception in any code that tries to index off them before they are
	 * properly setup.
	 */
	xorl	%eax, %eax		/* low 32 bits = 0 */
	movl	$2, %edx		/* high 32 bits = 2 */
	movl	$MSR_AMD_FSBASE, %ecx
	wrmsr

	movl	$MSR_AMD_KGSBASE, %ecx
	wrmsr

	/*
	 * Init %rsp to the exception stack set in tss_ist1 and create a legal
	 * AMD64 ABI stack frame
	 */
	movq	%gs:CPU_TSS, %rax
	movq	TSS_IST1(%rax), %rsp
	pushq	$0		/* null return address */
	pushq	$0		/* null frame pointer terminates stack trace */
	movq	%rsp, %rbp	/* stack aligned on 16-byte boundary */

	/*
	 * Get %cr0 into the state we (mostly) want, including turning on the
	 * caches.
	 */
	movq	%cr0, %rax
	andq    $~(CR0_CD|CR0_NW|CR0_TS|CR0_EM), %rax
	orq     $(CR0_MP|CR0_NE), %rax
	movq    %rax, %cr0		/* set machine status word */

	/*
	 * Before going any further, enable usage of page table NX bit if
	 * that's how our page tables are set up.
	 */
	btl	$X86FSET_NX, x86_featureset(%rip)
	jnc	1f
	movl	$MSR_AMD_EFER, %ecx
	rdmsr
	orl	$AMD_EFER_NXE, %eax
	wrmsr
1:

	/*
	 * Complete the rest of the setup and call mp_startup().
	 */
	movq	%gs:CPU_THREAD, %rax	/* get thread ptr */
	movq	T_PC(%rax), %rax
	INDIRECT_CALL_REG(rax)		/* call mp_startup_boot */
	/* not reached */
	int	$20			/* whoops, returned somehow! */

	SET_SIZE(real_mode_start_cpu)

	ENTRY_NP(real_mode_stop_cpu_stage1)

	/*
	 * NOTE:  The GNU assembler automatically does the right thing to
	 *	  generate data size operand prefixes based on the code size
	 *	  generation mode (e.g. .code16, .code32, .code64) and as such
	 *	  prefixes need not be used on instructions EXCEPT in the case
	 *	  of address prefixes for code for which the reference is not
	 *	  automatically of the default operand size.
	 */
	.code16
	cli
	movw		%cs, %ax
	movw		%ax, %ds	/* load cs into ds */
	movw		%ax, %ss	/* and into ss */

	/*
	 * Jump to the stage 2 code in the rm_platter_va->rm_cpu_halt_code
	 */
	movw		$CPUHALTCODEOFF, %ax
	jmp		*%ax

	.globl real_mode_stop_cpu_stage1_end
real_mode_stop_cpu_stage1_end:
	nop

	SET_SIZE(real_mode_stop_cpu_stage1)

	ENTRY_NP(real_mode_stop_cpu_stage2)

	movw		$0xdead, %ax
	movw		%ax, CPUHALTEDOFF

real_mode_stop_cpu_loop:
	/*
	 * Put CPU into halted state.
	 * Only INIT, SMI, NMI could break the loop.
	 */
	hlt
	jmp		real_mode_stop_cpu_loop

	.globl real_mode_stop_cpu_stage2_end
real_mode_stop_cpu_stage2_end:
	nop

	SET_SIZE(real_mode_stop_cpu_stage2)
/*
 * 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 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright 2019 Joyent, Inc.
 */

#include <sys/elf_notes.h>

#include "assym.h"

/*
 * Tell the booter that we'd like to load unix on a large page.
 */
	.section        .note
	.align          4
	.4byte           .name1_end - .name1_begin
	.4byte           .desc1_end - .desc1_begin
	.4byte		ELF_NOTE_PAGESIZE_HINT
.name1_begin:
	.string         ELF_NOTE_SOLARIS
.name1_end:
	.align          4
.desc1_begin:
	.4byte		FOUR_MEG
.desc1_end:
	.align		4
\
\ Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
\ Copyright 2012 Garrett D'Amore <garrett@damore.org>.  All rights reserved.
\ Copyright 2019 Joyent, Inc.
\ Copyright 2025 Oxide Computer Company
\
\ 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
\


\
\ offsets.in: input file to produce assym.h using the ctfstabs program
\

#ifndef	_GENASSYM
#define	_GENASSYM
#endif

#define	SIZES	1

#include <sys/types.h>
#include <sys/bootsvcs.h>
#include <sys/systm.h>
#include <sys/sysinfo.h>
#include <sys/user.h>
#include <sys/thread.h>
#include <sys/proc.h>
#include <sys/cpuvar.h>
#include <sys/tss.h>
#include <sys/privregs.h>
#include <sys/segments.h>
#include <sys/devops.h>
#include <sys/ddi_impldefs.h>
#include <vm/as.h>
#include <sys/avintr.h>
#include <sys/pic.h>
#include <sys/rm_platter.h>
#include <sys/stream.h>
#include <sys/strsubr.h>
#include <sys/sunddi.h>
#include <sys/modctl.h>
#include <sys/traptrace.h>
#include <sys/ontrap.h>
#include <sys/lgrp.h>
#include <sys/dtrace.h>
#include <sys/brand.h>
#include <sys/fastboot.h>
#include <sys/cpr_wakecode.h>
#include <sys/comm_page.h>

proc		PROCSIZE
	p_link
	p_next
	p_child
	p_sibling
	p_sig
	p_flag
	p_tlist
	p_as
	p_lockp
	p_user
	p_model
	p_pctx
	p_agenttp
	p_zone
	p_brand
	p_brand_data

_kthread	THREAD_SIZE
	t_pcb			T_LABEL
	t_lock
	t_lockstat
	t_lockp
	t_lock_flush
	t_oldspl
	t_pri
	t_pil
	t_lwp
	t_procp
	t_link
	t_state
	t_mstate
	t_preempt_lk
	t_stk			T_STACK
	t_swap
	t_lwpchan.lc_wchan	T_WCHAN
	t_flag			T_FLAGS
	t_ctx
	t_lofault
	t_onfault
	t_ontrap
	t_cpu
	t_lpl
	t_bound_cpu
	t_intr
	t_forw
	t_back
	t_sig
	t_tid
	t_pre_sys
	t_preempt
	t_proc_flag
	t_startpc
	t_sysnum
	t_intr_start
	_tu._ts._t_astflag	T_ASTFLAG
	_tu._ts._t_post_sys	T_POST_SYS
	_tu._t_post_sys_ast	T_POST_SYS_AST
	t_copyops
	t_useracc

as
	a_hat

user	USIZEBYTES
	u_comm
	u_signal

_label_t
	val	LABEL_VAL

\#define	LABEL_PC	LABEL_VAL
\#define	LABEL_SP	_CONST(LABEL_VAL + LABEL_VAL_INCR)
\#define	T_PC		_CONST(T_LABEL + LABEL_PC)
\#define	T_SP		_CONST(T_LABEL + LABEL_SP)

_klwp
	lwp_thread
	lwp_procp
	lwp_brand
	lwp_eosys
	lwp_regs
	lwp_arg
	lwp_ap
	lwp_cursig
	lwp_state
	lwp_mstate.ms_acct	LWP_MS_ACCT
	lwp_mstate.ms_prev	LWP_MS_PREV
	lwp_mstate.ms_start	LWP_MS_START
	lwp_mstate.ms_state_start LWP_MS_STATE_START
	lwp_pcb
	lwp_ru.sysc		LWP_RU_SYSC

\#define	LWP_ACCT_USER	_CONST(LWP_MS_ACCT + _MUL(LMS_USER, LWP_MS_ACCT_INCR))
\#define	LWP_ACCT_SYSTEM	_CONST(LWP_MS_ACCT + _MUL(LMS_SYSTEM, LWP_MS_ACCT_INCR))

fpu_ctx
	fpu_regs		FPU_CTX_FPU_REGS
	fpu_flags		FPU_CTX_FPU_FLAGS
	fpu_xsave_mask		FPU_CTX_FPU_XSAVE_MASK

fxsave_state	FXSAVE_STATE_SIZE
	fx_fsw			FXSAVE_STATE_FSW
	fx_mxcsr_mask		FXSAVE_STATE_MXCSR_MASK


autovec		AUTOVECSIZE
	av_vector
	av_intarg1
	av_intarg2
	av_ticksp
	av_link
	av_prilevel
	av_dip

av_head
	avh_link
	avh_hi_pri
	avh_lo_pri

cpu
	cpu_id
	cpu_flags
	cpu_self
	cpu_thread
	cpu_thread_lock
	cpu_kprunrun
	cpu_lwp
	cpu_fpowner
	cpu_idle_thread
	cpu_intr_thread
	cpu_intr_actv
	cpu_base_spl
	cpu_intr_stack
	cpu_stats.sys.cpumigrate	CPU_STATS_SYS_CPUMIGRATE
	cpu_stats.sys.intr		CPU_STATS_SYS_INTR
	cpu_stats.sys.intrblk		CPU_STATS_SYS_INTRBLK
	cpu_stats.sys.syscall		CPU_STATS_SYS_SYSCALL
	cpu_profile_pc
	cpu_profile_upc
	cpu_profile_pil
	cpu_ftrace.ftd_state		CPU_FTRACE_STATE
	cpu_mstate
	cpu_intracct

\#define	CPU_INTR_ACTV_REF	_CONST(CPU_INTR_ACTV + 2)

cpu
	cpu_m.pil_high_start	CPU_PIL_HIGH_START
	cpu_m.intrstat		CPU_INTRSTAT
	cpu_m.mcpu_current_hat	CPU_CURRENT_HAT
	cpu_m.mcpu_gdt		CPU_GDT
	cpu_m.mcpu_idt		CPU_IDT
	cpu_m.mcpu_tss		CPU_TSS
	cpu_m.mcpu_softinfo	CPU_SOFTINFO
	cpu_m.mcpu_pri		CPU_PRI
#if defined(__xpv)
	cpu_m.mcpu_vcpu_info	CPU_VCPU_INFO
#endif

cpu
	cpu_m.mcpu_kpti.kf_kernel_cr3	CPU_KPTI_KCR3
	cpu_m.mcpu_kpti.kf_user_cr3	CPU_KPTI_UCR3
	cpu_m.mcpu_kpti.kf_tr_rsp	CPU_KPTI_TR_RSP
	cpu_m.mcpu_kpti.kf_tr_cr3	CPU_KPTI_TR_CR3
	cpu_m.mcpu_kpti.kf_r13		CPU_KPTI_R13
	cpu_m.mcpu_kpti.kf_r14		CPU_KPTI_R14
	cpu_m.mcpu_kpti.kf_tr_ret_rsp	CPU_KPTI_RET_RSP

	cpu_m.mcpu_kpti.kf_ss		CPU_KPTI_SS
	cpu_m.mcpu_kpti.kf_rsp		CPU_KPTI_RSP
	cpu_m.mcpu_kpti.kf_rflags	CPU_KPTI_RFLAGS
	cpu_m.mcpu_kpti.kf_cs		CPU_KPTI_CS
	cpu_m.mcpu_kpti.kf_rip		CPU_KPTI_RIP
	cpu_m.mcpu_kpti.kf_err		CPU_KPTI_ERR

	cpu_m.mcpu_pad2			CPU_KPTI_START
	cpu_m.mcpu_pad3			CPU_KPTI_END

	cpu_m.mcpu_kpti_dbg		CPU_KPTI_DBG

kpti_frame
	kf_r14		KPTI_R14
	kf_r13		KPTI_R13
	kf_err		KPTI_ERR
	kf_rip		KPTI_RIP
	kf_cs		KPTI_CS
	kf_rflags	KPTI_RFLAGS
	kf_rsp		KPTI_RSP
	kf_ss		KPTI_SS

	kf_tr_rsp	KPTI_TOP

	kf_kernel_cr3	KPTI_KCR3
	kf_user_cr3	KPTI_UCR3
	kf_tr_ret_rsp	KPTI_RET_RSP
	kf_tr_cr3	KPTI_TR_CR3

	kf_tr_flag	KPTI_FLAG

standard_pic
	c_curmask
	c_iplmask

ddi_dma_impl
	dmai_rflags
	dmai_rdip

dev_info
	devi_ops		DEVI_DEV_OPS
	devi_bus_ctl
	devi_bus_dma_ctl
	devi_bus_dma_allochdl
	devi_bus_dma_freehdl
	devi_bus_dma_bindhdl
	devi_bus_dma_unbindhdl
	devi_bus_dma_flush
	devi_bus_dma_win

dev_ops
	devo_bus_ops		DEVI_BUS_OPS

bus_ops
	bus_ctl			OPS_CTL
	bus_dma_map		OPS_MAP
	bus_dma_ctl		OPS_MCTL
	bus_dma_allochdl	OPS_ALLOCHDL
	bus_dma_freehdl		OPS_FREEHDL
	bus_dma_bindhdl		OPS_BINDHDL
	bus_dma_unbindhdl	OPS_UNBINDHDL
	bus_dma_flush		OPS_FLUSH
	bus_dma_win		OPS_WIN

sysent	SYSENT_SIZE	SYSENT_SIZE_SHIFT
	sy_callc
	sy_flags
	sy_narg

stdata
	sd_lock

queue
	q_flag
	q_next
	q_stream
	q_syncq
	q_qinfo

qinit
	qi_putp

syncq
	sq_flags
	sq_count
	sq_lock
	sq_wait

rm_platter
	rm_idt_lim		IDTROFF
	rm_gdt_lim		GDTROFF
	rm_pdbr			CR3OFF
	rm_cpu			CPUNOFF
	rm_cr4			CR4OFF
	rm_cpu_halt_code	CPUHALTCODEOFF
	rm_cpu_halted		CPUHALTEDOFF

ddi_acc_impl
	ahi_acc_attr	ACC_ATTR
	ahi_get8	ACC_GETB
	ahi_get16	ACC_GETW
	ahi_get32	ACC_GETL
	ahi_get64	ACC_GETLL
	ahi_put8	ACC_PUTB
	ahi_put16	ACC_PUTW
	ahi_put32	ACC_PUTL
	ahi_put64	ACC_PUTLL
	ahi_rep_get8	ACC_REP_GETB
	ahi_rep_get16	ACC_REP_GETW
	ahi_rep_get32	ACC_REP_GETL
	ahi_rep_get64	ACC_REP_GETLL
	ahi_rep_put8	ACC_REP_PUTB
	ahi_rep_put16	ACC_REP_PUTW
	ahi_rep_put32	ACC_REP_PUTL
	ahi_rep_put64	ACC_REP_PUTLL

on_trap_data
	ot_prot
	ot_trap
	ot_trampoline
	ot_jmpbuf
	ot_prev
	ot_handle
	ot_pad1

trap_trace_ctl_t	__TRAPTR_SIZE TRAPTR_SIZE_SHIFT
	ttc_next	TRAPTR_NEXT
	ttc_first	TRAPTR_FIRST
	ttc_limit	TRAPTR_LIMIT

trap_trace_rec_t	TRAP_ENT_SIZE
	ttr_cr2
	ttr_info.idt_entry.vector	TTR_VECTOR
	ttr_info.idt_entry.ipl		TTR_IPL
	ttr_info.idt_entry.spl		TTR_SPL
	ttr_info.idt_entry.pri		TTR_PRI
	ttr_info.gate_entry.sysnum	TTR_SYSNUM
	ttr_marker
	ttr_stamp
	ttr_curthread
	ttr_sdepth
	ttr_stack

lgrp_ld
	lpl_lgrpid

dtrace_id_t	DTRACE_IDSIZE

cpu_core	CPU_CORE_SIZE	CPU_CORE_SHIFT
	cpuc_dtrace_flags
	cpuc_dtrace_illval

timespec	TIMESPEC_SIZE

gate_desc	GATE_DESC_SIZE

desctbr_t	DESCTBR_SIZE
	dtr_limit
	dtr_base

mod_stub_info	MODS_SIZE
	mods_func_adr	MODS_INSTFCN
	mods_errfcn	MODS_RETFCN
	mods_flag

\#define	TRAP_TSIZE		_MUL(TRAP_ENT_SIZE, TRAPTR_NENT)

copyops
	cp_copyin
	cp_xcopyin
	cp_copyout
	cp_xcopyout
	cp_copyinstr
	cp_copyoutstr
	cp_fuword8
	cp_fuword16
	cp_fuword32
	cp_fuword64
	cp_suword8
	cp_suword16
	cp_suword32
	cp_suword64
	cp_physio

brand
	b_machops

brand_proc_data_t
	spd_handler

fastboot_file_t
	fb_va
	fb_pte_list_va
	fb_pte_list_pa
	fb_dest_pa
	fb_size
	fb_next_pa
	fb_sections
	fb_sectcnt

fastboot_section_t
	fb_sec_offset
	fb_sec_paddr
	fb_sec_size
	fb_sec_bss_size

fastboot_info_t
	fi_files
	fi_has_pae
	fi_pagetable_va
	fi_pagetable_pa
	fi_last_table_pa
	fi_new_mbi_pa
	fi_valid

zone
	zone_brand_data

wc_cpu	WC_CPU_SIZE
	wc_retaddr
	wc_virtaddr
	wc_cr0
	wc_cr3
	wc_cr4
	wc_cr8
	wc_fs
	wc_fsbase
	wc_gs
	wc_gsbase
	wc_kgsbase
	wc_r8
	wc_r9
	wc_r10
	wc_r11
	wc_r12
	wc_r13
	wc_r14
	wc_r15
	wc_rax
	wc_rbp
	wc_rbx
	wc_rcx
	wc_rdi
	wc_rdx
	wc_rsi
	wc_rsp
	wc_gdt_limit	WC_GDT
	wc_gdt_base
	wc_idt_limit	WC_IDT
	wc_idt_base
	wc_tr
	wc_ldt
	wc_eflags
	wc_ebx
	wc_edi
	wc_esi
	wc_ebp
	wc_esp
	wc_esp
	wc_ss
	wc_cs
	wc_ds
	wc_es
	wc_cpu_id
	wc_saved_stack

wc_wakecode
	wc_cpu

comm_page_s	COMM_PAGE_S_SIZE
	_cp_pad1	COMM_PAGE_PAD1
	cp_tsc_sync_tick_delta	COMM_PAGE_TSC_SYNC_TICK_DELTA
	_cp_pad2	COMM_PAGE_PAD2
/*
 * 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 2019 Joyent, Inc.
 * Copyright (c) 2016 by Delphix. All rights reserved.
 * Copyright 2024 MNX Cloud, Inc.
 */

#include <sys/asm_linkage.h>
#include <sys/asm_misc.h>
#include <sys/regset.h>
#include <sys/privregs.h>
#include <sys/psw.h>
#include <sys/machbrand.h>

#include <sys/segments.h>
#include <sys/pcb.h>
#include <sys/trap.h>
#include <sys/ftrace.h>
#include <sys/traptrace.h>
#include <sys/clock.h>
#include <sys/model.h>
#include <sys/panic.h>

#if defined(__xpv)
#include <sys/hypervisor.h>
#endif

#include "assym.h"

/*
 * We implement five flavours of system call entry points
 *
 * -	syscall/sysretq		(amd64 generic)
 * -	syscall/sysretl		(i386 plus SYSC bit)
 * -	sysenter/sysexit	(i386 plus SEP bit)
 * -	int/iret		(i386 generic)
 * -	lcall/iret		(i386 generic)
 *
 * The current libc included in Solaris uses int/iret as the base unoptimized
 * kernel entry method. Older libc implementations and legacy binaries may use
 * the lcall call gate, so it must continue to be supported.
 *
 * System calls that use an lcall call gate are processed in trap() via a
 * segment-not-present trap, i.e. lcalls are extremely slow(!).
 *
 * The basic pattern used in the 32-bit SYSC handler at this point in time is
 * to have the bare minimum of assembler, and get to the C handlers as
 * quickly as possible.
 *
 * The 64-bit handler is much closer to the sparcv9 handler; that's
 * because of passing arguments in registers.  The 32-bit world still
 * passes arguments on the stack -- that makes that handler substantially
 * more complex.
 *
 * The two handlers share a few code fragments which are broken
 * out into preprocessor macros below.
 *
 * XX64	come back and speed all this up later.  The 32-bit stuff looks
 * especially easy to speed up the argument copying part ..
 *
 *
 * Notes about segment register usage (c.f. the 32-bit kernel)
 *
 * In the 32-bit kernel, segment registers are dutifully saved and
 * restored on all mode transitions because the kernel uses them directly.
 * When the processor is running in 64-bit mode, segment registers are
 * largely ignored.
 *
 * %cs and %ss
 *	controlled by the hardware mechanisms that make mode transitions
 *
 * The remaining segment registers have to either be pointing at a valid
 * descriptor i.e. with the 'present' bit set, or they can NULL descriptors
 *
 * %ds and %es
 *	always ignored
 *
 * %fs and %gs
 *	fsbase and gsbase are used to control the place they really point at.
 *	The kernel only depends on %gs, and controls its own gsbase via swapgs
 *
 * Note that loading segment registers is still costly because the GDT
 * lookup still happens (this is because the hardware can't know that we're
 * not setting up these segment registers for a 32-bit program).  Thus we
 * avoid doing this in the syscall path, and defer them to lwp context switch
 * handlers, so the register values remain virtualized to the lwp.
 */

#if defined(SYSCALLTRACE)
#define	ORL_SYSCALLTRACE(r32)		\
	orl	syscalltrace(%rip), r32
#else
#define	ORL_SYSCALLTRACE(r32)
#endif

/*
 * In the 32-bit kernel, we do absolutely nothing before getting into the
 * brand callback checks.  In 64-bit land, we do swapgs and then come here.
 * We assume that the %rsp- and %r15-stashing fields in the CPU structure
 * are still unused.
 *
 * Check if a brand_mach_ops callback is defined for the specified callback_id
 * type.  If so invoke it with the kernel's %gs value loaded and the following
 * data on the stack:
 *
 * stack:  --------------------------------------
 *      32 | callback pointer			|
 *    | 24 | user (or interrupt) stack pointer	|
 *    | 16 | lwp pointer			|
 *    v  8 | userland return address		|
 *       0 | callback wrapper return addr	|
 *         --------------------------------------
 *
 * Since we're pushing the userland return address onto the kernel stack
 * we need to get that address without accessing the user's stack (since we
 * can't trust that data).  There are different ways to get the userland
 * return address depending on how the syscall trap was made:
 *
 * a) For sys_syscall and sys_syscall32 the return address is in %rcx.
 * b) For sys_sysenter the return address is in %rdx.
 * c) For sys_int80 and sys_syscall_int (int91), upon entry into the macro,
 *    the stack pointer points at the state saved when we took the interrupt:
 *	 ------------------------
 *    |  | user's %ss		|
 *    |  | user's %esp		|
 *    |  | EFLAGS register	|
 *    v  | user's %cs		|
 *       | user's %eip		|
 *	 ------------------------
 *
 * The 2nd parameter to the BRAND_CALLBACK macro is either the
 * BRAND_URET_FROM_REG or BRAND_URET_FROM_INTR_STACK macro.  These macros are
 * used to generate the proper code to get the userland return address for
 * each syscall entry point.
 *
 * The interface to the brand callbacks on the 64-bit kernel assumes %r15
 * is available as a scratch register within the callback.  If the callback
 * returns within the kernel then this macro will restore %r15.  If the
 * callback is going to return directly to userland then it should restore
 * %r15 before returning to userland.
 */
#define BRAND_URET_FROM_REG(rip_reg)					\
	pushq	rip_reg			/* push the return address	*/

/*
 * The interrupt stack pointer we saved on entry to the BRAND_CALLBACK macro
 * is currently pointing at the user return address (%eip).
 */
#define BRAND_URET_FROM_INTR_STACK()					\
	movq	%gs:CPU_RTMP_RSP, %r15	/* grab the intr. stack pointer	*/ ;\
	pushq	(%r15)			/* push the return address	*/

#define	BRAND_CALLBACK(callback_id, push_userland_ret)			    \
	movq	%rsp, %gs:CPU_RTMP_RSP	/* save the stack pointer	*/ ;\
	movq	%r15, %gs:CPU_RTMP_R15	/* save %r15			*/ ;\
	movq	%gs:CPU_THREAD, %r15	/* load the thread pointer	*/ ;\
	movq	T_STACK(%r15), %rsp	/* switch to the kernel stack	*/ ;\
	subq	$16, %rsp		/* save space for 2 pointers	*/ ;\
	pushq	%r14			/* save %r14			*/ ;\
	movq	%gs:CPU_RTMP_RSP, %r14					   ;\
	movq	%r14, 8(%rsp)		/* stash the user stack pointer	*/ ;\
	popq	%r14			/* restore %r14			*/ ;\
	movq	T_LWP(%r15), %r15	/* load the lwp pointer		*/ ;\
	pushq	%r15			/* push the lwp pointer		*/ ;\
	movq	LWP_PROCP(%r15), %r15	/* load the proc pointer	*/ ;\
	movq	P_BRAND(%r15), %r15	/* load the brand pointer	*/ ;\
	movq	B_MACHOPS(%r15), %r15	/* load the machops pointer	*/ ;\
	movq	_CONST(_MUL(callback_id, CPTRSIZE))(%r15), %r15		   ;\
	cmpq	$0, %r15						   ;\
	je	1f							   ;\
	movq	%r15, 16(%rsp)		/* save the callback pointer	*/ ;\
	push_userland_ret		/* push the return address	*/ ;\
	movq	24(%rsp), %r15		/* load callback pointer	*/ ;\
	INDIRECT_CALL_REG(r15)		/* call callback		*/ ;\
1:	movq	%gs:CPU_RTMP_R15, %r15	/* restore %r15			*/ ;\
	movq	%gs:CPU_RTMP_RSP, %rsp	/* restore the stack pointer	*/

#define	MSTATE_TRANSITION(from, to)		\
	movl	$from, %edi;			\
	movl	$to, %esi;			\
	call	syscall_mstate

/*
 * Check to see if a simple (direct) return is possible i.e.
 *
 *	if (t->t_post_sys_ast | syscalltrace |
 *	    lwp->lwp_pcb.pcb_rupdate == 1)
 *		do full version	;
 *
 * Preconditions:
 * -	t is curthread
 * Postconditions:
 * -	condition code NE is set if post-sys is too complex
 * -	rtmp is zeroed if it isn't (we rely on this!)
 * -	ltmp is smashed
 */
#define	CHECK_POSTSYS_NE(t, ltmp, rtmp)			\
	movq	T_LWP(t), ltmp;				\
	movzbl	PCB_RUPDATE(ltmp), rtmp;		\
	ORL_SYSCALLTRACE(rtmp);				\
	orl	T_POST_SYS_AST(t), rtmp;		\
	cmpl	$0, rtmp

/*
 * Fix up the lwp, thread, and eflags for a successful return
 *
 * Preconditions:
 * -	zwreg contains zero
 */
#define	SIMPLE_SYSCALL_POSTSYS(t, lwp, zwreg)		\
	movb	$LWP_USER, LWP_STATE(lwp);		\
	movw	zwreg, T_SYSNUM(t);			\
	andb	$_CONST(0xffff - PS_C), REGOFF_RFL(%rsp)

/*
 * ASSERT(lwptoregs(lwp) == rp);
 *
 * This may seem obvious, but very odd things happen if this
 * assertion is false
 *
 * Preconditions:
 *	(%rsp is ready for normal call sequence)
 * Postconditions (if assertion is true):
 *	%r11 is smashed
 *
 * ASSERT(rp->r_cs == descnum)
 *
 * The code selector is written into the regs structure when the
 * lwp stack is created.  We use this ASSERT to validate that
 * the regs structure really matches how we came in.
 *
 * Preconditions:
 *	(%rsp is ready for normal call sequence)
 * Postconditions (if assertion is true):
 *	-none-
 *
 * ASSERT(lwp->lwp_pcb.pcb_rupdate == 0);
 *
 * If this is false, it meant that we returned to userland without
 * updating the segment registers as we were supposed to.
 *
 * Note that we must ensure no interrupts or other traps intervene
 * between entering privileged mode and performing the assertion,
 * otherwise we may perform a context switch on the thread, which
 * will end up setting pcb_rupdate to 1 again.
 *
 * ASSERT(%cr0 & CR0_TS == 0);
 * Preconditions:
 *	(%rsp is ready for normal call sequence)
 * Postconditions (if assertion is true):
 *      (specified register is clobbered)
 *
 * Check to make sure that we are returning to user land and that CR0.TS
 * is not set. This is required as part of the eager FPU (see
 * uts/intel/os/fpu.c for more information).
 */

#if defined(DEBUG)

__lwptoregs_msg:
	.string	"syscall_asm_amd64.s:%d lwptoregs(%p) [%p] != rp [%p]"

__codesel_msg:
	.string	"syscall_asm_amd64.s:%d rp->r_cs [%ld] != %ld"

__no_rupdate_msg:
	.string	"syscall_asm_amd64.s:%d lwp %p, pcb_rupdate != 0"

__bad_ts_msg:
	.string "syscall_asm_amd64.s:%d CR0.TS set on user return"

#define	ASSERT_LWPTOREGS(lwp, rp)			\
	movq	LWP_REGS(lwp), %r11;			\
	cmpq	rp, %r11;				\
	je	7f;					\
	leaq	__lwptoregs_msg(%rip), %rdi;		\
	movl	$__LINE__, %esi;			\
	movq	lwp, %rdx;				\
	movq	%r11, %rcx;				\
	movq	rp, %r8;				\
	xorl	%eax, %eax;				\
	call	panic;					\
7:

#define	ASSERT_NO_RUPDATE_PENDING(lwp)			\
	testb	$0x1, PCB_RUPDATE(lwp);			\
	je	8f;					\
	movq	lwp, %rdx;				\
	leaq	__no_rupdate_msg(%rip), %rdi;		\
	movl	$__LINE__, %esi;			\
	xorl	%eax, %eax;				\
	call	panic;					\
8:

#define	ASSERT_CR0TS_ZERO(reg)				\
	movq	%cr0, reg;				\
	testq	$CR0_TS, reg;				\
	jz	9f;					\
	leaq	__bad_ts_msg(%rip), %rdi;		\
	movl	$__LINE__, %esi;			\
	xorl	%eax, %eax;				\
	call	panic;					\
9:

#else
#define	ASSERT_LWPTOREGS(lwp, rp)
#define	ASSERT_NO_RUPDATE_PENDING(lwp)
#define	ASSERT_CR0TS_ZERO(reg)
#endif

/*
 * Do the traptrace thing and restore any registers we used
 * in situ.  Assumes that %rsp is pointing at the base of
 * the struct regs, obviously ..
 */
#ifdef TRAPTRACE
#define	SYSCALL_TRAPTRACE(ttype)				\
	TRACE_PTR(%rdi, %rbx, %ebx, %rcx, ttype);		\
	TRACE_REGS(%rdi, %rsp, %rbx, %rcx);			\
	TRACE_STAMP(%rdi);	/* rdtsc clobbers %eax, %edx */	\
	movq	REGOFF_RAX(%rsp), %rax;				\
	movq	REGOFF_RBX(%rsp), %rbx;				\
	movq	REGOFF_RCX(%rsp), %rcx;				\
	movq	REGOFF_RDX(%rsp), %rdx;				\
	movl	%eax, TTR_SYSNUM(%rdi);				\
	movq	REGOFF_RDI(%rsp), %rdi

#define	SYSCALL_TRAPTRACE32(ttype)				\
	SYSCALL_TRAPTRACE(ttype);				\
	/* paranoia: clean the top 32-bits of the registers */	\
	orl	%eax, %eax;					\
	orl	%ebx, %ebx;					\
	orl	%ecx, %ecx;					\
	orl	%edx, %edx;					\
	orl	%edi, %edi
#else	/* TRAPTRACE */
#define	SYSCALL_TRAPTRACE(ttype)
#define	SYSCALL_TRAPTRACE32(ttype)
#endif	/* TRAPTRACE */

/*
 * The 64-bit libc syscall wrapper does this:
 *
 * fn(<args>)
 * {
 *	movq	%rcx, %r10	-- because syscall smashes %rcx
 *	movl	$CODE, %eax
 *	syscall
 *	<error processing>
 * }
 *
 * Thus when we come into the kernel:
 *
 *	%rdi, %rsi, %rdx, %r10, %r8, %r9 contain first six args
 *	%rax is the syscall number
 *	%r12-%r15 contain caller state
 *
 * The syscall instruction arranges that:
 *
 *	%rcx contains the return %rip
 *	%r11d contains bottom 32-bits of %rflags
 *	%rflags is masked (as determined by the SFMASK msr)
 *	%cs is set to UCS_SEL (as determined by the STAR msr)
 *	%ss is set to UDS_SEL (as determined by the STAR msr)
 *	%rip is set to sys_syscall (as determined by the LSTAR msr)
 *
 * Or in other words, we have no registers available at all.
 * Only swapgs can save us!
 *
 * Under the hypervisor, the swapgs has happened already.  However, the
 * state of the world is very different from that we're familiar with.
 *
 * In particular, we have a stack structure like that for interrupt
 * gates, except that the %cs and %ss registers are modified for reasons
 * that are not entirely clear.  Critically, the %rcx/%r11 values do
 * *not* reflect the usage of those registers under a 'real' syscall[1];
 * the stack, therefore, looks like this:
 *
 *	0x0(rsp)	potentially junk %rcx
 *	0x8(rsp)	potentially junk %r11
 *	0x10(rsp)	user %rip
 *	0x18(rsp)	modified %cs
 *	0x20(rsp)	user %rflags
 *	0x28(rsp)	user %rsp
 *	0x30(rsp)	modified %ss
 *
 *
 * and before continuing on, we must load the %rip into %rcx and the
 * %rflags into %r11.
 *
 * [1] They used to, and we relied on it, but this was broken in 3.1.1.
 * Sigh.
 */
#if defined(__xpv)
#define	XPV_SYSCALL_PROD						\
	movq	0x10(%rsp), %rcx;					\
	movq	0x20(%rsp), %r11;					\
	movq	0x28(%rsp), %rsp
#else
#define	XPV_SYSCALL_PROD /* nothing */
#endif

	ENTRY_NP2(brand_sys_syscall,_allsyscalls)
	SWAPGS				/* kernel gsbase */
	XPV_SYSCALL_PROD
	BRAND_CALLBACK(BRAND_CB_SYSCALL, BRAND_URET_FROM_REG(%rcx))
	jmp	noprod_sys_syscall

	ALTENTRY(sys_syscall)
	SWAPGS				/* kernel gsbase */
	XPV_SYSCALL_PROD

noprod_sys_syscall:
	movq	%r15, %gs:CPU_RTMP_R15
	movq	%rsp, %gs:CPU_RTMP_RSP

	movq	%gs:CPU_THREAD, %r15
	movq	T_STACK(%r15), %rsp	/* switch from user to kernel stack */

	ASSERT_UPCALL_MASK_IS_SET

	movl	$UCS_SEL, REGOFF_CS(%rsp)
	movq	%rcx, REGOFF_RIP(%rsp)		/* syscall: %rip -> %rcx */
	movq	%r11, REGOFF_RFL(%rsp)		/* syscall: %rfl -> %r11d */
	movl	$UDS_SEL, REGOFF_SS(%rsp)

	movl	%eax, %eax			/* wrapper: sysc# -> %eax */
	movq	%rdi, REGOFF_RDI(%rsp)
	movq	%rsi, REGOFF_RSI(%rsp)
	movq	%rdx, REGOFF_RDX(%rsp)
	movq	%r10, REGOFF_RCX(%rsp)		/* wrapper: %rcx -> %r10 */
	movq	%r10, %rcx			/* arg[3] for direct calls */

	movq	%r8, REGOFF_R8(%rsp)
	movq	%r9, REGOFF_R9(%rsp)
	movq	%rax, REGOFF_RAX(%rsp)
	movq	%rbx, REGOFF_RBX(%rsp)

	movq	%rbp, REGOFF_RBP(%rsp)
	movq	%r10, REGOFF_R10(%rsp)
	movq	%gs:CPU_RTMP_RSP, %r11
	movq	%r11, REGOFF_RSP(%rsp)
	movq	%r12, REGOFF_R12(%rsp)

	movq	%r13, REGOFF_R13(%rsp)
	movq	%r14, REGOFF_R14(%rsp)
	movq	%gs:CPU_RTMP_R15, %r10
	movq	%r10, REGOFF_R15(%rsp)
	movq	$0, REGOFF_SAVFP(%rsp)
	movq	$0, REGOFF_SAVPC(%rsp)

	/*
	 * Copy these registers here in case we end up stopped with
	 * someone (like, say, /proc) messing with our register state.
	 * We don't -restore- them unless we have to in update_sregs.
	 *
	 * Since userland -can't- change fsbase or gsbase directly,
	 * and capturing them involves two serializing instructions,
	 * we don't bother to capture them here.
	 */
	xorl	%ebx, %ebx
	movw	%ds, %bx
	movq	%rbx, REGOFF_DS(%rsp)
	movw	%es, %bx
	movq	%rbx, REGOFF_ES(%rsp)
	movw	%fs, %bx
	movq	%rbx, REGOFF_FS(%rsp)
	movw	%gs, %bx
	movq	%rbx, REGOFF_GS(%rsp)

	/*
	 * If we're trying to use TRAPTRACE though, I take that back: we're
	 * probably debugging some problem in the SWAPGS logic and want to know
	 * what the incoming gsbase was.
	 *
	 * Since we already did SWAPGS, record the KGSBASE.
	 */
#if defined(DEBUG) && defined(TRAPTRACE) && !defined(__xpv)
	movl	$MSR_AMD_KGSBASE, %ecx
	rdmsr
	movl	%eax, REGOFF_GSBASE(%rsp)
	movl	%edx, REGOFF_GSBASE+4(%rsp)
#endif

	/*
	 * Machine state saved in the regs structure on the stack
	 * First six args in %rdi, %rsi, %rdx, %rcx, %r8, %r9
	 * %eax is the syscall number
	 * %rsp is the thread's stack, %r15 is curthread
	 * REG_RSP(%rsp) is the user's stack
	 */

	SYSCALL_TRAPTRACE($TT_SYSC64)

	movq	%rsp, %rbp

	movq	T_LWP(%r15), %r14
	ASSERT_NO_RUPDATE_PENDING(%r14)
	ENABLE_INTR_FLAGS

	MSTATE_TRANSITION(LMS_USER, LMS_SYSTEM)
	movl	REGOFF_RAX(%rsp), %eax	/* (%rax damaged by mstate call) */

	ASSERT_LWPTOREGS(%r14, %rsp)

	movb	$LWP_SYS, LWP_STATE(%r14)
	incq	LWP_RU_SYSC(%r14)
	movb	$NORMALRETURN, LWP_EOSYS(%r14)

	incq	%gs:CPU_STATS_SYS_SYSCALL

	movw	%ax, T_SYSNUM(%r15)
	movzbl	T_PRE_SYS(%r15), %ebx
	ORL_SYSCALLTRACE(%ebx)
	testl	%ebx, %ebx
	jne	_syscall_pre

_syscall_invoke:
	movq	REGOFF_RDI(%rbp), %rdi
	movq	REGOFF_RSI(%rbp), %rsi
	movq	REGOFF_RDX(%rbp), %rdx
	movq	REGOFF_RCX(%rbp), %rcx
	movq	REGOFF_R8(%rbp), %r8
	movq	REGOFF_R9(%rbp), %r9

	cmpl	$NSYSCALL, %eax
	jae	_syscall_ill
	shll	$SYSENT_SIZE_SHIFT, %eax
	leaq	sysent(%rax), %rbx

	movq	SY_CALLC(%rbx), %rax
	INDIRECT_CALL_REG(rax)

	movq	%rax, %r12
	movq	%rdx, %r13

	/*
	 * If the handler returns two ints, then we need to split the
	 * 64-bit return value into two 32-bit values.
	 */
	testw	$SE_32RVAL2, SY_FLAGS(%rbx)
	je	5f
	movq	%r12, %r13
	shrq	$32, %r13	/* upper 32-bits into %edx */
	movl	%r12d, %r12d	/* lower 32-bits into %eax */
5:
	/*
	 * Optimistically assume that there's no post-syscall
	 * work to do.  (This is to avoid having to call syscall_mstate()
	 * with interrupts disabled)
	 */
	MSTATE_TRANSITION(LMS_SYSTEM, LMS_USER)

	/*
	 * We must protect ourselves from being descheduled here;
	 * If we were, and we ended up on another cpu, or another
	 * lwp got in ahead of us, it could change the segment
	 * registers without us noticing before we return to userland.
	 */
	CLI(%r14)
	CHECK_POSTSYS_NE(%r15, %r14, %ebx)
	jne	_syscall_post

	/*
	 * We need to protect ourselves against non-canonical return values
	 * because Intel doesn't check for them on sysret (AMD does).  Canonical
	 * addresses on current amd64 processors only use 48-bits for VAs; an
	 * address is canonical if all upper bits (47-63) are identical. If we
	 * find a non-canonical %rip, we opt to go through the full
	 * _syscall_post path which takes us into an iretq which is not
	 * susceptible to the same problems sysret is.
	 *
	 * We're checking for a canonical address by first doing an arithmetic
	 * shift. This will fill in the remaining bits with the value of bit 63.
	 * If the address were canonical, the register would now have either all
	 * zeroes or all ones in it. Therefore we add one (inducing overflow)
	 * and compare against 1. A canonical address will either be zero or one
	 * at this point, hence the use of ja.
	 *
	 * At this point, r12 and r13 have the return value so we can't use
	 * those registers.
	 */
	movq	REGOFF_RIP(%rsp), %rcx
	sarq	$47, %rcx
	incq	%rcx
	cmpq	$1, %rcx
	ja	_syscall_post


	SIMPLE_SYSCALL_POSTSYS(%r15, %r14, %bx)

	movq	%r12, REGOFF_RAX(%rsp)
	movq	%r13, REGOFF_RDX(%rsp)

	/*
	 * Clobber %r11 as we check CR0.TS.
	 */
	ASSERT_CR0TS_ZERO(%r11)

	/*
	 * To get back to userland, we need the return %rip in %rcx and
	 * the return %rfl in %r11d.  The sysretq instruction also arranges
	 * to fix up %cs and %ss; everything else is our responsibility.
	 */
	movq	REGOFF_RDI(%rsp), %rdi
	movq	REGOFF_RSI(%rsp), %rsi
	movq	REGOFF_RDX(%rsp), %rdx
	/* %rcx used to restore %rip value */

	movq	REGOFF_R8(%rsp), %r8
	movq	REGOFF_R9(%rsp), %r9
	movq	REGOFF_RAX(%rsp), %rax
	movq	REGOFF_RBX(%rsp), %rbx

	movq	REGOFF_RBP(%rsp), %rbp
	movq	REGOFF_R10(%rsp), %r10
	/* %r11 used to restore %rfl value */
	movq	REGOFF_R12(%rsp), %r12

	movq	REGOFF_R13(%rsp), %r13
	movq	REGOFF_R14(%rsp), %r14
	movq	REGOFF_R15(%rsp), %r15

	movq	REGOFF_RIP(%rsp), %rcx
	movl	REGOFF_RFL(%rsp), %r11d

	/*
	 * Unlike other cases, because we need to restore the user stack pointer
	 * before exiting the kernel we must clear the microarch state before
	 * getting here. This should be safe because it means that the only
	 * values on the bus after this are based on the user's registers and
	 * potentially the addresses where we stored them. Given the constraints
	 * of sysret, that's how it has to be.
	 */
	call	x86_md_clear

#if defined(__xpv)
	addq	$REGOFF_RIP, %rsp
#else
	movq	REGOFF_RSP(%rsp), %rsp
#endif

        /*
         * There can be no instructions between the ALTENTRY below and
	 * SYSRET or we could end up breaking brand support. See label usage
         * in sn1_brand_syscall_callback for an example.
         */
	ASSERT_UPCALL_MASK_IS_SET
#if defined(__xpv)
	SYSRETQ
        ALTENTRY(nopop_sys_syscall_swapgs_sysretq)

	/*
	 * We can only get here after executing a brand syscall
	 * interposition callback handler and simply need to
	 * "sysretq" back to userland. On the hypervisor this
	 * involves the iret hypercall which requires us to construct
	 * just enough of the stack needed for the hypercall.
	 * (rip, cs, rflags, rsp, ss).
	 */
	movq    %rsp, %gs:CPU_RTMP_RSP		/* save user's rsp */
	movq	%gs:CPU_THREAD, %r11
	movq	T_STACK(%r11), %rsp

	movq	%rcx, REGOFF_RIP(%rsp)
	movl	$UCS_SEL, REGOFF_CS(%rsp)
	movq	%gs:CPU_RTMP_RSP, %r11
	movq	%r11, REGOFF_RSP(%rsp)
	pushfq
	popq	%r11				/* hypercall enables ints */
	movq	%r11, REGOFF_RFL(%rsp)
	movl	$UDS_SEL, REGOFF_SS(%rsp)
	addq	$REGOFF_RIP, %rsp
	/*
	 * XXPV: see comment in SYSRETQ definition for future optimization
	 *       we could take.
	 */
	ASSERT_UPCALL_MASK_IS_SET
	SYSRETQ
#else
        ALTENTRY(nopop_sys_syscall_swapgs_sysretq)
	jmp	tr_sysretq
#endif
        /*NOTREACHED*/
        SET_SIZE(nopop_sys_syscall_swapgs_sysretq)

_syscall_pre:
	call	pre_syscall
	movl	%eax, %r12d
	testl	%eax, %eax
	jne	_syscall_post_call
	/*
	 * Didn't abort, so reload the syscall args and invoke the handler.
	 */
	movzwl	T_SYSNUM(%r15), %eax
	jmp	_syscall_invoke

_syscall_ill:
	call	nosys
	movq	%rax, %r12
	movq	%rdx, %r13
	jmp	_syscall_post_call

_syscall_post:
	STI
	/*
	 * Sigh, our optimism wasn't justified, put it back to LMS_SYSTEM
	 * so that we can account for the extra work it takes us to finish.
	 */
	MSTATE_TRANSITION(LMS_USER, LMS_SYSTEM)
_syscall_post_call:
	movq	%r12, %rdi
	movq	%r13, %rsi
	call	post_syscall
	MSTATE_TRANSITION(LMS_SYSTEM, LMS_USER)
	jmp	_sys_rtt
	SET_SIZE(sys_syscall)
	SET_SIZE(brand_sys_syscall)

	ENTRY_NP(brand_sys_syscall32)
	SWAPGS				/* kernel gsbase */
	XPV_TRAP_POP
	BRAND_CALLBACK(BRAND_CB_SYSCALL32, BRAND_URET_FROM_REG(%rcx))
	jmp	nopop_sys_syscall32

	ALTENTRY(sys_syscall32)
	SWAPGS				/* kernel gsbase */
	XPV_TRAP_POP

nopop_sys_syscall32:
	movl	%esp, %r10d
	movq	%gs:CPU_THREAD, %r15
	movq	T_STACK(%r15), %rsp
	movl	%eax, %eax

	movl	$U32CS_SEL, REGOFF_CS(%rsp)
	movl	%ecx, REGOFF_RIP(%rsp)		/* syscall: %rip -> %rcx */
	movq	%r11, REGOFF_RFL(%rsp)		/* syscall: %rfl -> %r11d */
	movq	%r10, REGOFF_RSP(%rsp)
	movl	$UDS_SEL, REGOFF_SS(%rsp)

_syscall32_save:
	movl	%edi, REGOFF_RDI(%rsp)
	movl	%esi, REGOFF_RSI(%rsp)
	movl	%ebp, REGOFF_RBP(%rsp)
	movl	%ebx, REGOFF_RBX(%rsp)
	movl	%edx, REGOFF_RDX(%rsp)
	movl	%ecx, REGOFF_RCX(%rsp)
	movl	%eax, REGOFF_RAX(%rsp)		/* wrapper: sysc# -> %eax */
	movq	$0, REGOFF_SAVFP(%rsp)
	movq	$0, REGOFF_SAVPC(%rsp)

	/*
	 * Copy these registers here in case we end up stopped with
	 * someone (like, say, /proc) messing with our register state.
	 * We don't -restore- them unless we have to in update_sregs.
	 *
	 * Since userland -can't- change fsbase or gsbase directly,
	 * we don't bother to capture them here.
	 */
	xorl	%ebx, %ebx
	movw	%ds, %bx
	movq	%rbx, REGOFF_DS(%rsp)
	movw	%es, %bx
	movq	%rbx, REGOFF_ES(%rsp)
	movw	%fs, %bx
	movq	%rbx, REGOFF_FS(%rsp)
	movw	%gs, %bx
	movq	%rbx, REGOFF_GS(%rsp)

	/*
	 * If we're trying to use TRAPTRACE though, I take that back: we're
	 * probably debugging some problem in the SWAPGS logic and want to know
	 * what the incoming gsbase was.
	 *
	 * Since we already did SWAPGS, record the KGSBASE.
	 */
#if defined(DEBUG) && defined(TRAPTRACE) && !defined(__xpv)
	movl	$MSR_AMD_KGSBASE, %ecx
	rdmsr
	movl	%eax, REGOFF_GSBASE(%rsp)
	movl	%edx, REGOFF_GSBASE+4(%rsp)
#endif

	/*
	 * Application state saved in the regs structure on the stack
	 * %eax is the syscall number
	 * %rsp is the thread's stack, %r15 is curthread
	 * REG_RSP(%rsp) is the user's stack
	 */

	SYSCALL_TRAPTRACE32($TT_SYSC)

	movq	%rsp, %rbp

	movq	T_LWP(%r15), %r14
	ASSERT_NO_RUPDATE_PENDING(%r14)

	ENABLE_INTR_FLAGS

	MSTATE_TRANSITION(LMS_USER, LMS_SYSTEM)
	movl	REGOFF_RAX(%rsp), %eax	/* (%rax damaged by mstate call) */

	ASSERT_LWPTOREGS(%r14, %rsp)

	incq	 %gs:CPU_STATS_SYS_SYSCALL

	/*
	 * Make some space for MAXSYSARGS (currently 8) 32-bit args placed
	 * into 64-bit (long) arg slots, maintaining 16 byte alignment.  Or
	 * more succinctly:
	 *
	 *	SA(MAXSYSARGS * sizeof (long)) == 64
	 */
#define	SYS_DROP	64			/* drop for args */
	subq	$SYS_DROP, %rsp
	movb	$LWP_SYS, LWP_STATE(%r14)
	movq	%r15, %rdi
	movq	%rsp, %rsi
	call	syscall_entry

	/*
	 * Fetch the arguments copied onto the kernel stack and put
	 * them in the right registers to invoke a C-style syscall handler.
	 * %rax contains the handler address.
	 *
	 * Ideas for making all this go faster of course include simply
	 * forcibly fetching 6 arguments from the user stack under lofault
	 * protection, reverting to copyin_args only when watchpoints
	 * are in effect.
	 *
	 * (If we do this, make sure that exec and libthread leave
	 * enough space at the top of the stack to ensure that we'll
	 * never do a fetch from an invalid page.)
	 *
	 * Lots of ideas here, but they won't really help with bringup B-)
	 * Correctness can't wait, performance can wait a little longer ..
	 */

	movq	%rax, %rbx
	movl	0(%rsp), %edi
	movl	8(%rsp), %esi
	movl	0x10(%rsp), %edx
	movl	0x18(%rsp), %ecx
	movl	0x20(%rsp), %r8d
	movl	0x28(%rsp), %r9d

	movq	SY_CALLC(%rbx), %rax
	INDIRECT_CALL_REG(rax)

	movq	%rbp, %rsp	/* pop the args */

	/*
	 * amd64 syscall handlers -always- return a 64-bit value in %rax.
	 * On the 32-bit kernel, they always return that value in %eax:%edx
	 * as required by the 32-bit ABI.
	 *
	 * Simulate the same behaviour by unconditionally splitting the
	 * return value in the same way.
	 */
	movq	%rax, %r13
	shrq	$32, %r13	/* upper 32-bits into %edx */
	movl	%eax, %r12d	/* lower 32-bits into %eax */

	/*
	 * Optimistically assume that there's no post-syscall
	 * work to do.  (This is to avoid having to call syscall_mstate()
	 * with interrupts disabled)
	 */
	MSTATE_TRANSITION(LMS_SYSTEM, LMS_USER)

	/*
	 * We must protect ourselves from being descheduled here;
	 * If we were, and we ended up on another cpu, or another
	 * lwp got in ahead of us, it could change the segment
	 * registers without us noticing before we return to userland.
	 */
	CLI(%r14)
	CHECK_POSTSYS_NE(%r15, %r14, %ebx)
	jne	_full_syscall_postsys32
	SIMPLE_SYSCALL_POSTSYS(%r15, %r14, %bx)

	/*
	 * Clobber %r11 as we check CR0.TS.
	 */
	ASSERT_CR0TS_ZERO(%r11)

	/*
	 * To get back to userland, we need to put the return %rip in %rcx and
	 * the return %rfl in %r11d.  The sysret instruction also arranges
	 * to fix up %cs and %ss; everything else is our responsibility.
	 */

	movl	%r12d, %eax			/* %eax: rval1 */
	movl	REGOFF_RBX(%rsp), %ebx
	/* %ecx used for return pointer */
	movl	%r13d, %edx			/* %edx: rval2 */
	movl	REGOFF_RBP(%rsp), %ebp
	movl	REGOFF_RSI(%rsp), %esi
	movl	REGOFF_RDI(%rsp), %edi

	movl	REGOFF_RFL(%rsp), %r11d		/* %r11 -> eflags */
	movl	REGOFF_RIP(%rsp), %ecx		/* %ecx -> %eip */
	/*
	 * Unlike other cases, because we need to restore the user stack pointer
	 * before exiting the kernel we must clear the microarch state before
	 * getting here. This should be safe because it means that the only
	 * values on the bus after this are based on the user's registers and
	 * potentially the addresses where we stored them. Given the constraints
	 * of sysret, that's how it has to be.
	 */
	call	x86_md_clear

	movl	REGOFF_RSP(%rsp), %esp

	ASSERT_UPCALL_MASK_IS_SET
        ALTENTRY(nopop_sys_syscall32_swapgs_sysretl)
	jmp	tr_sysretl
        SET_SIZE(nopop_sys_syscall32_swapgs_sysretl)
	/*NOTREACHED*/

_full_syscall_postsys32:
	STI
	/*
	 * Sigh, our optimism wasn't justified, put it back to LMS_SYSTEM
	 * so that we can account for the extra work it takes us to finish.
	 */
	MSTATE_TRANSITION(LMS_USER, LMS_SYSTEM)
	movq	%r15, %rdi
	movq	%r12, %rsi			/* rval1 - %eax */
	movq	%r13, %rdx			/* rval2 - %edx */
	call	syscall_exit
	MSTATE_TRANSITION(LMS_SYSTEM, LMS_USER)
	jmp	_sys_rtt
	SET_SIZE(sys_syscall32)
	SET_SIZE(brand_sys_syscall32)

/*
 * System call handler via the sysenter instruction
 * Used only for 32-bit system calls on the 64-bit kernel.
 *
 * The caller in userland has arranged that:
 *
 * -	%eax contains the syscall number
 * -	%ecx contains the user %esp
 * -	%edx contains the return %eip
 * -	the user stack contains the args to the syscall
 *
 * Hardware and (privileged) initialization code have arranged that by
 * the time the sysenter instructions completes:
 *
 * - %rip is pointing to sys_sysenter (below).
 * - %cs and %ss are set to kernel text and stack (data) selectors.
 * - %rsp is pointing at the lwp's stack
 * - interrupts have been disabled.
 *
 * Note that we are unable to return both "rvals" to userland with
 * this call, as %edx is used by the sysexit instruction.
 *
 * One final complication in this routine is its interaction with
 * single-stepping in a debugger.  For most of the system call mechanisms, the
 * CPU automatically clears the single-step flag before we enter the kernel.
 * The sysenter mechanism does not clear the flag, so a user single-stepping
 * through a libc routine may suddenly find themself single-stepping through the
 * kernel.  To detect this, kmdb and trap() both compare the trap %pc to the
 * [brand_]sys_enter addresses on each single-step trap.  If it finds that we
 * have single-stepped to a sysenter entry point, it explicitly clears the flag
 * and executes the sys_sysenter routine.
 *
 * One final complication in this final complication is the fact that we have
 * two different entry points for sysenter: brand_sys_sysenter and sys_sysenter.
 * If we enter at brand_sys_sysenter and start single-stepping through the
 * kernel with kmdb, we will eventually hit the instruction at sys_sysenter.
 * kmdb cannot distinguish between that valid single-step and the undesirable
 * one mentioned above.  To avoid this situation, we simply add a jump over the
 * instruction at sys_sysenter to make it impossible to single-step to it.
 */

	ENTRY_NP(brand_sys_sysenter)
	SWAPGS				/* kernel gsbase */
	ALTENTRY(_brand_sys_sysenter_post_swapgs)

	BRAND_CALLBACK(BRAND_CB_SYSENTER, BRAND_URET_FROM_REG(%rdx))
	/*
	 * Jump over sys_sysenter to allow single-stepping as described
	 * above.
	 */
	jmp	_sys_sysenter_post_swapgs

	ALTENTRY(sys_sysenter)
	SWAPGS				/* kernel gsbase */
	ALTENTRY(_sys_sysenter_post_swapgs)

	movq	%gs:CPU_THREAD, %r15

	movl	$U32CS_SEL, REGOFF_CS(%rsp)
	movl	%ecx, REGOFF_RSP(%rsp)		/* wrapper: %esp -> %ecx */
	movl	%edx, REGOFF_RIP(%rsp)		/* wrapper: %eip -> %edx */
	/*
	 * NOTE: none of the instructions that run before we get here should
	 * clobber bits in (R)FLAGS! This includes the kpti trampoline.
	 */
	pushfq
	popq	%r10
	movl	$UDS_SEL, REGOFF_SS(%rsp)

	/*
	 * Set the interrupt flag before storing the flags to the
	 * flags image on the stack so we can return to user with
	 * interrupts enabled if we return via sys_rtt_syscall32
	 */
	orq	$PS_IE, %r10
	movq	%r10, REGOFF_RFL(%rsp)

	movl	%edi, REGOFF_RDI(%rsp)
	movl	%esi, REGOFF_RSI(%rsp)
	movl	%ebp, REGOFF_RBP(%rsp)
	movl	%ebx, REGOFF_RBX(%rsp)
	movl	%edx, REGOFF_RDX(%rsp)
	movl	%ecx, REGOFF_RCX(%rsp)
	movl	%eax, REGOFF_RAX(%rsp)		/* wrapper: sysc# -> %eax */
	movq	$0, REGOFF_SAVFP(%rsp)
	movq	$0, REGOFF_SAVPC(%rsp)

	/*
	 * Copy these registers here in case we end up stopped with
	 * someone (like, say, /proc) messing with our register state.
	 * We don't -restore- them unless we have to in update_sregs.
	 *
	 * Since userland -can't- change fsbase or gsbase directly,
	 * we don't bother to capture them here.
	 */
	xorl	%ebx, %ebx
	movw	%ds, %bx
	movq	%rbx, REGOFF_DS(%rsp)
	movw	%es, %bx
	movq	%rbx, REGOFF_ES(%rsp)
	movw	%fs, %bx
	movq	%rbx, REGOFF_FS(%rsp)
	movw	%gs, %bx
	movq	%rbx, REGOFF_GS(%rsp)

	/*
	 * If we're trying to use TRAPTRACE though, I take that back: we're
	 * probably debugging some problem in the SWAPGS logic and want to know
	 * what the incoming gsbase was.
	 *
	 * Since we already did SWAPGS, record the KGSBASE.
	 */
#if defined(DEBUG) && defined(TRAPTRACE) && !defined(__xpv)
	movl	$MSR_AMD_KGSBASE, %ecx
	rdmsr
	movl	%eax, REGOFF_GSBASE(%rsp)
	movl	%edx, REGOFF_GSBASE+4(%rsp)
#endif

	/*
	 * Application state saved in the regs structure on the stack
	 * %eax is the syscall number
	 * %rsp is the thread's stack, %r15 is curthread
	 * REG_RSP(%rsp) is the user's stack
	 */

	SYSCALL_TRAPTRACE($TT_SYSENTER)

	movq	%rsp, %rbp

	movq	T_LWP(%r15), %r14
	ASSERT_NO_RUPDATE_PENDING(%r14)

	ENABLE_INTR_FLAGS

	/*
	 * Catch 64-bit process trying to issue sysenter instruction
	 * on Nocona based systems.
	 */
	movq	LWP_PROCP(%r14), %rax
	cmpq	$DATAMODEL_ILP32, P_MODEL(%rax)
	je	7f

	/*
	 * For a non-32-bit process, simulate a #ud, since that's what
	 * native hardware does.  The traptrace entry (above) will
	 * let you know what really happened.
	 */
	movq	$T_ILLINST, REGOFF_TRAPNO(%rsp)
	movq	REGOFF_CS(%rsp), %rdi
	movq	%rdi, REGOFF_ERR(%rsp)
	movq	%rsp, %rdi
	movq	REGOFF_RIP(%rsp), %rsi
	movl	%gs:CPU_ID, %edx
	call	trap
	jmp	_sys_rtt
7:

	MSTATE_TRANSITION(LMS_USER, LMS_SYSTEM)
	movl	REGOFF_RAX(%rsp), %eax	/* (%rax damaged by mstate calls) */

	ASSERT_LWPTOREGS(%r14, %rsp)

	incq	%gs:CPU_STATS_SYS_SYSCALL

	/*
	 * Make some space for MAXSYSARGS (currently 8) 32-bit args
	 * placed into 64-bit (long) arg slots, plus one 64-bit
	 * (long) arg count, maintaining 16 byte alignment.
	 */
	subq	$SYS_DROP, %rsp
	movb	$LWP_SYS, LWP_STATE(%r14)
	movq	%r15, %rdi
	movq	%rsp, %rsi
	call	syscall_entry

	/*
	 * Fetch the arguments copied onto the kernel stack and put
	 * them in the right registers to invoke a C-style syscall handler.
	 * %rax contains the handler address.
	 */
	movq	%rax, %rbx
	movl	0(%rsp), %edi
	movl	8(%rsp), %esi
	movl	0x10(%rsp), %edx
	movl	0x18(%rsp), %ecx
	movl	0x20(%rsp), %r8d
	movl	0x28(%rsp), %r9d

	movq	SY_CALLC(%rbx), %rax
	INDIRECT_CALL_REG(rax)

	movq	%rbp, %rsp	/* pop the args */

	/*
	 * amd64 syscall handlers -always- return a 64-bit value in %rax.
	 * On the 32-bit kernel, the always return that value in %eax:%edx
	 * as required by the 32-bit ABI.
	 *
	 * Simulate the same behaviour by unconditionally splitting the
	 * return value in the same way.
	 */
	movq	%rax, %r13
	shrq	$32, %r13	/* upper 32-bits into %edx */
	movl	%eax, %r12d	/* lower 32-bits into %eax */

	/*
	 * Optimistically assume that there's no post-syscall
	 * work to do.  (This is to avoid having to call syscall_mstate()
	 * with interrupts disabled)
	 */
	MSTATE_TRANSITION(LMS_SYSTEM, LMS_USER)

	/*
	 * We must protect ourselves from being descheduled here;
	 * If we were, and we ended up on another cpu, or another
	 * lwp got int ahead of us, it could change the segment
	 * registers without us noticing before we return to userland.
	 *
	 * This cli is undone in the tr_sysexit trampoline code.
	 */
	cli
	CHECK_POSTSYS_NE(%r15, %r14, %ebx)
	jne	_full_syscall_postsys32
	SIMPLE_SYSCALL_POSTSYS(%r15, %r14, %bx)

	/*
	 * To get back to userland, load up the 32-bit registers and
	 * sysexit back where we came from.
	 */

	/*
	 * Interrupts will be turned on by the 'sti' executed just before
	 * sysexit.  The following ensures that restoring the user's rflags
	 * doesn't enable interrupts too soon.
	 */
	andq	$_BITNOT(PS_IE), REGOFF_RFL(%rsp)

	/*
	 * Clobber %r11 as we check CR0.TS.
	 */
	ASSERT_CR0TS_ZERO(%r11)

	/*
	 * (There's no point in loading up %edx because the sysexit
	 * mechanism smashes it.)
	 */
	movl	%r12d, %eax
	movl	REGOFF_RBX(%rsp), %ebx
	movl	REGOFF_RBP(%rsp), %ebp
	movl	REGOFF_RSI(%rsp), %esi
	movl	REGOFF_RDI(%rsp), %edi

	movl	REGOFF_RIP(%rsp), %edx	/* sysexit: %edx -> %eip */
	pushq	REGOFF_RFL(%rsp)
	popfq
	movl	REGOFF_RSP(%rsp), %ecx	/* sysexit: %ecx -> %esp */
        ALTENTRY(sys_sysenter_swapgs_sysexit)
	call	x86_md_clear
	jmp	tr_sysexit
	SET_SIZE(sys_sysenter_swapgs_sysexit)
	SET_SIZE(sys_sysenter)
	SET_SIZE(_sys_sysenter_post_swapgs)
	SET_SIZE(brand_sys_sysenter)

/*
 * This is the destination of the "int $T_SYSCALLINT" interrupt gate, used by
 * the generic i386 libc to do system calls. We do a small amount of setup
 * before jumping into the existing sys_syscall32 path.
 */

	ENTRY_NP(brand_sys_syscall_int)
	SWAPGS				/* kernel gsbase */
	XPV_TRAP_POP
	call	smap_enable
	BRAND_CALLBACK(BRAND_CB_INT91, BRAND_URET_FROM_INTR_STACK())
	jmp	nopop_syscall_int

	ALTENTRY(sys_syscall_int)
	SWAPGS				/* kernel gsbase */
	XPV_TRAP_POP
	call	smap_enable

nopop_syscall_int:
	movq	%gs:CPU_THREAD, %r15
	movq	T_STACK(%r15), %rsp
	movl	%eax, %eax
	/*
	 * Set t_post_sys on this thread to force ourselves out via the slow
	 * path. It might be possible at some later date to optimize this out
	 * and use a faster return mechanism.
	 */
	movb	$1, T_POST_SYS(%r15)
	CLEAN_CS
	jmp	_syscall32_save
	/*
	 * There should be no instructions between this label and SWAPGS/IRET
	 * or we could end up breaking branded zone support. See the usage of
	 * this label in lx_brand_int80_callback and sn1_brand_int91_callback
	 * for examples.
	 *
	 * We want to swapgs to maintain the invariant that all entries into
	 * tr_iret_user are done on the user gsbase.
	 */
	ALTENTRY(sys_sysint_swapgs_iret)
	call	x86_md_clear
	SWAPGS
	jmp	tr_iret_user
	/*NOTREACHED*/
	SET_SIZE(sys_sysint_swapgs_iret)
	SET_SIZE(sys_syscall_int)
	SET_SIZE(brand_sys_syscall_int)

/*
 * Legacy 32-bit applications and old libc implementations do lcalls;
 * we should never get here because the LDT entry containing the syscall
 * segment descriptor has the "segment present" bit cleared, which means
 * we end up processing those system calls in trap() via a not-present trap.
 *
 * We do it this way because a call gate unhelpfully does -nothing- to the
 * interrupt flag bit, so an interrupt can run us just after the lcall
 * completes, but just before the swapgs takes effect.   Thus the INTR_PUSH and
 * INTR_POP paths would have to be slightly more complex to dance around
 * this problem, and end up depending explicitly on the first
 * instruction of this handler being either swapgs or cli.
 */

	ENTRY_NP(sys_lcall32)
	SWAPGS				/* kernel gsbase */
	pushq	$0
	pushq	%rbp
	movq	%rsp, %rbp
	leaq	__lcall_panic_str(%rip), %rdi
	xorl	%eax, %eax
	call	panic
	SET_SIZE(sys_lcall32)

__lcall_panic_str:
	.string	"sys_lcall32: shouldn't be here!"

/*
 * Declare a uintptr_t which covers the entire pc range of syscall
 * handlers for the stack walkers that need this.
 */
	.align	CPTRSIZE
	.globl	_allsyscalls_size
	.type	_allsyscalls_size, @object
_allsyscalls_size:
	.NWORD	. - _allsyscalls
	SET_SIZE(_allsyscalls_size)

/*
 * These are the thread context handlers for lwps using sysenter/sysexit.
 */

	/*
	 * setting this value to zero as we switch away causes the
	 * stack-pointer-on-sysenter to be NULL, ensuring that we
	 * don't silently corrupt another (preempted) thread stack
	 * when running an lwp that (somehow) didn't get sep_restore'd
	 */
	ENTRY_NP(sep_save)
	xorl	%edx, %edx
	xorl	%eax, %eax
	movl	$MSR_INTC_SEP_ESP, %ecx
	wrmsr
	ret
	SET_SIZE(sep_save)

	/*
	 * Update the kernel stack pointer as we resume onto this cpu.
	 */
	ENTRY_NP(sep_restore)
	movq	%rdi, %rdx
	shrq	$32, %rdx
	movl	%edi, %eax
	movl	$MSR_INTC_SEP_ESP, %ecx
	wrmsr
	ret
	SET_SIZE(sep_restore)