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