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