xref: /titanic_51/usr/src/uts/i86pc/os/trap.c (revision c81d47afd05baeb768e2f032636019b717899efd)
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 		/* We took a fault so abort single step. */
1282 		lwp->lwp_pcb.pcb_flags &= ~(NORMAL_STEP|WATCH_STEP);
1283 		/*
1284 		 * Remember the fault and fault adddress
1285 		 * for real-time (SIGPROF) profiling.
1286 		 */
1287 		lwp->lwp_lastfault = fault;
1288 		lwp->lwp_lastfaddr = siginfo.si_addr;
1289 
1290 		DTRACE_PROC2(fault, int, fault, ksiginfo_t *, &siginfo);
1291 
1292 		/*
1293 		 * If a debugger has declared this fault to be an
1294 		 * event of interest, stop the lwp.  Otherwise just
1295 		 * deliver the associated signal.
1296 		 */
1297 		if (siginfo.si_signo != SIGKILL &&
1298 		    prismember(&p->p_fltmask, fault) &&
1299 		    stop_on_fault(fault, &siginfo) == 0)
1300 			siginfo.si_signo = 0;
1301 	}
1302 
1303 	if (siginfo.si_signo)
1304 		trapsig(&siginfo, (fault == FLTCPCOVF)? 0 : 1);
1305 
1306 	if (lwp->lwp_oweupc)
1307 		profil_tick(rp->r_pc);
1308 
1309 	if (ct->t_astflag | ct->t_sig_check) {
1310 		/*
1311 		 * Turn off the AST flag before checking all the conditions that
1312 		 * may have caused an AST.  This flag is on whenever a signal or
1313 		 * unusual condition should be handled after the next trap or
1314 		 * syscall.
1315 		 */
1316 		astoff(ct);
1317 		/*
1318 		 * If a single-step trap occurred on a syscall (see above)
1319 		 * recognize it now.  Do this before checking for signals
1320 		 * because deferred_singlestep_trap() may generate a SIGTRAP to
1321 		 * the LWP or may otherwise mark the LWP to call issig(FORREAL).
1322 		 */
1323 		if (lwp->lwp_pcb.pcb_flags & DEBUG_PENDING)
1324 			deferred_singlestep_trap((caddr_t)rp->r_pc);
1325 
1326 		ct->t_sig_check = 0;
1327 
1328 		mutex_enter(&p->p_lock);
1329 		if (curthread->t_proc_flag & TP_CHANGEBIND) {
1330 			timer_lwpbind();
1331 			curthread->t_proc_flag &= ~TP_CHANGEBIND;
1332 		}
1333 		mutex_exit(&p->p_lock);
1334 
1335 		/*
1336 		 * for kaio requests that are on the per-process poll queue,
1337 		 * aiop->aio_pollq, they're AIO_POLL bit is set, the kernel
1338 		 * should copyout their result_t to user memory. by copying
1339 		 * out the result_t, the user can poll on memory waiting
1340 		 * for the kaio request to complete.
1341 		 */
1342 		if (p->p_aio)
1343 			aio_cleanup(0);
1344 		/*
1345 		 * If this LWP was asked to hold, call holdlwp(), which will
1346 		 * stop.  holdlwps() sets this up and calls pokelwps() which
1347 		 * sets the AST flag.
1348 		 *
1349 		 * Also check TP_EXITLWP, since this is used by fresh new LWPs
1350 		 * through lwp_rtt().  That flag is set if the lwp_create(2)
1351 		 * syscall failed after creating the LWP.
1352 		 */
1353 		if (ISHOLD(p))
1354 			holdlwp();
1355 
1356 		/*
1357 		 * All code that sets signals and makes ISSIG evaluate true must
1358 		 * set t_astflag afterwards.
1359 		 */
1360 		if (ISSIG_PENDING(ct, lwp, p)) {
1361 			if (issig(FORREAL))
1362 				psig();
1363 			ct->t_sig_check = 1;
1364 		}
1365 
1366 		if (ct->t_rprof != NULL) {
1367 			realsigprof(0, 0);
1368 			ct->t_sig_check = 1;
1369 		}
1370 
1371 		/*
1372 		 * /proc can't enable/disable the trace bit itself
1373 		 * because that could race with the call gate used by
1374 		 * system calls via "lcall". If that happened, an
1375 		 * invalid EFLAGS would result. prstep()/prnostep()
1376 		 * therefore schedule an AST for the purpose.
1377 		 */
1378 		if (lwp->lwp_pcb.pcb_flags & REQUEST_STEP) {
1379 			lwp->lwp_pcb.pcb_flags &= ~REQUEST_STEP;
1380 			rp->r_ps |= PS_T;
1381 		}
1382 		if (lwp->lwp_pcb.pcb_flags & REQUEST_NOSTEP) {
1383 			lwp->lwp_pcb.pcb_flags &= ~REQUEST_NOSTEP;
1384 			rp->r_ps &= ~PS_T;
1385 		}
1386 	}
1387 
1388 out:	/* We can't get here from a system trap */
1389 	ASSERT(type & USER);
1390 
1391 	if (ISHOLD(p))
1392 		holdlwp();
1393 
1394 	/*
1395 	 * Set state to LWP_USER here so preempt won't give us a kernel
1396 	 * priority if it occurs after this point.  Call CL_TRAPRET() to
1397 	 * restore the user-level priority.
1398 	 *
1399 	 * It is important that no locks (other than spinlocks) be entered
1400 	 * after this point before returning to user mode (unless lwp_state
1401 	 * is set back to LWP_SYS).
1402 	 */
1403 	lwp->lwp_state = LWP_USER;
1404 
1405 	if (ct->t_trapret) {
1406 		ct->t_trapret = 0;
1407 		thread_lock(ct);
1408 		CL_TRAPRET(ct);
1409 		thread_unlock(ct);
1410 	}
1411 	if (CPU->cpu_runrun)
1412 		preempt();
1413 	(void) new_mstate(ct, mstate);
1414 
1415 	/* Kernel probe */
1416 	TNF_PROBE_1(thread_state, "thread", /* CSTYLED */,
1417 	    tnf_microstate, state, LMS_USER);
1418 
1419 	return;
1420 
1421 cleanup:	/* system traps end up here */
1422 	ASSERT(!(type & USER));
1423 }
1424 
1425 /*
1426  * Patch non-zero to disable preemption of threads in the kernel.
1427  */
1428 int IGNORE_KERNEL_PREEMPTION = 0;	/* XXX - delete this someday */
1429 
1430 struct kpreempt_cnts {		/* kernel preemption statistics */
1431 	int	kpc_idle;	/* executing idle thread */
1432 	int	kpc_intr;	/* executing interrupt thread */
1433 	int	kpc_clock;	/* executing clock thread */
1434 	int	kpc_blocked;	/* thread has blocked preemption (t_preempt) */
1435 	int	kpc_notonproc;	/* thread is surrendering processor */
1436 	int	kpc_inswtch;	/* thread has ratified scheduling decision */
1437 	int	kpc_prilevel;	/* processor interrupt level is too high */
1438 	int	kpc_apreempt;	/* asynchronous preemption */
1439 	int	kpc_spreempt;	/* synchronous preemption */
1440 } kpreempt_cnts;
1441 
1442 /*
1443  * kernel preemption: forced rescheduling, preempt the running kernel thread.
1444  *	the argument is old PIL for an interrupt,
1445  *	or the distingished value KPREEMPT_SYNC.
1446  */
1447 void
1448 kpreempt(int asyncspl)
1449 {
1450 	kthread_t *ct = curthread;
1451 
1452 	if (IGNORE_KERNEL_PREEMPTION) {
1453 		aston(CPU->cpu_dispthread);
1454 		return;
1455 	}
1456 
1457 	/*
1458 	 * Check that conditions are right for kernel preemption
1459 	 */
1460 	do {
1461 		if (ct->t_preempt) {
1462 			/*
1463 			 * either a privileged thread (idle, panic, interrupt)
1464 			 *	or will check when t_preempt is lowered
1465 			 */
1466 			if (ct->t_pri < 0)
1467 				kpreempt_cnts.kpc_idle++;
1468 			else if (ct->t_flag & T_INTR_THREAD) {
1469 				kpreempt_cnts.kpc_intr++;
1470 				if (ct->t_pil == CLOCK_LEVEL)
1471 					kpreempt_cnts.kpc_clock++;
1472 			} else
1473 				kpreempt_cnts.kpc_blocked++;
1474 			aston(CPU->cpu_dispthread);
1475 			return;
1476 		}
1477 		if (ct->t_state != TS_ONPROC ||
1478 		    ct->t_disp_queue != CPU->cpu_disp) {
1479 			/* this thread will be calling swtch() shortly */
1480 			kpreempt_cnts.kpc_notonproc++;
1481 			if (CPU->cpu_thread != CPU->cpu_dispthread) {
1482 				/* already in swtch(), force another */
1483 				kpreempt_cnts.kpc_inswtch++;
1484 				siron();
1485 			}
1486 			return;
1487 		}
1488 		if (getpil() >= DISP_LEVEL) {
1489 			/*
1490 			 * We can't preempt this thread if it is at
1491 			 * a PIL >= DISP_LEVEL since it may be holding
1492 			 * a spin lock (like sched_lock).
1493 			 */
1494 			siron();	/* check back later */
1495 			kpreempt_cnts.kpc_prilevel++;
1496 			return;
1497 		}
1498 		if (!interrupts_enabled()) {
1499 			/*
1500 			 * Can't preempt while running with ints disabled
1501 			 */
1502 			kpreempt_cnts.kpc_prilevel++;
1503 			return;
1504 		}
1505 		if (asyncspl != KPREEMPT_SYNC)
1506 			kpreempt_cnts.kpc_apreempt++;
1507 		else
1508 			kpreempt_cnts.kpc_spreempt++;
1509 
1510 		ct->t_preempt++;
1511 		preempt();
1512 		ct->t_preempt--;
1513 	} while (CPU->cpu_kprunrun);
1514 }
1515 
1516 /*
1517  * Print out debugging info.
1518  */
1519 static void
1520 showregs(uint_t type, struct regs *rp, caddr_t addr)
1521 {
1522 	int s;
1523 
1524 	s = spl7();
1525 	type &= ~USER;
1526 	if (PTOU(curproc)->u_comm[0])
1527 		printf("%s: ", PTOU(curproc)->u_comm);
1528 	if (type < TRAP_TYPES)
1529 		printf("#%s %s\n", trap_type_mnemonic[type], trap_type[type]);
1530 	else
1531 		switch (type) {
1532 		case T_SYSCALL:
1533 			printf("Syscall Trap:\n");
1534 			break;
1535 		case T_AST:
1536 			printf("AST\n");
1537 			break;
1538 		default:
1539 			printf("Bad Trap = %d\n", type);
1540 			break;
1541 		}
1542 	if (type == T_PGFLT) {
1543 		printf("Bad %s fault at addr=0x%lx\n",
1544 		    USERMODE(rp->r_cs) ? "user": "kernel", (uintptr_t)addr);
1545 	} else if (addr) {
1546 		printf("addr=0x%lx\n", (uintptr_t)addr);
1547 	}
1548 
1549 	printf("pid=%d, pc=0x%lx, sp=0x%lx, eflags=0x%lx\n",
1550 	    (ttoproc(curthread) && ttoproc(curthread)->p_pidp) ?
1551 	    ttoproc(curthread)->p_pid : 0, rp->r_pc, rp->r_sp, rp->r_ps);
1552 
1553 #if defined(__lint)
1554 	/*
1555 	 * this clause can be deleted when lint bug 4870403 is fixed
1556 	 * (lint thinks that bit 32 is illegal in a %b format string)
1557 	 */
1558 	printf("cr0: %x cr4: %b\n",
1559 	    (uint_t)getcr0(), (uint_t)getcr4(), FMT_CR4);
1560 #else
1561 	printf("cr0: %b cr4: %b\n",
1562 	    (uint_t)getcr0(), FMT_CR0, (uint_t)getcr4(), FMT_CR4);
1563 #endif	/* __lint */
1564 
1565 #if defined(__amd64)
1566 	printf("cr2: %lx cr3: %lx cr8: %lx\n", getcr2(), getcr3(), getcr8());
1567 #elif defined(__i386)
1568 	printf("cr2: %lx cr3: %lx\n", getcr2(), getcr3());
1569 #endif
1570 
1571 	dumpregs(rp);
1572 	splx(s);
1573 }
1574 
1575 static void
1576 dumpregs(struct regs *rp)
1577 {
1578 #if defined(__amd64)
1579 	const char fmt[] = "\t%3s: %16lx %3s: %16lx %3s: %16lx\n";
1580 
1581 	printf(fmt, "rdi", rp->r_rdi, "rsi", rp->r_rsi, "rdx", rp->r_rdx);
1582 	printf(fmt, "rcx", rp->r_rcx, " r8", rp->r_r8, " r9", rp->r_r9);
1583 	printf(fmt, "rax", rp->r_rax, "rbx", rp->r_rbx, "rbp", rp->r_rbp);
1584 	printf(fmt, "r10", rp->r_r10, "r11", rp->r_r11, "r12", rp->r_r12);
1585 	printf(fmt, "r13", rp->r_r13, "r14", rp->r_r14, "r15", rp->r_r15);
1586 
1587 	printf(fmt, "fsb", rdmsr(MSR_AMD_FSBASE), "gsb", rdmsr(MSR_AMD_GSBASE),
1588 	    " ds", rp->r_ds);
1589 	printf(fmt, " es", rp->r_es, " fs", rp->r_fs, " gs", rp->r_gs);
1590 
1591 	printf(fmt, "trp", rp->r_trapno, "err", rp->r_err, "rip", rp->r_rip);
1592 	printf(fmt, " cs", rp->r_cs, "rfl", rp->r_rfl, "rsp", rp->r_rsp);
1593 
1594 	printf("\t%3s: %16lx\n", " ss", rp->r_ss);
1595 
1596 #elif defined(__i386)
1597 	const char fmt[] = "\t%3s: %8lx %3s: %8lx %3s: %8lx %3s: %8lx\n";
1598 
1599 	printf(fmt, " gs", rp->r_gs, " fs", rp->r_fs,
1600 	    " es", rp->r_es, " ds", rp->r_ds);
1601 	printf(fmt, "edi", rp->r_edi, "esi", rp->r_esi,
1602 	    "ebp", rp->r_ebp, "esp", rp->r_esp);
1603 	printf(fmt, "ebx", rp->r_ebx, "edx", rp->r_edx,
1604 	    "ecx", rp->r_ecx, "eax", rp->r_eax);
1605 	printf(fmt, "trp", rp->r_trapno, "err", rp->r_err,
1606 	    "eip", rp->r_eip, " cs", rp->r_cs);
1607 	printf("\t%3s: %8lx %3s: %8lx %3s: %8lx\n",
1608 	    "efl", rp->r_efl, "usp", rp->r_uesp, " ss", rp->r_ss);
1609 
1610 #endif	/* __i386 */
1611 }
1612 
1613 /*
1614  * Handle #gp faults in kernel mode.
1615  *
1616  * One legitimate way this can happen is if we attempt to update segment
1617  * registers to naughty values on the way out of the kernel.
1618  *
1619  * This can happen in a couple of ways: someone - either accidentally or
1620  * on purpose - creates (setcontext(2), lwp_create(2)) or modifies
1621  * (signal(2)) a ucontext that contains silly segment register values.
1622  * Or someone - either accidentally or on purpose - modifies the prgregset_t
1623  * of a subject process via /proc to contain silly segment register values.
1624  *
1625  * (The unfortunate part is that we can end up discovering the bad segment
1626  * register value in the middle of an 'iret' after we've popped most of the
1627  * stack.  So it becomes quite difficult to associate an accurate ucontext
1628  * with the lwp, because the act of taking the #gp trap overwrites most of
1629  * what we were going to send the lwp.)
1630  *
1631  * OTOH if it turns out that's -not- the problem, and we're -not- an lwp
1632  * trying to return to user mode and we get a #gp fault, then we need
1633  * to die() -- which will happen if we return non-zero from this routine.
1634  */
1635 static int
1636 kern_gpfault(struct regs *rp)
1637 {
1638 	kthread_t *t = curthread;
1639 	proc_t *p = ttoproc(t);
1640 	klwp_t *lwp = ttolwp(t);
1641 	struct regs tmpregs, *trp = NULL;
1642 	caddr_t pc = (caddr_t)rp->r_pc;
1643 	int v;
1644 
1645 	extern void _sys_rtt(), sr_sup();
1646 
1647 #if defined(__amd64)
1648 	static const uint8_t iretq_insn[2] = { 0x48, 0xcf };
1649 
1650 #elif defined(__i386)
1651 	static const uint8_t iret_insn[1] = { 0xcf };
1652 
1653 	/*
1654 	 * Note carefully the appallingly awful dependency between
1655 	 * the instruction sequence used in __SEGREGS_POP and these
1656 	 * instructions encoded here.
1657 	 *
1658 	 * XX64	Add some commentary to locore.s/privregs.h to document this.
1659 	 */
1660 	static const uint8_t movw_0_esp_gs[4] = { 0x8e, 0x6c, 0x24, 0x0 };
1661 	static const uint8_t movw_4_esp_fs[4] = { 0x8e, 0x64, 0x24, 0x4 };
1662 	static const uint8_t movw_8_esp_es[4] = { 0x8e, 0x44, 0x24, 0x8 };
1663 	static const uint8_t movw_c_esp_ds[4] = { 0x8e, 0x5c, 0x24, 0xc };
1664 #endif
1665 	/*
1666 	 * if we're not an lwp, or the pc range is outside _sys_rtt, then
1667 	 * we should immediately be die()ing horribly
1668 	 */
1669 	if (lwp == NULL ||
1670 	    (uintptr_t)pc < (uintptr_t)_sys_rtt ||
1671 	    (uintptr_t)pc > (uintptr_t)sr_sup)
1672 		return (1);
1673 
1674 	/*
1675 	 * So at least we're in the right part of the kernel.
1676 	 *
1677 	 * Disassemble the instruction at the faulting pc.
1678 	 * Once we know what it is, we carefully reconstruct the stack
1679 	 * based on the order in which the stack is deconstructed in
1680 	 * _sys_rtt. Ew.
1681 	 */
1682 
1683 #if defined(__amd64)
1684 
1685 	if (bcmp(pc, iretq_insn, sizeof (iretq_insn)) == 0) {
1686 		/*
1687 		 * We took the #gp while trying to perform the iretq.
1688 		 * This means that either %cs or %ss are bad.
1689 		 * All we know for sure is that most of the general
1690 		 * registers have been restored, including the
1691 		 * segment registers, and all we have left on the
1692 		 * topmost part of the lwp's stack are the
1693 		 * registers that the iretq was unable to consume.
1694 		 *
1695 		 * All the rest of the state was crushed by the #gp
1696 		 * which pushed -its- registers atop our old save area
1697 		 * (because we had to decrement the stack pointer, sigh) so
1698 		 * all that we can try and do is to reconstruct the
1699 		 * crushed frame from the #gp trap frame itself.
1700 		 */
1701 		trp = &tmpregs;
1702 		trp->r_ss = lwptoregs(lwp)->r_ss;
1703 		trp->r_sp = lwptoregs(lwp)->r_sp;
1704 		trp->r_ps = lwptoregs(lwp)->r_ps;
1705 		trp->r_cs = lwptoregs(lwp)->r_cs;
1706 		trp->r_pc = lwptoregs(lwp)->r_pc;
1707 		bcopy(rp, trp, offsetof(struct regs, r_pc));
1708 
1709 		/*
1710 		 * Validate simple math
1711 		 */
1712 		ASSERT(trp->r_pc == lwptoregs(lwp)->r_pc);
1713 		ASSERT(trp->r_err == rp->r_err);
1714 
1715 	}
1716 
1717 #elif defined(__i386)
1718 
1719 	if (bcmp(pc, iret_insn, sizeof (iret_insn)) == 0) {
1720 		/*
1721 		 * We took the #gp while trying to perform the iret.
1722 		 * This means that either %cs or %ss are bad.
1723 		 * All we know for sure is that most of the general
1724 		 * registers have been restored, including the
1725 		 * segment registers, and all we have left on the
1726 		 * topmost part of the lwp's stack are the registers that
1727 		 * the iret was unable to consume.
1728 		 *
1729 		 * All the rest of the state was crushed by the #gp
1730 		 * which pushed -its- registers atop our old save area
1731 		 * (because we had to decrement the stack pointer, sigh) so
1732 		 * all that we can try and do is to reconstruct the
1733 		 * crushed frame from the #gp trap frame itself.
1734 		 */
1735 		trp = &tmpregs;
1736 		trp->r_ss = lwptoregs(lwp)->r_ss;
1737 		trp->r_sp = lwptoregs(lwp)->r_sp;
1738 		trp->r_ps = lwptoregs(lwp)->r_ps;
1739 		trp->r_cs = lwptoregs(lwp)->r_cs;
1740 		trp->r_pc = lwptoregs(lwp)->r_pc;
1741 		bcopy(rp, trp, offsetof(struct regs, r_pc));
1742 
1743 		ASSERT(trp->r_pc == lwptoregs(lwp)->r_pc);
1744 		ASSERT(trp->r_err == rp->r_err);
1745 
1746 	} else {
1747 		/*
1748 		 * Segment registers are reloaded in _sys_rtt
1749 		 * via the following sequence:
1750 		 *
1751 		 *	movw	0(%esp), %gs
1752 		 *	movw	4(%esp), %fs
1753 		 *	movw	8(%esp), %es
1754 		 *	movw	12(%esp), %ds
1755 		 *	addl	$16, %esp
1756 		 *
1757 		 * Thus if any of them fault, we know the user
1758 		 * registers are left unharmed on the stack.
1759 		 */
1760 		if (bcmp(pc, movw_0_esp_gs, sizeof (movw_0_esp_gs)) == 0 ||
1761 		    bcmp(pc, movw_4_esp_fs, sizeof (movw_4_esp_fs)) == 0 ||
1762 		    bcmp(pc, movw_8_esp_es, sizeof (movw_8_esp_es)) == 0 ||
1763 		    bcmp(pc, movw_c_esp_ds, sizeof (movw_c_esp_ds)) == 0)
1764 			trp = lwptoregs(lwp);
1765 	}
1766 #endif	/* __amd64 */
1767 
1768 	if (trp == NULL)
1769 		return (1);
1770 
1771 	/*
1772 	 * If we get to here, we're reasonably confident that we've
1773 	 * correctly decoded what happened on the way out of the kernel.
1774 	 * Rewrite the lwp's registers so that we can create a core dump
1775 	 * the (at least vaguely) represents the mcontext we were
1776 	 * being asked to restore when things went so terribly wrong.
1777 	 */
1778 
1779 	/*
1780 	 * Make sure that we have a meaningful %trapno and %err.
1781 	 */
1782 	trp->r_trapno = rp->r_trapno;
1783 	trp->r_err = rp->r_err;
1784 
1785 	if ((caddr_t)trp != (caddr_t)lwptoregs(lwp))
1786 		bcopy(trp, lwptoregs(lwp), sizeof (*trp));
1787 
1788 	mutex_enter(&p->p_lock);
1789 	lwp->lwp_cursig = SIGSEGV;
1790 	mutex_exit(&p->p_lock);
1791 
1792 	/*
1793 	 * Terminate all LWPs but don't discard them.  If another lwp beat us to
1794 	 * the punch by calling exit(), evaporate now.
1795 	 */
1796 	proc_is_exiting(p);
1797 	if (exitlwps(1) != 0) {
1798 		mutex_enter(&p->p_lock);
1799 		lwp_exit();
1800 	}
1801 
1802 #ifdef C2_AUDIT
1803 	if (audit_active)		/* audit core dump */
1804 		audit_core_start(SIGSEGV);
1805 #endif
1806 	v = core(SIGSEGV, B_FALSE);
1807 #ifdef C2_AUDIT
1808 	if (audit_active)		/* audit core dump */
1809 		audit_core_finish(v ? CLD_KILLED : CLD_DUMPED);
1810 #endif
1811 	exit(v ? CLD_KILLED : CLD_DUMPED, SIGSEGV);
1812 	return (0);
1813 }
1814 
1815 /*
1816  * dump_tss() - Display the TSS structure
1817  */
1818 
1819 #if defined(__amd64)
1820 
1821 static void
1822 dump_tss(void)
1823 {
1824 	const char tss_fmt[] = "tss.%s:\t0x%p\n";  /* Format string */
1825 	struct tss *tss = CPU->cpu_tss;
1826 
1827 	printf(tss_fmt, "tss_rsp0", (void *)tss->tss_rsp0);
1828 	printf(tss_fmt, "tss_rsp1", (void *)tss->tss_rsp1);
1829 	printf(tss_fmt, "tss_rsp2", (void *)tss->tss_rsp2);
1830 
1831 	printf(tss_fmt, "tss_ist1", (void *)tss->tss_ist1);
1832 	printf(tss_fmt, "tss_ist2", (void *)tss->tss_ist2);
1833 	printf(tss_fmt, "tss_ist3", (void *)tss->tss_ist3);
1834 	printf(tss_fmt, "tss_ist4", (void *)tss->tss_ist4);
1835 	printf(tss_fmt, "tss_ist5", (void *)tss->tss_ist5);
1836 	printf(tss_fmt, "tss_ist6", (void *)tss->tss_ist6);
1837 	printf(tss_fmt, "tss_ist7", (void *)tss->tss_ist7);
1838 }
1839 
1840 #elif defined(__i386)
1841 
1842 static void
1843 dump_tss(void)
1844 {
1845 	const char tss_fmt[] = "tss.%s:\t0x%p\n";  /* Format string */
1846 	struct tss *tss = CPU->cpu_tss;
1847 
1848 	printf(tss_fmt, "tss_link", (void *)(uintptr_t)tss->tss_link);
1849 	printf(tss_fmt, "tss_esp0", (void *)(uintptr_t)tss->tss_esp0);
1850 	printf(tss_fmt, "tss_ss0", (void *)(uintptr_t)tss->tss_ss0);
1851 	printf(tss_fmt, "tss_esp1", (void *)(uintptr_t)tss->tss_esp1);
1852 	printf(tss_fmt, "tss_ss1", (void *)(uintptr_t)tss->tss_ss1);
1853 	printf(tss_fmt, "tss_esp2", (void *)(uintptr_t)tss->tss_esp2);
1854 	printf(tss_fmt, "tss_ss2", (void *)(uintptr_t)tss->tss_ss2);
1855 	printf(tss_fmt, "tss_cr3", (void *)(uintptr_t)tss->tss_cr3);
1856 	printf(tss_fmt, "tss_eip", (void *)(uintptr_t)tss->tss_eip);
1857 	printf(tss_fmt, "tss_eflags", (void *)(uintptr_t)tss->tss_eflags);
1858 	printf(tss_fmt, "tss_eax", (void *)(uintptr_t)tss->tss_eax);
1859 	printf(tss_fmt, "tss_ebx", (void *)(uintptr_t)tss->tss_ebx);
1860 	printf(tss_fmt, "tss_ecx", (void *)(uintptr_t)tss->tss_ecx);
1861 	printf(tss_fmt, "tss_edx", (void *)(uintptr_t)tss->tss_edx);
1862 	printf(tss_fmt, "tss_esp", (void *)(uintptr_t)tss->tss_esp);
1863 }
1864 
1865 #endif	/* __amd64 */
1866 
1867 #if defined(TRAPTRACE)
1868 
1869 int ttrace_nrec = 0;		/* number of records to dump out */
1870 int ttrace_dump_nregs = 5;	/* dump out this many records with regs too */
1871 
1872 /*
1873  * Dump out the last ttrace_nrec traptrace records on each CPU
1874  */
1875 static void
1876 dump_ttrace(void)
1877 {
1878 	trap_trace_ctl_t *ttc;
1879 	trap_trace_rec_t *rec;
1880 	uintptr_t current;
1881 	int i, j, k;
1882 	int n = NCPU;
1883 #if defined(__amd64)
1884 	const char banner[] =
1885 		"\ncpu          address    timestamp "
1886 		"type  vc  handler   pc\n";
1887 	const char fmt1[] = "%3d %016lx %12llx ";
1888 #elif defined(__i386)
1889 	const char banner[] =
1890 		"\ncpu  address     timestamp type  vc  handler   pc\n";
1891 	const char fmt1[] = "%3d %08lx %12llx ";
1892 #endif
1893 	const char fmt2[] = "%4s %3x ";
1894 	const char fmt3[] = "%8s ";
1895 
1896 	if (ttrace_nrec == 0)
1897 		return;
1898 
1899 	printf(banner);
1900 
1901 	for (i = 0; i < n; i++) {
1902 		ttc = &trap_trace_ctl[i];
1903 		if (ttc->ttc_first == NULL)
1904 			continue;
1905 
1906 		current = ttc->ttc_next - sizeof (trap_trace_rec_t);
1907 		for (j = 0; j < ttrace_nrec; j++) {
1908 			struct sysent	*sys;
1909 			struct autovec	*vec;
1910 			extern struct av_head autovect[];
1911 			int type;
1912 			ulong_t	off;
1913 			char *sym, *stype;
1914 
1915 			if (current < ttc->ttc_first)
1916 				current =
1917 				    ttc->ttc_limit - sizeof (trap_trace_rec_t);
1918 
1919 			if (current == NULL)
1920 				continue;
1921 
1922 			rec = (trap_trace_rec_t *)current;
1923 
1924 			if (rec->ttr_stamp == 0)
1925 				break;
1926 
1927 			printf(fmt1, i, (uintptr_t)rec, rec->ttr_stamp);
1928 
1929 			switch (rec->ttr_marker) {
1930 			case TT_SYSCALL:
1931 			case TT_SYSENTER:
1932 			case TT_SYSC:
1933 			case TT_SYSC64:
1934 #if defined(__amd64)
1935 				sys = &sysent32[rec->ttr_sysnum];
1936 				switch (rec->ttr_marker) {
1937 				case TT_SYSC64:
1938 					sys = &sysent[rec->ttr_sysnum];
1939 					/*FALLTHROUGH*/
1940 #elif defined(__i386)
1941 				sys = &sysent[rec->ttr_sysnum];
1942 				switch (rec->ttr_marker) {
1943 				case TT_SYSC64:
1944 #endif
1945 				case TT_SYSC:
1946 					stype = "sysc";	/* syscall */
1947 					break;
1948 				case TT_SYSCALL:
1949 					stype = "lcal";	/* lcall */
1950 					break;
1951 				case TT_SYSENTER:
1952 					stype = "syse";	/* sysenter */
1953 					break;
1954 				default:
1955 					break;
1956 				}
1957 				printf(fmt2, "sysc", rec->ttr_sysnum);
1958 				if (sys != NULL) {
1959 					sym = kobj_getsymname(
1960 					    (uintptr_t)sys->sy_callc,
1961 					    &off);
1962 					if (sym != NULL)
1963 						printf(fmt3, sym);
1964 					else
1965 						printf("%p ", sys->sy_callc);
1966 				} else {
1967 					printf(fmt3, "unknown");
1968 				}
1969 				break;
1970 
1971 			case TT_INTERRUPT:
1972 				printf(fmt2, "intr", rec->ttr_vector);
1973 				vec = (&autovect[rec->ttr_vector])->avh_link;
1974 				if (vec != NULL) {
1975 					sym = kobj_getsymname(
1976 					    (uintptr_t)vec->av_vector, &off);
1977 					if (sym != NULL)
1978 						printf(fmt3, sym);
1979 					else
1980 						printf("%p ", vec->av_vector);
1981 				} else {
1982 					printf(fmt3, "unknown ");
1983 				}
1984 				break;
1985 
1986 			case TT_TRAP:
1987 			case TT_EVENT:
1988 				type = rec->ttr_regs.r_trapno;
1989 				printf(fmt2, "trap", type);
1990 				if (type < TRAP_TYPES)
1991 					printf("     #%s ",
1992 					    trap_type_mnemonic[type]);
1993 				else
1994 					switch (type) {
1995 					case T_AST:
1996 						printf(fmt3, "ast");
1997 						break;
1998 					default:
1999 						printf(fmt3, "");
2000 						break;
2001 					}
2002 				break;
2003 
2004 			case TT_XCALL:
2005 				printf(fmt2, "xcal",
2006 				    rec->ttr_info.xc_entry.xce_marker);
2007 				printf(fmt3, "");
2008 				break;
2009 
2010 			default:
2011 				break;
2012 			}
2013 
2014 			sym = kobj_getsymname(rec->ttr_regs.r_pc, &off);
2015 			if (sym != NULL)
2016 				printf("%s+%lx\n", sym, off);
2017 			else
2018 				printf("%lx\n", rec->ttr_regs.r_pc);
2019 
2020 			if (ttrace_dump_nregs-- > 0) {
2021 				int s;
2022 
2023 				if (rec->ttr_marker == TT_INTERRUPT)
2024 					printf(
2025 					    "\t\tipl %x spl %x pri %x\n",
2026 					    rec->ttr_ipl,
2027 					    rec->ttr_spl,
2028 					    rec->ttr_pri);
2029 
2030 				dumpregs(&rec->ttr_regs);
2031 
2032 				printf("\t%3s: %p\n\n", " ct",
2033 				    (void *)rec->ttr_curthread);
2034 
2035 				/*
2036 				 * print out the pc stack that we recorded
2037 				 * at trap time (if any)
2038 				 */
2039 				for (s = 0; s < rec->ttr_sdepth; s++) {
2040 					uintptr_t fullpc;
2041 
2042 					if (s >= TTR_STACK_DEPTH) {
2043 						printf("ttr_sdepth corrupt\n");
2044 						break;
2045 					}
2046 
2047 					fullpc = (uintptr_t)rec->ttr_stack[s];
2048 
2049 					sym = kobj_getsymname(fullpc, &off);
2050 					if (sym != NULL)
2051 						printf("-> %s+0x%lx()\n",
2052 						    sym, off);
2053 					else
2054 						printf("-> 0x%lx()\n", fullpc);
2055 				}
2056 				printf("\n");
2057 			}
2058 			current -= sizeof (trap_trace_rec_t);
2059 		}
2060 	}
2061 }
2062 
2063 /*
2064  * Help with constructing traptrace records in C
2065  */
2066 trap_trace_rec_t *
2067 trap_trace_get_traceptr(uint8_t marker, ulong_t pc, ulong_t sp)
2068 {
2069 	trap_trace_rec_t *ttr;
2070 
2071 	if (trap_trace_freeze)
2072 		ttr = &trap_trace_postmort;
2073 	else {
2074 		trap_trace_ctl_t *ttc = &trap_trace_ctl[CPU->cpu_id];
2075 
2076 		ttr = (void *)ttc->ttc_next;
2077 
2078 		if (ttc->ttc_next >= ttc->ttc_limit)
2079 			ttc->ttc_next = ttc->ttc_first;
2080 		else
2081 			ttc->ttc_next += sizeof (trap_trace_rec_t);
2082 	}
2083 
2084 	ttr->ttr_regs.r_sp = sp;
2085 	ttr->ttr_regs.r_pc = pc;
2086 	ttr->ttr_cr2 = getcr2();
2087 	ttr->ttr_curthread = (uintptr_t)curthread;
2088 	ttr->ttr_stamp = tsc_read();
2089 	ttr->ttr_marker = marker;
2090 	return (ttr);
2091 }
2092 
2093 #endif	/* TRAPTRACE */
2094 
2095 void
2096 panic_showtrap(struct trap_info *tip)
2097 {
2098 	showregs(tip->trap_type, tip->trap_regs, tip->trap_addr);
2099 
2100 #if defined(TRAPTRACE)
2101 	dump_ttrace();
2102 #endif	/* TRAPTRACE */
2103 
2104 	if (tip->trap_type == T_DBLFLT)
2105 		dump_tss();
2106 }
2107 
2108 void
2109 panic_savetrap(panic_data_t *pdp, struct trap_info *tip)
2110 {
2111 	panic_saveregs(pdp, tip->trap_regs);
2112 }
2113