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