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