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