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