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