xref: /freebsd/sys/amd64/amd64/trap.c (revision 5b9c547c)
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$");
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 
53 #include <sys/param.h>
54 #include <sys/bus.h>
55 #include <sys/systm.h>
56 #include <sys/proc.h>
57 #include <sys/pioctl.h>
58 #include <sys/ptrace.h>
59 #include <sys/kdb.h>
60 #include <sys/kernel.h>
61 #include <sys/ktr.h>
62 #include <sys/lock.h>
63 #include <sys/mutex.h>
64 #include <sys/resourcevar.h>
65 #include <sys/signalvar.h>
66 #include <sys/syscall.h>
67 #include <sys/sysctl.h>
68 #include <sys/sysent.h>
69 #include <sys/uio.h>
70 #include <sys/vmmeter.h>
71 #ifdef HWPMC_HOOKS
72 #include <sys/pmckern.h>
73 PMC_SOFT_DEFINE( , , page_fault, all);
74 PMC_SOFT_DEFINE( , , page_fault, read);
75 PMC_SOFT_DEFINE( , , page_fault, write);
76 #endif
77 
78 #include <vm/vm.h>
79 #include <vm/vm_param.h>
80 #include <vm/pmap.h>
81 #include <vm/vm_kern.h>
82 #include <vm/vm_map.h>
83 #include <vm/vm_page.h>
84 #include <vm/vm_extern.h>
85 
86 #include <machine/cpu.h>
87 #include <machine/intr_machdep.h>
88 #include <x86/mca.h>
89 #include <machine/md_var.h>
90 #include <machine/pcb.h>
91 #ifdef SMP
92 #include <machine/smp.h>
93 #endif
94 #include <machine/tss.h>
95 
96 #ifdef KDTRACE_HOOKS
97 #include <sys/dtrace_bsd.h>
98 #endif
99 
100 extern void __noinline trap(struct trapframe *frame);
101 extern void trap_check(struct trapframe *frame);
102 extern void syscall(struct trapframe *frame);
103 void dblfault_handler(struct trapframe *frame);
104 
105 static int trap_pfault(struct trapframe *, int);
106 static void trap_fatal(struct trapframe *, vm_offset_t);
107 
108 #define MAX_TRAP_MSG		32
109 static 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
146 static int kdb_on_nmi = 1;
147 SYSCTL_INT(_machdep, OID_AUTO, kdb_on_nmi, CTLFLAG_RWTUN,
148 	&kdb_on_nmi, 0, "Go to KDB on NMI");
149 #endif
150 static int panic_on_nmi = 1;
151 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RWTUN,
152 	&panic_on_nmi, 0, "Panic on NMI");
153 static int prot_fault_translation;
154 SYSCTL_INT(_machdep, OID_AUTO, prot_fault_translation, CTLFLAG_RWTUN,
155     &prot_fault_translation, 0,
156     "Select signal to deliver on protection fault");
157 static int uprintf_signal;
158 SYSCTL_INT(_machdep, OID_AUTO, uprintf_signal, CTLFLAG_RWTUN,
159     &uprintf_signal, 0,
160     "Print debugging information on trap signal to ctty");
161 
162 /*
163  * Exception, fault, and trap interface to the FreeBSD kernel.
164  * This common code is called from assembly language IDT gate entry
165  * routines that prepare a suitable stack frame, and restore this
166  * frame after the exception has been processed.
167  */
168 
169 void
170 trap(struct trapframe *frame)
171 {
172 #ifdef KDTRACE_HOOKS
173 	struct reg regs;
174 #endif
175 	struct thread *td = curthread;
176 	struct proc *p = td->td_proc;
177 	int i = 0, ucode = 0, code;
178 	u_int type;
179 	register_t addr = 0;
180 	ksiginfo_t ksi;
181 
182 	PCPU_INC(cnt.v_trap);
183 	type = frame->tf_trapno;
184 
185 #ifdef SMP
186 	/* Handler for NMI IPIs used for stopping CPUs. */
187 	if (type == T_NMI) {
188 	         if (ipi_nmi_handler() == 0)
189 	                   goto out;
190 	}
191 #endif /* SMP */
192 
193 #ifdef KDB
194 	if (kdb_active) {
195 		kdb_reenter();
196 		goto out;
197 	}
198 #endif
199 
200 	if (type == T_RESERVED) {
201 		trap_fatal(frame, 0);
202 		goto out;
203 	}
204 
205 #ifdef	HWPMC_HOOKS
206 	/*
207 	 * CPU PMCs interrupt using an NMI.  If the PMC module is
208 	 * active, pass the 'rip' value to the PMC module's interrupt
209 	 * handler.  A return value of '1' from the handler means that
210 	 * the NMI was handled by it and we can return immediately.
211 	 */
212 	if (type == T_NMI && pmc_intr &&
213 	    (*pmc_intr)(PCPU_GET(cpuid), frame))
214 		goto out;
215 #endif
216 
217 	if (type == T_MCHK) {
218 		mca_intr();
219 		goto out;
220 	}
221 
222 	if ((frame->tf_rflags & PSL_I) == 0) {
223 		/*
224 		 * Buggy application or kernel code has disabled
225 		 * interrupts and then trapped.  Enabling interrupts
226 		 * now is wrong, but it is better than running with
227 		 * interrupts disabled until they are accidentally
228 		 * enabled later.
229 		 */
230 		if (ISPL(frame->tf_cs) == SEL_UPL)
231 			uprintf(
232 			    "pid %ld (%s): trap %d with interrupts disabled\n",
233 			    (long)curproc->p_pid, curthread->td_name, type);
234 		else if (type != T_NMI && type != T_BPTFLT &&
235 		    type != T_TRCTRAP) {
236 			/*
237 			 * XXX not quite right, since this may be for a
238 			 * multiple fault in user mode.
239 			 */
240 			printf("kernel trap %d with interrupts disabled\n",
241 			    type);
242 
243 			/*
244 			 * We shouldn't enable interrupts while holding a
245 			 * spin lock.
246 			 */
247 			if (td->td_md.md_spinlock_count == 0)
248 				enable_intr();
249 		}
250 	}
251 
252 	code = frame->tf_err;
253 
254         if (ISPL(frame->tf_cs) == SEL_UPL) {
255 		/* user trap */
256 
257 		td->td_pticks = 0;
258 		td->td_frame = frame;
259 		addr = frame->tf_rip;
260 		if (td->td_ucred != p->p_ucred)
261 			cred_update_thread(td);
262 
263 		switch (type) {
264 		case T_PRIVINFLT:	/* privileged instruction fault */
265 			i = SIGILL;
266 			ucode = ILL_PRVOPC;
267 			break;
268 
269 		case T_BPTFLT:		/* bpt instruction fault */
270 		case T_TRCTRAP:		/* trace trap */
271 			enable_intr();
272 #ifdef KDTRACE_HOOKS
273 			if (type == T_BPTFLT) {
274 				fill_frame_regs(frame, &regs);
275 				if (dtrace_pid_probe_ptr != NULL &&
276 				    dtrace_pid_probe_ptr(&regs) == 0)
277 					goto out;
278 			}
279 #endif
280 			frame->tf_rflags &= ~PSL_T;
281 			i = SIGTRAP;
282 			ucode = (type == T_TRCTRAP ? TRAP_TRACE : TRAP_BRKPT);
283 			break;
284 
285 		case T_ARITHTRAP:	/* arithmetic trap */
286 			ucode = fputrap_x87();
287 			if (ucode == -1)
288 				goto userout;
289 			i = SIGFPE;
290 			break;
291 
292 		case T_PROTFLT:		/* general protection fault */
293 			i = SIGBUS;
294 			ucode = BUS_OBJERR;
295 			break;
296 		case T_STKFLT:		/* stack fault */
297 		case T_SEGNPFLT:	/* segment not present fault */
298 			i = SIGBUS;
299 			ucode = BUS_ADRERR;
300 			break;
301 		case T_TSSFLT:		/* invalid TSS fault */
302 			i = SIGBUS;
303 			ucode = BUS_OBJERR;
304 			break;
305 		case T_ALIGNFLT:
306 			i = SIGBUS;
307 			ucode = BUS_ADRALN;
308 			break;
309 		case T_DOUBLEFLT:	/* double fault */
310 		default:
311 			i = SIGBUS;
312 			ucode = BUS_OBJERR;
313 			break;
314 
315 		case T_PAGEFLT:		/* page fault */
316 			addr = frame->tf_addr;
317 			i = trap_pfault(frame, TRUE);
318 			if (i == -1)
319 				goto userout;
320 			if (i == 0)
321 				goto user;
322 
323 			if (i == SIGSEGV)
324 				ucode = SEGV_MAPERR;
325 			else {
326 				if (prot_fault_translation == 0) {
327 					/*
328 					 * Autodetect.
329 					 * This check also covers the images
330 					 * without the ABI-tag ELF note.
331 					 */
332 					if (SV_CURPROC_ABI() == SV_ABI_FREEBSD
333 					    && p->p_osrel >= P_OSREL_SIGSEGV) {
334 						i = SIGSEGV;
335 						ucode = SEGV_ACCERR;
336 					} else {
337 						i = SIGBUS;
338 						ucode = BUS_PAGE_FAULT;
339 					}
340 				} else if (prot_fault_translation == 1) {
341 					/*
342 					 * Always compat mode.
343 					 */
344 					i = SIGBUS;
345 					ucode = BUS_PAGE_FAULT;
346 				} else {
347 					/*
348 					 * Always SIGSEGV mode.
349 					 */
350 					i = SIGSEGV;
351 					ucode = SEGV_ACCERR;
352 				}
353 			}
354 			break;
355 
356 		case T_DIVIDE:		/* integer divide fault */
357 			ucode = FPE_INTDIV;
358 			i = SIGFPE;
359 			break;
360 
361 #ifdef DEV_ISA
362 		case T_NMI:
363 			/* machine/parity/power fail/"kitchen sink" faults */
364 			if (isa_nmi(code) == 0) {
365 #ifdef KDB
366 				/*
367 				 * NMI can be hooked up to a pushbutton
368 				 * for debugging.
369 				 */
370 				if (kdb_on_nmi) {
371 					printf ("NMI ... going to debugger\n");
372 					kdb_trap(type, 0, frame);
373 				}
374 #endif /* KDB */
375 				goto userout;
376 			} else if (panic_on_nmi)
377 				panic("NMI indicates hardware failure");
378 			break;
379 #endif /* DEV_ISA */
380 
381 		case T_OFLOW:		/* integer overflow fault */
382 			ucode = FPE_INTOVF;
383 			i = SIGFPE;
384 			break;
385 
386 		case T_BOUND:		/* bounds check fault */
387 			ucode = FPE_FLTSUB;
388 			i = SIGFPE;
389 			break;
390 
391 		case T_DNA:
392 			/* transparent fault (due to context switch "late") */
393 			KASSERT(PCB_USER_FPU(td->td_pcb),
394 			    ("kernel FPU ctx has leaked"));
395 			fpudna();
396 			goto userout;
397 
398 		case T_FPOPFLT:		/* FPU operand fetch fault */
399 			ucode = ILL_COPROC;
400 			i = SIGILL;
401 			break;
402 
403 		case T_XMMFLT:		/* SIMD floating-point exception */
404 			ucode = fputrap_sse();
405 			if (ucode == -1)
406 				goto userout;
407 			i = SIGFPE;
408 			break;
409 #ifdef KDTRACE_HOOKS
410 		case T_DTRACE_RET:
411 			enable_intr();
412 			fill_frame_regs(frame, &regs);
413 			if (dtrace_return_probe_ptr != NULL &&
414 			    dtrace_return_probe_ptr(&regs) == 0)
415 				goto out;
416 			break;
417 #endif
418 		}
419 	} else {
420 		/* kernel trap */
421 
422 		KASSERT(cold || td->td_ucred != NULL,
423 		    ("kernel trap doesn't have ucred"));
424 		switch (type) {
425 		case T_PAGEFLT:			/* page fault */
426 			(void) trap_pfault(frame, FALSE);
427 			goto out;
428 
429 		case T_DNA:
430 			KASSERT(!PCB_USER_FPU(td->td_pcb),
431 			    ("Unregistered use of FPU in kernel"));
432 			fpudna();
433 			goto out;
434 
435 		case T_ARITHTRAP:	/* arithmetic trap */
436 		case T_XMMFLT:		/* SIMD floating-point exception */
437 		case T_FPOPFLT:		/* FPU operand fetch fault */
438 			/*
439 			 * For now, supporting kernel handler
440 			 * registration for FPU traps is overkill.
441 			 */
442 			trap_fatal(frame, 0);
443 			goto out;
444 
445 		case T_STKFLT:		/* stack fault */
446 		case T_PROTFLT:		/* general protection fault */
447 		case T_SEGNPFLT:	/* segment not present fault */
448 			if (td->td_intr_nesting_level != 0)
449 				break;
450 
451 			/*
452 			 * Invalid segment selectors and out of bounds
453 			 * %rip's and %rsp's can be set up in user mode.
454 			 * This causes a fault in kernel mode when the
455 			 * kernel tries to return to user mode.  We want
456 			 * to get this fault so that we can fix the
457 			 * problem here and not have to check all the
458 			 * selectors and pointers when the user changes
459 			 * them.
460 			 */
461 			if (frame->tf_rip == (long)doreti_iret) {
462 				frame->tf_rip = (long)doreti_iret_fault;
463 				goto out;
464 			}
465 			if (frame->tf_rip == (long)ld_ds) {
466 				frame->tf_rip = (long)ds_load_fault;
467 				goto out;
468 			}
469 			if (frame->tf_rip == (long)ld_es) {
470 				frame->tf_rip = (long)es_load_fault;
471 				goto out;
472 			}
473 			if (frame->tf_rip == (long)ld_fs) {
474 				frame->tf_rip = (long)fs_load_fault;
475 				goto out;
476 			}
477 			if (frame->tf_rip == (long)ld_gs) {
478 				frame->tf_rip = (long)gs_load_fault;
479 				goto out;
480 			}
481 			if (frame->tf_rip == (long)ld_gsbase) {
482 				frame->tf_rip = (long)gsbase_load_fault;
483 				goto out;
484 			}
485 			if (frame->tf_rip == (long)ld_fsbase) {
486 				frame->tf_rip = (long)fsbase_load_fault;
487 				goto out;
488 			}
489 			if (curpcb->pcb_onfault != NULL) {
490 				frame->tf_rip = (long)curpcb->pcb_onfault;
491 				goto out;
492 			}
493 			break;
494 
495 		case T_TSSFLT:
496 			/*
497 			 * PSL_NT can be set in user mode and isn't cleared
498 			 * automatically when the kernel is entered.  This
499 			 * causes a TSS fault when the kernel attempts to
500 			 * `iret' because the TSS link is uninitialized.  We
501 			 * want to get this fault so that we can fix the
502 			 * problem here and not every time the kernel is
503 			 * entered.
504 			 */
505 			if (frame->tf_rflags & PSL_NT) {
506 				frame->tf_rflags &= ~PSL_NT;
507 				goto out;
508 			}
509 			break;
510 
511 		case T_TRCTRAP:	 /* trace trap */
512 			/*
513 			 * Ignore debug register trace traps due to
514 			 * accesses in the user's address space, which
515 			 * can happen under several conditions such as
516 			 * if a user sets a watchpoint on a buffer and
517 			 * then passes that buffer to a system call.
518 			 * We still want to get TRCTRAPS for addresses
519 			 * in kernel space because that is useful when
520 			 * debugging the kernel.
521 			 */
522 			if (user_dbreg_trap()) {
523 				/*
524 				 * Reset breakpoint bits because the
525 				 * processor doesn't
526 				 */
527 				/* XXX check upper bits here */
528 				load_dr6(rdr6() & 0xfffffff0);
529 				goto out;
530 			}
531 			/*
532 			 * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
533 			 */
534 		case T_BPTFLT:
535 			/*
536 			 * If KDB is enabled, let it handle the debugger trap.
537 			 * Otherwise, debugger traps "can't happen".
538 			 */
539 #ifdef KDB
540 			if (kdb_trap(type, 0, frame))
541 				goto out;
542 #endif
543 			break;
544 
545 #ifdef DEV_ISA
546 		case T_NMI:
547 			/* machine/parity/power fail/"kitchen sink" faults */
548 			if (isa_nmi(code) == 0) {
549 #ifdef KDB
550 				/*
551 				 * NMI can be hooked up to a pushbutton
552 				 * for debugging.
553 				 */
554 				if (kdb_on_nmi) {
555 					printf ("NMI ... going to debugger\n");
556 					kdb_trap(type, 0, frame);
557 				}
558 #endif /* KDB */
559 				goto out;
560 			} else if (panic_on_nmi == 0)
561 				goto out;
562 			/* FALLTHROUGH */
563 #endif /* DEV_ISA */
564 		}
565 
566 		trap_fatal(frame, 0);
567 		goto out;
568 	}
569 
570 	/* Translate fault for emulators (e.g. Linux) */
571 	if (*p->p_sysent->sv_transtrap)
572 		i = (*p->p_sysent->sv_transtrap)(i, type);
573 
574 	ksiginfo_init_trap(&ksi);
575 	ksi.ksi_signo = i;
576 	ksi.ksi_code = ucode;
577 	ksi.ksi_trapno = type;
578 	ksi.ksi_addr = (void *)addr;
579 	if (uprintf_signal) {
580 		uprintf("pid %d comm %s: signal %d err %lx code %d type %d "
581 		    "addr 0x%lx rsp 0x%lx rip 0x%lx "
582 		    "<%02x %02x %02x %02x %02x %02x %02x %02x>\n",
583 		    p->p_pid, p->p_comm, i, frame->tf_err, ucode, type, addr,
584 		    frame->tf_rsp, frame->tf_rip,
585 		    fubyte((void *)(frame->tf_rip + 0)),
586 		    fubyte((void *)(frame->tf_rip + 1)),
587 		    fubyte((void *)(frame->tf_rip + 2)),
588 		    fubyte((void *)(frame->tf_rip + 3)),
589 		    fubyte((void *)(frame->tf_rip + 4)),
590 		    fubyte((void *)(frame->tf_rip + 5)),
591 		    fubyte((void *)(frame->tf_rip + 6)),
592 		    fubyte((void *)(frame->tf_rip + 7)));
593 	}
594 	KASSERT((read_rflags() & PSL_I) != 0, ("interrupts disabled"));
595 	trapsignal(td, &ksi);
596 
597 user:
598 	userret(td, frame);
599 	KASSERT(PCB_USER_FPU(td->td_pcb),
600 	    ("Return from trap with kernel FPU ctx leaked"));
601 userout:
602 out:
603 	return;
604 }
605 
606 /*
607  * Ensure that we ignore any DTrace-induced faults. This function cannot
608  * be instrumented, so it cannot generate such faults itself.
609  */
610 void
611 trap_check(struct trapframe *frame)
612 {
613 
614 #ifdef KDTRACE_HOOKS
615 	if (dtrace_trap_func != NULL &&
616 	    (*dtrace_trap_func)(frame, frame->tf_trapno) != 0)
617 		return;
618 #endif
619 	trap(frame);
620 }
621 
622 static int
623 trap_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 	}
768 nogo:
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 		trap_fatal(frame, eva);
776 		return (-1);
777 	}
778 	return ((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
779 }
780 
781 static void
782 trap_fatal(frame, eva)
783 	struct trapframe *frame;
784 	vm_offset_t eva;
785 {
786 	int code, ss;
787 	u_int type;
788 	long esp;
789 	struct soft_segment_descriptor softseg;
790 	char *msg;
791 
792 	code = frame->tf_err;
793 	type = frame->tf_trapno;
794 	sdtossd(&gdt[NGDT * PCPU_GET(cpuid) + IDXSEL(frame->tf_cs & 0xffff)],
795 	    &softseg);
796 
797 	if (type <= MAX_TRAP_MSG)
798 		msg = trap_msg[type];
799 	else
800 		msg = "UNKNOWN";
801 	printf("\n\nFatal trap %d: %s while in %s mode\n", type, msg,
802 	    ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
803 #ifdef SMP
804 	/* two separate prints in case of a trap on an unmapped page */
805 	printf("cpuid = %d; ", PCPU_GET(cpuid));
806 	printf("apic id = %02x\n", PCPU_GET(apic_id));
807 #endif
808 	if (type == T_PAGEFLT) {
809 		printf("fault virtual address	= 0x%lx\n", eva);
810 		printf("fault code		= %s %s %s%s, %s\n",
811 			code & PGEX_U ? "user" : "supervisor",
812 			code & PGEX_W ? "write" : "read",
813 			code & PGEX_I ? "instruction" : "data",
814 			code & PGEX_RSV ? " rsv" : "",
815 			code & PGEX_P ? "protection violation" : "page not present");
816 	}
817 	printf("instruction pointer	= 0x%lx:0x%lx\n",
818 	       frame->tf_cs & 0xffff, frame->tf_rip);
819         if (ISPL(frame->tf_cs) == SEL_UPL) {
820 		ss = frame->tf_ss & 0xffff;
821 		esp = frame->tf_rsp;
822 	} else {
823 		ss = GSEL(GDATA_SEL, SEL_KPL);
824 		esp = (long)&frame->tf_rsp;
825 	}
826 	printf("stack pointer	        = 0x%x:0x%lx\n", ss, esp);
827 	printf("frame pointer	        = 0x%x:0x%lx\n", ss, frame->tf_rbp);
828 	printf("code segment		= base 0x%lx, limit 0x%lx, type 0x%x\n",
829 	       softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
830 	printf("			= DPL %d, pres %d, long %d, def32 %d, gran %d\n",
831 	       softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
832 	       softseg.ssd_gran);
833 	printf("processor eflags	= ");
834 	if (frame->tf_rflags & PSL_T)
835 		printf("trace trap, ");
836 	if (frame->tf_rflags & PSL_I)
837 		printf("interrupt enabled, ");
838 	if (frame->tf_rflags & PSL_NT)
839 		printf("nested task, ");
840 	if (frame->tf_rflags & PSL_RF)
841 		printf("resume, ");
842 	printf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
843 	printf("current process		= ");
844 	if (curproc) {
845 		printf("%lu (%s)\n",
846 		    (u_long)curproc->p_pid, curthread->td_name ?
847 		    curthread->td_name : "");
848 	} else {
849 		printf("Idle\n");
850 	}
851 
852 #ifdef KDB
853 	if (debugger_on_panic || kdb_active)
854 		if (kdb_trap(type, 0, frame))
855 			return;
856 #endif
857 	printf("trap number		= %d\n", type);
858 	if (type <= MAX_TRAP_MSG)
859 		panic("%s", trap_msg[type]);
860 	else
861 		panic("unknown/reserved trap");
862 }
863 
864 /*
865  * Double fault handler. Called when a fault occurs while writing
866  * a frame for a trap/exception onto the stack. This usually occurs
867  * when the stack overflows (such is the case with infinite recursion,
868  * for example).
869  */
870 void
871 dblfault_handler(struct trapframe *frame)
872 {
873 #ifdef KDTRACE_HOOKS
874 	if (dtrace_doubletrap_func != NULL)
875 		(*dtrace_doubletrap_func)();
876 #endif
877 	printf("\nFatal double fault\n");
878 	printf("rip = 0x%lx\n", frame->tf_rip);
879 	printf("rsp = 0x%lx\n", frame->tf_rsp);
880 	printf("rbp = 0x%lx\n", frame->tf_rbp);
881 #ifdef SMP
882 	/* two separate prints in case of a trap on an unmapped page */
883 	printf("cpuid = %d; ", PCPU_GET(cpuid));
884 	printf("apic id = %02x\n", PCPU_GET(apic_id));
885 #endif
886 	panic("double fault");
887 }
888 
889 int
890 cpu_fetch_syscall_args(struct thread *td, struct syscall_args *sa)
891 {
892 	struct proc *p;
893 	struct trapframe *frame;
894 	register_t *argp;
895 	caddr_t params;
896 	int reg, regcnt, error;
897 
898 	p = td->td_proc;
899 	frame = td->td_frame;
900 	reg = 0;
901 	regcnt = 6;
902 
903 	params = (caddr_t)frame->tf_rsp + sizeof(register_t);
904 	sa->code = frame->tf_rax;
905 
906 	if (sa->code == SYS_syscall || sa->code == SYS___syscall) {
907 		sa->code = frame->tf_rdi;
908 		reg++;
909 		regcnt--;
910 	}
911  	if (p->p_sysent->sv_mask)
912  		sa->code &= p->p_sysent->sv_mask;
913 
914  	if (sa->code >= p->p_sysent->sv_size)
915  		sa->callp = &p->p_sysent->sv_table[0];
916   	else
917  		sa->callp = &p->p_sysent->sv_table[sa->code];
918 
919 	sa->narg = sa->callp->sy_narg;
920 	KASSERT(sa->narg <= sizeof(sa->args) / sizeof(sa->args[0]),
921 	    ("Too many syscall arguments!"));
922 	error = 0;
923 	argp = &frame->tf_rdi;
924 	argp += reg;
925 	bcopy(argp, sa->args, sizeof(sa->args[0]) * regcnt);
926 	if (sa->narg > regcnt) {
927 		KASSERT(params != NULL, ("copyin args with no params!"));
928 		error = copyin(params, &sa->args[regcnt],
929 	    	    (sa->narg - regcnt) * sizeof(sa->args[0]));
930 	}
931 
932 	if (error == 0) {
933 		td->td_retval[0] = 0;
934 		td->td_retval[1] = frame->tf_rdx;
935 	}
936 
937 	return (error);
938 }
939 
940 #include "../../kern/subr_syscall.c"
941 
942 /*
943  * System call handler for native binaries.  The trap frame is already
944  * set up by the assembler trampoline and a pointer to it is saved in
945  * td_frame.
946  */
947 void
948 amd64_syscall(struct thread *td, int traced)
949 {
950 	struct syscall_args sa;
951 	int error;
952 	ksiginfo_t ksi;
953 
954 #ifdef DIAGNOSTIC
955 	if (ISPL(td->td_frame->tf_cs) != SEL_UPL) {
956 		panic("syscall");
957 		/* NOT REACHED */
958 	}
959 #endif
960 	error = syscallenter(td, &sa);
961 
962 	/*
963 	 * Traced syscall.
964 	 */
965 	if (__predict_false(traced)) {
966 		td->td_frame->tf_rflags &= ~PSL_T;
967 		ksiginfo_init_trap(&ksi);
968 		ksi.ksi_signo = SIGTRAP;
969 		ksi.ksi_code = TRAP_TRACE;
970 		ksi.ksi_addr = (void *)td->td_frame->tf_rip;
971 		trapsignal(td, &ksi);
972 	}
973 
974 	KASSERT(PCB_USER_FPU(td->td_pcb),
975 	    ("System call %s returing with kernel FPU ctx leaked",
976 	     syscallname(td->td_proc, sa.code)));
977 	KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td),
978 	    ("System call %s returning with mangled pcb_save",
979 	     syscallname(td->td_proc, sa.code)));
980 
981 	syscallret(td, error, &sa);
982 
983 	/*
984 	 * If the user-supplied value of %rip is not a canonical
985 	 * address, then some CPUs will trigger a ring 0 #GP during
986 	 * the sysret instruction.  However, the fault handler would
987 	 * execute in ring 0 with the user's %gs and %rsp which would
988 	 * not be safe.  Instead, use the full return path which
989 	 * catches the problem safely.
990 	 */
991 	if (td->td_frame->tf_rip >= VM_MAXUSER_ADDRESS)
992 		set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
993 }
994