trap.c revision 269752
1/*-
2 * Copyright (C) 1994, David Greenman
3 * Copyright (c) 1990, 1993
4 *	The Regents of the University of California.  All rights reserved.
5 *
6 * This code is derived from software contributed to Berkeley by
7 * the University of Utah, and William Jolitz.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 *    must display the following acknowledgement:
19 *	This product includes software developed by the University of
20 *	California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 *    may be used to endorse or promote products derived from this software
23 *    without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
36 *
37 *	from: @(#)trap.c	7.4 (Berkeley) 5/13/91
38 */
39
40#include <sys/cdefs.h>
41__FBSDID("$FreeBSD: stable/10/sys/amd64/amd64/trap.c 269752 2014-08-09 14:05:01Z markj $");
42
43/*
44 * AMD64 Trap and System call handling
45 */
46
47#include "opt_clock.h"
48#include "opt_cpu.h"
49#include "opt_hwpmc_hooks.h"
50#include "opt_isa.h"
51#include "opt_kdb.h"
52#include "opt_kdtrace.h"
53
54#include <sys/param.h>
55#include <sys/bus.h>
56#include <sys/systm.h>
57#include <sys/proc.h>
58#include <sys/pioctl.h>
59#include <sys/ptrace.h>
60#include <sys/kdb.h>
61#include <sys/kernel.h>
62#include <sys/ktr.h>
63#include <sys/lock.h>
64#include <sys/mutex.h>
65#include <sys/resourcevar.h>
66#include <sys/signalvar.h>
67#include <sys/syscall.h>
68#include <sys/sysctl.h>
69#include <sys/sysent.h>
70#include <sys/uio.h>
71#include <sys/vmmeter.h>
72#ifdef HWPMC_HOOKS
73#include <sys/pmckern.h>
74PMC_SOFT_DEFINE( , , page_fault, all);
75PMC_SOFT_DEFINE( , , page_fault, read);
76PMC_SOFT_DEFINE( , , page_fault, write);
77#endif
78
79#include <vm/vm.h>
80#include <vm/vm_param.h>
81#include <vm/pmap.h>
82#include <vm/vm_kern.h>
83#include <vm/vm_map.h>
84#include <vm/vm_page.h>
85#include <vm/vm_extern.h>
86
87#include <machine/cpu.h>
88#include <machine/intr_machdep.h>
89#include <x86/mca.h>
90#include <machine/md_var.h>
91#include <machine/pcb.h>
92#ifdef SMP
93#include <machine/smp.h>
94#endif
95#include <machine/tss.h>
96
97#ifdef KDTRACE_HOOKS
98#include <sys/dtrace_bsd.h>
99#endif
100
101extern void trap(struct trapframe *frame);
102extern void syscall(struct trapframe *frame);
103void dblfault_handler(struct trapframe *frame);
104
105static int trap_pfault(struct trapframe *, int);
106static void trap_fatal(struct trapframe *, vm_offset_t);
107
108#define MAX_TRAP_MSG		32
109static char *trap_msg[] = {
110	"",					/*  0 unused */
111	"privileged instruction fault",		/*  1 T_PRIVINFLT */
112	"",					/*  2 unused */
113	"breakpoint instruction fault",		/*  3 T_BPTFLT */
114	"",					/*  4 unused */
115	"",					/*  5 unused */
116	"arithmetic trap",			/*  6 T_ARITHTRAP */
117	"",					/*  7 unused */
118	"",					/*  8 unused */
119	"general protection fault",		/*  9 T_PROTFLT */
120	"trace trap",				/* 10 T_TRCTRAP */
121	"",					/* 11 unused */
122	"page fault",				/* 12 T_PAGEFLT */
123	"",					/* 13 unused */
124	"alignment fault",			/* 14 T_ALIGNFLT */
125	"",					/* 15 unused */
126	"",					/* 16 unused */
127	"",					/* 17 unused */
128	"integer divide fault",			/* 18 T_DIVIDE */
129	"non-maskable interrupt trap",		/* 19 T_NMI */
130	"overflow trap",			/* 20 T_OFLOW */
131	"FPU bounds check fault",		/* 21 T_BOUND */
132	"FPU device not available",		/* 22 T_DNA */
133	"double fault",				/* 23 T_DOUBLEFLT */
134	"FPU operand fetch fault",		/* 24 T_FPOPFLT */
135	"invalid TSS fault",			/* 25 T_TSSFLT */
136	"segment not present fault",		/* 26 T_SEGNPFLT */
137	"stack fault",				/* 27 T_STKFLT */
138	"machine check trap",			/* 28 T_MCHK */
139	"SIMD floating-point exception",	/* 29 T_XMMFLT */
140	"reserved (unknown) fault",		/* 30 T_RESERVED */
141	"",					/* 31 unused (reserved) */
142	"DTrace pid return trap",		/* 32 T_DTRACE_RET */
143};
144
145#ifdef KDB
146static int kdb_on_nmi = 1;
147SYSCTL_INT(_machdep, OID_AUTO, kdb_on_nmi, CTLFLAG_RW,
148	&kdb_on_nmi, 0, "Go to KDB on NMI");
149TUNABLE_INT("machdep.kdb_on_nmi", &kdb_on_nmi);
150#endif
151static int panic_on_nmi = 1;
152SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
153	&panic_on_nmi, 0, "Panic on NMI");
154TUNABLE_INT("machdep.panic_on_nmi", &panic_on_nmi);
155static int prot_fault_translation;
156SYSCTL_INT(_machdep, OID_AUTO, prot_fault_translation, CTLFLAG_RW,
157    &prot_fault_translation, 0,
158    "Select signal to deliver on protection fault");
159static int uprintf_signal;
160SYSCTL_INT(_machdep, OID_AUTO, uprintf_signal, CTLFLAG_RW,
161    &uprintf_signal, 0,
162    "Print debugging information on trap signal to ctty");
163
164/*
165 * Exception, fault, and trap interface to the FreeBSD kernel.
166 * This common code is called from assembly language IDT gate entry
167 * routines that prepare a suitable stack frame, and restore this
168 * frame after the exception has been processed.
169 */
170
171void
172trap(struct trapframe *frame)
173{
174#ifdef KDTRACE_HOOKS
175	struct reg regs;
176#endif
177	struct thread *td = curthread;
178	struct proc *p = td->td_proc;
179	int i = 0, ucode = 0, code;
180	u_int type;
181	register_t addr = 0;
182	ksiginfo_t ksi;
183
184	PCPU_INC(cnt.v_trap);
185	type = frame->tf_trapno;
186
187#ifdef SMP
188	/* Handler for NMI IPIs used for stopping CPUs. */
189	if (type == T_NMI) {
190	         if (ipi_nmi_handler() == 0)
191	                   goto out;
192	}
193#endif /* SMP */
194
195#ifdef KDB
196	if (kdb_active) {
197		kdb_reenter();
198		goto out;
199	}
200#endif
201
202	if (type == T_RESERVED) {
203		trap_fatal(frame, 0);
204		goto out;
205	}
206
207#ifdef	HWPMC_HOOKS
208	/*
209	 * CPU PMCs interrupt using an NMI.  If the PMC module is
210	 * active, pass the 'rip' value to the PMC module's interrupt
211	 * handler.  A return value of '1' from the handler means that
212	 * the NMI was handled by it and we can return immediately.
213	 */
214	if (type == T_NMI && pmc_intr &&
215	    (*pmc_intr)(PCPU_GET(cpuid), frame))
216		goto out;
217#endif
218
219	if (type == T_MCHK) {
220		mca_intr();
221		goto out;
222	}
223
224#ifdef KDTRACE_HOOKS
225	/*
226	 * A trap can occur while DTrace executes a probe. Before
227	 * executing the probe, DTrace blocks re-scheduling and sets
228	 * a flag in its per-cpu flags to indicate that it doesn't
229	 * want to fault. On returning from the probe, the no-fault
230	 * flag is cleared and finally re-scheduling is enabled.
231	 */
232	if (dtrace_trap_func != NULL && (*dtrace_trap_func)(frame, type))
233		goto out;
234#endif
235
236	if ((frame->tf_rflags & PSL_I) == 0) {
237		/*
238		 * Buggy application or kernel code has disabled
239		 * interrupts and then trapped.  Enabling interrupts
240		 * now is wrong, but it is better than running with
241		 * interrupts disabled until they are accidentally
242		 * enabled later.
243		 */
244		if (ISPL(frame->tf_cs) == SEL_UPL)
245			uprintf(
246			    "pid %ld (%s): trap %d with interrupts disabled\n",
247			    (long)curproc->p_pid, curthread->td_name, type);
248		else if (type != T_NMI && type != T_BPTFLT &&
249		    type != T_TRCTRAP) {
250			/*
251			 * XXX not quite right, since this may be for a
252			 * multiple fault in user mode.
253			 */
254			printf("kernel trap %d with interrupts disabled\n",
255			    type);
256
257			/*
258			 * We shouldn't enable interrupts while holding a
259			 * spin lock.
260			 */
261			if (td->td_md.md_spinlock_count == 0)
262				enable_intr();
263		}
264	}
265
266	code = frame->tf_err;
267
268        if (ISPL(frame->tf_cs) == SEL_UPL) {
269		/* user trap */
270
271		td->td_pticks = 0;
272		td->td_frame = frame;
273		addr = frame->tf_rip;
274		if (td->td_ucred != p->p_ucred)
275			cred_update_thread(td);
276
277		switch (type) {
278		case T_PRIVINFLT:	/* privileged instruction fault */
279			i = SIGILL;
280			ucode = ILL_PRVOPC;
281			break;
282
283		case T_BPTFLT:		/* bpt instruction fault */
284		case T_TRCTRAP:		/* trace trap */
285			enable_intr();
286#ifdef KDTRACE_HOOKS
287			if (type == T_BPTFLT) {
288				fill_frame_regs(frame, &regs);
289				if (dtrace_pid_probe_ptr != NULL &&
290				    dtrace_pid_probe_ptr(&regs) == 0)
291					goto out;
292			}
293#endif
294			frame->tf_rflags &= ~PSL_T;
295			i = SIGTRAP;
296			ucode = (type == T_TRCTRAP ? TRAP_TRACE : TRAP_BRKPT);
297			break;
298
299		case T_ARITHTRAP:	/* arithmetic trap */
300			ucode = fputrap_x87();
301			if (ucode == -1)
302				goto userout;
303			i = SIGFPE;
304			break;
305
306		case T_PROTFLT:		/* general protection fault */
307			i = SIGBUS;
308			ucode = BUS_OBJERR;
309			break;
310		case T_STKFLT:		/* stack fault */
311		case T_SEGNPFLT:	/* segment not present fault */
312			i = SIGBUS;
313			ucode = BUS_ADRERR;
314			break;
315		case T_TSSFLT:		/* invalid TSS fault */
316			i = SIGBUS;
317			ucode = BUS_OBJERR;
318			break;
319		case T_ALIGNFLT:
320			i = SIGBUS;
321			ucode = BUS_ADRALN;
322			break;
323		case T_DOUBLEFLT:	/* double fault */
324		default:
325			i = SIGBUS;
326			ucode = BUS_OBJERR;
327			break;
328
329		case T_PAGEFLT:		/* page fault */
330			addr = frame->tf_addr;
331			i = trap_pfault(frame, TRUE);
332			if (i == -1)
333				goto userout;
334			if (i == 0)
335				goto user;
336
337			if (i == SIGSEGV)
338				ucode = SEGV_MAPERR;
339			else {
340				if (prot_fault_translation == 0) {
341					/*
342					 * Autodetect.
343					 * This check also covers the images
344					 * without the ABI-tag ELF note.
345					 */
346					if (SV_CURPROC_ABI() == SV_ABI_FREEBSD
347					    && p->p_osrel >= P_OSREL_SIGSEGV) {
348						i = SIGSEGV;
349						ucode = SEGV_ACCERR;
350					} else {
351						i = SIGBUS;
352						ucode = BUS_PAGE_FAULT;
353					}
354				} else if (prot_fault_translation == 1) {
355					/*
356					 * Always compat mode.
357					 */
358					i = SIGBUS;
359					ucode = BUS_PAGE_FAULT;
360				} else {
361					/*
362					 * Always SIGSEGV mode.
363					 */
364					i = SIGSEGV;
365					ucode = SEGV_ACCERR;
366				}
367			}
368			break;
369
370		case T_DIVIDE:		/* integer divide fault */
371			ucode = FPE_INTDIV;
372			i = SIGFPE;
373			break;
374
375#ifdef DEV_ISA
376		case T_NMI:
377			/* machine/parity/power fail/"kitchen sink" faults */
378			if (isa_nmi(code) == 0) {
379#ifdef KDB
380				/*
381				 * NMI can be hooked up to a pushbutton
382				 * for debugging.
383				 */
384				if (kdb_on_nmi) {
385					printf ("NMI ... going to debugger\n");
386					kdb_trap(type, 0, frame);
387				}
388#endif /* KDB */
389				goto userout;
390			} else if (panic_on_nmi)
391				panic("NMI indicates hardware failure");
392			break;
393#endif /* DEV_ISA */
394
395		case T_OFLOW:		/* integer overflow fault */
396			ucode = FPE_INTOVF;
397			i = SIGFPE;
398			break;
399
400		case T_BOUND:		/* bounds check fault */
401			ucode = FPE_FLTSUB;
402			i = SIGFPE;
403			break;
404
405		case T_DNA:
406			/* transparent fault (due to context switch "late") */
407			KASSERT(PCB_USER_FPU(td->td_pcb),
408			    ("kernel FPU ctx has leaked"));
409			fpudna();
410			goto userout;
411
412		case T_FPOPFLT:		/* FPU operand fetch fault */
413			ucode = ILL_COPROC;
414			i = SIGILL;
415			break;
416
417		case T_XMMFLT:		/* SIMD floating-point exception */
418			ucode = fputrap_sse();
419			if (ucode == -1)
420				goto userout;
421			i = SIGFPE;
422			break;
423#ifdef KDTRACE_HOOKS
424		case T_DTRACE_RET:
425			enable_intr();
426			fill_frame_regs(frame, &regs);
427			if (dtrace_return_probe_ptr != NULL &&
428			    dtrace_return_probe_ptr(&regs) == 0)
429				goto out;
430			break;
431#endif
432		}
433	} else {
434		/* kernel trap */
435
436		KASSERT(cold || td->td_ucred != NULL,
437		    ("kernel trap doesn't have ucred"));
438		switch (type) {
439		case T_PAGEFLT:			/* page fault */
440			(void) trap_pfault(frame, FALSE);
441			goto out;
442
443		case T_DNA:
444			KASSERT(!PCB_USER_FPU(td->td_pcb),
445			    ("Unregistered use of FPU in kernel"));
446			fpudna();
447			goto out;
448
449		case T_ARITHTRAP:	/* arithmetic trap */
450		case T_XMMFLT:		/* SIMD floating-point exception */
451		case T_FPOPFLT:		/* FPU operand fetch fault */
452			/*
453			 * XXXKIB for now disable any FPU traps in kernel
454			 * handler registration seems to be overkill
455			 */
456			trap_fatal(frame, 0);
457			goto out;
458
459		case T_STKFLT:		/* stack fault */
460			break;
461
462		case T_PROTFLT:		/* general protection fault */
463		case T_SEGNPFLT:	/* segment not present fault */
464			if (td->td_intr_nesting_level != 0)
465				break;
466
467			/*
468			 * Invalid segment selectors and out of bounds
469			 * %rip's and %rsp's can be set up in user mode.
470			 * This causes a fault in kernel mode when the
471			 * kernel tries to return to user mode.  We want
472			 * to get this fault so that we can fix the
473			 * problem here and not have to check all the
474			 * selectors and pointers when the user changes
475			 * them.
476			 */
477			if (frame->tf_rip == (long)doreti_iret) {
478				frame->tf_rip = (long)doreti_iret_fault;
479				goto out;
480			}
481			if (frame->tf_rip == (long)ld_ds) {
482				frame->tf_rip = (long)ds_load_fault;
483				goto out;
484			}
485			if (frame->tf_rip == (long)ld_es) {
486				frame->tf_rip = (long)es_load_fault;
487				goto out;
488			}
489			if (frame->tf_rip == (long)ld_fs) {
490				frame->tf_rip = (long)fs_load_fault;
491				goto out;
492			}
493			if (frame->tf_rip == (long)ld_gs) {
494				frame->tf_rip = (long)gs_load_fault;
495				goto out;
496			}
497			if (frame->tf_rip == (long)ld_gsbase) {
498				frame->tf_rip = (long)gsbase_load_fault;
499				goto out;
500			}
501			if (frame->tf_rip == (long)ld_fsbase) {
502				frame->tf_rip = (long)fsbase_load_fault;
503				goto out;
504			}
505			if (curpcb->pcb_onfault != NULL) {
506				frame->tf_rip = (long)curpcb->pcb_onfault;
507				goto out;
508			}
509			break;
510
511		case T_TSSFLT:
512			/*
513			 * PSL_NT can be set in user mode and isn't cleared
514			 * automatically when the kernel is entered.  This
515			 * causes a TSS fault when the kernel attempts to
516			 * `iret' because the TSS link is uninitialized.  We
517			 * want to get this fault so that we can fix the
518			 * problem here and not every time the kernel is
519			 * entered.
520			 */
521			if (frame->tf_rflags & PSL_NT) {
522				frame->tf_rflags &= ~PSL_NT;
523				goto out;
524			}
525			break;
526
527		case T_TRCTRAP:	 /* trace trap */
528			/*
529			 * Ignore debug register trace traps due to
530			 * accesses in the user's address space, which
531			 * can happen under several conditions such as
532			 * if a user sets a watchpoint on a buffer and
533			 * then passes that buffer to a system call.
534			 * We still want to get TRCTRAPS for addresses
535			 * in kernel space because that is useful when
536			 * debugging the kernel.
537			 */
538			if (user_dbreg_trap()) {
539				/*
540				 * Reset breakpoint bits because the
541				 * processor doesn't
542				 */
543				/* XXX check upper bits here */
544				load_dr6(rdr6() & 0xfffffff0);
545				goto out;
546			}
547			/*
548			 * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
549			 */
550		case T_BPTFLT:
551			/*
552			 * If KDB is enabled, let it handle the debugger trap.
553			 * Otherwise, debugger traps "can't happen".
554			 */
555#ifdef KDB
556			if (kdb_trap(type, 0, frame))
557				goto out;
558#endif
559			break;
560
561#ifdef DEV_ISA
562		case T_NMI:
563			/* machine/parity/power fail/"kitchen sink" faults */
564			if (isa_nmi(code) == 0) {
565#ifdef KDB
566				/*
567				 * NMI can be hooked up to a pushbutton
568				 * for debugging.
569				 */
570				if (kdb_on_nmi) {
571					printf ("NMI ... going to debugger\n");
572					kdb_trap(type, 0, frame);
573				}
574#endif /* KDB */
575				goto out;
576			} else if (panic_on_nmi == 0)
577				goto out;
578			/* FALLTHROUGH */
579#endif /* DEV_ISA */
580		}
581
582		trap_fatal(frame, 0);
583		goto out;
584	}
585
586	/* Translate fault for emulators (e.g. Linux) */
587	if (*p->p_sysent->sv_transtrap)
588		i = (*p->p_sysent->sv_transtrap)(i, type);
589
590	ksiginfo_init_trap(&ksi);
591	ksi.ksi_signo = i;
592	ksi.ksi_code = ucode;
593	ksi.ksi_trapno = type;
594	ksi.ksi_addr = (void *)addr;
595	if (uprintf_signal) {
596		uprintf("pid %d comm %s: signal %d err %lx code %d type %d "
597		    "addr 0x%lx rsp 0x%lx rip 0x%lx "
598		    "<%02x %02x %02x %02x %02x %02x %02x %02x>\n",
599		    p->p_pid, p->p_comm, i, frame->tf_err, ucode, type, addr,
600		    frame->tf_rsp, frame->tf_rip,
601		    fubyte((void *)(frame->tf_rip + 0)),
602		    fubyte((void *)(frame->tf_rip + 1)),
603		    fubyte((void *)(frame->tf_rip + 2)),
604		    fubyte((void *)(frame->tf_rip + 3)),
605		    fubyte((void *)(frame->tf_rip + 4)),
606		    fubyte((void *)(frame->tf_rip + 5)),
607		    fubyte((void *)(frame->tf_rip + 6)),
608		    fubyte((void *)(frame->tf_rip + 7)));
609	}
610	KASSERT((read_rflags() & PSL_I) != 0, ("interrupts disabled"));
611	trapsignal(td, &ksi);
612
613user:
614	userret(td, frame);
615	KASSERT(PCB_USER_FPU(td->td_pcb),
616	    ("Return from trap with kernel FPU ctx leaked"));
617userout:
618out:
619	return;
620}
621
622static int
623trap_pfault(frame, usermode)
624	struct trapframe *frame;
625	int usermode;
626{
627	vm_offset_t va;
628	struct vmspace *vm;
629	vm_map_t map;
630	int rv = 0;
631	vm_prot_t ftype;
632	struct thread *td = curthread;
633	struct proc *p = td->td_proc;
634	vm_offset_t eva = frame->tf_addr;
635
636	if (__predict_false((td->td_pflags & TDP_NOFAULTING) != 0)) {
637		/*
638		 * Due to both processor errata and lazy TLB invalidation when
639		 * access restrictions are removed from virtual pages, memory
640		 * accesses that are allowed by the physical mapping layer may
641		 * nonetheless cause one spurious page fault per virtual page.
642		 * When the thread is executing a "no faulting" section that
643		 * is bracketed by vm_fault_{disable,enable}_pagefaults(),
644		 * every page fault is treated as a spurious page fault,
645		 * unless it accesses the same virtual address as the most
646		 * recent page fault within the same "no faulting" section.
647		 */
648		if (td->td_md.md_spurflt_addr != eva ||
649		    (td->td_pflags & TDP_RESETSPUR) != 0) {
650			/*
651			 * Do nothing to the TLB.  A stale TLB entry is
652			 * flushed automatically by a page fault.
653			 */
654			td->td_md.md_spurflt_addr = eva;
655			td->td_pflags &= ~TDP_RESETSPUR;
656			return (0);
657		}
658	} else {
659		/*
660		 * If we get a page fault while in a critical section, then
661		 * it is most likely a fatal kernel page fault.  The kernel
662		 * is already going to panic trying to get a sleep lock to
663		 * do the VM lookup, so just consider it a fatal trap so the
664		 * kernel can print out a useful trap message and even get
665		 * to the debugger.
666		 *
667		 * If we get a page fault while holding a non-sleepable
668		 * lock, then it is most likely a fatal kernel page fault.
669		 * If WITNESS is enabled, then it's going to whine about
670		 * bogus LORs with various VM locks, so just skip to the
671		 * fatal trap handling directly.
672		 */
673		if (td->td_critnest != 0 ||
674		    WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
675		    "Kernel page fault") != 0) {
676			trap_fatal(frame, eva);
677			return (-1);
678		}
679	}
680	va = trunc_page(eva);
681	if (va >= VM_MIN_KERNEL_ADDRESS) {
682		/*
683		 * Don't allow user-mode faults in kernel address space.
684		 */
685		if (usermode)
686			goto nogo;
687
688		map = kernel_map;
689	} else {
690		/*
691		 * This is a fault on non-kernel virtual memory.  If either
692		 * p or p->p_vmspace is NULL, then the fault is fatal.
693		 */
694		if (p == NULL || (vm = p->p_vmspace) == NULL)
695			goto nogo;
696
697		map = &vm->vm_map;
698
699		/*
700		 * When accessing a usermode address, kernel must be
701		 * ready to accept the page fault, and provide a
702		 * handling routine.  Since accessing the address
703		 * without the handler is a bug, do not try to handle
704		 * it normally, and panic immediately.
705		 */
706		if (!usermode && (td->td_intr_nesting_level != 0 ||
707		    curpcb->pcb_onfault == NULL)) {
708			trap_fatal(frame, eva);
709			return (-1);
710		}
711	}
712
713	/*
714	 * If the trap was caused by errant bits in the PTE then panic.
715	 */
716	if (frame->tf_err & PGEX_RSV) {
717		trap_fatal(frame, eva);
718		return (-1);
719	}
720
721	/*
722	 * PGEX_I is defined only if the execute disable bit capability is
723	 * supported and enabled.
724	 */
725	if (frame->tf_err & PGEX_W)
726		ftype = VM_PROT_WRITE;
727	else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
728		ftype = VM_PROT_EXECUTE;
729	else
730		ftype = VM_PROT_READ;
731
732	if (map != kernel_map) {
733		/*
734		 * Keep swapout from messing with us during this
735		 *	critical time.
736		 */
737		PROC_LOCK(p);
738		++p->p_lock;
739		PROC_UNLOCK(p);
740
741		/* Fault in the user page: */
742		rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
743
744		PROC_LOCK(p);
745		--p->p_lock;
746		PROC_UNLOCK(p);
747	} else {
748		/*
749		 * Don't have to worry about process locking or stacks in the
750		 * kernel.
751		 */
752		rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
753	}
754	if (rv == KERN_SUCCESS) {
755#ifdef HWPMC_HOOKS
756		if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
757			PMC_SOFT_CALL_TF( , , page_fault, all, frame);
758			if (ftype == VM_PROT_READ)
759				PMC_SOFT_CALL_TF( , , page_fault, read,
760				    frame);
761			else
762				PMC_SOFT_CALL_TF( , , page_fault, write,
763				    frame);
764		}
765#endif
766		return (0);
767	}
768nogo:
769	if (!usermode) {
770		if (td->td_intr_nesting_level == 0 &&
771		    curpcb->pcb_onfault != NULL) {
772			frame->tf_rip = (long)curpcb->pcb_onfault;
773			return (0);
774		}
775		if ((td->td_pflags & TDP_DEVMEMIO) != 0) {
776			KASSERT(curpcb->pcb_onfault != NULL,
777			    ("/dev/mem without pcb_onfault"));
778			frame->tf_rip = (long)curpcb->pcb_onfault;
779			return (0);
780		}
781		trap_fatal(frame, eva);
782		return (-1);
783	}
784	return ((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
785}
786
787static void
788trap_fatal(frame, eva)
789	struct trapframe *frame;
790	vm_offset_t eva;
791{
792	int code, ss;
793	u_int type;
794	long esp;
795	struct soft_segment_descriptor softseg;
796	char *msg;
797
798	code = frame->tf_err;
799	type = frame->tf_trapno;
800	sdtossd(&gdt[NGDT * PCPU_GET(cpuid) + IDXSEL(frame->tf_cs & 0xffff)],
801	    &softseg);
802
803	if (type <= MAX_TRAP_MSG)
804		msg = trap_msg[type];
805	else
806		msg = "UNKNOWN";
807	printf("\n\nFatal trap %d: %s while in %s mode\n", type, msg,
808	    ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
809#ifdef SMP
810	/* two separate prints in case of a trap on an unmapped page */
811	printf("cpuid = %d; ", PCPU_GET(cpuid));
812	printf("apic id = %02x\n", PCPU_GET(apic_id));
813#endif
814	if (type == T_PAGEFLT) {
815		printf("fault virtual address	= 0x%lx\n", eva);
816		printf("fault code		= %s %s %s%s, %s\n",
817			code & PGEX_U ? "user" : "supervisor",
818			code & PGEX_W ? "write" : "read",
819			code & PGEX_I ? "instruction" : "data",
820			code & PGEX_RSV ? " rsv" : "",
821			code & PGEX_P ? "protection violation" : "page not present");
822	}
823	printf("instruction pointer	= 0x%lx:0x%lx\n",
824	       frame->tf_cs & 0xffff, frame->tf_rip);
825        if (ISPL(frame->tf_cs) == SEL_UPL) {
826		ss = frame->tf_ss & 0xffff;
827		esp = frame->tf_rsp;
828	} else {
829		ss = GSEL(GDATA_SEL, SEL_KPL);
830		esp = (long)&frame->tf_rsp;
831	}
832	printf("stack pointer	        = 0x%x:0x%lx\n", ss, esp);
833	printf("frame pointer	        = 0x%x:0x%lx\n", ss, frame->tf_rbp);
834	printf("code segment		= base 0x%lx, limit 0x%lx, type 0x%x\n",
835	       softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
836	printf("			= DPL %d, pres %d, long %d, def32 %d, gran %d\n",
837	       softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
838	       softseg.ssd_gran);
839	printf("processor eflags	= ");
840	if (frame->tf_rflags & PSL_T)
841		printf("trace trap, ");
842	if (frame->tf_rflags & PSL_I)
843		printf("interrupt enabled, ");
844	if (frame->tf_rflags & PSL_NT)
845		printf("nested task, ");
846	if (frame->tf_rflags & PSL_RF)
847		printf("resume, ");
848	printf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
849	printf("current process		= ");
850	if (curproc) {
851		printf("%lu (%s)\n",
852		    (u_long)curproc->p_pid, curthread->td_name ?
853		    curthread->td_name : "");
854	} else {
855		printf("Idle\n");
856	}
857
858#ifdef KDB
859	if (debugger_on_panic || kdb_active)
860		if (kdb_trap(type, 0, frame))
861			return;
862#endif
863	printf("trap number		= %d\n", type);
864	if (type <= MAX_TRAP_MSG)
865		panic("%s", trap_msg[type]);
866	else
867		panic("unknown/reserved trap");
868}
869
870/*
871 * Double fault handler. Called when a fault occurs while writing
872 * a frame for a trap/exception onto the stack. This usually occurs
873 * when the stack overflows (such is the case with infinite recursion,
874 * for example).
875 */
876void
877dblfault_handler(struct trapframe *frame)
878{
879#ifdef KDTRACE_HOOKS
880	if (dtrace_doubletrap_func != NULL)
881		(*dtrace_doubletrap_func)();
882#endif
883	printf("\nFatal double fault\n");
884	printf("rip = 0x%lx\n", frame->tf_rip);
885	printf("rsp = 0x%lx\n", frame->tf_rsp);
886	printf("rbp = 0x%lx\n", frame->tf_rbp);
887#ifdef SMP
888	/* two separate prints in case of a trap on an unmapped page */
889	printf("cpuid = %d; ", PCPU_GET(cpuid));
890	printf("apic id = %02x\n", PCPU_GET(apic_id));
891#endif
892	panic("double fault");
893}
894
895int
896cpu_fetch_syscall_args(struct thread *td, struct syscall_args *sa)
897{
898	struct proc *p;
899	struct trapframe *frame;
900	register_t *argp;
901	caddr_t params;
902	int reg, regcnt, error;
903
904	p = td->td_proc;
905	frame = td->td_frame;
906	reg = 0;
907	regcnt = 6;
908
909	params = (caddr_t)frame->tf_rsp + sizeof(register_t);
910	sa->code = frame->tf_rax;
911
912	if (sa->code == SYS_syscall || sa->code == SYS___syscall) {
913		sa->code = frame->tf_rdi;
914		reg++;
915		regcnt--;
916	}
917 	if (p->p_sysent->sv_mask)
918 		sa->code &= p->p_sysent->sv_mask;
919
920 	if (sa->code >= p->p_sysent->sv_size)
921 		sa->callp = &p->p_sysent->sv_table[0];
922  	else
923 		sa->callp = &p->p_sysent->sv_table[sa->code];
924
925	sa->narg = sa->callp->sy_narg;
926	KASSERT(sa->narg <= sizeof(sa->args) / sizeof(sa->args[0]),
927	    ("Too many syscall arguments!"));
928	error = 0;
929	argp = &frame->tf_rdi;
930	argp += reg;
931	bcopy(argp, sa->args, sizeof(sa->args[0]) * regcnt);
932	if (sa->narg > regcnt) {
933		KASSERT(params != NULL, ("copyin args with no params!"));
934		error = copyin(params, &sa->args[regcnt],
935	    	    (sa->narg - regcnt) * sizeof(sa->args[0]));
936	}
937
938	if (error == 0) {
939		td->td_retval[0] = 0;
940		td->td_retval[1] = frame->tf_rdx;
941	}
942
943	return (error);
944}
945
946#include "../../kern/subr_syscall.c"
947
948/*
949 * System call handler for native binaries.  The trap frame is already
950 * set up by the assembler trampoline and a pointer to it is saved in
951 * td_frame.
952 */
953void
954amd64_syscall(struct thread *td, int traced)
955{
956	struct syscall_args sa;
957	int error;
958	ksiginfo_t ksi;
959
960#ifdef DIAGNOSTIC
961	if (ISPL(td->td_frame->tf_cs) != SEL_UPL) {
962		panic("syscall");
963		/* NOT REACHED */
964	}
965#endif
966	error = syscallenter(td, &sa);
967
968	/*
969	 * Traced syscall.
970	 */
971	if (__predict_false(traced)) {
972		td->td_frame->tf_rflags &= ~PSL_T;
973		ksiginfo_init_trap(&ksi);
974		ksi.ksi_signo = SIGTRAP;
975		ksi.ksi_code = TRAP_TRACE;
976		ksi.ksi_addr = (void *)td->td_frame->tf_rip;
977		trapsignal(td, &ksi);
978	}
979
980	KASSERT(PCB_USER_FPU(td->td_pcb),
981	    ("System call %s returing with kernel FPU ctx leaked",
982	     syscallname(td->td_proc, sa.code)));
983	KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td),
984	    ("System call %s returning with mangled pcb_save",
985	     syscallname(td->td_proc, sa.code)));
986
987	syscallret(td, error, &sa);
988
989	/*
990	 * If the user-supplied value of %rip is not a canonical
991	 * address, then some CPUs will trigger a ring 0 #GP during
992	 * the sysret instruction.  However, the fault handler would
993	 * execute in ring 0 with the user's %gs and %rsp which would
994	 * not be safe.  Instead, use the full return path which
995	 * catches the problem safely.
996	 */
997	if (td->td_frame->tf_rip >= VM_MAXUSER_ADDRESS)
998		set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
999}
1000