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