Loading...
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
/*
 * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. The rights granted to you under the License
 * may not be used to create, or enable the creation or redistribution of,
 * unlawful or unlicensed copies of an Apple operating system, or to
 * circumvent, violate, or enable the circumvention or violation of, any
 * terms of an Apple operating system software license agreement.
 *
 * Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
 */
/*
 * @OSF_COPYRIGHT@
 */
/*
 * Mach Operating System
 * Copyright (c) 1991,1990,1989,1988 Carnegie Mellon University
 * All Rights Reserved.
 *
 * Permission to use, copy, modify and distribute this software and its
 * documentation is hereby granted, provided that both the copyright
 * notice and this permission notice appear in all copies of the
 * software, derivative works or modified versions, and any portions
 * thereof, and that both notices appear in supporting documentation.
 *
 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
 * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
 *
 * Carnegie Mellon requests users of this software to return to
 *
 *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
 *  School of Computer Science
 *  Carnegie Mellon University
 *  Pittsburgh PA 15213-3890
 *
 * any improvements or extensions that they make and grant Carnegie Mellon
 * the rights to redistribute these changes.
 */
/*
 */

/*
 * Hardware trap/fault handler.
 */

#include <mach_kdp.h>
#include <mach_ldebug.h>

#include <types.h>
#include <i386/eflags.h>
#include <i386/trap_internal.h>
#include <i386/pmap.h>
#include <i386/fpu.h>
#include <i386/panic_notify.h>
#include <i386/lapic.h>

#include <mach/exception.h>
#include <mach/kern_return.h>
#include <mach/vm_param.h>
#include <mach/i386/thread_status.h>

#include <vm/vm_kern.h>
#include <vm/vm_fault.h>
#include <vm/vm_map_xnu.h>

#include <kern/kern_types.h>
#include <kern/processor.h>
#include <kern/thread.h>
#include <kern/task.h>
#include <kern/restartable.h>
#include <kern/sched.h>
#include <kern/sched_prim.h>
#include <kern/exception.h>
#include <kern/spl.h>
#include <kern/misc_protos.h>
#include <kern/debug.h>
#if CONFIG_TELEMETRY
#include <kern/telemetry.h>
#include <kern/trap_telemetry.h>
#endif
#include <kern/zalloc_internal.h>
#include <sys/kdebug.h>
#include <kperf/kperf.h>
#include <prng/random.h>
#include <prng/entropy.h>

#include <string.h>

#include <i386/postcode.h>
#include <i386/mp_desc.h>
#include <i386/proc_reg.h>
#include <i386/machine_routines.h>
#if CONFIG_MCA
#include <i386/machine_check.h>
#endif
#include <mach/i386/syscall_sw.h>

#include <libkern/OSDebug.h>
#include <i386/cpu_threads.h>
#include <machine/pal_routines.h>
#include <i386/lbr.h>

extern void throttle_lowpri_io(int);
extern void kprint_state(x86_saved_state64_t *saved_state);
#if DEVELOPMENT || DEBUG
int insnstream_force_cacheline_mismatch = 0;
extern int panic_on_cacheline_mismatch;
extern char panic_on_trap_procname[];
extern uint32_t panic_on_trap_mask;
#endif

extern int insn_copyin_count;

/*
 * Forward declarations
 */
static void panic_trap(x86_saved_state64_t *saved_state, uint16_t comment, const char *trapreason, uint32_t pl, kern_return_t fault_result) __dead2;
static void set_recovery_ip(x86_saved_state64_t *saved_state, vm_offset_t ip);
#if DEVELOPMENT || DEBUG
static __attribute__((noinline)) void copy_instruction_stream(thread_t thread, uint64_t rip, int trap_code, bool inspect_cacheline);
#else
static __attribute__((noinline)) void copy_instruction_stream(thread_t thread, uint64_t rip, int trap_code);
#endif

#if CONFIG_DTRACE
/* See <rdar://problem/4613924> */
perfCallback tempDTraceTrapHook = NULL; /* Pointer to DTrace fbt trap hook routine */

extern boolean_t dtrace_tally_fault(user_addr_t);
extern boolean_t dtrace_handle_trap(int, x86_saved_state_t *);
#endif

#ifdef MACH_BSD
extern char *   proc_name_address(void *p);
#endif /* MACH_BSD */

extern boolean_t pmap_smep_enabled;
extern boolean_t pmap_smap_enabled;

__attribute__((noreturn))
void
thread_syscall_return(
	kern_return_t ret)
{
	thread_t        thr_act = current_thread();
	boolean_t       is_mach;
	int             code;

	pal_register_cache_state(thr_act, DIRTY);

	if (thread_is_64bit_addr(thr_act)) {
		x86_saved_state64_t     *regs;

		regs = USER_REGS64(thr_act);

		code = (int) (regs->rax & SYSCALL_NUMBER_MASK);
		is_mach = (regs->rax & SYSCALL_CLASS_MASK)
		    == (SYSCALL_CLASS_MACH << SYSCALL_CLASS_SHIFT);
		if (kdebug_enable && is_mach) {
			/* Mach trap */
			KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
			    MACHDBG_CODE(DBG_MACH_EXCP_SC, code) | DBG_FUNC_END,
			    ret, 0, 0, 0, 0);
		}
		regs->rax = ret;
#if DEBUG
		if (is_mach) {
			DEBUG_KPRINT_SYSCALL_MACH(
				"thread_syscall_return: 64-bit mach ret=%u\n",
				ret);
		} else {
			DEBUG_KPRINT_SYSCALL_UNIX(
				"thread_syscall_return: 64-bit unix ret=%u\n",
				ret);
		}
#endif
	} else {
		x86_saved_state32_t     *regs;

		regs = USER_REGS32(thr_act);

		code = ((int) regs->eax);
		is_mach = (code < 0);
		if (kdebug_enable && is_mach) {
			/* Mach trap */
			KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
			    MACHDBG_CODE(DBG_MACH_EXCP_SC, -code) | DBG_FUNC_END,
			    ret, 0, 0, 0, 0);
		}
		regs->eax = ret;
#if DEBUG
		if (is_mach) {
			DEBUG_KPRINT_SYSCALL_MACH(
				"thread_syscall_return: 32-bit mach ret=%u\n",
				ret);
		} else {
			DEBUG_KPRINT_SYSCALL_UNIX(
				"thread_syscall_return: 32-bit unix ret=%u\n",
				ret);
		}
#endif
	}

#if DEBUG || DEVELOPMENT
	kern_allocation_name_t
	prior __assert_only = thread_get_kernel_state(thr_act)->allocation_name;
	assertf(prior == NULL, "thread_set_allocation_name(\"%s\") not cleared", kern_allocation_get_name(prior));
#endif /* DEBUG || DEVELOPMENT */

	throttle_lowpri_io(1);

	thread_exception_return();
	/*NOTREACHED*/
}

/*
 * Fault recovery in copyin/copyout routines.
 */
struct recovery {
	uintptr_t       fault_addr;
	uintptr_t       recover_addr;
};

extern struct recovery  recover_table[];
extern struct recovery  recover_table_end[];

const char *    trap_type[] = {TRAP_NAMES};
unsigned        TRAP_TYPES = sizeof(trap_type) / sizeof(trap_type[0]);

extern void     PE_incoming_interrupt(int interrupt);

#if defined(__x86_64__) && DEBUG
void
kprint_state(x86_saved_state64_t        *saved_state)
{
	kprintf("current_cpu_datap() 0x%lx\n", (uintptr_t)current_cpu_datap());
	kprintf("Current GS base MSR 0x%llx\n", rdmsr64(MSR_IA32_GS_BASE));
	kprintf("Kernel  GS base MSR 0x%llx\n", rdmsr64(MSR_IA32_KERNEL_GS_BASE));
	kprintf("state at 0x%lx:\n", (uintptr_t) saved_state);

	kprintf("      rdi    0x%llx\n", saved_state->rdi);
	kprintf("      rsi    0x%llx\n", saved_state->rsi);
	kprintf("      rdx    0x%llx\n", saved_state->rdx);
	kprintf("      r10    0x%llx\n", saved_state->r10);
	kprintf("      r8     0x%llx\n", saved_state->r8);
	kprintf("      r9     0x%llx\n", saved_state->r9);

	kprintf("      cr2    0x%llx\n", saved_state->cr2);
	kprintf("real  cr2    0x%lx\n", get_cr2());
	kprintf("      r15    0x%llx\n", saved_state->r15);
	kprintf("      r14    0x%llx\n", saved_state->r14);
	kprintf("      r13    0x%llx\n", saved_state->r13);
	kprintf("      r12    0x%llx\n", saved_state->r12);
	kprintf("      r11    0x%llx\n", saved_state->r11);
	kprintf("      rbp    0x%llx\n", saved_state->rbp);
	kprintf("      rbx    0x%llx\n", saved_state->rbx);
	kprintf("      rcx    0x%llx\n", saved_state->rcx);
	kprintf("      rax    0x%llx\n", saved_state->rax);

	kprintf("      gs     0x%x\n", saved_state->gs);
	kprintf("      fs     0x%x\n", saved_state->fs);

	kprintf("  isf.trapno 0x%x\n", saved_state->isf.trapno);
	kprintf("  isf._pad   0x%x\n", saved_state->isf._pad);
	kprintf("  isf.trapfn 0x%llx\n", saved_state->isf.trapfn);
	kprintf("  isf.err    0x%llx\n", saved_state->isf.err);
	kprintf("  isf.rip    0x%llx\n", saved_state->isf.rip);
	kprintf("  isf.cs     0x%llx\n", saved_state->isf.cs);
	kprintf("  isf.rflags 0x%llx\n", saved_state->isf.rflags);
	kprintf("  isf.rsp    0x%llx\n", saved_state->isf.rsp);
	kprintf("  isf.ss     0x%llx\n", saved_state->isf.ss);
}
#endif


/*
 * Non-zero indicates latency assert is enabled and capped at valued
 * absolute time units.
 */

uint64_t interrupt_latency_cap = 0;
boolean_t ilat_assert = FALSE;

void
interrupt_latency_tracker_setup(void)
{
	uint32_t ilat_cap_us;
	if (PE_parse_boot_argn("interrupt_latency_cap_us", &ilat_cap_us, sizeof(ilat_cap_us))) {
		interrupt_latency_cap = ilat_cap_us * NSEC_PER_USEC;
		nanoseconds_to_absolutetime(interrupt_latency_cap, &interrupt_latency_cap);
	} else {
		interrupt_latency_cap = LockTimeOut;
	}
	PE_parse_boot_argn("-interrupt_latency_assert_enable", &ilat_assert, sizeof(ilat_assert));
}

void
interrupt_reset_latency_stats(void)
{
	uint32_t i;
	for (i = 0; i < real_ncpus; i++) {
		cpu_data_ptr[i]->cpu_max_observed_int_latency =
		    cpu_data_ptr[i]->cpu_max_observed_int_latency_vector = 0;
	}
}

void
interrupt_populate_latency_stats(char *buf, unsigned bufsize)
{
	uint32_t i, tcpu = ~0;
	uint64_t cur_max = 0;

	for (i = 0; i < real_ncpus; i++) {
		if (cur_max < cpu_data_ptr[i]->cpu_max_observed_int_latency) {
			cur_max = cpu_data_ptr[i]->cpu_max_observed_int_latency;
			tcpu = i;
		}
	}

	if (tcpu < real_ncpus) {
		snprintf(buf, bufsize, "0x%x 0x%x 0x%llx", tcpu, cpu_data_ptr[tcpu]->cpu_max_observed_int_latency_vector, cpu_data_ptr[tcpu]->cpu_max_observed_int_latency);
	}
}

uint32_t interrupt_timer_coalescing_enabled = 1;
uint64_t interrupt_coalesced_timers;

/*
 * Handle interrupts:
 *  - local APIC interrupts (IPIs, timers, etc) are handled by the kernel,
 *  - device interrupts go to the platform expert.
 */
void
interrupt(x86_saved_state_t *state)
{
	uint64_t        rip;
	uint64_t        rsp;
	int             interrupt_num;
	boolean_t       user_mode = FALSE;
	int             ipl;
	int             cnum = cpu_number();
	cpu_data_t      *cdp = cpu_data_ptr[cnum];
	int             itype = DBG_INTR_TYPE_UNKNOWN;
	int             handled;


	x86_saved_state64_t     *state64 = saved_state64(state);
	rip = state64->isf.rip;
	rsp = state64->isf.rsp;
	interrupt_num = state64->isf.trapno;
	if (state64->isf.cs & 0x03) {
		user_mode = TRUE;
	}

#if DEVELOPMENT || DEBUG
	uint64_t frameptr = is_saved_state64(state) ? state64->rbp : saved_state32(state)->ebp;
	uint32_t traptrace_index = traptrace_start(interrupt_num, rip, mach_absolute_time(), frameptr);
#endif

	if (cpu_data_ptr[cnum]->lcpu.package->num_idle == topoParms.nLThreadsPerPackage) {
		cpu_data_ptr[cnum]->cpu_hwIntpexits[interrupt_num]++;
	}

	if (interrupt_num == (LAPIC_DEFAULT_INTERRUPT_BASE + LAPIC_INTERPROCESSOR_INTERRUPT)) {
		itype = DBG_INTR_TYPE_IPI;
	} else if (interrupt_num == (LAPIC_DEFAULT_INTERRUPT_BASE + LAPIC_TIMER_INTERRUPT)) {
		itype = DBG_INTR_TYPE_TIMER;
	} else {
		itype = DBG_INTR_TYPE_OTHER;
	}

	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
	    MACHDBG_CODE(DBG_MACH_EXCP_INTR, 0) | DBG_FUNC_START,
	    interrupt_num,
	    (user_mode ? rip : VM_KERNEL_UNSLIDE(rip)),
	    user_mode, itype, 0);

	SCHED_STATS_INC(interrupt_count);

	ipl = get_preemption_level();

	/*
	 * Handle local APIC interrupts
	 * else call platform expert for devices.
	 */
	handled = lapic_interrupt(interrupt_num, state);

	if (!handled) {
		if (interrupt_num == (LAPIC_DEFAULT_INTERRUPT_BASE + LAPIC_CMCI_INTERRUPT)) {
			/*
			 * CMCI can be signalled on any logical processor, and the kexts
			 * that implement handling CMCI use IOKit to register handlers for
			 * the CMCI vector, so if we see a CMCI, do not encode a CPU
			 * number in bits 8:31 (since the vector is the same regardless of
			 * the handling CPU).
			 */
			PE_incoming_interrupt(interrupt_num);
		} else if (cnum <= lapic_max_interrupt_cpunum) {
			PE_incoming_interrupt((cnum << 8) | interrupt_num);
		}
	}

	if (__improbable(get_preemption_level() != ipl)) {
		panic("Preemption level altered by interrupt vector 0x%x: initial 0x%x, final: 0x%x", interrupt_num, ipl, get_preemption_level());
	}


	if (__improbable(cdp->cpu_nested_istack)) {
		cdp->cpu_nested_istack_events++;
	} else {
		uint64_t ctime = mach_absolute_time();
		uint64_t int_latency = ctime - cdp->cpu_int_event_time;
		uint64_t esdeadline, ehdeadline;
		/* Attempt to process deferred timers in the context of
		 * this interrupt, unless interrupt time has already exceeded
		 * TCOAL_ILAT_THRESHOLD.
		 */
#define TCOAL_ILAT_THRESHOLD (30000ULL)

		if ((int_latency < TCOAL_ILAT_THRESHOLD) &&
		    interrupt_timer_coalescing_enabled) {
			esdeadline = cdp->rtclock_timer.queue.earliest_soft_deadline;
			ehdeadline = cdp->rtclock_timer.deadline;
			if ((ctime >= esdeadline) && (ctime < ehdeadline)) {
				interrupt_coalesced_timers++;
				TCOAL_DEBUG(0x88880000 | DBG_FUNC_START, ctime, esdeadline, ehdeadline, interrupt_coalesced_timers, 0);
				rtclock_intr(state);
				TCOAL_DEBUG(0x88880000 | DBG_FUNC_END, ctime, esdeadline, interrupt_coalesced_timers, 0, 0);
			} else {
				TCOAL_DEBUG(0x77770000, ctime, cdp->rtclock_timer.queue.earliest_soft_deadline, cdp->rtclock_timer.deadline, interrupt_coalesced_timers, 0);
			}
		}

		if (__improbable(ilat_assert && (int_latency > interrupt_latency_cap) && !machine_timeout_suspended())) {
			panic("Interrupt vector 0x%x exceeded interrupt latency threshold, 0x%llx absolute time delta, prior signals: 0x%x, current signals: 0x%x", interrupt_num, int_latency, cdp->cpu_prior_signals, cdp->cpu_signals);
		}

		if (__improbable(int_latency > cdp->cpu_max_observed_int_latency)) {
			cdp->cpu_max_observed_int_latency = int_latency;
			cdp->cpu_max_observed_int_latency_vector = interrupt_num;
		}
	}

	/*
	 * Having serviced the interrupt first, look at the interrupted stack depth.
	 */
	if (!user_mode) {
		uint64_t depth = cdp->cpu_kernel_stack
		    + sizeof(struct thread_kernel_state)
		    + sizeof(struct i386_exception_link *)
		    - rsp;
		if (__improbable(depth > kernel_stack_depth_max)) {
			kernel_stack_depth_max = (vm_offset_t)depth;
			KERNEL_DEBUG_CONSTANT(
				MACHDBG_CODE(DBG_MACH_SCHED, MACH_STACK_DEPTH),
				(long) depth, (long) VM_KERNEL_UNSLIDE(rip), 0, 0, 0);
		}
	}

	if (cnum == master_cpu) {
		entropy_collect();
	}

#if KPERF
	kperf_interrupt();
#endif /* KPERF */

	KDBG_RELEASE(MACHDBG_CODE(DBG_MACH_EXCP_INTR, 0) | DBG_FUNC_END,
	    interrupt_num);

	assert(ml_get_interrupts_enabled() == FALSE);

#if DEVELOPMENT || DEBUG
	if (traptrace_index != TRAPTRACE_INVALID_INDEX) {
		traptrace_end(traptrace_index, mach_absolute_time());
	}
#endif
}

static inline void
reset_dr7(void)
{
	long dr7 = 0x400; /* magic dr7 reset value; 32 bit on i386, 64 bit on x86_64 */
	__asm__ volatile ("mov %0,%%dr7" : : "r" (dr7));
}
#if MACH_KDP
unsigned kdp_has_active_watchpoints = 0;
#define NO_WATCHPOINTS (!kdp_has_active_watchpoints)
#else
#define NO_WATCHPOINTS 1
#endif

static uint32_t bound_chk_violations_event;

static const char *
xnu_soft_trap_handle_breakpoint(void *tstate, uint16_t comment)
{
#pragma unused(tstate)
	if (comment == CLANG_SOFT_TRAP_BOUND_CHK) {
		os_atomic_inc(&bound_chk_violations_event, relaxed);
	}

	return NULL;
}

static const char *
xnu_hard_trap_handle_breakpoint(void *tstate, uint16_t comment)
{
	kernel_panic_reason_t pr = PERCPU_GET(panic_reason);
	x86_saved_state64_t *state = tstate;

	switch (comment) {
	case XNU_HARD_TRAP_SAFE_UNLINK:
		snprintf(pr->buf, sizeof(pr->buf),
		    "panic: corrupt list around element %p",
		    (void *)state->rax);
		return pr->buf;

	case XNU_HARD_TRAP_STRING_CHK:
		return "panic: string operation caused an overflow";

	case XNU_HARD_TRAP_ASSERT_FAILURE:
		/*
		 * Read the implicit assert arguments, see:
		 * ML_TRAP_REGISTER_1: rax
		 * ML_TRAP_REGISTER_2: r10
		 * ML_TRAP_REGISTER_3: r11
		 */
		panic_assert_format(pr->buf, sizeof(pr->buf),
		    (struct mach_assert_hdr *)state->rax,
		    state->r10, state->r11);
		return pr->buf;

	default:
		return NULL;
	}
}

KERNEL_BRK_DESCRIPTOR_DEFINE(clang_desc,
    .type                = TRAP_TELEMETRY_TYPE_KERNEL_BRK_CLANG,
    .base                = CLANG_X86_TRAP_START,
    .max                 = CLANG_X86_TRAP_END,
    .options             = BRK_TELEMETRY_OPTIONS_FATAL_DEFAULT,
    .handle_breakpoint   = NULL);

KERNEL_BRK_DESCRIPTOR_DEFINE(xnu_soft_traps_desc,
    .type                = TRAP_TELEMETRY_TYPE_KERNEL_BRK_TELEMETRY,
    .base                = XNU_SOFT_TRAP_START,
    .max                 = XNU_SOFT_TRAP_END,
    .options             = BRK_TELEMETRY_OPTIONS_RECOVERABLE_DEFAULT(
	    /* enable_telemetry */ true),
    .handle_breakpoint   = xnu_soft_trap_handle_breakpoint);

KERNEL_BRK_DESCRIPTOR_DEFINE(libcxx_desc,
    .type                = TRAP_TELEMETRY_TYPE_KERNEL_BRK_LIBCXX,
    .base                = LIBCXX_TRAP_START,
    .max                 = LIBCXX_TRAP_END,
    .options             = BRK_TELEMETRY_OPTIONS_FATAL_DEFAULT,
    .handle_breakpoint   = NULL);

KERNEL_BRK_DESCRIPTOR_DEFINE(xnu_hard_traps_desc,
    .type                = TRAP_TELEMETRY_TYPE_KERNEL_BRK_XNU,
    .base                = XNU_HARD_TRAP_START,
    .max                 = XNU_HARD_TRAP_END,
    .options             = BRK_TELEMETRY_OPTIONS_FATAL_DEFAULT,
    .handle_breakpoint   = xnu_hard_trap_handle_breakpoint);

static bool
handle_kernel_breakpoint(
	x86_saved_state64_t    *state,
	const char            **reason,
	uint16_t               *out_comment)
{
	uint16_t comment;
	const struct kernel_brk_descriptor *desc;
	uint8_t inst_buf[8];
	uint32_t prefix16 = 0x80B90F67; /* Encoding prefix for ud1 <16-bit code>(%eax), %eax */
	uint32_t prefix8 = 0x40B90F67; /* Encoding prefix for ud1 <8-bit code>(%eax), %eax */
	bool found_prefix8 = false;

	vm_size_t sz = ml_nofault_copy(state->isf.rip, (vm_offset_t)inst_buf, sizeof(inst_buf));
	if (sz != sizeof(inst_buf)) {
		return false;
	}

	if (bcmp(inst_buf, &prefix16, sizeof(prefix16)) == 0) {
		/* The two bytes following the prefix is our code */
		comment = inst_buf[5] << 8 | inst_buf[4];
	} else if (bcmp(inst_buf, &prefix8, sizeof(prefix8)) == 0) {
		/* The one byte following the prefix is our code */
		found_prefix8 = true;
		comment = inst_buf[4];
	} else {
		return false;
	}

	if (out_comment) {
		*out_comment = comment;
	}
	desc = find_kernel_brk_descriptor_by_comment(comment);

	if (!desc) {
		return false;
	}

	if (desc->options.enable_trap_telemetry) {
		trap_telemetry_report_exception(
			/* trap_type   */ desc->type,
			/* trap_code   */ comment,
			/* options     */ desc->options.telemetry_options,
			/* saved_state */ (void *)state);
	}

	if (desc->handle_breakpoint) {
		*reason = desc->handle_breakpoint(state, comment);
	}

	/* Still alive? Check if we should recover. */
	if (desc->options.recoverable) {
		/* ud1 can be five or eight-byte long depending on the prefix */
		set_recovery_ip(state, state->isf.rip + (found_prefix8 ? 5 : 8));
		return true;
	}

	return false;
}

// Find a recovery entry for an instruction address if one is present.
static struct recovery const*
find_recovery_entry(vm_offset_t kern_ip)
{
	for (struct recovery const* rp = recover_table; rp < recover_table_end; rp++) {
		if (kern_ip == rp->fault_addr) {
			return rp;
		}
	}
	return NULL;
}

/*
 * Trap from kernel mode.  Only page-fault errors are recoverable,
 * and then only in special circumstances.  All other errors are
 * fatal.  Return value indicates if trap was handled.
 */

void
kernel_trap(
	x86_saved_state_t       *state,
	uintptr_t *lo_spp)
{
	const char             *reason = NULL;
	uint16_t                trapcomment = 0;

	x86_saved_state64_t     *saved_state;
	int                     code;
	user_addr_t             vaddr;
	int                     type;
	vm_map_t                map = 0;        /* protected by T_PAGE_FAULT */
	kern_return_t           result = KERN_FAILURE;
	kern_return_t           fault_result = KERN_SUCCESS;
	thread_t                thread;
	boolean_t               intr;
	vm_prot_t               prot;
	struct recovery const   *rp = NULL;
	vm_offset_t             kern_ip;
	int                     is_user;
	int                     trap_pl = get_preemption_level();

	thread = current_thread();

	if (__improbable(is_saved_state32(state))) {
		panic("kernel_trap(%p) with 32-bit state", state);
	}
	saved_state = saved_state64(state);

	/* Record cpu where state was captured */
	saved_state->isf.cpu = cpu_number();

	vaddr = (user_addr_t)saved_state->cr2;
	type  = saved_state->isf.trapno;
	code  = (int)(saved_state->isf.err & 0xffff);
	intr  = (saved_state->isf.rflags & EFL_IF) != 0;        /* state of ints at trap */
	kern_ip = (vm_offset_t)saved_state->isf.rip;

	is_user = (vaddr < VM_MAX_USER_PAGE_ADDRESS);

#if DEVELOPMENT || DEBUG
	uint32_t traptrace_index = traptrace_start(type, kern_ip, mach_absolute_time(), saved_state->rbp);
#endif

#if CONFIG_DTRACE
	/*
	 * Is there a DTrace hook?
	 */
	if (__improbable(tempDTraceTrapHook != NULL)) {
		if (tempDTraceTrapHook(type, state, lo_spp, 0) == KERN_SUCCESS) {
			/*
			 * If it succeeds, we are done...
			 */
			goto common_return;
		}
	}

	/* Handle traps originated from probe context. */
	if (thread != THREAD_NULL && thread->t_dtrace_inprobe) {
		if (dtrace_handle_trap(type, state)) {
			goto common_return;
		}
	}

#endif /* CONFIG_DTRACE */

	/*
	 * we come here with interrupts off as we don't want to recurse
	 * on preemption below.  but we do want to re-enable interrupts
	 * as soon we possibly can to hold latency down
	 */
	if (__improbable(T_PREEMPT == type)) {
		ast_taken_kernel();

		KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
		    (MACHDBG_CODE(DBG_MACH_EXCP_KTRAP_x86, type)) | DBG_FUNC_NONE,
		    0, 0, 0, VM_KERNEL_UNSLIDE(kern_ip), 0);

		goto common_return;
	}

	user_addr_t     kd_vaddr = is_user ? vaddr : VM_KERNEL_UNSLIDE(vaddr);
	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
	    (MACHDBG_CODE(DBG_MACH_EXCP_KTRAP_x86, type)) | DBG_FUNC_NONE,
	    (unsigned)(kd_vaddr >> 32), (unsigned)kd_vaddr, is_user,
	    VM_KERNEL_UNSLIDE(kern_ip), 0);


	if (T_PAGE_FAULT == type) {
		/*
		 * assume we're faulting in the kernel map
		 */
		map = kernel_map;

		if (__probable((thread != THREAD_NULL) && (thread->map != kernel_map) &&
		    (vaddr < VM_MAX_USER_PAGE_ADDRESS))) {
			/* fault occurred in userspace */
			map = thread->map;

			/* Intercept a potential Supervisor Mode Execute
			 * Protection fault. These criteria identify
			 * both NX faults and SMEP faults, but both
			 * are fatal. We avoid checking PTEs (racy).
			 * (The VM could just redrive a SMEP fault, hence
			 * the intercept).
			 */
			if (__improbable((code == (T_PF_PROT | T_PF_EXECUTE)) &&
			    (pmap_smep_enabled) && (saved_state->isf.rip == vaddr))) {
				goto debugger_entry;
			}

			/*
			 * Additionally check for SMAP faults...
			 * which are characterized by page-present and
			 * the AC bit unset (i.e. not from copyin/out path).
			 */
			if (__improbable(code & T_PF_PROT &&
			    pmap_smap_enabled &&
			    (saved_state->isf.rflags & EFL_AC) == 0)) {
				goto debugger_entry;
			}

			/*
			 * If we're not sharing cr3 with the user
			 * and we faulted in copyio,
			 * then switch cr3 here and dismiss the fault.
			 */
			if (no_shared_cr3 &&
			    (thread->machine.specFlags & CopyIOActive) &&
			    map->pmap->pm_cr3 != get_cr3_base()) {
				pmap_assert(current_cpu_datap()->cpu_pmap_pcid_enabled == FALSE);
				set_cr3_raw(map->pmap->pm_cr3);
				return;
			}
			if (__improbable(vaddr < PAGE_SIZE) &&
			    ((thread->machine.specFlags & CopyIOActive) == 0)) {
				goto debugger_entry;
			}
		}
	}

	(void) ml_set_interrupts_enabled(intr);

	switch (type) {
	case T_NO_FPU:
		fpnoextflt();
		goto common_return;

	case T_FPU_FAULT:
		fpextovrflt();
		goto common_return;

	case T_FLOATING_POINT_ERROR:
		fpexterrflt();
		goto common_return;

	case T_SSE_FLOAT_ERROR:
		fpSSEexterrflt();
		goto common_return;

	case T_INVALID_OPCODE:
		if (handle_kernel_breakpoint(saved_state, &reason, &trapcomment)) {
			goto common_return;
		}
		fpUDflt(kern_ip);
		goto debugger_entry;

	case T_DEBUG:
		/*
		 * Re-enable LBR tracing for core/panic files if necessary. i386_lbr_enable confirms LBR should be re-enabled.
		 */
		i386_lbr_enable();
		if ((saved_state->isf.rflags & EFL_TF) == 0 && NO_WATCHPOINTS) {
			/* We've somehow encountered a debug
			 * register match that does not belong
			 * to the kernel debugger.
			 * This isn't supposed to happen.
			 */
			reset_dr7();
			goto common_return;
		}
		goto debugger_entry;
	case T_INT3:
		goto debugger_entry;
	case T_PAGE_FAULT:

#if CONFIG_DTRACE
		if (thread != THREAD_NULL && thread->t_dtrace_inprobe) { /* Executing under dtrace_probe? */
			if (dtrace_tally_fault(vaddr)) { /* Should a fault under dtrace be ignored? */
				/*
				 * DTrace has "anticipated" the possibility of this fault, and has
				 * established the suitable recovery state. Drop down now into the
				 * recovery handling code in "case T_GENERAL_PROTECTION:".
				 */
				goto FALL_THROUGH;
			}
		}
#endif /* CONFIG_DTRACE */

		prot = VM_PROT_READ;

		if (code & T_PF_WRITE) {
			prot |= VM_PROT_WRITE;
		}
		if (code & T_PF_EXECUTE) {
			prot |= VM_PROT_EXECUTE;
		}

		/**
		 * vm_fault() can be called with preemption disabled (and indeed this is expected for
		 * certain copyio() scenarios), but can't safely be called with interrupts disabled
		 * once the system has gone multi-threaded.  Other than some early-boot situations
		 * such as startup kext loading, kernel paging operations should never be triggered
		 * by non-interruptible code in the first place, so a fault from such a context will
		 * ultimately produce a kernel page fault panic anyway.  In these cases, skip calling
		 * vm_fault() to avoid masking the real kernel panic with a failed VM locking assertion.
		 */
		if (__improbable(!(intr ||
		    startup_phase < STARTUP_SUB_EARLY_BOOT ||
		    current_cpu_datap()->cpu_hibernate))) {
			fault_result = result = KERN_FAILURE;
			goto FALL_THROUGH;
		}

		// VM will query this property when deciding to throttle this fault, we don't want to
		// throttle kernel faults for copyio faults. The presence of a recovery entry is used as a
		// proxy for being in copyio code.
		rp = find_recovery_entry(kern_ip);
		const bool was_recover = thread->recover;
		thread->recover = was_recover || (rp != NULL);

		fault_result = result = vm_fault(map,
		    vaddr,
		    prot,
		    FALSE, VM_KERN_MEMORY_NONE,
		    THREAD_UNINT, NULL, 0);

		thread->recover = was_recover;
		if (result == KERN_SUCCESS) {
			goto common_return;
		}
		/*
		 * fall through
		 */
FALL_THROUGH:

	case T_GENERAL_PROTECTION:
		/*
		 * If there is a failure recovery address
		 * for this fault, go there.
		 */
		if ((rp != NULL) || (rp = find_recovery_entry(kern_ip))) {
			set_recovery_ip(saved_state, rp->recover_addr);
			goto common_return;
		}

		/*
		 * Unanticipated page-fault errors in kernel
		 * should not happen.
		 *
		 * fall through...
		 */
		OS_FALLTHROUGH;
	default:
		/*
		 * Exception 15 is reserved but some chips may generate it
		 * spuriously. Seen at startup on AMD Athlon-64.
		 */
		if (type == 15) {
			kprintf("kernel_trap() ignoring spurious trap 15\n");
			goto common_return;
		}
debugger_entry:
		/* Ensure that the i386_kernel_state at the base of the
		 * current thread's stack (if any) is synchronized with the
		 * context at the moment of the trap, to facilitate
		 * access through the debugger.
		 */
		sync_iss_to_iks(state);
#if  MACH_KDP
		if (kdp_i386_trap(type, saved_state, result, (vm_offset_t)vaddr)) {
			goto common_return;
		}
#endif
	}
	if (type == T_PAGE_FAULT) {
		panic_fault_address = vaddr;
	}
	pal_cli();

	panic_trap(saved_state, trapcomment, reason, trap_pl, fault_result);
	/*
	 * NO RETURN
	 */

common_return:
#if DEVELOPMENT || DEBUG
	if (traptrace_index != TRAPTRACE_INVALID_INDEX) {
		traptrace_end(traptrace_index, mach_absolute_time());
	}
#endif
	return;
}

static void
set_recovery_ip(x86_saved_state64_t  *saved_state, vm_offset_t ip)
{
	saved_state->isf.rip = ip;
}

static void
panic_trap(
	x86_saved_state64_t    *regs,
	uint16_t                trapcomment,
	const char             *trapreason,
	uint32_t                pl,
	kern_return_t           fault_result)
{
	char            trapbuf[64];
	pal_cr_t        cr0, cr2, cr3, cr4;
	boolean_t       potential_smep_fault = FALSE, potential_kernel_NX_fault = FALSE;
	boolean_t       potential_smap_fault = FALSE;

	pal_get_control_registers( &cr0, &cr2, &cr3, &cr4 );
	assert(ml_get_interrupts_enabled() == FALSE);
	current_cpu_datap()->cpu_fatal_trap_state = regs;
	/*
	 * Issue an I/O port read if one has been requested - this is an
	 * event logic analyzers can use as a trigger point.
	 */
	panic_notify();

	kprintf("CPU %d panic trap number 0x%x, rip 0x%016llx\n",
	    cpu_number(), regs->isf.trapno, regs->isf.rip);
	kprintf("cr0 0x%016llx cr2 0x%016llx cr3 0x%016llx cr4 0x%016llx\n",
	    cr0, cr2, cr3, cr4);

	if ((regs->isf.trapno == T_PAGE_FAULT) && (regs->isf.err == (T_PF_PROT | T_PF_EXECUTE)) && (regs->isf.rip == regs->cr2)) {
		if (pmap_smep_enabled && (regs->isf.rip < VM_MAX_USER_PAGE_ADDRESS)) {
			potential_smep_fault = TRUE;
		} else if (regs->isf.rip >= VM_MIN_KERNEL_AND_KEXT_ADDRESS) {
			potential_kernel_NX_fault = TRUE;
		}
	} else if (pmap_smap_enabled &&
	    regs->isf.trapno == T_PAGE_FAULT &&
	    regs->isf.err & T_PF_PROT &&
	    regs->cr2 < VM_MAX_USER_PAGE_ADDRESS &&
	    regs->isf.rip >= VM_MIN_KERNEL_AND_KEXT_ADDRESS) {
		potential_smap_fault = TRUE;
	}

	if (trapreason == NULL) {
		const char *traptype = "Unknown";

		if (regs->isf.trapno < TRAP_TYPES) {
			traptype = trap_type[regs->isf.trapno];
		}

		trapreason = "Kernel trap";

		if (trapcomment == 0) {
			snprintf(trapbuf, sizeof(trapbuf),
			    "type = %d=%s, ",
			    regs->isf.trapno, traptype);
		} else {
			snprintf(trapbuf, sizeof(trapbuf),
			    "type = %d=%s #%#04hx, ",
			    regs->isf.trapno, traptype, trapcomment);
		}
	} else {
		trapbuf[0] = '\0';
	}

#undef panic
	panic("%s at 0x%016llx, %sregisters:\n"
	    "CR0: 0x%016llx, CR2: 0x%016llx, CR3: 0x%016llx, CR4: 0x%016llx\n"
	    "RAX: 0x%016llx, RBX: 0x%016llx, RCX: 0x%016llx, RDX: 0x%016llx\n"
	    "RSP: 0x%016llx, RBP: 0x%016llx, RSI: 0x%016llx, RDI: 0x%016llx\n"
	    "R8:  0x%016llx, R9:  0x%016llx, R10: 0x%016llx, R11: 0x%016llx\n"
	    "R12: 0x%016llx, R13: 0x%016llx, R14: 0x%016llx, R15: 0x%016llx\n"
	    "RFL: 0x%016llx, RIP: 0x%016llx, CS:  0x%016llx, SS:  0x%016llx\n"
	    "Fault CR2: 0x%016llx, Error code: 0x%016llx, Fault CPU: 0x%x%s%s%s%s, PL: %d, VF: %d\n",
	    trapreason, regs->isf.rip, trapbuf,
	    cr0, cr2, cr3, cr4,
	    regs->rax, regs->rbx, regs->rcx, regs->rdx,
	    regs->isf.rsp, regs->rbp, regs->rsi, regs->rdi,
	    regs->r8, regs->r9, regs->r10, regs->r11,
	    regs->r12, regs->r13, regs->r14, regs->r15,
	    regs->isf.rflags, regs->isf.rip, regs->isf.cs & 0xFFFF,
	    regs->isf.ss & 0xFFFF, regs->cr2, regs->isf.err, regs->isf.cpu,
	    virtualized ? " VMM" : "",
	    potential_kernel_NX_fault ? " Kernel NX fault" : "",
	    potential_smep_fault ? " SMEP/User NX fault" : "",
	    potential_smap_fault ? " SMAP fault" : "",
	    pl,
	    fault_result);
}

#if CONFIG_DTRACE
extern kern_return_t dtrace_user_probe(x86_saved_state_t *);
#endif

#if DEBUG
uint32_t fsigs[2];
uint32_t fsigns, fsigcs;
#endif

/*
 *	Trap from user mode.
 */
void
user_trap(
	x86_saved_state_t *saved_state)
{
	int                     exc;
	int                     err;
	mach_exception_code_t   code;
	mach_exception_subcode_t subcode;
	int                     type;
	user_addr_t             vaddr;
	vm_prot_t               prot;
	thread_t                thread = current_thread();
	kern_return_t           kret;
	user_addr_t             rip;
	unsigned long           dr6 = 0; /* 32 bit for i386, 64 bit for x86_64 */
	int                     current_cpu = cpu_number();
#if DEVELOPMENT || DEBUG
	bool                    inspect_cacheline = false;
	uint32_t                traptrace_index;
#endif
	assert((is_saved_state32(saved_state) && !thread_is_64bit_addr(thread)) ||
	    (is_saved_state64(saved_state) && thread_is_64bit_addr(thread)));

	if (is_saved_state64(saved_state)) {
		x86_saved_state64_t     *regs;

		regs = saved_state64(saved_state);

		/* Record cpu where state was captured */
		regs->isf.cpu = current_cpu;

		type = regs->isf.trapno;
		err  = (int)regs->isf.err & 0xffff;
		vaddr = (user_addr_t)regs->cr2;
		rip   = (user_addr_t)regs->isf.rip;
#if DEVELOPMENT || DEBUG
		traptrace_index = traptrace_start(type, rip, mach_absolute_time(), regs->rbp);
#endif
	} else {
		x86_saved_state32_t     *regs;

		regs = saved_state32(saved_state);

		/* Record cpu where state was captured */
		regs->cpu = current_cpu;

		type  = regs->trapno;
		err   = regs->err & 0xffff;
		vaddr = (user_addr_t)regs->cr2;
		rip   = (user_addr_t)regs->eip;
#if DEVELOPMENT || DEBUG
		traptrace_index = traptrace_start(type, rip, mach_absolute_time(), regs->ebp);
#endif
	}

#if DEVELOPMENT || DEBUG
	/*
	 * Copy the cacheline of code into the thread's instruction stream save area
	 * before enabling interrupts (the assumption is that we have not otherwise faulted or
	 * trapped since the original cache line stores).  If the saved code is not valid,
	 * we'll catch it below when we process the copyin() for unhandled faults.
	 */
	if (thread->machine.insn_copy_optout == false &&
	    (type == T_PAGE_FAULT || type == T_INVALID_OPCODE || type == T_GENERAL_PROTECTION)) {
#define CACHELINE_SIZE 64
		THREAD_TO_PCB(thread)->insn_cacheline[CACHELINE_SIZE] = (uint8_t)(rip & (CACHELINE_SIZE - 1));
		bcopy(&cpu_shadowp(current_cpu)->cpu_rtimes[0],
		    &THREAD_TO_PCB(thread)->insn_cacheline[0],
		    sizeof(THREAD_TO_PCB(thread)->insn_cacheline) - 1);
		inspect_cacheline = true;
	}
#endif

	if (type == T_DEBUG) {
		if (thread->machine.ids) {
			unsigned long clear = 0;
			/* Stash and clear this processor's DR6 value, in the event
			 * this was a debug register match
			 */
			__asm__ volatile ("mov %%db6, %0" : "=r" (dr6));
			__asm__ volatile ("mov %0, %%db6" : : "r" (clear));
		}
		/* [Re]Enable LBRs *BEFORE* enabling interrupts to ensure we hit the right CPU */
		i386_lbr_enable();
	}

	if (type == T_PAGE_FAULT) {
		thread_reset_pcs_will_fault(thread);
	}

	pal_sti();

	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
	    (MACHDBG_CODE(DBG_MACH_EXCP_UTRAP_x86, type)) | DBG_FUNC_NONE,
	    (unsigned)(vaddr >> 32), (unsigned)vaddr,
	    (unsigned)(rip >> 32), (unsigned)rip, 0);

	code = 0;
	subcode = 0;
	exc = 0;

#if CONFIG_DTRACE
	/*
	 * DTrace does not consume all user traps, only INT_3's for now.
	 * Avoid needlessly calling tempDTraceTrapHook here, and let the
	 * INT_3 case handle them.
	 */
#endif

	DEBUG_KPRINT_SYSCALL_MASK(1,
	    "user_trap: type=0x%x(%s) err=0x%x cr2=%p rip=%p\n",
	    type, trap_type[type], err, (void *)(long) vaddr, (void *)(long) rip);

	switch (type) {
	case T_DIVIDE_ERROR:
		exc = EXC_ARITHMETIC;
		code = EXC_I386_DIV;
		break;

	case T_DEBUG:
	{
		pcb_t   pcb;
		/*
		 * Update the PCB with this processor's DR6 value
		 * in the event this was a debug register match.
		 */
		pcb = THREAD_TO_PCB(thread);
		if (pcb->ids) {
			/*
			 * We can get and set the status register
			 * in 32-bit mode even on a 64-bit thread
			 * because the high order bits are not
			 * used on x86_64
			 */
			if (thread_is_64bit_addr(thread)) {
				x86_debug_state64_t *ids = pcb->ids;
				ids->dr6 = dr6;
			} else {         /* 32 bit thread */
				x86_debug_state32_t *ids = pcb->ids;
				ids->dr6 = (uint32_t) dr6;
			}
		}
		exc = EXC_BREAKPOINT;
		code = EXC_I386_SGL;
		break;
	}
	case T_INT3:
#if CONFIG_DTRACE
		if (dtrace_user_probe(saved_state) == KERN_SUCCESS) {
			return; /* If it succeeds, we are done... */
		}
#endif
		exc = EXC_BREAKPOINT;
		code = EXC_I386_BPT;
		break;

	case T_OVERFLOW:
		exc = EXC_ARITHMETIC;
		code = EXC_I386_INTO;
		break;

	case T_OUT_OF_BOUNDS:
		exc = EXC_SOFTWARE;
		code = EXC_I386_BOUND;
		break;

	case T_INVALID_OPCODE:
		if (fpUDflt(rip) == 1) {
			exc = EXC_BAD_INSTRUCTION;
			code = EXC_I386_INVOP;
		}
		break;

	case T_NO_FPU:
		fpnoextflt();
		break;

	case T_FPU_FAULT:
		fpextovrflt();
		/*
		 * Raise exception.
		 */
		exc = EXC_BAD_ACCESS;
		code = VM_PROT_READ | VM_PROT_EXECUTE;
		subcode = 0;
		break;

	case T_INVALID_TSS:     /* invalid TSS == iret with NT flag set */
		exc = EXC_BAD_INSTRUCTION;
		code = EXC_I386_INVTSSFLT;
		subcode = err;
		break;

	case T_SEGMENT_NOT_PRESENT:
		exc = EXC_BAD_INSTRUCTION;
		code = EXC_I386_SEGNPFLT;
		subcode = err;
		break;

	case T_STACK_FAULT:
		exc = EXC_BAD_INSTRUCTION;
		code = EXC_I386_STKFLT;
		subcode = err;
		break;

	case T_GENERAL_PROTECTION:
		/*
		 * There's a wide range of circumstances which generate this
		 * class of exception. From user-space, many involve bad
		 * addresses (such as a non-canonical 64-bit address).
		 * So we map this to EXC_BAD_ACCESS (and thereby SIGSEGV).
		 * The trouble is cr2 doesn't contain the faulting address;
		 * we'd need to decode the faulting instruction to really
		 * determine this. We'll leave that to debuggers.
		 * However, attempted execution of privileged instructions
		 * (e.g. cli) also generate GP faults and so we map these to
		 * to EXC_BAD_ACCESS (and thence SIGSEGV) also - rather than
		 * EXC_BAD_INSTRUCTION which is more accurate. We just can't
		 * win!
		 */
		exc = EXC_BAD_ACCESS;
		code = EXC_I386_GPFLT;
		subcode = err;
		break;

	case T_PAGE_FAULT:
	{
		prot = VM_PROT_READ;

		if (err & T_PF_WRITE) {
			prot |= VM_PROT_WRITE;
		}
		if (__improbable(err & T_PF_EXECUTE)) {
			prot |= VM_PROT_EXECUTE;
		}
#if DEVELOPMENT || DEBUG
		bool do_simd_hash = thread_fpsimd_hash_enabled();
		uint32_t fsig = 0;
		fsig = do_simd_hash ? thread_fpsimd_hash(thread) : 0;
#if DEBUG
		fsigs[0] = fsig;
#endif
#endif
		kret = vm_fault(thread->map,
		    vaddr,
		    prot, FALSE, VM_KERN_MEMORY_NONE,
		    THREAD_ABORTSAFE, NULL, 0);
#if DEVELOPMENT || DEBUG
		if (do_simd_hash && fsig) {
			uint32_t fsig2 = thread_fpsimd_hash(thread);
#if DEBUG
			fsigcs++;
			fsigs[1] = fsig2;
#endif
			if (fsig != fsig2) {
				panic("FP/SIMD state hash mismatch across fault thread: %p 0x%x->0x%x", thread, fsig, fsig2);
			}
		} else {
#if DEBUG
			fsigns++;
#endif
		}
#endif
		if (__probable((kret == KERN_SUCCESS) || (kret == KERN_ABORTED))) {
			break;
		} else if (__improbable(kret == KERN_FAILURE)) {
			/*
			 * For a user trap, vm_fault() should never return KERN_FAILURE.
			 * If it does, we're leaking preemption disables somewhere in the kernel.
			 */
			panic("vm_fault() KERN_FAILURE from user fault on thread %p", thread);
		}

		/* PAL debug hook (empty on x86) */
		pal_dbg_page_fault(thread, vaddr, kret);
		exc = EXC_BAD_ACCESS;
		code = kret;
		subcode = vaddr;
	}
	break;

	case T_SSE_FLOAT_ERROR:
		fpSSEexterrflt();
		exc = EXC_ARITHMETIC;
		code = EXC_I386_SSEEXTERR;
		subcode = ((struct x86_fx_thread_state *)thread->machine.ifps)->fx_MXCSR;
		break;


	case T_FLOATING_POINT_ERROR:
		fpexterrflt();
		exc = EXC_ARITHMETIC;
		code = EXC_I386_EXTERR;
		subcode = ((struct x86_fx_thread_state *)thread->machine.ifps)->fx_status;
		break;

	case T_DTRACE_RET:
#if CONFIG_DTRACE
		if (dtrace_user_probe(saved_state) == KERN_SUCCESS) {
			return; /* If it succeeds, we are done... */
		}
#endif
		/*
		 * If we get an INT 0x7f when we do not expect to,
		 * treat it as an illegal instruction
		 */
		exc = EXC_BAD_INSTRUCTION;
		code = EXC_I386_INVOP;
		break;

	default:
		panic("Unexpected user trap, type %d", type);
	}

	if (type == T_PAGE_FAULT) {
		thread_reset_pcs_done_faulting(thread);
	}

	if (exc != 0) {
		uint16_t cs;
		boolean_t intrs;

		if (is_saved_state64(saved_state)) {
			cs = saved_state64(saved_state)->isf.cs;
		} else {
			cs = saved_state32(saved_state)->cs;
		}

		if (last_branch_enabled_modes == LBR_ENABLED_USERMODE) {
			intrs = ml_set_interrupts_enabled(FALSE);
			/*
			 * This is a bit racy (it's possible for this thread to migrate to another CPU, then
			 * migrate back, but that seems rather rare in practice), but good enough to ensure
			 * the LBRs are saved before proceeding with exception/signal dispatch.
			 */
			if (current_cpu == cpu_number()) {
				i386_lbr_synch(thread);
			}
			ml_set_interrupts_enabled(intrs);
		}

		/*
		 * Do not try to copyin from the instruction stream if the page fault was due
		 * to an access to rip and was unhandled.
		 * Do not deal with cases when %cs != USER[64]_CS
		 * And of course there's no need to copy the instruction stream if the boot-arg
		 * was set to 0.
		 */
		if (thread->machine.insn_copy_optout == false && insn_copyin_count > 0 &&
		    (cs == USER64_CS || cs == USER_CS) && (type != T_PAGE_FAULT || vaddr != rip)) {
#if DEVELOPMENT || DEBUG
			copy_instruction_stream(thread, rip, type, inspect_cacheline);
#else
			copy_instruction_stream(thread, rip, type);
#endif
		}

#if DEVELOPMENT || DEBUG
		if (traptrace_index != TRAPTRACE_INVALID_INDEX) {
			traptrace_end(traptrace_index, mach_absolute_time());
		}
#endif
		/*
		 * Note: Codepaths that directly return from user_trap() have pending
		 * ASTs processed in locore
		 */
		i386_exception(exc, code, subcode);
		/* NOTREACHED */
	} else {
#if DEVELOPMENT || DEBUG
		if (traptrace_index != TRAPTRACE_INVALID_INDEX) {
			traptrace_end(traptrace_index, mach_absolute_time());
		}
#endif
	}
}

/*
 * Copyin up to x86_INSTRUCTION_STATE_MAX_INSN_BYTES bytes from the page that includes `rip`,
 * ensuring that we stay on the same page, clipping the start or end, as needed.
 * Add the clipped amount back at the start or end, depending on where it fits.
 * Consult the variable populated by the boot-arg `insn_capcnt'
 */
static __attribute__((noinline)) void
copy_instruction_stream(thread_t thread, uint64_t rip, int __unused trap_code
#if DEVELOPMENT || DEBUG
    , bool inspect_cacheline
#endif
    )
{
#if x86_INSTRUCTION_STATE_MAX_INSN_BYTES > 4096
#error x86_INSTRUCTION_STATE_MAX_INSN_BYTES cannot exceed a page in size.
#endif
	pcb_t pcb = THREAD_TO_PCB(thread);
	vm_map_offset_t pagemask = ~vm_map_page_mask(current_map());
	vm_map_offset_t rip_page = rip & pagemask;
	vm_map_offset_t start_addr;
	vm_map_offset_t insn_offset;
	vm_map_offset_t end_addr = rip + (insn_copyin_count / 2);
	void *stack_buffer;
	int copyin_err = 0;
#if defined(MACH_BSD) && (DEVELOPMENT || DEBUG)
	void *procname;
#endif

#if DEVELOPMENT || DEBUG
	assert(insn_copyin_count <= x86_INSTRUCTION_STATE_MAX_INSN_BYTES);
#else
	if (insn_copyin_count > x86_INSTRUCTION_STATE_MAX_INSN_BYTES ||
	    insn_copyin_count < 64 /* CACHELINE_SIZE */) {
		return;
	}
#endif

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Walloca"
	stack_buffer = __builtin_alloca(insn_copyin_count);
#pragma clang diagnostic pop

	if (rip >= (insn_copyin_count / 2)) {
		start_addr = rip - (insn_copyin_count / 2);
	} else {
		start_addr = 0;
	}

	if (start_addr < rip_page) {
		insn_offset = (insn_copyin_count / 2) - (rip_page - start_addr);
		end_addr += (rip_page - start_addr);
		start_addr = rip_page;
	} else if (end_addr >= (rip_page + (~pagemask + 1))) {
		start_addr -= (end_addr - (rip_page + (~pagemask + 1))); /* Adjust start address backward */
		/* Adjust instruction offset due to start address change */
		insn_offset = (insn_copyin_count / 2) + (end_addr - (rip_page + (~pagemask + 1)));
		end_addr = rip_page + (~pagemask + 1);  /* clip to the start of the next page (non-inclusive */
	} else {
		insn_offset = insn_copyin_count / 2;
	}

	disable_preemption();   /* Prevent copyin from faulting in the instruction stream */
	if (
#if DEVELOPMENT || DEBUG
		(insnstream_force_cacheline_mismatch < 2) &&
#endif
		((end_addr > start_addr) && (copyin_err = copyin(start_addr, stack_buffer, end_addr - start_addr)) == 0)) {
		enable_preemption();

		if (pcb->insn_state == 0) {
			pcb->insn_state = kalloc_data(sizeof(x86_instruction_state_t), Z_WAITOK);
		}

		if (pcb->insn_state != 0) {
			bcopy(stack_buffer, pcb->insn_state->insn_bytes, end_addr - start_addr);
			bzero(&pcb->insn_state->insn_bytes[end_addr - start_addr],
			    insn_copyin_count - (end_addr - start_addr));

			pcb->insn_state->insn_stream_valid_bytes = (int)(end_addr - start_addr);
			pcb->insn_state->insn_offset = (int)insn_offset;

#if DEVELOPMENT || DEBUG
			/* Now try to validate the cacheline we read at early-fault time matches the code
			 * copied in. Before we do that, we have to make sure the buffer contains a valid
			 * cacheline by looking for the 2 sentinel values written in the event the cacheline
			 * could not be copied.
			 */
#define CACHELINE_DATA_NOT_PRESENT 0xdeadc0debeefcafeULL
#define CACHELINE_MASK (CACHELINE_SIZE - 1)

			if (inspect_cacheline &&
			    (*(uint64_t *)(uintptr_t)&pcb->insn_cacheline[0] != CACHELINE_DATA_NOT_PRESENT &&
			    *(uint64_t *)(uintptr_t)&pcb->insn_cacheline[8] != CACHELINE_DATA_NOT_PRESENT)) {
				/*
				 * The position of the cacheline in the instruction buffer is at offset
				 * insn_offset - (rip & CACHELINE_MASK)
				 */
				if (__improbable((rip & CACHELINE_MASK) > insn_offset)) {
					printf("thread %p code cacheline @ %p clipped wrt copied-in code (offset %d)\n",
					    thread, (void *)(rip & ~CACHELINE_MASK), (int)(rip & CACHELINE_MASK));
				} else if (bcmp(&pcb->insn_state->insn_bytes[insn_offset - (rip & CACHELINE_MASK)],
				    &pcb->insn_cacheline[0], CACHELINE_SIZE) != 0
				    || insnstream_force_cacheline_mismatch
				    ) {
#if x86_INSTRUCTION_STATE_CACHELINE_SIZE != CACHELINE_SIZE
#error cacheline size mismatch
#endif
					bcopy(&pcb->insn_cacheline[0], &pcb->insn_state->insn_cacheline[0],
					    x86_INSTRUCTION_STATE_CACHELINE_SIZE);
					/* Mark the instruction stream as being out-of-synch */
					pcb->insn_state->out_of_synch = 1;

					printf("thread %p code cacheline @ %p mismatches with copied-in code [trap 0x%x]\n",
					    thread, (void *)(rip & ~CACHELINE_MASK), trap_code);
					for (int i = 0; i < 8; i++) {
						printf("\t[%d] cl=0x%08llx vs. ci=0x%08llx\n", i, *(uint64_t *)(uintptr_t)&pcb->insn_cacheline[i * 8],
						    *(uint64_t *)(uintptr_t)&pcb->insn_state->insn_bytes[(i * 8) + insn_offset - (rip & CACHELINE_MASK)]);
					}
					if (panic_on_cacheline_mismatch) {
						panic("Cacheline mismatch while processing unhandled exception.");
					}
				} else {
					pcb->insn_state->out_of_synch = 0;
				}
			} else if (inspect_cacheline) {
				printf("thread %p could not capture code cacheline at fault IP %p [offset %d]\n",
				    (void *)thread, (void *)rip, (int)(insn_offset - (rip & CACHELINE_MASK)));
				pcb->insn_state->out_of_synch = 0;
			}
#else
			pcb->insn_state->out_of_synch = 0;
#endif /* DEVELOPMENT || DEBUG */

#if defined(MACH_BSD) && (DEVELOPMENT || DEBUG)
			if (panic_on_trap_procname[0] != 0) {
				task_t task = get_threadtask(thread);
				char procnamebuf[65] = {0};

				if (get_bsdtask_info(task) != NULL) {
					procname = proc_name_address(get_bsdtask_info(task));
					strlcpy(procnamebuf, procname, sizeof(procnamebuf));

					if (strcasecmp(panic_on_trap_procname, procnamebuf) == 0 &&
					    ((1U << trap_code) & panic_on_trap_mask) != 0) {
						panic("Panic requested on trap type 0x%x for process `%s'", trap_code,
						    panic_on_trap_procname);
						/*NORETURN*/
					}
				}
			}
#endif /* MACH_BSD && (DEVELOPMENT || DEBUG) */
		}
	} else {
		enable_preemption();

		pcb->insn_state_copyin_failure_errorcode = copyin_err;
#if DEVELOPMENT || DEBUG
		if (inspect_cacheline && pcb->insn_state == 0) {
			pcb->insn_state = kalloc_data(sizeof(x86_instruction_state_t), Z_WAITOK);
		}
		if (pcb->insn_state != 0) {
			pcb->insn_state->insn_stream_valid_bytes = 0;
			pcb->insn_state->insn_offset = 0;

			if (inspect_cacheline &&
			    (*(uint64_t *)(uintptr_t)&pcb->insn_cacheline[0] != CACHELINE_DATA_NOT_PRESENT &&
			    *(uint64_t *)(uintptr_t)&pcb->insn_cacheline[8] != CACHELINE_DATA_NOT_PRESENT)) {
				/*
				 * We can still copy the cacheline into the instruction state structure
				 * if it contains valid data
				 */
				pcb->insn_state->out_of_synch = 1;
				bcopy(&pcb->insn_cacheline[0], &pcb->insn_state->insn_cacheline[0],
				    x86_INSTRUCTION_STATE_CACHELINE_SIZE);
			}
		}
#endif /* DEVELOPMENT || DEBUG */
	}
}

/*
 * Handle exceptions for i386.
 *
 * If we are an AT bus machine, we must turn off the AST for a
 * delayed floating-point exception.
 *
 * If we are providing floating-point emulation, we may have
 * to retrieve the real register values from the floating point
 * emulator.
 */
void
i386_exception(
	int     exc,
	mach_exception_code_t code,
	mach_exception_subcode_t subcode)
{
	mach_exception_data_type_t   codes[EXCEPTION_CODE_MAX];

	DEBUG_KPRINT_SYSCALL_MACH("i386_exception: exc=%d code=0x%llx subcode=0x%llx\n",
	    exc, code, subcode);
	codes[0] = code;                /* new exception interface */
	codes[1] = subcode;
	exception_triage(exc, codes, 2);
	/*NOTREACHED*/
}


/* Synchronize a thread's x86_kernel_state (if any) with the given
 * x86_saved_state_t obtained from the trap/IPI handler; called in
 * kernel_trap() prior to entering the debugger, and when receiving
 * an "MP_KDP" IPI. Called with null saved_state if an incoming IPI
 * was detected from the kernel while spinning with interrupts masked.
 */

void
sync_iss_to_iks(x86_saved_state_t *saved_state)
{
	struct x86_kernel_state *iks = NULL;
	vm_offset_t kstack;
	boolean_t record_active_regs = FALSE;

	/* The PAL may have a special way to sync registers */
	if (saved_state && saved_state->flavor == THREAD_STATE_NONE) {
		pal_get_kern_regs( saved_state );
	}

	if (current_thread() != NULL &&
	    (kstack = current_thread()->kernel_stack) != 0) {
		x86_saved_state64_t     *regs = saved_state64(saved_state);

		iks = STACK_IKS(kstack);

		/* Did we take the trap/interrupt in kernel mode? */
		if (saved_state == NULL || /* NULL => polling in kernel */
		    regs == USER_REGS64(current_thread())) {
			record_active_regs = TRUE;
		} else {
			iks->k_rbx = regs->rbx;
			iks->k_rsp = regs->isf.rsp;
			iks->k_rbp = regs->rbp;
			iks->k_r12 = regs->r12;
			iks->k_r13 = regs->r13;
			iks->k_r14 = regs->r14;
			iks->k_r15 = regs->r15;
			iks->k_rip = regs->isf.rip;
		}
	}

	if (record_active_regs == TRUE) {
		/* Show the trap handler path */
		__asm__ volatile ("movq %%rbx, %0" : "=m" (iks->k_rbx));
		__asm__ volatile ("movq %%rsp, %0" : "=m" (iks->k_rsp));
		__asm__ volatile ("movq %%rbp, %0" : "=m" (iks->k_rbp));
		__asm__ volatile ("movq %%r12, %0" : "=m" (iks->k_r12));
		__asm__ volatile ("movq %%r13, %0" : "=m" (iks->k_r13));
		__asm__ volatile ("movq %%r14, %0" : "=m" (iks->k_r14));
		__asm__ volatile ("movq %%r15, %0" : "=m" (iks->k_r15));
		/* "Current" instruction pointer */
		__asm__ volatile ("leaq 1f(%%rip), %%rax; mov %%rax, %0\n1:"
                                  : "=m" (iks->k_rip)
                                  :
                                  : "rax");
	}
}

/*
 * This is used by the NMI interrupt handler (from mp.c) to
 * uncondtionally sync the trap handler context to the IKS
 * irrespective of whether the NMI was fielded in kernel
 * or user space.
 */
void
sync_iss_to_iks_unconditionally(__unused x86_saved_state_t *saved_state)
{
	struct x86_kernel_state *iks;
	vm_offset_t kstack;

	if ((kstack = current_thread()->kernel_stack) != 0) {
		iks = STACK_IKS(kstack);
		/* Display the trap handler path */
		__asm__ volatile ("movq %%rbx, %0" : "=m" (iks->k_rbx));
		__asm__ volatile ("movq %%rsp, %0" : "=m" (iks->k_rsp));
		__asm__ volatile ("movq %%rbp, %0" : "=m" (iks->k_rbp));
		__asm__ volatile ("movq %%r12, %0" : "=m" (iks->k_r12));
		__asm__ volatile ("movq %%r13, %0" : "=m" (iks->k_r13));
		__asm__ volatile ("movq %%r14, %0" : "=m" (iks->k_r14));
		__asm__ volatile ("movq %%r15, %0" : "=m" (iks->k_r15));
		/* "Current" instruction pointer */
		__asm__ volatile ("leaq 1f(%%rip), %%rax; mov %%rax, %0\n1:" : "=m" (iks->k_rip)::"rax");
	}
}

#if DEBUG
#define TERI 1
#endif

#if TERI
extern void     thread_exception_return_internal(void) __dead2;

void
thread_exception_return(void)
{
	thread_t thread = current_thread();
	task_t   task   = current_task();

	ml_set_interrupts_enabled(FALSE);
	if (thread_is_64bit_addr(thread) != task_has_64Bit_addr(task)) {
		panic("Task/thread bitness mismatch %p %p, task: %d, thread: %d",
		    thread, task, thread_is_64bit_addr(thread), task_has_64Bit_addr(task));
	}

	if (thread_is_64bit_addr(thread)) {
		if ((gdt_desc_p(USER64_CS)->access & ACC_PL_U) == 0) {
			panic("64-GDT mismatch %p, descriptor: %p", thread, gdt_desc_p(USER64_CS));
		}
	} else {
		if ((gdt_desc_p(USER_CS)->access & ACC_PL_U) == 0) {
			panic("32-GDT mismatch %p, descriptor: %p", thread, gdt_desc_p(USER_CS));
		}
	}
	assert(get_preemption_level() == 0);
	thread_exception_return_internal();
}
#endif

#if DEVELOPMENT || DEBUG
static int trap_handled;

static const char *
handle_recoverable_kernel_trap(
	__unused void     *tstate,
	uint16_t          comment)
{
	assert(comment == TEST_RECOVERABLE_SOFT_TRAP);

	printf("Recoverable trap handled.\n");
	trap_handled = 1;

	return NULL;
}

KERNEL_BRK_DESCRIPTOR_DEFINE(test_desc,
    .type                = TRAP_TELEMETRY_TYPE_KERNEL_BRK_TEST,
    .base                = TEST_RECOVERABLE_SOFT_TRAP,
    .max                 = TEST_RECOVERABLE_SOFT_TRAP,
    .options             = BRK_TELEMETRY_OPTIONS_RECOVERABLE_DEFAULT(
	    /* enable_telemetry */ false),
    .handle_breakpoint   = handle_recoverable_kernel_trap);

static int
recoverable_kernel_trap_test(__unused int64_t in, int64_t *out)
{
	ml_recoverable_trap(TEST_RECOVERABLE_SOFT_TRAP);

	*out = trap_handled;
	return 0;
}

SYSCTL_TEST_REGISTER(recoverable_kernel_trap, recoverable_kernel_trap_test);
#endif