xref: /titanic_51/usr/src/uts/i86pc/os/trap.c (revision 2a9459bdd821c1cf59590a7a9069ac9c591e8a6b)
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 #if defined(__amd64) || defined(__xpv)
1092 		/*
1093 		 * On amd64, we can get a #gp from referencing addresses
1094 		 * in the virtual address hole e.g. from a copyin or in
1095 		 * update_sregs while updating user segment registers.
1096 		 *
1097 		 * On the 32-bit hypervisor we could also generate one in
1098 		 * mfn_to_pfn by reaching around or into where the hypervisor
1099 		 * lives which is protected by segmentation.
1100 		 */
1101 
1102 		/*
1103 		 * If we're under on_trap() protection (see <sys/ontrap.h>),
1104 		 * set ot_trap and trampoline back to the on_trap() call site
1105 		 * for OT_DATA_ACCESS or OT_SEGMENT_ACCESS.
1106 		 */
1107 		if (ct->t_ontrap != NULL) {
1108 			int ttype =  ct->t_ontrap->ot_prot &
1109 			    (OT_DATA_ACCESS | OT_SEGMENT_ACCESS);
1110 
1111 			if (ttype != 0) {
1112 				ct->t_ontrap->ot_trap |= ttype;
1113 				if (tudebug)
1114 					showregs(type, rp, (caddr_t)0);
1115 				rp->r_pc = ct->t_ontrap->ot_trampoline;
1116 				goto cleanup;
1117 			}
1118 		}
1119 
1120 		/*
1121 		 * If we're under lofault protection (copyin etc.),
1122 		 * longjmp back to lofault with an EFAULT.
1123 		 */
1124 		if (ct->t_lofault) {
1125 			/*
1126 			 * Fault is not resolvable, so just return to lofault
1127 			 */
1128 			if (lodebug) {
1129 				showregs(type, rp, addr);
1130 				traceregs(rp);
1131 			}
1132 			rp->r_r0 = EFAULT;
1133 			rp->r_pc = ct->t_lofault;
1134 			goto cleanup;
1135 		}
1136 		/*FALLTHROUGH*/
1137 #endif	/* __amd64 || __xpv */
1138 	case T_SEGFLT:	/* segment not present fault */
1139 #if defined(__amd64)
1140 		/*
1141 		 * One example of this is #NP in update_sregs while
1142 		 * attempting to update a user segment register
1143 		 * that points to a descriptor that is marked not
1144 		 * present.
1145 		 */
1146 		if (ct->t_ontrap != NULL &&
1147 		    ct->t_ontrap->ot_prot & OT_SEGMENT_ACCESS) {
1148 			ct->t_ontrap->ot_trap |= OT_SEGMENT_ACCESS;
1149 			if (tudebug)
1150 				showregs(type, rp, (caddr_t)0);
1151 			rp->r_pc = ct->t_ontrap->ot_trampoline;
1152 			goto cleanup;
1153 		}
1154 #endif	/* __amd64 */
1155 		/*FALLTHROUGH*/
1156 	case T_STKFLT:	/* stack fault */
1157 	case T_TSSFLT:	/* invalid TSS fault */
1158 		if (tudebug)
1159 			showregs(type, rp, (caddr_t)0);
1160 		if (kern_gpfault(rp))
1161 			(void) die(type, rp, addr, cpuid);
1162 		goto cleanup;
1163 		/*FALLTHROUGH*/
1164 
1165 	/*
1166 	 * ONLY 32-bit PROCESSES can USE a PRIVATE LDT! 64-bit apps
1167 	 * should have no need for them, so we put a stop to it here.
1168 	 *
1169 	 * So: not-present fault is ONLY valid for 32-bit processes with
1170 	 * a private LDT trying to do a system call. Emulate it.
1171 	 *
1172 	 * #gp fault is ONLY valid for 32-bit processes also, which DO NOT
1173 	 * have a private LDT, and are trying to do a system call. Emulate it.
1174 	 */
1175 
1176 	case T_SEGFLT + USER:	/* segment not present fault */
1177 	case T_GPFLT + USER:	/* general protection violation */
1178 #ifdef _SYSCALL32_IMPL
1179 		if (p->p_model != DATAMODEL_NATIVE) {
1180 #endif /* _SYSCALL32_IMPL */
1181 		if (instr_is_lcall_syscall((caddr_t)rp->r_pc)) {
1182 			if (type == T_SEGFLT + USER)
1183 				ASSERT(p->p_ldt != NULL);
1184 
1185 			if ((p->p_ldt == NULL && type == T_GPFLT + USER) ||
1186 			    type == T_SEGFLT + USER) {
1187 
1188 			/*
1189 			 * The user attempted a system call via the obsolete
1190 			 * call gate mechanism. Because the process doesn't have
1191 			 * an LDT (i.e. the ldtr contains 0), a #gp results.
1192 			 * Emulate the syscall here, just as we do above for a
1193 			 * #np trap.
1194 			 */
1195 
1196 			/*
1197 			 * Since this is a not-present trap, rp->r_pc points to
1198 			 * the trapping lcall instruction. We need to bump it
1199 			 * to the next insn so the app can continue on.
1200 			 */
1201 			rp->r_pc += LCALLSIZE;
1202 			lwp->lwp_regs = rp;
1203 
1204 			/*
1205 			 * Normally the microstate of the LWP is forced back to
1206 			 * LMS_USER by the syscall handlers. Emulate that
1207 			 * behavior here.
1208 			 */
1209 			mstate = LMS_USER;
1210 
1211 			dosyscall();
1212 			goto out;
1213 			}
1214 		}
1215 #ifdef _SYSCALL32_IMPL
1216 		}
1217 #endif /* _SYSCALL32_IMPL */
1218 		/*
1219 		 * If the current process is using a private LDT and the
1220 		 * trapping instruction is sysenter, the sysenter instruction
1221 		 * has been disabled on the CPU because it destroys segment
1222 		 * registers. If this is the case, rewrite the instruction to
1223 		 * be a safe system call and retry it. If this occurs on a CPU
1224 		 * which doesn't even support sysenter, the result of all of
1225 		 * this will be to emulate that particular instruction.
1226 		 */
1227 		if (p->p_ldt != NULL &&
1228 		    ldt_rewrite_syscall(rp, p, X86_SEP))
1229 			goto out;
1230 
1231 		/*FALLTHROUGH*/
1232 
1233 	case T_BOUNDFLT + USER:	/* bound fault */
1234 	case T_STKFLT + USER:	/* stack fault */
1235 	case T_TSSFLT + USER:	/* invalid TSS fault */
1236 		if (tudebug)
1237 			showregs(type, rp, (caddr_t)0);
1238 		siginfo.si_signo = SIGSEGV;
1239 		siginfo.si_code  = SEGV_MAPERR;
1240 		siginfo.si_addr  = (caddr_t)rp->r_pc;
1241 		fault = FLTBOUNDS;
1242 		break;
1243 
1244 	case T_ALIGNMENT + USER:	/* user alignment error (486) */
1245 		if (tudebug)
1246 			showregs(type, rp, (caddr_t)0);
1247 		bzero(&siginfo, sizeof (siginfo));
1248 		siginfo.si_signo = SIGBUS;
1249 		siginfo.si_code = BUS_ADRALN;
1250 		siginfo.si_addr = (caddr_t)rp->r_pc;
1251 		fault = FLTACCESS;
1252 		break;
1253 
1254 	case T_SGLSTP + USER: /* single step/hw breakpoint exception */
1255 		if (tudebug && tudebugbpt)
1256 			showregs(type, rp, (caddr_t)0);
1257 
1258 		/* Was it single-stepping? */
1259 		if (lwp->lwp_pcb.pcb_drstat & DR_SINGLESTEP) {
1260 			pcb_t *pcb = &lwp->lwp_pcb;
1261 
1262 			rp->r_ps &= ~PS_T;
1263 			/*
1264 			 * If both NORMAL_STEP and WATCH_STEP are in effect,
1265 			 * give precedence to WATCH_STEP.  If neither is set,
1266 			 * user must have set the PS_T bit in %efl; treat this
1267 			 * as NORMAL_STEP.
1268 			 */
1269 			if ((fault = undo_watch_step(&siginfo)) == 0 &&
1270 			    ((pcb->pcb_flags & NORMAL_STEP) ||
1271 			    !(pcb->pcb_flags & WATCH_STEP))) {
1272 				siginfo.si_signo = SIGTRAP;
1273 				siginfo.si_code = TRAP_TRACE;
1274 				siginfo.si_addr = (caddr_t)rp->r_pc;
1275 				fault = FLTTRACE;
1276 			}
1277 			pcb->pcb_flags &= ~(NORMAL_STEP|WATCH_STEP);
1278 		} else {
1279 			cmn_err(CE_WARN,
1280 			    "Unexpected INT 1 in user mode, dr6=%lx",
1281 			    lwp->lwp_pcb.pcb_drstat);
1282 		}
1283 		break;
1284 
1285 	case T_BPTFLT + USER:	/* breakpoint trap */
1286 		if (tudebug && tudebugbpt)
1287 			showregs(type, rp, (caddr_t)0);
1288 		/*
1289 		 * int 3 (the breakpoint instruction) leaves the pc referring
1290 		 * to the address one byte after the breakpointed address.
1291 		 * If the P_PR_BPTADJ flag has been set via /proc, We adjust
1292 		 * it back so it refers to the breakpointed address.
1293 		 */
1294 		if (p->p_proc_flag & P_PR_BPTADJ)
1295 			rp->r_pc--;
1296 		siginfo.si_signo = SIGTRAP;
1297 		siginfo.si_code  = TRAP_BRKPT;
1298 		siginfo.si_addr  = (caddr_t)rp->r_pc;
1299 		fault = FLTBPT;
1300 		break;
1301 
1302 	case T_AST:
1303 		/*
1304 		 * This occurs only after the cs register has been made to
1305 		 * look like a kernel selector, either through debugging or
1306 		 * possibly by functions like setcontext().  The thread is
1307 		 * about to cause a general protection fault at common_iret()
1308 		 * in locore.  We let that happen immediately instead of
1309 		 * doing the T_AST processing.
1310 		 */
1311 		goto cleanup;
1312 
1313 	case T_AST + USER:	/* profiling, resched, h/w error pseudo trap */
1314 		if (lwp->lwp_pcb.pcb_flags & ASYNC_HWERR) {
1315 			proc_t *p = ttoproc(curthread);
1316 
1317 			lwp->lwp_pcb.pcb_flags &= ~ASYNC_HWERR;
1318 			contract_process_hwerr(p->p_ct_process, p);
1319 			siginfo.si_signo = SIGKILL;
1320 			siginfo.si_code = SI_NOINFO;
1321 		} else if (lwp->lwp_pcb.pcb_flags & CPC_OVERFLOW) {
1322 			lwp->lwp_pcb.pcb_flags &= ~CPC_OVERFLOW;
1323 			if (kcpc_overflow_ast()) {
1324 				/*
1325 				 * Signal performance counter overflow
1326 				 */
1327 				if (tudebug)
1328 					showregs(type, rp, (caddr_t)0);
1329 				bzero(&siginfo, sizeof (siginfo));
1330 				siginfo.si_signo = SIGEMT;
1331 				siginfo.si_code = EMT_CPCOVF;
1332 				siginfo.si_addr = (caddr_t)rp->r_pc;
1333 				fault = FLTCPCOVF;
1334 			}
1335 		}
1336 
1337 		break;
1338 	}
1339 
1340 	/*
1341 	 * We can't get here from a system trap
1342 	 */
1343 	ASSERT(type & USER);
1344 
1345 	if (fault) {
1346 		/* We took a fault so abort single step. */
1347 		lwp->lwp_pcb.pcb_flags &= ~(NORMAL_STEP|WATCH_STEP);
1348 		/*
1349 		 * Remember the fault and fault adddress
1350 		 * for real-time (SIGPROF) profiling.
1351 		 */
1352 		lwp->lwp_lastfault = fault;
1353 		lwp->lwp_lastfaddr = siginfo.si_addr;
1354 
1355 		DTRACE_PROC2(fault, int, fault, ksiginfo_t *, &siginfo);
1356 
1357 		/*
1358 		 * If a debugger has declared this fault to be an
1359 		 * event of interest, stop the lwp.  Otherwise just
1360 		 * deliver the associated signal.
1361 		 */
1362 		if (siginfo.si_signo != SIGKILL &&
1363 		    prismember(&p->p_fltmask, fault) &&
1364 		    stop_on_fault(fault, &siginfo) == 0)
1365 			siginfo.si_signo = 0;
1366 	}
1367 
1368 	if (siginfo.si_signo)
1369 		trapsig(&siginfo, (fault == FLTCPCOVF)? 0 : 1);
1370 
1371 	if (lwp->lwp_oweupc)
1372 		profil_tick(rp->r_pc);
1373 
1374 	if (ct->t_astflag | ct->t_sig_check) {
1375 		/*
1376 		 * Turn off the AST flag before checking all the conditions that
1377 		 * may have caused an AST.  This flag is on whenever a signal or
1378 		 * unusual condition should be handled after the next trap or
1379 		 * syscall.
1380 		 */
1381 		astoff(ct);
1382 		/*
1383 		 * If a single-step trap occurred on a syscall (see above)
1384 		 * recognize it now.  Do this before checking for signals
1385 		 * because deferred_singlestep_trap() may generate a SIGTRAP to
1386 		 * the LWP or may otherwise mark the LWP to call issig(FORREAL).
1387 		 */
1388 		if (lwp->lwp_pcb.pcb_flags & DEBUG_PENDING)
1389 			deferred_singlestep_trap((caddr_t)rp->r_pc);
1390 
1391 		ct->t_sig_check = 0;
1392 
1393 		mutex_enter(&p->p_lock);
1394 		if (curthread->t_proc_flag & TP_CHANGEBIND) {
1395 			timer_lwpbind();
1396 			curthread->t_proc_flag &= ~TP_CHANGEBIND;
1397 		}
1398 		mutex_exit(&p->p_lock);
1399 
1400 		/*
1401 		 * for kaio requests that are on the per-process poll queue,
1402 		 * aiop->aio_pollq, they're AIO_POLL bit is set, the kernel
1403 		 * should copyout their result_t to user memory. by copying
1404 		 * out the result_t, the user can poll on memory waiting
1405 		 * for the kaio request to complete.
1406 		 */
1407 		if (p->p_aio)
1408 			aio_cleanup(0);
1409 		/*
1410 		 * If this LWP was asked to hold, call holdlwp(), which will
1411 		 * stop.  holdlwps() sets this up and calls pokelwps() which
1412 		 * sets the AST flag.
1413 		 *
1414 		 * Also check TP_EXITLWP, since this is used by fresh new LWPs
1415 		 * through lwp_rtt().  That flag is set if the lwp_create(2)
1416 		 * syscall failed after creating the LWP.
1417 		 */
1418 		if (ISHOLD(p))
1419 			holdlwp();
1420 
1421 		/*
1422 		 * All code that sets signals and makes ISSIG evaluate true must
1423 		 * set t_astflag afterwards.
1424 		 */
1425 		if (ISSIG_PENDING(ct, lwp, p)) {
1426 			if (issig(FORREAL))
1427 				psig();
1428 			ct->t_sig_check = 1;
1429 		}
1430 
1431 		if (ct->t_rprof != NULL) {
1432 			realsigprof(0, 0);
1433 			ct->t_sig_check = 1;
1434 		}
1435 
1436 		/*
1437 		 * /proc can't enable/disable the trace bit itself
1438 		 * because that could race with the call gate used by
1439 		 * system calls via "lcall". If that happened, an
1440 		 * invalid EFLAGS would result. prstep()/prnostep()
1441 		 * therefore schedule an AST for the purpose.
1442 		 */
1443 		if (lwp->lwp_pcb.pcb_flags & REQUEST_STEP) {
1444 			lwp->lwp_pcb.pcb_flags &= ~REQUEST_STEP;
1445 			rp->r_ps |= PS_T;
1446 		}
1447 		if (lwp->lwp_pcb.pcb_flags & REQUEST_NOSTEP) {
1448 			lwp->lwp_pcb.pcb_flags &= ~REQUEST_NOSTEP;
1449 			rp->r_ps &= ~PS_T;
1450 		}
1451 	}
1452 
1453 out:	/* We can't get here from a system trap */
1454 	ASSERT(type & USER);
1455 
1456 	if (ISHOLD(p))
1457 		holdlwp();
1458 
1459 	/*
1460 	 * Set state to LWP_USER here so preempt won't give us a kernel
1461 	 * priority if it occurs after this point.  Call CL_TRAPRET() to
1462 	 * restore the user-level priority.
1463 	 *
1464 	 * It is important that no locks (other than spinlocks) be entered
1465 	 * after this point before returning to user mode (unless lwp_state
1466 	 * is set back to LWP_SYS).
1467 	 */
1468 	lwp->lwp_state = LWP_USER;
1469 
1470 	if (ct->t_trapret) {
1471 		ct->t_trapret = 0;
1472 		thread_lock(ct);
1473 		CL_TRAPRET(ct);
1474 		thread_unlock(ct);
1475 	}
1476 	if (CPU->cpu_runrun || curthread->t_schedflag & TS_ANYWAITQ)
1477 		preempt();
1478 	(void) new_mstate(ct, mstate);
1479 
1480 	/* Kernel probe */
1481 	TNF_PROBE_1(thread_state, "thread", /* CSTYLED */,
1482 	    tnf_microstate, state, LMS_USER);
1483 
1484 	return;
1485 
1486 cleanup:	/* system traps end up here */
1487 	ASSERT(!(type & USER));
1488 }
1489 
1490 /*
1491  * Patch non-zero to disable preemption of threads in the kernel.
1492  */
1493 int IGNORE_KERNEL_PREEMPTION = 0;	/* XXX - delete this someday */
1494 
1495 struct kpreempt_cnts {		/* kernel preemption statistics */
1496 	int	kpc_idle;	/* executing idle thread */
1497 	int	kpc_intr;	/* executing interrupt thread */
1498 	int	kpc_clock;	/* executing clock thread */
1499 	int	kpc_blocked;	/* thread has blocked preemption (t_preempt) */
1500 	int	kpc_notonproc;	/* thread is surrendering processor */
1501 	int	kpc_inswtch;	/* thread has ratified scheduling decision */
1502 	int	kpc_prilevel;	/* processor interrupt level is too high */
1503 	int	kpc_apreempt;	/* asynchronous preemption */
1504 	int	kpc_spreempt;	/* synchronous preemption */
1505 } kpreempt_cnts;
1506 
1507 /*
1508  * kernel preemption: forced rescheduling, preempt the running kernel thread.
1509  *	the argument is old PIL for an interrupt,
1510  *	or the distingished value KPREEMPT_SYNC.
1511  */
1512 void
1513 kpreempt(int asyncspl)
1514 {
1515 	kthread_t *ct = curthread;
1516 
1517 	if (IGNORE_KERNEL_PREEMPTION) {
1518 		aston(CPU->cpu_dispthread);
1519 		return;
1520 	}
1521 
1522 	/*
1523 	 * Check that conditions are right for kernel preemption
1524 	 */
1525 	do {
1526 		if (ct->t_preempt) {
1527 			/*
1528 			 * either a privileged thread (idle, panic, interrupt)
1529 			 *	or will check when t_preempt is lowered
1530 			 */
1531 			if (ct->t_pri < 0)
1532 				kpreempt_cnts.kpc_idle++;
1533 			else if (ct->t_flag & T_INTR_THREAD) {
1534 				kpreempt_cnts.kpc_intr++;
1535 				if (ct->t_pil == CLOCK_LEVEL)
1536 					kpreempt_cnts.kpc_clock++;
1537 			} else
1538 				kpreempt_cnts.kpc_blocked++;
1539 			aston(CPU->cpu_dispthread);
1540 			return;
1541 		}
1542 		if (ct->t_state != TS_ONPROC ||
1543 		    ct->t_disp_queue != CPU->cpu_disp) {
1544 			/* this thread will be calling swtch() shortly */
1545 			kpreempt_cnts.kpc_notonproc++;
1546 			if (CPU->cpu_thread != CPU->cpu_dispthread) {
1547 				/* already in swtch(), force another */
1548 				kpreempt_cnts.kpc_inswtch++;
1549 				siron();
1550 			}
1551 			return;
1552 		}
1553 		if (getpil() >= DISP_LEVEL) {
1554 			/*
1555 			 * We can't preempt this thread if it is at
1556 			 * a PIL >= DISP_LEVEL since it may be holding
1557 			 * a spin lock (like sched_lock).
1558 			 */
1559 			siron();	/* check back later */
1560 			kpreempt_cnts.kpc_prilevel++;
1561 			return;
1562 		}
1563 		if (!interrupts_enabled()) {
1564 			/*
1565 			 * Can't preempt while running with ints disabled
1566 			 */
1567 			kpreempt_cnts.kpc_prilevel++;
1568 			return;
1569 		}
1570 		if (asyncspl != KPREEMPT_SYNC)
1571 			kpreempt_cnts.kpc_apreempt++;
1572 		else
1573 			kpreempt_cnts.kpc_spreempt++;
1574 
1575 		ct->t_preempt++;
1576 		preempt();
1577 		ct->t_preempt--;
1578 	} while (CPU->cpu_kprunrun);
1579 }
1580 
1581 /*
1582  * Print out debugging info.
1583  */
1584 static void
1585 showregs(uint_t type, struct regs *rp, caddr_t addr)
1586 {
1587 	int s;
1588 
1589 	s = spl7();
1590 	type &= ~USER;
1591 	if (PTOU(curproc)->u_comm[0])
1592 		printf("%s: ", PTOU(curproc)->u_comm);
1593 	if (type < TRAP_TYPES)
1594 		printf("#%s %s\n", trap_type_mnemonic[type], trap_type[type]);
1595 	else
1596 		switch (type) {
1597 		case T_SYSCALL:
1598 			printf("Syscall Trap:\n");
1599 			break;
1600 		case T_AST:
1601 			printf("AST\n");
1602 			break;
1603 		default:
1604 			printf("Bad Trap = %d\n", type);
1605 			break;
1606 		}
1607 	if (type == T_PGFLT) {
1608 		printf("Bad %s fault at addr=0x%lx\n",
1609 		    USERMODE(rp->r_cs) ? "user": "kernel", (uintptr_t)addr);
1610 	} else if (addr) {
1611 		printf("addr=0x%lx\n", (uintptr_t)addr);
1612 	}
1613 
1614 	printf("pid=%d, pc=0x%lx, sp=0x%lx, eflags=0x%lx\n",
1615 	    (ttoproc(curthread) && ttoproc(curthread)->p_pidp) ?
1616 	    ttoproc(curthread)->p_pid : 0, rp->r_pc, rp->r_sp, rp->r_ps);
1617 
1618 #if defined(__lint)
1619 	/*
1620 	 * this clause can be deleted when lint bug 4870403 is fixed
1621 	 * (lint thinks that bit 32 is illegal in a %b format string)
1622 	 */
1623 	printf("cr0: %x cr4: %b\n",
1624 	    (uint_t)getcr0(), (uint_t)getcr4(), FMT_CR4);
1625 #else
1626 	printf("cr0: %b cr4: %b\n",
1627 	    (uint_t)getcr0(), FMT_CR0, (uint_t)getcr4(), FMT_CR4);
1628 #endif	/* __lint */
1629 
1630 	printf("cr2: %lx", getcr2());
1631 #if !defined(__xpv)
1632 	printf("cr3: %lx", getcr3());
1633 #if defined(__amd64)
1634 	printf("cr8: %lx\n", getcr8());
1635 #endif
1636 #endif
1637 	printf("\n");
1638 
1639 	dumpregs(rp);
1640 	splx(s);
1641 }
1642 
1643 static void
1644 dumpregs(struct regs *rp)
1645 {
1646 #if defined(__amd64)
1647 	const char fmt[] = "\t%3s: %16lx %3s: %16lx %3s: %16lx\n";
1648 
1649 	printf(fmt, "rdi", rp->r_rdi, "rsi", rp->r_rsi, "rdx", rp->r_rdx);
1650 	printf(fmt, "rcx", rp->r_rcx, " r8", rp->r_r8, " r9", rp->r_r9);
1651 	printf(fmt, "rax", rp->r_rax, "rbx", rp->r_rbx, "rbp", rp->r_rbp);
1652 	printf(fmt, "r10", rp->r_r10, "r11", rp->r_r11, "r12", rp->r_r12);
1653 	printf(fmt, "r13", rp->r_r13, "r14", rp->r_r14, "r15", rp->r_r15);
1654 
1655 	printf(fmt, "fsb", rdmsr(MSR_AMD_FSBASE), "gsb", rdmsr(MSR_AMD_GSBASE),
1656 	    " ds", rp->r_ds);
1657 	printf(fmt, " es", rp->r_es, " fs", rp->r_fs, " gs", rp->r_gs);
1658 
1659 	printf(fmt, "trp", rp->r_trapno, "err", rp->r_err, "rip", rp->r_rip);
1660 	printf(fmt, " cs", rp->r_cs, "rfl", rp->r_rfl, "rsp", rp->r_rsp);
1661 
1662 	printf("\t%3s: %16lx\n", " ss", rp->r_ss);
1663 
1664 #elif defined(__i386)
1665 	const char fmt[] = "\t%3s: %8lx %3s: %8lx %3s: %8lx %3s: %8lx\n";
1666 
1667 	printf(fmt, " gs", rp->r_gs, " fs", rp->r_fs,
1668 	    " es", rp->r_es, " ds", rp->r_ds);
1669 	printf(fmt, "edi", rp->r_edi, "esi", rp->r_esi,
1670 	    "ebp", rp->r_ebp, "esp", rp->r_esp);
1671 	printf(fmt, "ebx", rp->r_ebx, "edx", rp->r_edx,
1672 	    "ecx", rp->r_ecx, "eax", rp->r_eax);
1673 	printf(fmt, "trp", rp->r_trapno, "err", rp->r_err,
1674 	    "eip", rp->r_eip, " cs", rp->r_cs);
1675 	printf("\t%3s: %8lx %3s: %8lx %3s: %8lx\n",
1676 	    "efl", rp->r_efl, "usp", rp->r_uesp, " ss", rp->r_ss);
1677 
1678 #endif	/* __i386 */
1679 }
1680 
1681 /*
1682  * Test to see if the instruction is iret on i386 or iretq on amd64.
1683  *
1684  * On the hypervisor we can only test for nopop_sys_rtt_syscall. If true
1685  * then we are in the context of hypervisor's failsafe handler because it
1686  * tried to iret and failed due to a bad selector. See xen_failsafe_callback.
1687  */
1688 static int
1689 instr_is_iret(caddr_t pc)
1690 {
1691 
1692 #if defined(__xpv)
1693 	extern void nopop_sys_rtt_syscall(void);
1694 	return ((pc == (caddr_t)nopop_sys_rtt_syscall) ? 1 : 0);
1695 
1696 #else
1697 
1698 #if defined(__amd64)
1699 	static const uint8_t iret_insn[2] = { 0x48, 0xcf };	/* iretq */
1700 
1701 #elif defined(__i386)
1702 	static const uint8_t iret_insn[1] = { 0xcf };		/* iret */
1703 #endif	/* __i386 */
1704 	return (bcmp(pc, iret_insn, sizeof (iret_insn)) == 0);
1705 
1706 #endif	/* __xpv */
1707 }
1708 
1709 #if defined(__i386)
1710 
1711 /*
1712  * Test to see if the instruction is part of __SEGREGS_POP
1713  *
1714  * Note carefully the appallingly awful dependency between
1715  * the instruction sequence used in __SEGREGS_POP and these
1716  * instructions encoded here.
1717  */
1718 static int
1719 instr_is_segregs_pop(caddr_t pc)
1720 {
1721 	static const uint8_t movw_0_esp_gs[4] = { 0x8e, 0x6c, 0x24, 0x0 };
1722 	static const uint8_t movw_4_esp_fs[4] = { 0x8e, 0x64, 0x24, 0x4 };
1723 	static const uint8_t movw_8_esp_es[4] = { 0x8e, 0x44, 0x24, 0x8 };
1724 	static const uint8_t movw_c_esp_ds[4] = { 0x8e, 0x5c, 0x24, 0xc };
1725 
1726 	if (bcmp(pc, movw_0_esp_gs, sizeof (movw_0_esp_gs)) == 0 ||
1727 	    bcmp(pc, movw_4_esp_fs, sizeof (movw_4_esp_fs)) == 0 ||
1728 	    bcmp(pc, movw_8_esp_es, sizeof (movw_8_esp_es)) == 0 ||
1729 	    bcmp(pc, movw_c_esp_ds, sizeof (movw_c_esp_ds)) == 0)
1730 		return (1);
1731 
1732 	return (0);
1733 }
1734 
1735 #endif	/* __i386 */
1736 
1737 /*
1738  * Test to see if the instruction is part of _sys_rtt.
1739  *
1740  * Again on the hypervisor if we try to IRET to user land with a bad code
1741  * or stack selector we will get vectored through xen_failsafe_callback.
1742  * In which case we assume we got here via _sys_rtt since we only allow
1743  * IRET to user land to take place in _sys_rtt.
1744  */
1745 static int
1746 instr_is_sys_rtt(caddr_t pc)
1747 {
1748 	extern void _sys_rtt(), _sys_rtt_end();
1749 
1750 	if ((uintptr_t)pc < (uintptr_t)_sys_rtt ||
1751 	    (uintptr_t)pc > (uintptr_t)_sys_rtt_end)
1752 		return (0);
1753 
1754 	return (1);
1755 }
1756 
1757 /*
1758  * Handle #gp faults in kernel mode.
1759  *
1760  * One legitimate way this can happen is if we attempt to update segment
1761  * registers to naughty values on the way out of the kernel.
1762  *
1763  * This can happen in a couple of ways: someone - either accidentally or
1764  * on purpose - creates (setcontext(2), lwp_create(2)) or modifies
1765  * (signal(2)) a ucontext that contains silly segment register values.
1766  * Or someone - either accidentally or on purpose - modifies the prgregset_t
1767  * of a subject process via /proc to contain silly segment register values.
1768  *
1769  * (The unfortunate part is that we can end up discovering the bad segment
1770  * register value in the middle of an 'iret' after we've popped most of the
1771  * stack.  So it becomes quite difficult to associate an accurate ucontext
1772  * with the lwp, because the act of taking the #gp trap overwrites most of
1773  * what we were going to send the lwp.)
1774  *
1775  * OTOH if it turns out that's -not- the problem, and we're -not- an lwp
1776  * trying to return to user mode and we get a #gp fault, then we need
1777  * to die() -- which will happen if we return non-zero from this routine.
1778  */
1779 static int
1780 kern_gpfault(struct regs *rp)
1781 {
1782 	kthread_t *t = curthread;
1783 	proc_t *p = ttoproc(t);
1784 	klwp_t *lwp = ttolwp(t);
1785 	struct regs tmpregs, *trp = NULL;
1786 	caddr_t pc = (caddr_t)rp->r_pc;
1787 	int v;
1788 
1789 	/*
1790 	 * if we're not an lwp, or in the case of running native the
1791 	 * pc range is outside _sys_rtt, then we should immediately
1792 	 * be die()ing horribly.
1793 	 */
1794 	if (lwp == NULL || !instr_is_sys_rtt(pc))
1795 		return (1);
1796 
1797 	/*
1798 	 * So at least we're in the right part of the kernel.
1799 	 *
1800 	 * Disassemble the instruction at the faulting pc.
1801 	 * Once we know what it is, we carefully reconstruct the stack
1802 	 * based on the order in which the stack is deconstructed in
1803 	 * _sys_rtt. Ew.
1804 	 */
1805 	if (instr_is_iret(pc)) {
1806 		/*
1807 		 * We took the #gp while trying to perform the IRET.
1808 		 * This means that either %cs or %ss are bad.
1809 		 * All we know for sure is that most of the general
1810 		 * registers have been restored, including the
1811 		 * segment registers, and all we have left on the
1812 		 * topmost part of the lwp's stack are the
1813 		 * registers that the iretq was unable to consume.
1814 		 *
1815 		 * All the rest of the state was crushed by the #gp
1816 		 * which pushed -its- registers atop our old save area
1817 		 * (because we had to decrement the stack pointer, sigh) so
1818 		 * all that we can try and do is to reconstruct the
1819 		 * crushed frame from the #gp trap frame itself.
1820 		 */
1821 		trp = &tmpregs;
1822 		trp->r_ss = lwptoregs(lwp)->r_ss;
1823 		trp->r_sp = lwptoregs(lwp)->r_sp;
1824 		trp->r_ps = lwptoregs(lwp)->r_ps;
1825 		trp->r_cs = lwptoregs(lwp)->r_cs;
1826 		trp->r_pc = lwptoregs(lwp)->r_pc;
1827 		bcopy(rp, trp, offsetof(struct regs, r_pc));
1828 
1829 		/*
1830 		 * Validate simple math
1831 		 */
1832 		ASSERT(trp->r_pc == lwptoregs(lwp)->r_pc);
1833 		ASSERT(trp->r_err == rp->r_err);
1834 
1835 
1836 
1837 	}
1838 
1839 #if defined(__amd64)
1840 	if (trp == NULL && lwp->lwp_pcb.pcb_rupdate != 0) {
1841 
1842 		/*
1843 		 * This is the common case -- we're trying to load
1844 		 * a bad segment register value in the only section
1845 		 * of kernel code that ever loads segment registers.
1846 		 *
1847 		 * We don't need to do anything at this point because
1848 		 * the pcb contains all the pending segment register
1849 		 * state, and the regs are still intact because we
1850 		 * didn't adjust the stack pointer yet.  Given the fidelity
1851 		 * of all this, we could conceivably send a signal
1852 		 * to the lwp, rather than core-ing.
1853 		 */
1854 		trp = lwptoregs(lwp);
1855 		ASSERT((caddr_t)trp == (caddr_t)rp->r_sp);
1856 	}
1857 
1858 #elif defined(__i386)
1859 
1860 	if (trp == NULL && instr_is_segregs_pop(pc))
1861 		trp = lwptoregs(lwp);
1862 
1863 #endif	/* __i386 */
1864 
1865 	if (trp == NULL)
1866 		return (1);
1867 
1868 	/*
1869 	 * If we get to here, we're reasonably confident that we've
1870 	 * correctly decoded what happened on the way out of the kernel.
1871 	 * Rewrite the lwp's registers so that we can create a core dump
1872 	 * the (at least vaguely) represents the mcontext we were
1873 	 * being asked to restore when things went so terribly wrong.
1874 	 */
1875 
1876 	/*
1877 	 * Make sure that we have a meaningful %trapno and %err.
1878 	 */
1879 	trp->r_trapno = rp->r_trapno;
1880 	trp->r_err = rp->r_err;
1881 
1882 	if ((caddr_t)trp != (caddr_t)lwptoregs(lwp))
1883 		bcopy(trp, lwptoregs(lwp), sizeof (*trp));
1884 
1885 
1886 	mutex_enter(&p->p_lock);
1887 	lwp->lwp_cursig = SIGSEGV;
1888 	mutex_exit(&p->p_lock);
1889 
1890 	/*
1891 	 * Terminate all LWPs but don't discard them.  If another lwp beat
1892 	 * us to the punch by calling exit(), evaporate now.
1893 	 */
1894 	proc_is_exiting(p);
1895 	if (exitlwps(1) != 0) {
1896 		mutex_enter(&p->p_lock);
1897 		lwp_exit();
1898 	}
1899 
1900 #ifdef C2_AUDIT
1901 	if (audit_active)		/* audit core dump */
1902 		audit_core_start(SIGSEGV);
1903 #endif
1904 	v = core(SIGSEGV, B_FALSE);
1905 #ifdef C2_AUDIT
1906 	if (audit_active)		/* audit core dump */
1907 		audit_core_finish(v ? CLD_KILLED : CLD_DUMPED);
1908 #endif
1909 	exit(v ? CLD_KILLED : CLD_DUMPED, SIGSEGV);
1910 	return (0);
1911 }
1912 
1913 /*
1914  * dump_tss() - Display the TSS structure
1915  */
1916 
1917 #if !defined(__xpv)
1918 #if defined(__amd64)
1919 
1920 static void
1921 dump_tss(void)
1922 {
1923 	const char tss_fmt[] = "tss.%s:\t0x%p\n";  /* Format string */
1924 	struct tss *tss = CPU->cpu_tss;
1925 
1926 	printf(tss_fmt, "tss_rsp0", (void *)tss->tss_rsp0);
1927 	printf(tss_fmt, "tss_rsp1", (void *)tss->tss_rsp1);
1928 	printf(tss_fmt, "tss_rsp2", (void *)tss->tss_rsp2);
1929 
1930 	printf(tss_fmt, "tss_ist1", (void *)tss->tss_ist1);
1931 	printf(tss_fmt, "tss_ist2", (void *)tss->tss_ist2);
1932 	printf(tss_fmt, "tss_ist3", (void *)tss->tss_ist3);
1933 	printf(tss_fmt, "tss_ist4", (void *)tss->tss_ist4);
1934 	printf(tss_fmt, "tss_ist5", (void *)tss->tss_ist5);
1935 	printf(tss_fmt, "tss_ist6", (void *)tss->tss_ist6);
1936 	printf(tss_fmt, "tss_ist7", (void *)tss->tss_ist7);
1937 }
1938 
1939 #elif defined(__i386)
1940 
1941 static void
1942 dump_tss(void)
1943 {
1944 	const char tss_fmt[] = "tss.%s:\t0x%p\n";  /* Format string */
1945 	struct tss *tss = CPU->cpu_tss;
1946 
1947 	printf(tss_fmt, "tss_link", (void *)(uintptr_t)tss->tss_link);
1948 	printf(tss_fmt, "tss_esp0", (void *)(uintptr_t)tss->tss_esp0);
1949 	printf(tss_fmt, "tss_ss0", (void *)(uintptr_t)tss->tss_ss0);
1950 	printf(tss_fmt, "tss_esp1", (void *)(uintptr_t)tss->tss_esp1);
1951 	printf(tss_fmt, "tss_ss1", (void *)(uintptr_t)tss->tss_ss1);
1952 	printf(tss_fmt, "tss_esp2", (void *)(uintptr_t)tss->tss_esp2);
1953 	printf(tss_fmt, "tss_ss2", (void *)(uintptr_t)tss->tss_ss2);
1954 	printf(tss_fmt, "tss_cr3", (void *)(uintptr_t)tss->tss_cr3);
1955 	printf(tss_fmt, "tss_eip", (void *)(uintptr_t)tss->tss_eip);
1956 	printf(tss_fmt, "tss_eflags", (void *)(uintptr_t)tss->tss_eflags);
1957 	printf(tss_fmt, "tss_eax", (void *)(uintptr_t)tss->tss_eax);
1958 	printf(tss_fmt, "tss_ebx", (void *)(uintptr_t)tss->tss_ebx);
1959 	printf(tss_fmt, "tss_ecx", (void *)(uintptr_t)tss->tss_ecx);
1960 	printf(tss_fmt, "tss_edx", (void *)(uintptr_t)tss->tss_edx);
1961 	printf(tss_fmt, "tss_esp", (void *)(uintptr_t)tss->tss_esp);
1962 }
1963 
1964 #endif	/* __amd64 */
1965 #endif	/* !__xpv */
1966 
1967 #if defined(TRAPTRACE)
1968 
1969 int ttrace_nrec = 10;		/* number of records to dump out */
1970 int ttrace_dump_nregs = 0;	/* dump out this many records with regs too */
1971 
1972 /*
1973  * Dump out the last ttrace_nrec traptrace records on each CPU
1974  */
1975 static void
1976 dump_ttrace(void)
1977 {
1978 	trap_trace_ctl_t *ttc;
1979 	trap_trace_rec_t *rec;
1980 	uintptr_t current;
1981 	int i, j, k;
1982 	int n = NCPU;
1983 #if defined(__amd64)
1984 	const char banner[] =
1985 	    "\ncpu          address    timestamp "
1986 	    "type  vc  handler   pc\n";
1987 	const char fmt1[] = "%3d %016lx %12llx ";
1988 #elif defined(__i386)
1989 	const char banner[] =
1990 	    "\ncpu  address     timestamp type  vc  handler   pc\n";
1991 	const char fmt1[] = "%3d %08lx %12llx ";
1992 #endif
1993 	const char fmt2[] = "%4s %3x ";
1994 	const char fmt3[] = "%8s ";
1995 
1996 	if (ttrace_nrec == 0)
1997 		return;
1998 
1999 	printf(banner);
2000 
2001 	for (i = 0; i < n; i++) {
2002 		ttc = &trap_trace_ctl[i];
2003 		if (ttc->ttc_first == NULL)
2004 			continue;
2005 
2006 		current = ttc->ttc_next - sizeof (trap_trace_rec_t);
2007 		for (j = 0; j < ttrace_nrec; j++) {
2008 			struct sysent	*sys;
2009 			struct autovec	*vec;
2010 			extern struct av_head autovect[];
2011 			int type;
2012 			ulong_t	off;
2013 			char *sym, *stype;
2014 
2015 			if (current < ttc->ttc_first)
2016 				current =
2017 				    ttc->ttc_limit - sizeof (trap_trace_rec_t);
2018 
2019 			if (current == NULL)
2020 				continue;
2021 
2022 			rec = (trap_trace_rec_t *)current;
2023 
2024 			if (rec->ttr_stamp == 0)
2025 				break;
2026 
2027 			printf(fmt1, i, (uintptr_t)rec, rec->ttr_stamp);
2028 
2029 			switch (rec->ttr_marker) {
2030 			case TT_SYSCALL:
2031 			case TT_SYSENTER:
2032 			case TT_SYSC:
2033 			case TT_SYSC64:
2034 #if defined(__amd64)
2035 				sys = &sysent32[rec->ttr_sysnum];
2036 				switch (rec->ttr_marker) {
2037 				case TT_SYSC64:
2038 					sys = &sysent[rec->ttr_sysnum];
2039 					/*FALLTHROUGH*/
2040 #elif defined(__i386)
2041 				sys = &sysent[rec->ttr_sysnum];
2042 				switch (rec->ttr_marker) {
2043 				case TT_SYSC64:
2044 #endif
2045 				case TT_SYSC:
2046 					stype = "sysc";	/* syscall */
2047 					break;
2048 				case TT_SYSCALL:
2049 					stype = "lcal";	/* lcall */
2050 					break;
2051 				case TT_SYSENTER:
2052 					stype = "syse";	/* sysenter */
2053 					break;
2054 				default:
2055 					break;
2056 				}
2057 				printf(fmt2, "sysc", rec->ttr_sysnum);
2058 				if (sys != NULL) {
2059 					sym = kobj_getsymname(
2060 					    (uintptr_t)sys->sy_callc,
2061 					    &off);
2062 					if (sym != NULL)
2063 						printf(fmt3, sym);
2064 					else
2065 						printf("%p ", sys->sy_callc);
2066 				} else {
2067 					printf(fmt3, "unknown");
2068 				}
2069 				break;
2070 
2071 			case TT_INTERRUPT:
2072 				printf(fmt2, "intr", rec->ttr_vector);
2073 				vec = (&autovect[rec->ttr_vector])->avh_link;
2074 				if (vec != NULL) {
2075 					sym = kobj_getsymname(
2076 					    (uintptr_t)vec->av_vector, &off);
2077 					if (sym != NULL)
2078 						printf(fmt3, sym);
2079 					else
2080 						printf("%p ", vec->av_vector);
2081 				} else {
2082 					printf(fmt3, "unknown ");
2083 				}
2084 				break;
2085 
2086 			case TT_TRAP:
2087 			case TT_EVENT:
2088 				type = rec->ttr_regs.r_trapno;
2089 				printf(fmt2, "trap", type);
2090 				if (type < TRAP_TYPES)
2091 					printf("     #%s ",
2092 					    trap_type_mnemonic[type]);
2093 				else
2094 					switch (type) {
2095 					case T_AST:
2096 						printf(fmt3, "ast");
2097 						break;
2098 					default:
2099 						printf(fmt3, "");
2100 						break;
2101 					}
2102 				break;
2103 
2104 			case TT_XCALL:
2105 				printf(fmt2, "xcal",
2106 				    rec->ttr_info.xc_entry.xce_marker);
2107 				printf(fmt3, "");
2108 				break;
2109 
2110 			default:
2111 				break;
2112 			}
2113 
2114 			sym = kobj_getsymname(rec->ttr_regs.r_pc, &off);
2115 			if (sym != NULL)
2116 				printf("%s+%lx\n", sym, off);
2117 			else
2118 				printf("%lx\n", rec->ttr_regs.r_pc);
2119 
2120 			if (ttrace_dump_nregs-- > 0) {
2121 				int s;
2122 
2123 				if (rec->ttr_marker == TT_INTERRUPT)
2124 					printf(
2125 					    "\t\tipl %x spl %x pri %x\n",
2126 					    rec->ttr_ipl,
2127 					    rec->ttr_spl,
2128 					    rec->ttr_pri);
2129 
2130 				dumpregs(&rec->ttr_regs);
2131 
2132 				printf("\t%3s: %p\n\n", " ct",
2133 				    (void *)rec->ttr_curthread);
2134 
2135 				/*
2136 				 * print out the pc stack that we recorded
2137 				 * at trap time (if any)
2138 				 */
2139 				for (s = 0; s < rec->ttr_sdepth; s++) {
2140 					uintptr_t fullpc;
2141 
2142 					if (s >= TTR_STACK_DEPTH) {
2143 						printf("ttr_sdepth corrupt\n");
2144 						break;
2145 					}
2146 
2147 					fullpc = (uintptr_t)rec->ttr_stack[s];
2148 
2149 					sym = kobj_getsymname(fullpc, &off);
2150 					if (sym != NULL)
2151 						printf("-> %s+0x%lx()\n",
2152 						    sym, off);
2153 					else
2154 						printf("-> 0x%lx()\n", fullpc);
2155 				}
2156 				printf("\n");
2157 			}
2158 			current -= sizeof (trap_trace_rec_t);
2159 		}
2160 	}
2161 }
2162 
2163 /*
2164  * Help with constructing traptrace records in C
2165  */
2166 trap_trace_rec_t *
2167 trap_trace_get_traceptr(uint8_t marker, ulong_t pc, ulong_t sp)
2168 {
2169 	trap_trace_rec_t *ttr;
2170 
2171 	if (trap_trace_freeze)
2172 		ttr = &trap_trace_postmort;
2173 	else {
2174 		trap_trace_ctl_t *ttc = &trap_trace_ctl[CPU->cpu_id];
2175 
2176 		ttr = (void *)ttc->ttc_next;
2177 
2178 		if (ttc->ttc_next >= ttc->ttc_limit)
2179 			ttc->ttc_next = ttc->ttc_first;
2180 		else
2181 			ttc->ttc_next += sizeof (trap_trace_rec_t);
2182 	}
2183 
2184 	ttr->ttr_regs.r_sp = sp;
2185 	ttr->ttr_regs.r_pc = pc;
2186 	ttr->ttr_cr2 = getcr2();
2187 	ttr->ttr_curthread = (uintptr_t)curthread;
2188 	ttr->ttr_stamp = tsc_read();
2189 	ttr->ttr_marker = marker;
2190 	return (ttr);
2191 }
2192 
2193 #endif	/* TRAPTRACE */
2194 
2195 void
2196 panic_showtrap(struct panic_trap_info *tip)
2197 {
2198 	showregs(tip->trap_type, tip->trap_regs, tip->trap_addr);
2199 
2200 #if defined(TRAPTRACE)
2201 	dump_ttrace();
2202 #endif
2203 
2204 #if !defined(__xpv)
2205 	if (tip->trap_type == T_DBLFLT)
2206 		dump_tss();
2207 #endif
2208 }
2209 
2210 void
2211 panic_savetrap(panic_data_t *pdp, struct panic_trap_info *tip)
2212 {
2213 	panic_saveregs(pdp, tip->trap_regs);
2214 }
2215