xref: /illumos-gate/usr/src/uts/i86pc/os/trap.c (revision ba5ca68405ba4441c86a6cfc87f4ddcb3565c81d)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 1992, 2010, Oracle and/or its affiliates. All rights reserved.
24  */
25 
26 /*	Copyright (c) 1990, 1991 UNIX System Laboratories, Inc. */
27 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989, 1990 AT&T   */
28 /*		All Rights Reserved				*/
29 /*								*/
30 /*	Copyright (c) 1987, 1988 Microsoft Corporation		*/
31 /*		All Rights Reserved				*/
32 /*								*/
33 
34 /*
35  * Copyright 2018 Joyent, Inc.
36  */
37 
38 #include <sys/types.h>
39 #include <sys/sysmacros.h>
40 #include <sys/param.h>
41 #include <sys/signal.h>
42 #include <sys/systm.h>
43 #include <sys/user.h>
44 #include <sys/proc.h>
45 #include <sys/disp.h>
46 #include <sys/class.h>
47 #include <sys/core.h>
48 #include <sys/syscall.h>
49 #include <sys/cpuvar.h>
50 #include <sys/vm.h>
51 #include <sys/sysinfo.h>
52 #include <sys/fault.h>
53 #include <sys/stack.h>
54 #include <sys/psw.h>
55 #include <sys/regset.h>
56 #include <sys/fp.h>
57 #include <sys/trap.h>
58 #include <sys/kmem.h>
59 #include <sys/vtrace.h>
60 #include <sys/cmn_err.h>
61 #include <sys/prsystm.h>
62 #include <sys/mutex_impl.h>
63 #include <sys/machsystm.h>
64 #include <sys/archsystm.h>
65 #include <sys/sdt.h>
66 #include <sys/avintr.h>
67 #include <sys/kobj.h>
68 
69 #include <vm/hat.h>
70 
71 #include <vm/seg_kmem.h>
72 #include <vm/as.h>
73 #include <vm/seg.h>
74 #include <vm/hat_pte.h>
75 #include <vm/hat_i86.h>
76 
77 #include <sys/procfs.h>
78 
79 #include <sys/reboot.h>
80 #include <sys/debug.h>
81 #include <sys/debugreg.h>
82 #include <sys/modctl.h>
83 #include <sys/aio_impl.h>
84 #include <sys/tnf.h>
85 #include <sys/tnf_probe.h>
86 #include <sys/cred.h>
87 #include <sys/mman.h>
88 #include <sys/x86_archext.h>
89 #include <sys/copyops.h>
90 #include <c2/audit.h>
91 #include <sys/ftrace.h>
92 #include <sys/panic.h>
93 #include <sys/traptrace.h>
94 #include <sys/ontrap.h>
95 #include <sys/cpc_impl.h>
96 #include <sys/bootconf.h>
97 #include <sys/bootinfo.h>
98 #include <sys/promif.h>
99 #include <sys/mach_mmu.h>
100 #if defined(__xpv)
101 #include <sys/hypervisor.h>
102 #endif
103 #include <sys/contract/process_impl.h>
104 
105 #define	USER	0x10000		/* user-mode flag added to trap type */
106 
107 static const char *trap_type_mnemonic[] = {
108 	"de",	"db",	"2",	"bp",
109 	"of",	"br",	"ud",	"nm",
110 	"df",	"9",	"ts",	"np",
111 	"ss",	"gp",	"pf",	"15",
112 	"mf",	"ac",	"mc",	"xf"
113 };
114 
115 static const char *trap_type[] = {
116 	"Divide error",				/* trap id 0	*/
117 	"Debug",				/* trap id 1	*/
118 	"NMI interrupt",			/* trap id 2	*/
119 	"Breakpoint",				/* trap id 3	*/
120 	"Overflow",				/* trap id 4	*/
121 	"BOUND range exceeded",			/* trap id 5	*/
122 	"Invalid opcode",			/* trap id 6	*/
123 	"Device not available",			/* trap id 7	*/
124 	"Double fault",				/* trap id 8	*/
125 	"Coprocessor segment overrun",		/* trap id 9	*/
126 	"Invalid TSS",				/* trap id 10	*/
127 	"Segment not present",			/* trap id 11	*/
128 	"Stack segment fault",			/* trap id 12	*/
129 	"General protection",			/* trap id 13	*/
130 	"Page fault",				/* trap id 14	*/
131 	"Reserved",				/* trap id 15	*/
132 	"x87 floating point error",		/* trap id 16	*/
133 	"Alignment check",			/* trap id 17	*/
134 	"Machine check",			/* trap id 18	*/
135 	"SIMD floating point exception",	/* trap id 19	*/
136 };
137 
138 #define	TRAP_TYPES	(sizeof (trap_type) / sizeof (trap_type[0]))
139 
140 #define	SLOW_SCALL_SIZE	2
141 #define	FAST_SCALL_SIZE	2
142 
143 int tudebug = 0;
144 int tudebugbpt = 0;
145 int tudebugfpe = 0;
146 int tudebugsse = 0;
147 
148 #if defined(TRAPDEBUG) || defined(lint)
149 int tdebug = 0;
150 int lodebug = 0;
151 int faultdebug = 0;
152 #else
153 #define	tdebug	0
154 #define	lodebug	0
155 #define	faultdebug	0
156 #endif /* defined(TRAPDEBUG) || defined(lint) */
157 
158 #if defined(TRAPTRACE)
159 /*
160  * trap trace record for cpu0 is allocated here.
161  * trap trace records for non-boot cpus are allocated in mp_startup_init().
162  */
163 static trap_trace_rec_t trap_tr0[TRAPTR_NENT];
164 trap_trace_ctl_t trap_trace_ctl[NCPU] = {
165 	{
166 	    (uintptr_t)trap_tr0,			/* next record */
167 	    (uintptr_t)trap_tr0,			/* first record */
168 	    (uintptr_t)(trap_tr0 + TRAPTR_NENT),	/* limit */
169 	    (uintptr_t)0				/* current */
170 	},
171 };
172 
173 /*
174  * default trap buffer size
175  */
176 size_t trap_trace_bufsize = TRAPTR_NENT * sizeof (trap_trace_rec_t);
177 int trap_trace_freeze = 0;
178 int trap_trace_off = 0;
179 
180 /*
181  * A dummy TRAPTRACE entry to use after death.
182  */
183 trap_trace_rec_t trap_trace_postmort;
184 
185 static void dump_ttrace(void);
186 #endif	/* TRAPTRACE */
187 static void dumpregs(struct regs *);
188 static void showregs(uint_t, struct regs *, caddr_t);
189 static int kern_gpfault(struct regs *);
190 
191 /*ARGSUSED*/
192 static int
193 die(uint_t type, struct regs *rp, caddr_t addr, processorid_t cpuid)
194 {
195 	struct panic_trap_info ti;
196 	const char *trap_name, *trap_mnemonic;
197 
198 	if (type < TRAP_TYPES) {
199 		trap_name = trap_type[type];
200 		trap_mnemonic = trap_type_mnemonic[type];
201 	} else {
202 		trap_name = "trap";
203 		trap_mnemonic = "-";
204 	}
205 
206 #ifdef TRAPTRACE
207 	TRAPTRACE_FREEZE;
208 #endif
209 
210 	ti.trap_regs = rp;
211 	ti.trap_type = type & ~USER;
212 	ti.trap_addr = addr;
213 
214 	curthread->t_panic_trap = &ti;
215 
216 	if (type == T_PGFLT && addr < (caddr_t)kernelbase) {
217 		panic("BAD TRAP: type=%x (#%s %s) rp=%p addr=%p "
218 		    "occurred in module \"%s\" due to %s",
219 		    type, trap_mnemonic, trap_name, (void *)rp, (void *)addr,
220 		    mod_containing_pc((caddr_t)rp->r_pc),
221 		    addr < (caddr_t)PAGESIZE ?
222 		    "a NULL pointer dereference" :
223 		    "an illegal access to a user address");
224 	} else
225 		panic("BAD TRAP: type=%x (#%s %s) rp=%p addr=%p",
226 		    type, trap_mnemonic, trap_name, (void *)rp, (void *)addr);
227 	return (0);
228 }
229 
230 /*
231  * Rewrite the instruction at pc to be an int $T_SYSCALLINT instruction.
232  *
233  * int <vector> is two bytes: 0xCD <vector>
234  */
235 
236 static int
237 rewrite_syscall(caddr_t pc)
238 {
239 	uchar_t instr[SLOW_SCALL_SIZE] = { 0xCD, T_SYSCALLINT };
240 
241 	if (uwrite(curthread->t_procp, instr, SLOW_SCALL_SIZE,
242 	    (uintptr_t)pc) != 0)
243 		return (1);
244 
245 	return (0);
246 }
247 
248 /*
249  * Test to see if the instruction at pc is sysenter or syscall. The second
250  * argument should be the x86 feature flag corresponding to the expected
251  * instruction.
252  *
253  * sysenter is two bytes: 0x0F 0x34
254  * syscall is two bytes:  0x0F 0x05
255  * int $T_SYSCALLINT is two bytes: 0xCD 0x91
256  */
257 
258 static int
259 instr_is_other_syscall(caddr_t pc, int which)
260 {
261 	uchar_t instr[FAST_SCALL_SIZE];
262 
263 	ASSERT(which == X86FSET_SEP || which == X86FSET_ASYSC || which == 0xCD);
264 
265 	if (copyin_nowatch(pc, (caddr_t)instr, FAST_SCALL_SIZE) != 0)
266 		return (0);
267 
268 	switch (which) {
269 	case X86FSET_SEP:
270 		if (instr[0] == 0x0F && instr[1] == 0x34)
271 			return (1);
272 		break;
273 	case X86FSET_ASYSC:
274 		if (instr[0] == 0x0F && instr[1] == 0x05)
275 			return (1);
276 		break;
277 	case 0xCD:
278 		if (instr[0] == 0xCD && instr[1] == T_SYSCALLINT)
279 			return (1);
280 		break;
281 	}
282 
283 	return (0);
284 }
285 
286 #ifdef DEBUG
287 static const char *
288 syscall_insn_string(int syscall_insn)
289 {
290 	switch (syscall_insn) {
291 	case X86FSET_SEP:
292 		return ("sysenter");
293 	case X86FSET_ASYSC:
294 		return ("syscall");
295 	case 0xCD:
296 		return ("int");
297 	default:
298 		return ("Unknown");
299 	}
300 }
301 #endif /* DEBUG */
302 
303 static int
304 ldt_rewrite_syscall(struct regs *rp, proc_t *p, int syscall_insn)
305 {
306 	caddr_t	linearpc;
307 	int return_code = 0;
308 
309 	mutex_enter(&p->p_ldtlock);	/* Must be held across linear_pc() */
310 
311 	if (linear_pc(rp, p, &linearpc) == 0) {
312 
313 		/*
314 		 * If another thread beat us here, it already changed
315 		 * this site to the slower (int) syscall instruction.
316 		 */
317 		if (instr_is_other_syscall(linearpc, 0xCD)) {
318 			return_code = 1;
319 		} else if (instr_is_other_syscall(linearpc, syscall_insn)) {
320 
321 			if (rewrite_syscall(linearpc) == 0) {
322 				return_code = 1;
323 			}
324 #ifdef DEBUG
325 			else
326 				cmn_err(CE_WARN, "failed to rewrite %s "
327 				    "instruction in process %d",
328 				    syscall_insn_string(syscall_insn),
329 				    p->p_pid);
330 #endif /* DEBUG */
331 		}
332 	}
333 
334 	mutex_exit(&p->p_ldtlock);	/* Must be held across linear_pc() */
335 
336 	return (return_code);
337 }
338 
339 /*
340  * Test to see if the instruction at pc is a system call instruction.
341  *
342  * The bytes of an lcall instruction used for the syscall trap.
343  * static uchar_t lcall[7] = { 0x9a, 0, 0, 0, 0, 0x7, 0 };
344  * static uchar_t lcallalt[7] = { 0x9a, 0, 0, 0, 0, 0x27, 0 };
345  */
346 
347 #define	LCALLSIZE	7
348 
349 static int
350 instr_is_lcall_syscall(caddr_t pc)
351 {
352 	uchar_t instr[LCALLSIZE];
353 
354 	if (copyin_nowatch(pc, (caddr_t)instr, LCALLSIZE) == 0 &&
355 	    instr[0] == 0x9a &&
356 	    instr[1] == 0 &&
357 	    instr[2] == 0 &&
358 	    instr[3] == 0 &&
359 	    instr[4] == 0 &&
360 	    (instr[5] == 0x7 || instr[5] == 0x27) &&
361 	    instr[6] == 0)
362 		return (1);
363 
364 	return (0);
365 }
366 
367 /*
368  * In the first revisions of amd64 CPUs produced by AMD, the LAHF and
369  * SAHF instructions were not implemented in 64-bit mode. Later revisions
370  * did implement these instructions. An extension to the cpuid instruction
371  * was added to check for the capability of executing these instructions
372  * in 64-bit mode.
373  *
374  * Intel originally did not implement these instructions in EM64T either,
375  * but added them in later revisions.
376  *
377  * So, there are different chip revisions by both vendors out there that
378  * may or may not implement these instructions. The easy solution is to
379  * just always emulate these instructions on demand.
380  *
381  * SAHF == store %ah in the lower 8 bits of %rflags (opcode 0x9e)
382  * LAHF == load the lower 8 bits of %rflags into %ah (opcode 0x9f)
383  */
384 
385 #define	LSAHFSIZE 1
386 
387 static int
388 instr_is_lsahf(caddr_t pc, uchar_t *instr)
389 {
390 	if (copyin_nowatch(pc, (caddr_t)instr, LSAHFSIZE) == 0 &&
391 	    (*instr == 0x9e || *instr == 0x9f))
392 		return (1);
393 	return (0);
394 }
395 
396 /*
397  * Emulate the LAHF and SAHF instructions. The reference manuals define
398  * these instructions to always load/store bit 1 as a 1, and bits 3 and 5
399  * as a 0. The other, defined, bits are copied (the PS_ICC bits and PS_P).
400  *
401  * Note that %ah is bits 8-15 of %rax.
402  */
403 static void
404 emulate_lsahf(struct regs *rp, uchar_t instr)
405 {
406 	if (instr == 0x9e) {
407 		/* sahf. Copy bits from %ah to flags. */
408 		rp->r_ps = (rp->r_ps & ~0xff) |
409 		    ((rp->r_rax >> 8) & PSL_LSAHFMASK) | PS_MB1;
410 	} else {
411 		/* lahf. Copy bits from flags to %ah. */
412 		rp->r_rax = (rp->r_rax & ~0xff00) |
413 		    (((rp->r_ps & PSL_LSAHFMASK) | PS_MB1) << 8);
414 	}
415 	rp->r_pc += LSAHFSIZE;
416 }
417 
418 #ifdef OPTERON_ERRATUM_91
419 
420 /*
421  * Test to see if the instruction at pc is a prefetch instruction.
422  *
423  * The first byte of prefetch instructions is always 0x0F.
424  * The second byte is 0x18 for regular prefetch or 0x0D for AMD 3dnow prefetch.
425  * The third byte (ModRM) contains the register field bits (bits 3-5).
426  * These bits must be between 0 and 3 inclusive for regular prefetch and
427  * 0 and 1 inclusive for AMD 3dnow prefetch.
428  *
429  * In 64-bit mode, there may be a one-byte REX prefex (0x40-0x4F).
430  */
431 
432 static int
433 cmp_to_prefetch(uchar_t *p)
434 {
435 #ifdef _LP64
436 	if ((p[0] & 0xF0) == 0x40)	/* 64-bit REX prefix */
437 		p++;
438 #endif
439 	return ((p[0] == 0x0F && p[1] == 0x18 && ((p[2] >> 3) & 7) <= 3) ||
440 	    (p[0] == 0x0F && p[1] == 0x0D && ((p[2] >> 3) & 7) <= 1));
441 }
442 
443 static int
444 instr_is_prefetch(caddr_t pc)
445 {
446 	uchar_t instr[4];	/* optional REX prefix plus 3-byte opcode */
447 
448 	return (copyin_nowatch(pc, instr, sizeof (instr)) == 0 &&
449 	    cmp_to_prefetch(instr));
450 }
451 
452 #endif /* OPTERON_ERRATUM_91 */
453 
454 /*
455  * Called from the trap handler when a processor trap occurs.
456  *
457  * Note: All user-level traps that might call stop() must exit
458  * trap() by 'goto out' or by falling through.
459  * Note Also: trap() is usually called with interrupts enabled, (PS_IE == 1)
460  * however, there are paths that arrive here with PS_IE == 0 so special care
461  * must be taken in those cases.
462  */
463 void
464 trap(struct regs *rp, caddr_t addr, processorid_t cpuid)
465 {
466 	kthread_t *ct = curthread;
467 	enum seg_rw rw;
468 	unsigned type;
469 	proc_t *p = ttoproc(ct);
470 	klwp_t *lwp = ttolwp(ct);
471 	uintptr_t lofault;
472 	label_t *onfault;
473 	faultcode_t pagefault(), res, errcode;
474 	enum fault_type fault_type;
475 	k_siginfo_t siginfo;
476 	uint_t fault = 0;
477 	int mstate;
478 	int sicode = 0;
479 	int watchcode;
480 	int watchpage;
481 	caddr_t vaddr;
482 	size_t sz;
483 	int ta;
484 	uchar_t instr;
485 
486 	ASSERT_STACK_ALIGNED();
487 
488 	errcode = 0;
489 	mstate = 0;
490 	rw = S_OTHER;
491 	type = rp->r_trapno;
492 	CPU_STATS_ADDQ(CPU, sys, trap, 1);
493 	ASSERT(ct->t_schedflag & TS_DONT_SWAP);
494 
495 	if (type == T_PGFLT) {
496 		errcode = rp->r_err;
497 		if (errcode & PF_ERR_WRITE) {
498 			rw = S_WRITE;
499 		} else if ((caddr_t)rp->r_pc == addr ||
500 		    (mmu.pt_nx != 0 && (errcode & PF_ERR_EXEC))) {
501 			rw = S_EXEC;
502 		} else {
503 			rw = S_READ;
504 		}
505 	} else if (type == T_SGLSTP && lwp != NULL) {
506 		lwp->lwp_pcb.pcb_drstat = (uintptr_t)addr;
507 	}
508 
509 	if (tdebug)
510 		showregs(type, rp, addr);
511 
512 	if (USERMODE(rp->r_cs)) {
513 		/*
514 		 * Set up the current cred to use during this trap. u_cred
515 		 * no longer exists.  t_cred is used instead.
516 		 * The current process credential applies to the thread for
517 		 * the entire trap.  If trapping from the kernel, this
518 		 * should already be set up.
519 		 */
520 		if (ct->t_cred != p->p_cred) {
521 			cred_t *oldcred = ct->t_cred;
522 			/*
523 			 * DTrace accesses t_cred in probe context.  t_cred
524 			 * must always be either NULL, or point to a valid,
525 			 * allocated cred structure.
526 			 */
527 			ct->t_cred = crgetcred();
528 			crfree(oldcred);
529 		}
530 		ASSERT(lwp != NULL);
531 		type |= USER;
532 		ASSERT(lwptoregs(lwp) == rp);
533 		lwp->lwp_state = LWP_SYS;
534 
535 		switch (type) {
536 		case T_PGFLT + USER:
537 			if ((caddr_t)rp->r_pc == addr)
538 				mstate = LMS_TFAULT;
539 			else
540 				mstate = LMS_DFAULT;
541 			break;
542 		default:
543 			mstate = LMS_TRAP;
544 			break;
545 		}
546 		/* Kernel probe */
547 		TNF_PROBE_1(thread_state, "thread", /* CSTYLED */,
548 		    tnf_microstate, state, mstate);
549 		mstate = new_mstate(ct, mstate);
550 
551 		bzero(&siginfo, sizeof (siginfo));
552 	}
553 
554 	switch (type) {
555 	case T_PGFLT + USER:
556 	case T_SGLSTP:
557 	case T_SGLSTP + USER:
558 	case T_BPTFLT + USER:
559 		break;
560 
561 	default:
562 		FTRACE_2("trap(): type=0x%lx, regs=0x%lx",
563 		    (ulong_t)type, (ulong_t)rp);
564 		break;
565 	}
566 
567 	switch (type) {
568 	case T_SIMDFPE:
569 		/* Make sure we enable interrupts before die()ing */
570 		sti();	/* The SIMD exception comes in via cmninttrap */
571 		/*FALLTHROUGH*/
572 	default:
573 		if (type & USER) {
574 			if (tudebug)
575 				showregs(type, rp, (caddr_t)0);
576 			printf("trap: Unknown trap type %d in user mode\n",
577 			    type & ~USER);
578 			siginfo.si_signo = SIGILL;
579 			siginfo.si_code  = ILL_ILLTRP;
580 			siginfo.si_addr  = (caddr_t)rp->r_pc;
581 			siginfo.si_trapno = type & ~USER;
582 			fault = FLTILL;
583 		} else {
584 			(void) die(type, rp, addr, cpuid);
585 			/*NOTREACHED*/
586 		}
587 		break;
588 
589 	case T_PGFLT:		/* system page fault */
590 		/*
591 		 * If we're under on_trap() protection (see <sys/ontrap.h>),
592 		 * set ot_trap and bounce back to the on_trap() call site
593 		 * via the installed trampoline.
594 		 */
595 		if ((ct->t_ontrap != NULL) &&
596 		    (ct->t_ontrap->ot_prot & OT_DATA_ACCESS)) {
597 			ct->t_ontrap->ot_trap |= OT_DATA_ACCESS;
598 			rp->r_pc = ct->t_ontrap->ot_trampoline;
599 			goto cleanup;
600 		}
601 
602 		/*
603 		 * If we have an Instruction fault in kernel mode, then that
604 		 * means we've tried to execute a user page (SMEP) or both of
605 		 * PAE and NXE are enabled. In either case, given that it's a
606 		 * kernel fault, we should panic immediately and not try to make
607 		 * any more forward progress. This indicates a bug in the
608 		 * kernel, which if execution continued, could be exploited to
609 		 * wreak havoc on the system.
610 		 */
611 		if (errcode & PF_ERR_EXEC) {
612 			(void) die(type, rp, addr, cpuid);
613 		}
614 
615 		/*
616 		 * We need to check if SMAP is in play. If SMAP is in play, then
617 		 * any access to a user page will show up as a protection
618 		 * violation. To see if SMAP is enabled we first check if it's a
619 		 * user address and whether we have the feature flag set. If we
620 		 * do and the interrupted registers do not allow for user
621 		 * accesses (PS_ACHK is not enabled), then we need to die
622 		 * immediately.
623 		 */
624 		if (addr < (caddr_t)kernelbase &&
625 		    is_x86_feature(x86_featureset, X86FSET_SMAP) == B_TRUE &&
626 		    (rp->r_ps & PS_ACHK) == 0) {
627 			(void) die(type, rp, addr, cpuid);
628 		}
629 
630 		/*
631 		 * See if we can handle as pagefault. Save lofault and onfault
632 		 * across this. Here we assume that an address less than
633 		 * KERNELBASE is a user fault.  We can do this as copy.s
634 		 * routines verify that the starting address is less than
635 		 * KERNELBASE before starting and because we know that we
636 		 * always have KERNELBASE mapped as invalid to serve as a
637 		 * "barrier".
638 		 */
639 		lofault = ct->t_lofault;
640 		onfault = ct->t_onfault;
641 		ct->t_lofault = 0;
642 
643 		mstate = new_mstate(ct, LMS_KFAULT);
644 
645 		if (addr < (caddr_t)kernelbase) {
646 			res = pagefault(addr,
647 			    (errcode & PF_ERR_PROT)? F_PROT: F_INVAL, rw, 0);
648 			if (res == FC_NOMAP &&
649 			    addr < p->p_usrstack &&
650 			    grow(addr))
651 				res = 0;
652 		} else {
653 			res = pagefault(addr,
654 			    (errcode & PF_ERR_PROT)? F_PROT: F_INVAL, rw, 1);
655 		}
656 		(void) new_mstate(ct, mstate);
657 
658 		/*
659 		 * Restore lofault and onfault. If we resolved the fault, exit.
660 		 * If we didn't and lofault wasn't set, die.
661 		 */
662 		ct->t_lofault = lofault;
663 		ct->t_onfault = onfault;
664 		if (res == 0)
665 			goto cleanup;
666 
667 #if defined(OPTERON_ERRATUM_93) && defined(_LP64)
668 		if (lofault == 0 && opteron_erratum_93) {
669 			/*
670 			 * Workaround for Opteron Erratum 93. On return from
671 			 * a System Managment Interrupt at a HLT instruction
672 			 * the %rip might be truncated to a 32 bit value.
673 			 * BIOS is supposed to fix this, but some don't.
674 			 * If this occurs we simply restore the high order bits.
675 			 * The HLT instruction is 1 byte of 0xf4.
676 			 */
677 			uintptr_t	rip = rp->r_pc;
678 
679 			if ((rip & 0xfffffffful) == rip) {
680 				rip |= 0xfffffffful << 32;
681 				if (hat_getpfnum(kas.a_hat, (caddr_t)rip) !=
682 				    PFN_INVALID &&
683 				    (*(uchar_t *)rip == 0xf4 ||
684 				    *(uchar_t *)(rip - 1) == 0xf4)) {
685 					rp->r_pc = rip;
686 					goto cleanup;
687 				}
688 			}
689 		}
690 #endif /* OPTERON_ERRATUM_93 && _LP64 */
691 
692 #ifdef OPTERON_ERRATUM_91
693 		if (lofault == 0 && opteron_erratum_91) {
694 			/*
695 			 * Workaround for Opteron Erratum 91. Prefetches may
696 			 * generate a page fault (they're not supposed to do
697 			 * that!). If this occurs we simply return back to the
698 			 * instruction.
699 			 */
700 			caddr_t		pc = (caddr_t)rp->r_pc;
701 
702 			/*
703 			 * If the faulting PC is not mapped, this is a
704 			 * legitimate kernel page fault that must result in a
705 			 * panic. If the faulting PC is mapped, it could contain
706 			 * a prefetch instruction. Check for that here.
707 			 */
708 			if (hat_getpfnum(kas.a_hat, pc) != PFN_INVALID) {
709 				if (cmp_to_prefetch((uchar_t *)pc)) {
710 #ifdef DEBUG
711 					cmn_err(CE_WARN, "Opteron erratum 91 "
712 					    "occurred: kernel prefetch"
713 					    " at %p generated a page fault!",
714 					    (void *)rp->r_pc);
715 #endif /* DEBUG */
716 					goto cleanup;
717 				}
718 			}
719 			(void) die(type, rp, addr, cpuid);
720 		}
721 #endif /* OPTERON_ERRATUM_91 */
722 
723 		if (lofault == 0)
724 			(void) die(type, rp, addr, cpuid);
725 
726 		/*
727 		 * Cannot resolve fault.  Return to lofault.
728 		 */
729 		if (lodebug) {
730 			showregs(type, rp, addr);
731 			traceregs(rp);
732 		}
733 		if (FC_CODE(res) == FC_OBJERR)
734 			res = FC_ERRNO(res);
735 		else
736 			res = EFAULT;
737 		rp->r_r0 = res;
738 		rp->r_pc = ct->t_lofault;
739 		goto cleanup;
740 
741 	case T_PGFLT + USER:	/* user page fault */
742 		if (faultdebug) {
743 			char *fault_str;
744 
745 			switch (rw) {
746 			case S_READ:
747 				fault_str = "read";
748 				break;
749 			case S_WRITE:
750 				fault_str = "write";
751 				break;
752 			case S_EXEC:
753 				fault_str = "exec";
754 				break;
755 			default:
756 				fault_str = "";
757 				break;
758 			}
759 			printf("user %s fault:  addr=0x%lx errcode=0x%x\n",
760 			    fault_str, (uintptr_t)addr, errcode);
761 		}
762 
763 #if defined(OPTERON_ERRATUM_100) && defined(_LP64)
764 		/*
765 		 * Workaround for AMD erratum 100
766 		 *
767 		 * A 32-bit process may receive a page fault on a non
768 		 * 32-bit address by mistake. The range of the faulting
769 		 * address will be
770 		 *
771 		 *	0xffffffff80000000 .. 0xffffffffffffffff or
772 		 *	0x0000000100000000 .. 0x000000017fffffff
773 		 *
774 		 * The fault is always due to an instruction fetch, however
775 		 * the value of r_pc should be correct (in 32 bit range),
776 		 * so we ignore the page fault on the bogus address.
777 		 */
778 		if (p->p_model == DATAMODEL_ILP32 &&
779 		    (0xffffffff80000000 <= (uintptr_t)addr ||
780 		    (0x100000000 <= (uintptr_t)addr &&
781 		    (uintptr_t)addr <= 0x17fffffff))) {
782 			if (!opteron_erratum_100)
783 				panic("unexpected erratum #100");
784 			if (rp->r_pc <= 0xffffffff)
785 				goto out;
786 		}
787 #endif /* OPTERON_ERRATUM_100 && _LP64 */
788 
789 		ASSERT(!(curthread->t_flag & T_WATCHPT));
790 		watchpage = (pr_watch_active(p) && pr_is_watchpage(addr, rw));
791 		vaddr = addr;
792 		if (!watchpage || (sz = instr_size(rp, &vaddr, rw)) <= 0)
793 			fault_type = (errcode & PF_ERR_PROT)? F_PROT: F_INVAL;
794 		else if ((watchcode = pr_is_watchpoint(&vaddr, &ta,
795 		    sz, NULL, rw)) != 0) {
796 			if (ta) {
797 				do_watch_step(vaddr, sz, rw,
798 				    watchcode, rp->r_pc);
799 				fault_type = F_INVAL;
800 			} else {
801 				bzero(&siginfo, sizeof (siginfo));
802 				siginfo.si_signo = SIGTRAP;
803 				siginfo.si_code = watchcode;
804 				siginfo.si_addr = vaddr;
805 				siginfo.si_trapafter = 0;
806 				siginfo.si_pc = (caddr_t)rp->r_pc;
807 				fault = FLTWATCH;
808 				break;
809 			}
810 		} else {
811 			/* XXX pr_watch_emul() never succeeds (for now) */
812 			if (rw != S_EXEC && pr_watch_emul(rp, vaddr, rw))
813 				goto out;
814 			do_watch_step(vaddr, sz, rw, 0, 0);
815 			fault_type = F_INVAL;
816 		}
817 
818 		res = pagefault(addr, fault_type, rw, 0);
819 
820 		/*
821 		 * If pagefault() succeeded, ok.
822 		 * Otherwise attempt to grow the stack.
823 		 */
824 		if (res == 0 ||
825 		    (res == FC_NOMAP &&
826 		    addr < p->p_usrstack &&
827 		    grow(addr))) {
828 			lwp->lwp_lastfault = FLTPAGE;
829 			lwp->lwp_lastfaddr = addr;
830 			if (prismember(&p->p_fltmask, FLTPAGE)) {
831 				bzero(&siginfo, sizeof (siginfo));
832 				siginfo.si_addr = addr;
833 				(void) stop_on_fault(FLTPAGE, &siginfo);
834 			}
835 			goto out;
836 		} else if (res == FC_PROT && addr < p->p_usrstack &&
837 		    (mmu.pt_nx != 0 && (errcode & PF_ERR_EXEC))) {
838 			report_stack_exec(p, addr);
839 		}
840 
841 #ifdef OPTERON_ERRATUM_91
842 		/*
843 		 * Workaround for Opteron Erratum 91. Prefetches may generate a
844 		 * page fault (they're not supposed to do that!). If this
845 		 * occurs we simply return back to the instruction.
846 		 *
847 		 * We rely on copyin to properly fault in the page with r_pc.
848 		 */
849 		if (opteron_erratum_91 &&
850 		    addr != (caddr_t)rp->r_pc &&
851 		    instr_is_prefetch((caddr_t)rp->r_pc)) {
852 #ifdef DEBUG
853 			cmn_err(CE_WARN, "Opteron erratum 91 occurred: "
854 			    "prefetch at %p in pid %d generated a trap!",
855 			    (void *)rp->r_pc, p->p_pid);
856 #endif /* DEBUG */
857 			goto out;
858 		}
859 #endif /* OPTERON_ERRATUM_91 */
860 
861 		if (tudebug)
862 			showregs(type, rp, addr);
863 		/*
864 		 * In the case where both pagefault and grow fail,
865 		 * set the code to the value provided by pagefault.
866 		 * We map all errors returned from pagefault() to SIGSEGV.
867 		 */
868 		bzero(&siginfo, sizeof (siginfo));
869 		siginfo.si_addr = addr;
870 		switch (FC_CODE(res)) {
871 		case FC_HWERR:
872 		case FC_NOSUPPORT:
873 			siginfo.si_signo = SIGBUS;
874 			siginfo.si_code = BUS_ADRERR;
875 			fault = FLTACCESS;
876 			break;
877 		case FC_ALIGN:
878 			siginfo.si_signo = SIGBUS;
879 			siginfo.si_code = BUS_ADRALN;
880 			fault = FLTACCESS;
881 			break;
882 		case FC_OBJERR:
883 			if ((siginfo.si_errno = FC_ERRNO(res)) != EINTR) {
884 				siginfo.si_signo = SIGBUS;
885 				siginfo.si_code = BUS_OBJERR;
886 				fault = FLTACCESS;
887 			}
888 			break;
889 		default:	/* FC_NOMAP or FC_PROT */
890 			siginfo.si_signo = SIGSEGV;
891 			siginfo.si_code =
892 			    (res == FC_NOMAP)? SEGV_MAPERR : SEGV_ACCERR;
893 			fault = FLTBOUNDS;
894 			break;
895 		}
896 		break;
897 
898 	case T_ILLINST + USER:	/* invalid opcode fault */
899 		/*
900 		 * If the syscall instruction is disabled due to LDT usage, a
901 		 * user program that attempts to execute it will trigger a #ud
902 		 * trap. Check for that case here. If this occurs on a CPU which
903 		 * doesn't even support syscall, the result of all of this will
904 		 * be to emulate that particular instruction.
905 		 */
906 		if (p->p_ldt != NULL &&
907 		    ldt_rewrite_syscall(rp, p, X86FSET_ASYSC))
908 			goto out;
909 
910 		/*
911 		 * Emulate the LAHF and SAHF instructions if needed.
912 		 * See the instr_is_lsahf function for details.
913 		 */
914 		if (p->p_model == DATAMODEL_LP64 &&
915 		    instr_is_lsahf((caddr_t)rp->r_pc, &instr)) {
916 			emulate_lsahf(rp, instr);
917 			goto out;
918 		}
919 
920 		/*FALLTHROUGH*/
921 
922 		if (tudebug)
923 			showregs(type, rp, (caddr_t)0);
924 		siginfo.si_signo = SIGILL;
925 		siginfo.si_code  = ILL_ILLOPC;
926 		siginfo.si_addr  = (caddr_t)rp->r_pc;
927 		fault = FLTILL;
928 		break;
929 
930 	case T_ZERODIV + USER:		/* integer divide by zero */
931 		if (tudebug && tudebugfpe)
932 			showregs(type, rp, (caddr_t)0);
933 		siginfo.si_signo = SIGFPE;
934 		siginfo.si_code  = FPE_INTDIV;
935 		siginfo.si_addr  = (caddr_t)rp->r_pc;
936 		fault = FLTIZDIV;
937 		break;
938 
939 	case T_OVFLW + USER:	/* integer overflow */
940 		if (tudebug && tudebugfpe)
941 			showregs(type, rp, (caddr_t)0);
942 		siginfo.si_signo = SIGFPE;
943 		siginfo.si_code  = FPE_INTOVF;
944 		siginfo.si_addr  = (caddr_t)rp->r_pc;
945 		fault = FLTIOVF;
946 		break;
947 
948 	/*
949 	 * When using an eager FPU on x86, the #NM trap is no longer meaningful.
950 	 * Userland should not be able to trigger it. Anything that does
951 	 * represents a fatal error in the kernel and likely in the register
952 	 * state of the system. User FPU state should always be valid.
953 	 */
954 	case T_NOEXTFLT + USER:	/* math coprocessor not available */
955 	case T_NOEXTFLT:
956 		(void) die(type, rp, addr, cpuid);
957 		break;
958 
959 	/*
960 	 * Kernel threads leveraging floating point need to mask the exceptions
961 	 * or ensure that they cannot happen. There is no recovery from this.
962 	 */
963 	case T_EXTERRFLT:	/* x87 floating point exception pending */
964 		sti(); /* T_EXTERRFLT comes in via cmninttrap */
965 		(void) die(type, rp, addr, cpuid);
966 		break;
967 
968 	case T_EXTERRFLT + USER: /* x87 floating point exception pending */
969 		if (tudebug && tudebugfpe)
970 			showregs(type, rp, addr);
971 		if ((sicode = fpexterrflt(rp)) != 0) {
972 			siginfo.si_signo = SIGFPE;
973 			siginfo.si_code  = sicode;
974 			siginfo.si_addr  = (caddr_t)rp->r_pc;
975 			fault = FLTFPE;
976 		}
977 		break;
978 
979 	case T_SIMDFPE + USER:		/* SSE and SSE2 exceptions */
980 		if (tudebug && tudebugsse)
981 			showregs(type, rp, addr);
982 		if (!is_x86_feature(x86_featureset, X86FSET_SSE) &&
983 		    !is_x86_feature(x86_featureset, X86FSET_SSE2)) {
984 			/*
985 			 * There are rumours that some user instructions
986 			 * on older CPUs can cause this trap to occur; in
987 			 * which case send a SIGILL instead of a SIGFPE.
988 			 */
989 			siginfo.si_signo = SIGILL;
990 			siginfo.si_code  = ILL_ILLTRP;
991 			siginfo.si_addr  = (caddr_t)rp->r_pc;
992 			siginfo.si_trapno = type & ~USER;
993 			fault = FLTILL;
994 		} else if ((sicode = fpsimderrflt(rp)) != 0) {
995 			siginfo.si_signo = SIGFPE;
996 			siginfo.si_code = sicode;
997 			siginfo.si_addr = (caddr_t)rp->r_pc;
998 			fault = FLTFPE;
999 		}
1000 
1001 		sti();	/* The SIMD exception comes in via cmninttrap */
1002 		break;
1003 
1004 	case T_BPTFLT:	/* breakpoint trap */
1005 		/*
1006 		 * Kernel breakpoint traps should only happen when kmdb is
1007 		 * active, and even then, it'll have interposed on the IDT, so
1008 		 * control won't get here.  If it does, we've hit a breakpoint
1009 		 * without the debugger, which is very strange, and very
1010 		 * fatal.
1011 		 */
1012 		if (tudebug && tudebugbpt)
1013 			showregs(type, rp, (caddr_t)0);
1014 
1015 		(void) die(type, rp, addr, cpuid);
1016 		break;
1017 
1018 	case T_SGLSTP: /* single step/hw breakpoint exception */
1019 
1020 #if !defined(__xpv)
1021 		/*
1022 		 * We'd never normally get here, as kmdb handles its own single
1023 		 * step traps.  There is one nasty exception though, as
1024 		 * described in more detail in sys_sysenter().  Note that
1025 		 * checking for all four locations covers both the KPTI and the
1026 		 * non-KPTI cases correctly: the former will never be found at
1027 		 * (brand_)sys_sysenter, and vice versa.
1028 		 */
1029 		if (lwp != NULL && (lwp->lwp_pcb.pcb_drstat & DR_SINGLESTEP)) {
1030 			if (rp->r_pc == (greg_t)brand_sys_sysenter ||
1031 			    rp->r_pc == (greg_t)sys_sysenter ||
1032 			    rp->r_pc == (greg_t)tr_brand_sys_sysenter ||
1033 			    rp->r_pc == (greg_t)tr_sys_sysenter) {
1034 
1035 				rp->r_pc += 0x3; /* sizeof (swapgs) */
1036 
1037 				rp->r_ps &= ~PS_T; /* turn off trace */
1038 				lwp->lwp_pcb.pcb_flags |= DEBUG_PENDING;
1039 				ct->t_post_sys = 1;
1040 				aston(curthread);
1041 				goto cleanup;
1042 			} else {
1043 				if (tudebug && tudebugbpt)
1044 					showregs(type, rp, (caddr_t)0);
1045 			}
1046 		}
1047 #endif /* !__xpv */
1048 
1049 		if (boothowto & RB_DEBUG)
1050 			debug_enter((char *)NULL);
1051 		else
1052 			(void) die(type, rp, addr, cpuid);
1053 		break;
1054 
1055 	case T_NMIFLT:	/* NMI interrupt */
1056 		printf("Unexpected NMI in system mode\n");
1057 		goto cleanup;
1058 
1059 	case T_NMIFLT + USER:	/* NMI interrupt */
1060 		printf("Unexpected NMI in user mode\n");
1061 		break;
1062 
1063 	case T_GPFLT:	/* general protection violation */
1064 		/*
1065 		 * Any #GP that occurs during an on_trap .. no_trap bracket
1066 		 * with OT_DATA_ACCESS or OT_SEGMENT_ACCESS protection,
1067 		 * or in a on_fault .. no_fault bracket, is forgiven
1068 		 * and we trampoline.  This protection is given regardless
1069 		 * of whether we are 32/64 bit etc - if a distinction is
1070 		 * required then define new on_trap protection types.
1071 		 *
1072 		 * On amd64, we can get a #gp from referencing addresses
1073 		 * in the virtual address hole e.g. from a copyin or in
1074 		 * update_sregs while updating user segment registers.
1075 		 *
1076 		 * On the 32-bit hypervisor we could also generate one in
1077 		 * mfn_to_pfn by reaching around or into where the hypervisor
1078 		 * lives which is protected by segmentation.
1079 		 */
1080 
1081 		/*
1082 		 * If we're under on_trap() protection (see <sys/ontrap.h>),
1083 		 * set ot_trap and trampoline back to the on_trap() call site
1084 		 * for OT_DATA_ACCESS or OT_SEGMENT_ACCESS.
1085 		 */
1086 		if (ct->t_ontrap != NULL) {
1087 			int ttype =  ct->t_ontrap->ot_prot &
1088 			    (OT_DATA_ACCESS | OT_SEGMENT_ACCESS);
1089 
1090 			if (ttype != 0) {
1091 				ct->t_ontrap->ot_trap |= ttype;
1092 				if (tudebug)
1093 					showregs(type, rp, (caddr_t)0);
1094 				rp->r_pc = ct->t_ontrap->ot_trampoline;
1095 				goto cleanup;
1096 			}
1097 		}
1098 
1099 		/*
1100 		 * If we're under lofault protection (copyin etc.),
1101 		 * longjmp back to lofault with an EFAULT.
1102 		 */
1103 		if (ct->t_lofault) {
1104 			/*
1105 			 * Fault is not resolvable, so just return to lofault
1106 			 */
1107 			if (lodebug) {
1108 				showregs(type, rp, addr);
1109 				traceregs(rp);
1110 			}
1111 			rp->r_r0 = EFAULT;
1112 			rp->r_pc = ct->t_lofault;
1113 			goto cleanup;
1114 		}
1115 
1116 		/*
1117 		 * We fall through to the next case, which repeats
1118 		 * the OT_SEGMENT_ACCESS check which we've already
1119 		 * done, so we'll always fall through to the
1120 		 * T_STKFLT case.
1121 		 */
1122 		/*FALLTHROUGH*/
1123 	case T_SEGFLT:	/* segment not present fault */
1124 		/*
1125 		 * One example of this is #NP in update_sregs while
1126 		 * attempting to update a user segment register
1127 		 * that points to a descriptor that is marked not
1128 		 * present.
1129 		 */
1130 		if (ct->t_ontrap != NULL &&
1131 		    ct->t_ontrap->ot_prot & OT_SEGMENT_ACCESS) {
1132 			ct->t_ontrap->ot_trap |= OT_SEGMENT_ACCESS;
1133 			if (tudebug)
1134 				showregs(type, rp, (caddr_t)0);
1135 			rp->r_pc = ct->t_ontrap->ot_trampoline;
1136 			goto cleanup;
1137 		}
1138 		/*FALLTHROUGH*/
1139 	case T_STKFLT:	/* stack fault */
1140 	case T_TSSFLT:	/* invalid TSS fault */
1141 		if (tudebug)
1142 			showregs(type, rp, (caddr_t)0);
1143 		if (kern_gpfault(rp))
1144 			(void) die(type, rp, addr, cpuid);
1145 		goto cleanup;
1146 
1147 	/*
1148 	 * ONLY 32-bit PROCESSES can USE a PRIVATE LDT! 64-bit apps
1149 	 * should have no need for them, so we put a stop to it here.
1150 	 *
1151 	 * So: not-present fault is ONLY valid for 32-bit processes with
1152 	 * a private LDT trying to do a system call. Emulate it.
1153 	 *
1154 	 * #gp fault is ONLY valid for 32-bit processes also, which DO NOT
1155 	 * have a private LDT, and are trying to do a system call. Emulate it.
1156 	 */
1157 
1158 	case T_SEGFLT + USER:	/* segment not present fault */
1159 	case T_GPFLT + USER:	/* general protection violation */
1160 #ifdef _SYSCALL32_IMPL
1161 		if (p->p_model != DATAMODEL_NATIVE) {
1162 #endif /* _SYSCALL32_IMPL */
1163 		if (instr_is_lcall_syscall((caddr_t)rp->r_pc)) {
1164 			if (type == T_SEGFLT + USER)
1165 				ASSERT(p->p_ldt != NULL);
1166 
1167 			if ((p->p_ldt == NULL && type == T_GPFLT + USER) ||
1168 			    type == T_SEGFLT + USER) {
1169 
1170 			/*
1171 			 * The user attempted a system call via the obsolete
1172 			 * call gate mechanism. Because the process doesn't have
1173 			 * an LDT (i.e. the ldtr contains 0), a #gp results.
1174 			 * Emulate the syscall here, just as we do above for a
1175 			 * #np trap.
1176 			 */
1177 
1178 			/*
1179 			 * Since this is a not-present trap, rp->r_pc points to
1180 			 * the trapping lcall instruction. We need to bump it
1181 			 * to the next insn so the app can continue on.
1182 			 */
1183 			rp->r_pc += LCALLSIZE;
1184 			lwp->lwp_regs = rp;
1185 
1186 			/*
1187 			 * Normally the microstate of the LWP is forced back to
1188 			 * LMS_USER by the syscall handlers. Emulate that
1189 			 * behavior here.
1190 			 */
1191 			mstate = LMS_USER;
1192 
1193 			dosyscall();
1194 			goto out;
1195 			}
1196 		}
1197 #ifdef _SYSCALL32_IMPL
1198 		}
1199 #endif /* _SYSCALL32_IMPL */
1200 		/*
1201 		 * If the current process is using a private LDT and the
1202 		 * trapping instruction is sysenter, the sysenter instruction
1203 		 * has been disabled on the CPU because it destroys segment
1204 		 * registers. If this is the case, rewrite the instruction to
1205 		 * be a safe system call and retry it. If this occurs on a CPU
1206 		 * which doesn't even support sysenter, the result of all of
1207 		 * this will be to emulate that particular instruction.
1208 		 */
1209 		if (p->p_ldt != NULL &&
1210 		    ldt_rewrite_syscall(rp, p, X86FSET_SEP))
1211 			goto out;
1212 
1213 		/*FALLTHROUGH*/
1214 
1215 	case T_BOUNDFLT + USER:	/* bound fault */
1216 	case T_STKFLT + USER:	/* stack fault */
1217 	case T_TSSFLT + USER:	/* invalid TSS fault */
1218 		if (tudebug)
1219 			showregs(type, rp, (caddr_t)0);
1220 		siginfo.si_signo = SIGSEGV;
1221 		siginfo.si_code  = SEGV_MAPERR;
1222 		siginfo.si_addr  = (caddr_t)rp->r_pc;
1223 		fault = FLTBOUNDS;
1224 		break;
1225 
1226 	case T_ALIGNMENT + USER:	/* user alignment error (486) */
1227 		if (tudebug)
1228 			showregs(type, rp, (caddr_t)0);
1229 		bzero(&siginfo, sizeof (siginfo));
1230 		siginfo.si_signo = SIGBUS;
1231 		siginfo.si_code = BUS_ADRALN;
1232 		siginfo.si_addr = (caddr_t)rp->r_pc;
1233 		fault = FLTACCESS;
1234 		break;
1235 
1236 	case T_SGLSTP + USER: /* single step/hw breakpoint exception */
1237 		if (tudebug && tudebugbpt)
1238 			showregs(type, rp, (caddr_t)0);
1239 
1240 		/* Was it single-stepping? */
1241 		if (lwp->lwp_pcb.pcb_drstat & DR_SINGLESTEP) {
1242 			pcb_t *pcb = &lwp->lwp_pcb;
1243 
1244 			rp->r_ps &= ~PS_T;
1245 			/*
1246 			 * If both NORMAL_STEP and WATCH_STEP are in effect,
1247 			 * give precedence to WATCH_STEP.  If neither is set,
1248 			 * user must have set the PS_T bit in %efl; treat this
1249 			 * as NORMAL_STEP.
1250 			 */
1251 			if ((fault = undo_watch_step(&siginfo)) == 0 &&
1252 			    ((pcb->pcb_flags & NORMAL_STEP) ||
1253 			    !(pcb->pcb_flags & WATCH_STEP))) {
1254 				siginfo.si_signo = SIGTRAP;
1255 				siginfo.si_code = TRAP_TRACE;
1256 				siginfo.si_addr = (caddr_t)rp->r_pc;
1257 				fault = FLTTRACE;
1258 			}
1259 			pcb->pcb_flags &= ~(NORMAL_STEP|WATCH_STEP);
1260 		}
1261 		break;
1262 
1263 	case T_BPTFLT + USER:	/* breakpoint trap */
1264 		if (tudebug && tudebugbpt)
1265 			showregs(type, rp, (caddr_t)0);
1266 		/*
1267 		 * int 3 (the breakpoint instruction) leaves the pc referring
1268 		 * to the address one byte after the breakpointed address.
1269 		 * If the P_PR_BPTADJ flag has been set via /proc, We adjust
1270 		 * it back so it refers to the breakpointed address.
1271 		 */
1272 		if (p->p_proc_flag & P_PR_BPTADJ)
1273 			rp->r_pc--;
1274 		siginfo.si_signo = SIGTRAP;
1275 		siginfo.si_code  = TRAP_BRKPT;
1276 		siginfo.si_addr  = (caddr_t)rp->r_pc;
1277 		fault = FLTBPT;
1278 		break;
1279 
1280 	case T_AST:
1281 		/*
1282 		 * This occurs only after the cs register has been made to
1283 		 * look like a kernel selector, either through debugging or
1284 		 * possibly by functions like setcontext().  The thread is
1285 		 * about to cause a general protection fault at common_iret()
1286 		 * in locore.  We let that happen immediately instead of
1287 		 * doing the T_AST processing.
1288 		 */
1289 		goto cleanup;
1290 
1291 	case T_AST + USER:	/* profiling, resched, h/w error pseudo trap */
1292 		if (lwp->lwp_pcb.pcb_flags & ASYNC_HWERR) {
1293 			proc_t *p = ttoproc(curthread);
1294 			extern void print_msg_hwerr(ctid_t ct_id, proc_t *p);
1295 
1296 			lwp->lwp_pcb.pcb_flags &= ~ASYNC_HWERR;
1297 			print_msg_hwerr(p->p_ct_process->conp_contract.ct_id,
1298 			    p);
1299 			contract_process_hwerr(p->p_ct_process, p);
1300 			siginfo.si_signo = SIGKILL;
1301 			siginfo.si_code = SI_NOINFO;
1302 		} else if (lwp->lwp_pcb.pcb_flags & CPC_OVERFLOW) {
1303 			lwp->lwp_pcb.pcb_flags &= ~CPC_OVERFLOW;
1304 			if (kcpc_overflow_ast()) {
1305 				/*
1306 				 * Signal performance counter overflow
1307 				 */
1308 				if (tudebug)
1309 					showregs(type, rp, (caddr_t)0);
1310 				bzero(&siginfo, sizeof (siginfo));
1311 				siginfo.si_signo = SIGEMT;
1312 				siginfo.si_code = EMT_CPCOVF;
1313 				siginfo.si_addr = (caddr_t)rp->r_pc;
1314 				fault = FLTCPCOVF;
1315 			}
1316 		}
1317 
1318 		break;
1319 	}
1320 
1321 	/*
1322 	 * We can't get here from a system trap
1323 	 */
1324 	ASSERT(type & USER);
1325 
1326 	if (fault) {
1327 		/* We took a fault so abort single step. */
1328 		lwp->lwp_pcb.pcb_flags &= ~(NORMAL_STEP|WATCH_STEP);
1329 		/*
1330 		 * Remember the fault and fault adddress
1331 		 * for real-time (SIGPROF) profiling.
1332 		 */
1333 		lwp->lwp_lastfault = fault;
1334 		lwp->lwp_lastfaddr = siginfo.si_addr;
1335 
1336 		DTRACE_PROC2(fault, int, fault, ksiginfo_t *, &siginfo);
1337 
1338 		/*
1339 		 * If a debugger has declared this fault to be an
1340 		 * event of interest, stop the lwp.  Otherwise just
1341 		 * deliver the associated signal.
1342 		 */
1343 		if (siginfo.si_signo != SIGKILL &&
1344 		    prismember(&p->p_fltmask, fault) &&
1345 		    stop_on_fault(fault, &siginfo) == 0)
1346 			siginfo.si_signo = 0;
1347 	}
1348 
1349 	if (siginfo.si_signo)
1350 		trapsig(&siginfo, (fault != FLTFPE && fault != FLTCPCOVF));
1351 
1352 	if (lwp->lwp_oweupc)
1353 		profil_tick(rp->r_pc);
1354 
1355 	if (ct->t_astflag | ct->t_sig_check) {
1356 		/*
1357 		 * Turn off the AST flag before checking all the conditions that
1358 		 * may have caused an AST.  This flag is on whenever a signal or
1359 		 * unusual condition should be handled after the next trap or
1360 		 * syscall.
1361 		 */
1362 		astoff(ct);
1363 		/*
1364 		 * If a single-step trap occurred on a syscall (see above)
1365 		 * recognize it now.  Do this before checking for signals
1366 		 * because deferred_singlestep_trap() may generate a SIGTRAP to
1367 		 * the LWP or may otherwise mark the LWP to call issig(FORREAL).
1368 		 */
1369 		if (lwp->lwp_pcb.pcb_flags & DEBUG_PENDING)
1370 			deferred_singlestep_trap((caddr_t)rp->r_pc);
1371 
1372 		ct->t_sig_check = 0;
1373 
1374 		/*
1375 		 * As in other code paths that check against TP_CHANGEBIND,
1376 		 * we perform the check first without p_lock held -- only
1377 		 * acquiring p_lock in the unlikely event that it is indeed
1378 		 * set.  This is safe because we are doing this after the
1379 		 * astoff(); if we are racing another thread setting
1380 		 * TP_CHANGEBIND on us, we will pick it up on a subsequent
1381 		 * lap through.
1382 		 */
1383 		if (curthread->t_proc_flag & TP_CHANGEBIND) {
1384 			mutex_enter(&p->p_lock);
1385 			if (curthread->t_proc_flag & TP_CHANGEBIND) {
1386 				timer_lwpbind();
1387 				curthread->t_proc_flag &= ~TP_CHANGEBIND;
1388 			}
1389 			mutex_exit(&p->p_lock);
1390 		}
1391 
1392 		/*
1393 		 * for kaio requests that are on the per-process poll queue,
1394 		 * aiop->aio_pollq, they're AIO_POLL bit is set, the kernel
1395 		 * should copyout their result_t to user memory. by copying
1396 		 * out the result_t, the user can poll on memory waiting
1397 		 * for the kaio request to complete.
1398 		 */
1399 		if (p->p_aio)
1400 			aio_cleanup(0);
1401 		/*
1402 		 * If this LWP was asked to hold, call holdlwp(), which will
1403 		 * stop.  holdlwps() sets this up and calls pokelwps() which
1404 		 * sets the AST flag.
1405 		 *
1406 		 * Also check TP_EXITLWP, since this is used by fresh new LWPs
1407 		 * through lwp_rtt().  That flag is set if the lwp_create(2)
1408 		 * syscall failed after creating the LWP.
1409 		 */
1410 		if (ISHOLD(p))
1411 			holdlwp();
1412 
1413 		/*
1414 		 * All code that sets signals and makes ISSIG evaluate true must
1415 		 * set t_astflag afterwards.
1416 		 */
1417 		if (ISSIG_PENDING(ct, lwp, p)) {
1418 			if (issig(FORREAL))
1419 				psig();
1420 			ct->t_sig_check = 1;
1421 		}
1422 
1423 		if (ct->t_rprof != NULL) {
1424 			realsigprof(0, 0, 0);
1425 			ct->t_sig_check = 1;
1426 		}
1427 
1428 		/*
1429 		 * /proc can't enable/disable the trace bit itself
1430 		 * because that could race with the call gate used by
1431 		 * system calls via "lcall". If that happened, an
1432 		 * invalid EFLAGS would result. prstep()/prnostep()
1433 		 * therefore schedule an AST for the purpose.
1434 		 */
1435 		if (lwp->lwp_pcb.pcb_flags & REQUEST_STEP) {
1436 			lwp->lwp_pcb.pcb_flags &= ~REQUEST_STEP;
1437 			rp->r_ps |= PS_T;
1438 		}
1439 		if (lwp->lwp_pcb.pcb_flags & REQUEST_NOSTEP) {
1440 			lwp->lwp_pcb.pcb_flags &= ~REQUEST_NOSTEP;
1441 			rp->r_ps &= ~PS_T;
1442 		}
1443 	}
1444 
1445 out:	/* We can't get here from a system trap */
1446 	ASSERT(type & USER);
1447 
1448 	if (ISHOLD(p))
1449 		holdlwp();
1450 
1451 	/*
1452 	 * Set state to LWP_USER here so preempt won't give us a kernel
1453 	 * priority if it occurs after this point.  Call CL_TRAPRET() to
1454 	 * restore the user-level priority.
1455 	 *
1456 	 * It is important that no locks (other than spinlocks) be entered
1457 	 * after this point before returning to user mode (unless lwp_state
1458 	 * is set back to LWP_SYS).
1459 	 */
1460 	lwp->lwp_state = LWP_USER;
1461 
1462 	if (ct->t_trapret) {
1463 		ct->t_trapret = 0;
1464 		thread_lock(ct);
1465 		CL_TRAPRET(ct);
1466 		thread_unlock(ct);
1467 	}
1468 	if (CPU->cpu_runrun || curthread->t_schedflag & TS_ANYWAITQ)
1469 		preempt();
1470 	prunstop();
1471 	(void) new_mstate(ct, mstate);
1472 
1473 	/* Kernel probe */
1474 	TNF_PROBE_1(thread_state, "thread", /* CSTYLED */,
1475 	    tnf_microstate, state, LMS_USER);
1476 
1477 	return;
1478 
1479 cleanup:	/* system traps end up here */
1480 	ASSERT(!(type & USER));
1481 }
1482 
1483 /*
1484  * Patch non-zero to disable preemption of threads in the kernel.
1485  */
1486 int IGNORE_KERNEL_PREEMPTION = 0;	/* XXX - delete this someday */
1487 
1488 struct kpreempt_cnts {		/* kernel preemption statistics */
1489 	int	kpc_idle;	/* executing idle thread */
1490 	int	kpc_intr;	/* executing interrupt thread */
1491 	int	kpc_clock;	/* executing clock thread */
1492 	int	kpc_blocked;	/* thread has blocked preemption (t_preempt) */
1493 	int	kpc_notonproc;	/* thread is surrendering processor */
1494 	int	kpc_inswtch;	/* thread has ratified scheduling decision */
1495 	int	kpc_prilevel;	/* processor interrupt level is too high */
1496 	int	kpc_apreempt;	/* asynchronous preemption */
1497 	int	kpc_spreempt;	/* synchronous preemption */
1498 } kpreempt_cnts;
1499 
1500 /*
1501  * kernel preemption: forced rescheduling, preempt the running kernel thread.
1502  *	the argument is old PIL for an interrupt,
1503  *	or the distingished value KPREEMPT_SYNC.
1504  */
1505 void
1506 kpreempt(int asyncspl)
1507 {
1508 	kthread_t *ct = curthread;
1509 
1510 	if (IGNORE_KERNEL_PREEMPTION) {
1511 		aston(CPU->cpu_dispthread);
1512 		return;
1513 	}
1514 
1515 	/*
1516 	 * Check that conditions are right for kernel preemption
1517 	 */
1518 	do {
1519 		if (ct->t_preempt) {
1520 			/*
1521 			 * either a privileged thread (idle, panic, interrupt)
1522 			 * or will check when t_preempt is lowered
1523 			 * We need to specifically handle the case where
1524 			 * the thread is in the middle of swtch (resume has
1525 			 * been called) and has its t_preempt set
1526 			 * [idle thread and a thread which is in kpreempt
1527 			 * already] and then a high priority thread is
1528 			 * available in the local dispatch queue.
1529 			 * In this case the resumed thread needs to take a
1530 			 * trap so that it can call kpreempt. We achieve
1531 			 * this by using siron().
1532 			 * How do we detect this condition:
1533 			 * idle thread is running and is in the midst of
1534 			 * resume: curthread->t_pri == -1 && CPU->dispthread
1535 			 * != CPU->thread
1536 			 * Need to ensure that this happens only at high pil
1537 			 * resume is called at high pil
1538 			 * Only in resume_from_idle is the pil changed.
1539 			 */
1540 			if (ct->t_pri < 0) {
1541 				kpreempt_cnts.kpc_idle++;
1542 				if (CPU->cpu_dispthread != CPU->cpu_thread)
1543 					siron();
1544 			} else if (ct->t_flag & T_INTR_THREAD) {
1545 				kpreempt_cnts.kpc_intr++;
1546 				if (ct->t_pil == CLOCK_LEVEL)
1547 					kpreempt_cnts.kpc_clock++;
1548 			} else {
1549 				kpreempt_cnts.kpc_blocked++;
1550 				if (CPU->cpu_dispthread != CPU->cpu_thread)
1551 					siron();
1552 			}
1553 			aston(CPU->cpu_dispthread);
1554 			return;
1555 		}
1556 		if (ct->t_state != TS_ONPROC ||
1557 		    ct->t_disp_queue != CPU->cpu_disp) {
1558 			/* this thread will be calling swtch() shortly */
1559 			kpreempt_cnts.kpc_notonproc++;
1560 			if (CPU->cpu_thread != CPU->cpu_dispthread) {
1561 				/* already in swtch(), force another */
1562 				kpreempt_cnts.kpc_inswtch++;
1563 				siron();
1564 			}
1565 			return;
1566 		}
1567 		if (getpil() >= DISP_LEVEL) {
1568 			/*
1569 			 * We can't preempt this thread if it is at
1570 			 * a PIL >= DISP_LEVEL since it may be holding
1571 			 * a spin lock (like sched_lock).
1572 			 */
1573 			siron();	/* check back later */
1574 			kpreempt_cnts.kpc_prilevel++;
1575 			return;
1576 		}
1577 		if (!interrupts_enabled()) {
1578 			/*
1579 			 * Can't preempt while running with ints disabled
1580 			 */
1581 			kpreempt_cnts.kpc_prilevel++;
1582 			return;
1583 		}
1584 		if (asyncspl != KPREEMPT_SYNC)
1585 			kpreempt_cnts.kpc_apreempt++;
1586 		else
1587 			kpreempt_cnts.kpc_spreempt++;
1588 
1589 		ct->t_preempt++;
1590 		preempt();
1591 		ct->t_preempt--;
1592 	} while (CPU->cpu_kprunrun);
1593 }
1594 
1595 /*
1596  * Print out debugging info.
1597  */
1598 static void
1599 showregs(uint_t type, struct regs *rp, caddr_t addr)
1600 {
1601 	int s;
1602 
1603 	s = spl7();
1604 	type &= ~USER;
1605 	if (PTOU(curproc)->u_comm[0])
1606 		printf("%s: ", PTOU(curproc)->u_comm);
1607 	if (type < TRAP_TYPES)
1608 		printf("#%s %s\n", trap_type_mnemonic[type], trap_type[type]);
1609 	else
1610 		switch (type) {
1611 		case T_SYSCALL:
1612 			printf("Syscall Trap:\n");
1613 			break;
1614 		case T_AST:
1615 			printf("AST\n");
1616 			break;
1617 		default:
1618 			printf("Bad Trap = %d\n", type);
1619 			break;
1620 		}
1621 	if (type == T_PGFLT) {
1622 		printf("Bad %s fault at addr=0x%lx\n",
1623 		    USERMODE(rp->r_cs) ? "user": "kernel", (uintptr_t)addr);
1624 	} else if (addr) {
1625 		printf("addr=0x%lx\n", (uintptr_t)addr);
1626 	}
1627 
1628 	printf("pid=%d, pc=0x%lx, sp=0x%lx, eflags=0x%lx\n",
1629 	    (ttoproc(curthread) && ttoproc(curthread)->p_pidp) ?
1630 	    ttoproc(curthread)->p_pid : 0, rp->r_pc, rp->r_sp, rp->r_ps);
1631 
1632 #if defined(__lint)
1633 	/*
1634 	 * this clause can be deleted when lint bug 4870403 is fixed
1635 	 * (lint thinks that bit 32 is illegal in a %b format string)
1636 	 */
1637 	printf("cr0: %x  cr4: %b\n",
1638 	    (uint_t)getcr0(), (uint_t)getcr4(), FMT_CR4);
1639 #else
1640 	printf("cr0: %b  cr4: %b\n",
1641 	    (uint_t)getcr0(), FMT_CR0, (uint_t)getcr4(), FMT_CR4);
1642 #endif	/* __lint */
1643 
1644 	printf("cr2: %lx  ", getcr2());
1645 #if !defined(__xpv)
1646 	printf("cr3: %lx  ", getcr3());
1647 	printf("cr8: %lx\n", getcr8());
1648 #endif
1649 	printf("\n");
1650 
1651 	dumpregs(rp);
1652 	splx(s);
1653 }
1654 
1655 static void
1656 dumpregs(struct regs *rp)
1657 {
1658 	const char fmt[] = "\t%3s: %16lx %3s: %16lx %3s: %16lx\n";
1659 
1660 	printf(fmt, "rdi", rp->r_rdi, "rsi", rp->r_rsi, "rdx", rp->r_rdx);
1661 	printf(fmt, "rcx", rp->r_rcx, " r8", rp->r_r8, " r9", rp->r_r9);
1662 	printf(fmt, "rax", rp->r_rax, "rbx", rp->r_rbx, "rbp", rp->r_rbp);
1663 	printf(fmt, "r10", rp->r_r10, "r11", rp->r_r11, "r12", rp->r_r12);
1664 	printf(fmt, "r13", rp->r_r13, "r14", rp->r_r14, "r15", rp->r_r15);
1665 
1666 	printf(fmt, "fsb", rdmsr(MSR_AMD_FSBASE), "gsb", rdmsr(MSR_AMD_GSBASE),
1667 	    " ds", rp->r_ds);
1668 	printf(fmt, " es", rp->r_es, " fs", rp->r_fs, " gs", rp->r_gs);
1669 
1670 	printf(fmt, "trp", rp->r_trapno, "err", rp->r_err, "rip", rp->r_rip);
1671 	printf(fmt, " cs", rp->r_cs, "rfl", rp->r_rfl, "rsp", rp->r_rsp);
1672 
1673 	printf("\t%3s: %16lx\n", " ss", rp->r_ss);
1674 
1675 }
1676 
1677 /*
1678  * Test to see if the instruction is iret on i386 or iretq on amd64.
1679  *
1680  * On the hypervisor we can only test for nopop_sys_rtt_syscall. If true
1681  * then we are in the context of hypervisor's failsafe handler because it
1682  * tried to iret and failed due to a bad selector. See xen_failsafe_callback.
1683  */
1684 static int
1685 instr_is_iret(caddr_t pc)
1686 {
1687 
1688 #if defined(__xpv)
1689 	extern void nopop_sys_rtt_syscall(void);
1690 	return ((pc == (caddr_t)nopop_sys_rtt_syscall) ? 1 : 0);
1691 
1692 #else
1693 
1694 	static const uint8_t iret_insn[2] = { 0x48, 0xcf };	/* iretq */
1695 
1696 	return (bcmp(pc, iret_insn, sizeof (iret_insn)) == 0);
1697 
1698 #endif	/* __xpv */
1699 }
1700 
1701 
1702 /*
1703  * Test to see if the instruction is part of _sys_rtt (or the KPTI trampolines
1704  * which are used by _sys_rtt).
1705  *
1706  * Again on the hypervisor if we try to IRET to user land with a bad code
1707  * or stack selector we will get vectored through xen_failsafe_callback.
1708  * In which case we assume we got here via _sys_rtt since we only allow
1709  * IRET to user land to take place in _sys_rtt.
1710  */
1711 static int
1712 instr_is_sys_rtt(caddr_t pc)
1713 {
1714 	extern void _sys_rtt(), _sys_rtt_end();
1715 
1716 #if !defined(__xpv)
1717 	extern void tr_sysc_ret_start(), tr_sysc_ret_end();
1718 	extern void tr_intr_ret_start(), tr_intr_ret_end();
1719 
1720 	if ((uintptr_t)pc >= (uintptr_t)tr_sysc_ret_start &&
1721 	    (uintptr_t)pc <= (uintptr_t)tr_sysc_ret_end)
1722 		return (1);
1723 
1724 	if ((uintptr_t)pc >= (uintptr_t)tr_intr_ret_start &&
1725 	    (uintptr_t)pc <= (uintptr_t)tr_intr_ret_end)
1726 		return (1);
1727 #endif
1728 
1729 	if ((uintptr_t)pc < (uintptr_t)_sys_rtt ||
1730 	    (uintptr_t)pc > (uintptr_t)_sys_rtt_end)
1731 		return (0);
1732 
1733 	return (1);
1734 }
1735 
1736 /*
1737  * Handle #gp faults in kernel mode.
1738  *
1739  * One legitimate way this can happen is if we attempt to update segment
1740  * registers to naughty values on the way out of the kernel.
1741  *
1742  * This can happen in a couple of ways: someone - either accidentally or
1743  * on purpose - creates (setcontext(2), lwp_create(2)) or modifies
1744  * (signal(2)) a ucontext that contains silly segment register values.
1745  * Or someone - either accidentally or on purpose - modifies the prgregset_t
1746  * of a subject process via /proc to contain silly segment register values.
1747  *
1748  * (The unfortunate part is that we can end up discovering the bad segment
1749  * register value in the middle of an 'iret' after we've popped most of the
1750  * stack.  So it becomes quite difficult to associate an accurate ucontext
1751  * with the lwp, because the act of taking the #gp trap overwrites most of
1752  * what we were going to send the lwp.)
1753  *
1754  * OTOH if it turns out that's -not- the problem, and we're -not- an lwp
1755  * trying to return to user mode and we get a #gp fault, then we need
1756  * to die() -- which will happen if we return non-zero from this routine.
1757  */
1758 static int
1759 kern_gpfault(struct regs *rp)
1760 {
1761 	kthread_t *t = curthread;
1762 	proc_t *p = ttoproc(t);
1763 	klwp_t *lwp = ttolwp(t);
1764 	struct regs tmpregs, *trp = NULL;
1765 	caddr_t pc = (caddr_t)rp->r_pc;
1766 	int v;
1767 	uint32_t auditing = AU_AUDITING();
1768 
1769 	/*
1770 	 * if we're not an lwp, or in the case of running native the
1771 	 * pc range is outside _sys_rtt, then we should immediately
1772 	 * be die()ing horribly.
1773 	 */
1774 	if (lwp == NULL || !instr_is_sys_rtt(pc))
1775 		return (1);
1776 
1777 	/*
1778 	 * So at least we're in the right part of the kernel.
1779 	 *
1780 	 * Disassemble the instruction at the faulting pc.
1781 	 * Once we know what it is, we carefully reconstruct the stack
1782 	 * based on the order in which the stack is deconstructed in
1783 	 * _sys_rtt. Ew.
1784 	 */
1785 	if (instr_is_iret(pc)) {
1786 		/*
1787 		 * We took the #gp while trying to perform the IRET.
1788 		 * This means that either %cs or %ss are bad.
1789 		 * All we know for sure is that most of the general
1790 		 * registers have been restored, including the
1791 		 * segment registers, and all we have left on the
1792 		 * topmost part of the lwp's stack are the
1793 		 * registers that the iretq was unable to consume.
1794 		 *
1795 		 * All the rest of the state was crushed by the #gp
1796 		 * which pushed -its- registers atop our old save area
1797 		 * (because we had to decrement the stack pointer, sigh) so
1798 		 * all that we can try and do is to reconstruct the
1799 		 * crushed frame from the #gp trap frame itself.
1800 		 */
1801 		trp = &tmpregs;
1802 		trp->r_ss = lwptoregs(lwp)->r_ss;
1803 		trp->r_sp = lwptoregs(lwp)->r_sp;
1804 		trp->r_ps = lwptoregs(lwp)->r_ps;
1805 		trp->r_cs = lwptoregs(lwp)->r_cs;
1806 		trp->r_pc = lwptoregs(lwp)->r_pc;
1807 		bcopy(rp, trp, offsetof(struct regs, r_pc));
1808 
1809 		/*
1810 		 * Validate simple math
1811 		 */
1812 		ASSERT(trp->r_pc == lwptoregs(lwp)->r_pc);
1813 		ASSERT(trp->r_err == rp->r_err);
1814 
1815 
1816 
1817 	}
1818 
1819 	if (trp == NULL && PCB_NEED_UPDATE_SEGS(&lwp->lwp_pcb)) {
1820 
1821 		/*
1822 		 * This is the common case -- we're trying to load
1823 		 * a bad segment register value in the only section
1824 		 * of kernel code that ever loads segment registers.
1825 		 *
1826 		 * We don't need to do anything at this point because
1827 		 * the pcb contains all the pending segment register
1828 		 * state, and the regs are still intact because we
1829 		 * didn't adjust the stack pointer yet.  Given the fidelity
1830 		 * of all this, we could conceivably send a signal
1831 		 * to the lwp, rather than core-ing.
1832 		 */
1833 		trp = lwptoregs(lwp);
1834 		ASSERT((caddr_t)trp == (caddr_t)rp->r_sp);
1835 	}
1836 
1837 	if (trp == NULL)
1838 		return (1);
1839 
1840 	/*
1841 	 * If we get to here, we're reasonably confident that we've
1842 	 * correctly decoded what happened on the way out of the kernel.
1843 	 * Rewrite the lwp's registers so that we can create a core dump
1844 	 * the (at least vaguely) represents the mcontext we were
1845 	 * being asked to restore when things went so terribly wrong.
1846 	 */
1847 
1848 	/*
1849 	 * Make sure that we have a meaningful %trapno and %err.
1850 	 */
1851 	trp->r_trapno = rp->r_trapno;
1852 	trp->r_err = rp->r_err;
1853 
1854 	if ((caddr_t)trp != (caddr_t)lwptoregs(lwp))
1855 		bcopy(trp, lwptoregs(lwp), sizeof (*trp));
1856 
1857 
1858 	mutex_enter(&p->p_lock);
1859 	lwp->lwp_cursig = SIGSEGV;
1860 	mutex_exit(&p->p_lock);
1861 
1862 	/*
1863 	 * Terminate all LWPs but don't discard them.  If another lwp beat
1864 	 * us to the punch by calling exit(), evaporate now.
1865 	 */
1866 	proc_is_exiting(p);
1867 	if (exitlwps(1) != 0) {
1868 		mutex_enter(&p->p_lock);
1869 		lwp_exit();
1870 	}
1871 
1872 	if (auditing)		/* audit core dump */
1873 		audit_core_start(SIGSEGV);
1874 	v = core(SIGSEGV, B_FALSE);
1875 	if (auditing)		/* audit core dump */
1876 		audit_core_finish(v ? CLD_KILLED : CLD_DUMPED);
1877 	exit(v ? CLD_KILLED : CLD_DUMPED, SIGSEGV);
1878 	return (0);
1879 }
1880 
1881 /*
1882  * dump_tss() - Display the TSS structure
1883  */
1884 
1885 #if !defined(__xpv)
1886 
1887 static void
1888 dump_tss(void)
1889 {
1890 	const char tss_fmt[] = "tss.%s:\t0x%p\n";  /* Format string */
1891 	tss_t *tss = CPU->cpu_tss;
1892 
1893 	printf(tss_fmt, "tss_rsp0", (void *)tss->tss_rsp0);
1894 	printf(tss_fmt, "tss_rsp1", (void *)tss->tss_rsp1);
1895 	printf(tss_fmt, "tss_rsp2", (void *)tss->tss_rsp2);
1896 
1897 	printf(tss_fmt, "tss_ist1", (void *)tss->tss_ist1);
1898 	printf(tss_fmt, "tss_ist2", (void *)tss->tss_ist2);
1899 	printf(tss_fmt, "tss_ist3", (void *)tss->tss_ist3);
1900 	printf(tss_fmt, "tss_ist4", (void *)tss->tss_ist4);
1901 	printf(tss_fmt, "tss_ist5", (void *)tss->tss_ist5);
1902 	printf(tss_fmt, "tss_ist6", (void *)tss->tss_ist6);
1903 	printf(tss_fmt, "tss_ist7", (void *)tss->tss_ist7);
1904 }
1905 
1906 #endif	/* !__xpv */
1907 
1908 #if defined(TRAPTRACE)
1909 
1910 int ttrace_nrec = 10;		/* number of records to dump out */
1911 int ttrace_dump_nregs = 0;	/* dump out this many records with regs too */
1912 
1913 /*
1914  * Dump out the last ttrace_nrec traptrace records on each CPU
1915  */
1916 static void
1917 dump_ttrace(void)
1918 {
1919 	trap_trace_ctl_t *ttc;
1920 	trap_trace_rec_t *rec;
1921 	uintptr_t current;
1922 	int i, j;
1923 	int n = NCPU;
1924 	const char banner[] =
1925 	    "CPU          ADDRESS    TIMESTAMP TYPE  VC HANDLER          PC\n";
1926 	/* Define format for the CPU, ADDRESS, and TIMESTAMP fields */
1927 	const char fmt1[] = "%3d %016lx %12llx";
1928 	char data1[34];	/* length of string formatted by fmt1 + 1 */
1929 	/* Define format for the TYPE and VC fields */
1930 	const char fmt2[] = "%4s %3x";
1931 	const char fmt2s[] = "%4s %3s";
1932 	char data2[9];	/* length of string formatted by fmt2 + 1 */
1933 	/*
1934 	 * Define format for the HANDLER field. Width is arbitrary, but should
1935 	 * be enough for common handler's names, and leave enough space for
1936 	 * the PC field, especially when we are in kmdb.
1937 	 */
1938 	const char fmt3h[] = "#%-15s";
1939 	const char fmt3p[] = "%-16p";
1940 	const char fmt3s[] = "%-16s";
1941 	char data3[17];	/* length of string formatted by fmt3* + 1 */
1942 
1943 	if (ttrace_nrec == 0)
1944 		return;
1945 
1946 	printf("\n");
1947 	printf(banner);
1948 
1949 	for (i = 0; i < n; i++) {
1950 		ttc = &trap_trace_ctl[i];
1951 		if (ttc->ttc_first == (uintptr_t)NULL)
1952 			continue;
1953 
1954 		current = ttc->ttc_next - sizeof (trap_trace_rec_t);
1955 		for (j = 0; j < ttrace_nrec; j++) {
1956 			struct sysent	*sys;
1957 			struct autovec	*vec;
1958 			extern struct av_head autovect[];
1959 			int type;
1960 			ulong_t	off;
1961 			char *sym, *stype;
1962 
1963 			if (current < ttc->ttc_first)
1964 				current =
1965 				    ttc->ttc_limit - sizeof (trap_trace_rec_t);
1966 
1967 			if (current == (uintptr_t)NULL)
1968 				continue;
1969 
1970 			rec = (trap_trace_rec_t *)current;
1971 
1972 			if (rec->ttr_stamp == 0)
1973 				break;
1974 
1975 			(void) snprintf(data1, sizeof (data1), fmt1, i,
1976 			    (uintptr_t)rec, rec->ttr_stamp);
1977 
1978 			switch (rec->ttr_marker) {
1979 			case TT_SYSCALL:
1980 			case TT_SYSENTER:
1981 			case TT_SYSC:
1982 			case TT_SYSC64:
1983 				sys = &sysent32[rec->ttr_sysnum];
1984 				switch (rec->ttr_marker) {
1985 				case TT_SYSC64:
1986 					sys = &sysent[rec->ttr_sysnum];
1987 					/* FALLTHROUGH */
1988 				case TT_SYSC:
1989 					stype = "sysc";	/* syscall */
1990 					break;
1991 				case TT_SYSCALL:
1992 					stype = "lcal";	/* lcall */
1993 					break;
1994 				case TT_SYSENTER:
1995 					stype = "syse";	/* sysenter */
1996 					break;
1997 				default:
1998 					stype = "";
1999 					break;
2000 				}
2001 				(void) snprintf(data2, sizeof (data2), fmt2,
2002 				    stype, rec->ttr_sysnum);
2003 				if (sys != NULL) {
2004 					sym = kobj_getsymname(
2005 					    (uintptr_t)sys->sy_callc,
2006 					    &off);
2007 					if (sym != NULL) {
2008 						(void) snprintf(data3,
2009 						    sizeof (data3), fmt3s, sym);
2010 					} else {
2011 						(void) snprintf(data3,
2012 						    sizeof (data3), fmt3p,
2013 						    sys->sy_callc);
2014 					}
2015 				} else {
2016 					(void) snprintf(data3, sizeof (data3),
2017 					    fmt3s, "unknown");
2018 				}
2019 				break;
2020 
2021 			case TT_INTERRUPT:
2022 				if (rec->ttr_regs.r_trapno == T_SOFTINT) {
2023 					(void) snprintf(data2, sizeof (data2),
2024 					    fmt2s, "intr", "-");
2025 					(void) snprintf(data3, sizeof (data3),
2026 					    fmt3s, "(fakesoftint)");
2027 					break;
2028 				}
2029 
2030 				(void) snprintf(data2, sizeof (data2), fmt2,
2031 				    "intr", rec->ttr_vector);
2032 				if (get_intr_handler != NULL)
2033 					vec = (struct autovec *)
2034 					    (*get_intr_handler)
2035 					    (rec->ttr_cpuid, rec->ttr_vector);
2036 				else
2037 					vec =
2038 					    autovect[rec->ttr_vector].avh_link;
2039 
2040 				if (vec != NULL) {
2041 					sym = kobj_getsymname(
2042 					    (uintptr_t)vec->av_vector, &off);
2043 					if (sym != NULL) {
2044 						(void) snprintf(data3,
2045 						    sizeof (data3), fmt3s, sym);
2046 					} else {
2047 						(void) snprintf(data3,
2048 						    sizeof (data3), fmt3p,
2049 						    vec->av_vector);
2050 					}
2051 				} else {
2052 					(void) snprintf(data3, sizeof (data3),
2053 					    fmt3s, "unknown");
2054 				}
2055 				break;
2056 
2057 			case TT_TRAP:
2058 			case TT_EVENT:
2059 				type = rec->ttr_regs.r_trapno;
2060 				(void) snprintf(data2, sizeof (data2), fmt2,
2061 				    "trap", type);
2062 				if (type < TRAP_TYPES) {
2063 					(void) snprintf(data3, sizeof (data3),
2064 					    fmt3h, trap_type_mnemonic[type]);
2065 				} else {
2066 					switch (type) {
2067 					case T_AST:
2068 						(void) snprintf(data3,
2069 						    sizeof (data3), fmt3s,
2070 						    "ast");
2071 						break;
2072 					default:
2073 						(void) snprintf(data3,
2074 						    sizeof (data3), fmt3s, "");
2075 						break;
2076 					}
2077 				}
2078 				break;
2079 
2080 			default:
2081 				break;
2082 			}
2083 
2084 			sym = kobj_getsymname(rec->ttr_regs.r_pc, &off);
2085 			if (sym != NULL) {
2086 				printf("%s %s %s %s+%lx\n", data1, data2, data3,
2087 				    sym, off);
2088 			} else {
2089 				printf("%s %s %s %lx\n", data1, data2, data3,
2090 				    rec->ttr_regs.r_pc);
2091 			}
2092 
2093 			if (ttrace_dump_nregs-- > 0) {
2094 				int s;
2095 
2096 				if (rec->ttr_marker == TT_INTERRUPT)
2097 					printf(
2098 					    "\t\tipl %x spl %x pri %x\n",
2099 					    rec->ttr_ipl,
2100 					    rec->ttr_spl,
2101 					    rec->ttr_pri);
2102 
2103 				dumpregs(&rec->ttr_regs);
2104 
2105 				printf("\t%3s: %p\n\n", " ct",
2106 				    (void *)rec->ttr_curthread);
2107 
2108 				/*
2109 				 * print out the pc stack that we recorded
2110 				 * at trap time (if any)
2111 				 */
2112 				for (s = 0; s < rec->ttr_sdepth; s++) {
2113 					uintptr_t fullpc;
2114 
2115 					if (s >= TTR_STACK_DEPTH) {
2116 						printf("ttr_sdepth corrupt\n");
2117 						break;
2118 					}
2119 
2120 					fullpc = (uintptr_t)rec->ttr_stack[s];
2121 
2122 					sym = kobj_getsymname(fullpc, &off);
2123 					if (sym != NULL)
2124 						printf("-> %s+0x%lx()\n",
2125 						    sym, off);
2126 					else
2127 						printf("-> 0x%lx()\n", fullpc);
2128 				}
2129 				printf("\n");
2130 			}
2131 			current -= sizeof (trap_trace_rec_t);
2132 		}
2133 	}
2134 }
2135 
2136 #endif	/* TRAPTRACE */
2137 
2138 void
2139 panic_showtrap(struct panic_trap_info *tip)
2140 {
2141 	showregs(tip->trap_type, tip->trap_regs, tip->trap_addr);
2142 
2143 #if defined(TRAPTRACE)
2144 	dump_ttrace();
2145 #endif
2146 
2147 #if !defined(__xpv)
2148 	if (tip->trap_type == T_DBLFLT)
2149 		dump_tss();
2150 #endif
2151 }
2152 
2153 void
2154 panic_savetrap(panic_data_t *pdp, struct panic_trap_info *tip)
2155 {
2156 	panic_saveregs(pdp, tip->trap_regs);
2157 }
2158