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