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