]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/trap.c
Update from svn-1.8.14 to 1.9.2.
[FreeBSD/FreeBSD.git] / sys / amd64 / amd64 / trap.c
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 #include "opt_stack.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>
74 PMC_SOFT_DEFINE( , , page_fault, all);
75 PMC_SOFT_DEFINE( , , page_fault, read);
76 PMC_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/stack.h>
96 #include <machine/tss.h>
97
98 #ifdef KDTRACE_HOOKS
99 #include <sys/dtrace_bsd.h>
100 #endif
101
102 extern void __noinline trap(struct trapframe *frame);
103 extern void trap_check(struct trapframe *frame);
104 extern void syscall(struct trapframe *frame);
105 void dblfault_handler(struct trapframe *frame);
106
107 static int trap_pfault(struct trapframe *, int);
108 static void trap_fatal(struct trapframe *, vm_offset_t);
109
110 #define MAX_TRAP_MSG            32
111 static char *trap_msg[] = {
112         "",                                     /*  0 unused */
113         "privileged instruction fault",         /*  1 T_PRIVINFLT */
114         "",                                     /*  2 unused */
115         "breakpoint instruction fault",         /*  3 T_BPTFLT */
116         "",                                     /*  4 unused */
117         "",                                     /*  5 unused */
118         "arithmetic trap",                      /*  6 T_ARITHTRAP */
119         "",                                     /*  7 unused */
120         "",                                     /*  8 unused */
121         "general protection fault",             /*  9 T_PROTFLT */
122         "trace trap",                           /* 10 T_TRCTRAP */
123         "",                                     /* 11 unused */
124         "page fault",                           /* 12 T_PAGEFLT */
125         "",                                     /* 13 unused */
126         "alignment fault",                      /* 14 T_ALIGNFLT */
127         "",                                     /* 15 unused */
128         "",                                     /* 16 unused */
129         "",                                     /* 17 unused */
130         "integer divide fault",                 /* 18 T_DIVIDE */
131         "non-maskable interrupt trap",          /* 19 T_NMI */
132         "overflow trap",                        /* 20 T_OFLOW */
133         "FPU bounds check fault",               /* 21 T_BOUND */
134         "FPU device not available",             /* 22 T_DNA */
135         "double fault",                         /* 23 T_DOUBLEFLT */
136         "FPU operand fetch fault",              /* 24 T_FPOPFLT */
137         "invalid TSS fault",                    /* 25 T_TSSFLT */
138         "segment not present fault",            /* 26 T_SEGNPFLT */
139         "stack fault",                          /* 27 T_STKFLT */
140         "machine check trap",                   /* 28 T_MCHK */
141         "SIMD floating-point exception",        /* 29 T_XMMFLT */
142         "reserved (unknown) fault",             /* 30 T_RESERVED */
143         "",                                     /* 31 unused (reserved) */
144         "DTrace pid return trap",               /* 32 T_DTRACE_RET */
145 };
146
147 #ifdef KDB
148 static int kdb_on_nmi = 1;
149 SYSCTL_INT(_machdep, OID_AUTO, kdb_on_nmi, CTLFLAG_RWTUN,
150         &kdb_on_nmi, 0, "Go to KDB on NMI");
151 #endif
152 static int panic_on_nmi = 1;
153 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RWTUN,
154         &panic_on_nmi, 0, "Panic on NMI");
155 static int prot_fault_translation;
156 SYSCTL_INT(_machdep, OID_AUTO, prot_fault_translation, CTLFLAG_RWTUN,
157     &prot_fault_translation, 0,
158     "Select signal to deliver on protection fault");
159 static int uprintf_signal;
160 SYSCTL_INT(_machdep, OID_AUTO, uprintf_signal, CTLFLAG_RWTUN,
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
171 void
172 trap(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         if (type == T_NMI) {
208 #ifdef HWPMC_HOOKS
209                 /*
210                  * CPU PMCs interrupt using an NMI.  If the PMC module is
211                  * active, pass the 'rip' value to the PMC module's interrupt
212                  * handler.  A non-zero return value from the handler means that
213                  * the NMI was consumed by it and we can return immediately.
214                  */
215                 if (pmc_intr != NULL &&
216                     (*pmc_intr)(PCPU_GET(cpuid), frame) != 0)
217                         goto out;
218 #endif
219
220 #ifdef STACK
221                 if (stack_nmi_handler(frame) != 0)
222                         goto out;
223 #endif
224         }
225
226         if (type == T_MCHK) {
227                 mca_intr();
228                 goto out;
229         }
230
231         if ((frame->tf_rflags & PSL_I) == 0) {
232                 /*
233                  * Buggy application or kernel code has disabled
234                  * interrupts and then trapped.  Enabling interrupts
235                  * now is wrong, but it is better than running with
236                  * interrupts disabled until they are accidentally
237                  * enabled later.
238                  */
239                 if (ISPL(frame->tf_cs) == SEL_UPL)
240                         uprintf(
241                             "pid %ld (%s): trap %d with interrupts disabled\n",
242                             (long)curproc->p_pid, curthread->td_name, type);
243                 else if (type != T_NMI && type != T_BPTFLT &&
244                     type != T_TRCTRAP) {
245                         /*
246                          * XXX not quite right, since this may be for a
247                          * multiple fault in user mode.
248                          */
249                         printf("kernel trap %d with interrupts disabled\n",
250                             type);
251
252                         /*
253                          * We shouldn't enable interrupts while holding a
254                          * spin lock.
255                          */
256                         if (td->td_md.md_spinlock_count == 0)
257                                 enable_intr();
258                 }
259         }
260
261         code = frame->tf_err;
262
263         if (ISPL(frame->tf_cs) == SEL_UPL) {
264                 /* user trap */
265
266                 td->td_pticks = 0;
267                 td->td_frame = frame;
268                 addr = frame->tf_rip;
269                 if (td->td_cowgen != p->p_cowgen)
270                         thread_cow_update(td);
271
272                 switch (type) {
273                 case T_PRIVINFLT:       /* privileged instruction fault */
274                         i = SIGILL;
275                         ucode = ILL_PRVOPC;
276                         break;
277
278                 case T_BPTFLT:          /* bpt instruction fault */
279                 case T_TRCTRAP:         /* trace trap */
280                         enable_intr();
281 #ifdef KDTRACE_HOOKS
282                         if (type == T_BPTFLT) {
283                                 fill_frame_regs(frame, &regs);
284                                 if (dtrace_pid_probe_ptr != NULL &&
285                                     dtrace_pid_probe_ptr(&regs) == 0)
286                                         goto out;
287                         }
288 #endif
289                         frame->tf_rflags &= ~PSL_T;
290                         i = SIGTRAP;
291                         ucode = (type == T_TRCTRAP ? TRAP_TRACE : TRAP_BRKPT);
292                         break;
293
294                 case T_ARITHTRAP:       /* arithmetic trap */
295                         ucode = fputrap_x87();
296                         if (ucode == -1)
297                                 goto userout;
298                         i = SIGFPE;
299                         break;
300
301                 case T_PROTFLT:         /* general protection fault */
302                         i = SIGBUS;
303                         ucode = BUS_OBJERR;
304                         break;
305                 case T_STKFLT:          /* stack fault */
306                 case T_SEGNPFLT:        /* segment not present fault */
307                         i = SIGBUS;
308                         ucode = BUS_ADRERR;
309                         break;
310                 case T_TSSFLT:          /* invalid TSS fault */
311                         i = SIGBUS;
312                         ucode = BUS_OBJERR;
313                         break;
314                 case T_ALIGNFLT:
315                         i = SIGBUS;
316                         ucode = BUS_ADRALN;
317                         break;
318                 case T_DOUBLEFLT:       /* double fault */
319                 default:
320                         i = SIGBUS;
321                         ucode = BUS_OBJERR;
322                         break;
323
324                 case T_PAGEFLT:         /* page fault */
325                         addr = frame->tf_addr;
326                         i = trap_pfault(frame, TRUE);
327                         if (i == -1)
328                                 goto userout;
329                         if (i == 0)
330                                 goto user;
331
332                         if (i == SIGSEGV)
333                                 ucode = SEGV_MAPERR;
334                         else {
335                                 if (prot_fault_translation == 0) {
336                                         /*
337                                          * Autodetect.
338                                          * This check also covers the images
339                                          * without the ABI-tag ELF note.
340                                          */
341                                         if (SV_CURPROC_ABI() == SV_ABI_FREEBSD
342                                             && p->p_osrel >= P_OSREL_SIGSEGV) {
343                                                 i = SIGSEGV;
344                                                 ucode = SEGV_ACCERR;
345                                         } else {
346                                                 i = SIGBUS;
347                                                 ucode = BUS_PAGE_FAULT;
348                                         }
349                                 } else if (prot_fault_translation == 1) {
350                                         /*
351                                          * Always compat mode.
352                                          */
353                                         i = SIGBUS;
354                                         ucode = BUS_PAGE_FAULT;
355                                 } else {
356                                         /*
357                                          * Always SIGSEGV mode.
358                                          */
359                                         i = SIGSEGV;
360                                         ucode = SEGV_ACCERR;
361                                 }
362                         }
363                         break;
364
365                 case T_DIVIDE:          /* integer divide fault */
366                         ucode = FPE_INTDIV;
367                         i = SIGFPE;
368                         break;
369
370 #ifdef DEV_ISA
371                 case T_NMI:
372                         /* machine/parity/power fail/"kitchen sink" faults */
373                         if (isa_nmi(code) == 0) {
374 #ifdef KDB
375                                 /*
376                                  * NMI can be hooked up to a pushbutton
377                                  * for debugging.
378                                  */
379                                 if (kdb_on_nmi) {
380                                         printf ("NMI ... going to debugger\n");
381                                         kdb_trap(type, 0, frame);
382                                 }
383 #endif /* KDB */
384                                 goto userout;
385                         } else if (panic_on_nmi)
386                                 panic("NMI indicates hardware failure");
387                         break;
388 #endif /* DEV_ISA */
389
390                 case T_OFLOW:           /* integer overflow fault */
391                         ucode = FPE_INTOVF;
392                         i = SIGFPE;
393                         break;
394
395                 case T_BOUND:           /* bounds check fault */
396                         ucode = FPE_FLTSUB;
397                         i = SIGFPE;
398                         break;
399
400                 case T_DNA:
401                         /* transparent fault (due to context switch "late") */
402                         KASSERT(PCB_USER_FPU(td->td_pcb),
403                             ("kernel FPU ctx has leaked"));
404                         fpudna();
405                         goto userout;
406
407                 case T_FPOPFLT:         /* FPU operand fetch fault */
408                         ucode = ILL_COPROC;
409                         i = SIGILL;
410                         break;
411
412                 case T_XMMFLT:          /* SIMD floating-point exception */
413                         ucode = fputrap_sse();
414                         if (ucode == -1)
415                                 goto userout;
416                         i = SIGFPE;
417                         break;
418 #ifdef KDTRACE_HOOKS
419                 case T_DTRACE_RET:
420                         enable_intr();
421                         fill_frame_regs(frame, &regs);
422                         if (dtrace_return_probe_ptr != NULL &&
423                             dtrace_return_probe_ptr(&regs) == 0)
424                                 goto out;
425                         break;
426 #endif
427                 }
428         } else {
429                 /* kernel trap */
430
431                 KASSERT(cold || td->td_ucred != NULL,
432                     ("kernel trap doesn't have ucred"));
433                 switch (type) {
434                 case T_PAGEFLT:                 /* page fault */
435                         (void) trap_pfault(frame, FALSE);
436                         goto out;
437
438                 case T_DNA:
439                         KASSERT(!PCB_USER_FPU(td->td_pcb),
440                             ("Unregistered use of FPU in kernel"));
441                         fpudna();
442                         goto out;
443
444                 case T_ARITHTRAP:       /* arithmetic trap */
445                 case T_XMMFLT:          /* SIMD floating-point exception */
446                 case T_FPOPFLT:         /* FPU operand fetch fault */
447                         /*
448                          * For now, supporting kernel handler
449                          * registration for FPU traps is overkill.
450                          */
451                         trap_fatal(frame, 0);
452                         goto out;
453
454                 case T_STKFLT:          /* stack fault */
455                 case T_PROTFLT:         /* general protection fault */
456                 case T_SEGNPFLT:        /* segment not present fault */
457                         if (td->td_intr_nesting_level != 0)
458                                 break;
459
460                         /*
461                          * Invalid segment selectors and out of bounds
462                          * %rip's and %rsp's can be set up in user mode.
463                          * This causes a fault in kernel mode when the
464                          * kernel tries to return to user mode.  We want
465                          * to get this fault so that we can fix the
466                          * problem here and not have to check all the
467                          * selectors and pointers when the user changes
468                          * them.
469                          */
470                         if (frame->tf_rip == (long)doreti_iret) {
471                                 frame->tf_rip = (long)doreti_iret_fault;
472                                 goto out;
473                         }
474                         if (frame->tf_rip == (long)ld_ds) {
475                                 frame->tf_rip = (long)ds_load_fault;
476                                 goto out;
477                         }
478                         if (frame->tf_rip == (long)ld_es) {
479                                 frame->tf_rip = (long)es_load_fault;
480                                 goto out;
481                         }
482                         if (frame->tf_rip == (long)ld_fs) {
483                                 frame->tf_rip = (long)fs_load_fault;
484                                 goto out;
485                         }
486                         if (frame->tf_rip == (long)ld_gs) {
487                                 frame->tf_rip = (long)gs_load_fault;
488                                 goto out;
489                         }
490                         if (frame->tf_rip == (long)ld_gsbase) {
491                                 frame->tf_rip = (long)gsbase_load_fault;
492                                 goto out;
493                         }
494                         if (frame->tf_rip == (long)ld_fsbase) {
495                                 frame->tf_rip = (long)fsbase_load_fault;
496                                 goto out;
497                         }
498                         if (curpcb->pcb_onfault != NULL) {
499                                 frame->tf_rip = (long)curpcb->pcb_onfault;
500                                 goto out;
501                         }
502                         break;
503
504                 case T_TSSFLT:
505                         /*
506                          * PSL_NT can be set in user mode and isn't cleared
507                          * automatically when the kernel is entered.  This
508                          * causes a TSS fault when the kernel attempts to
509                          * `iret' because the TSS link is uninitialized.  We
510                          * want to get this fault so that we can fix the
511                          * problem here and not every time the kernel is
512                          * entered.
513                          */
514                         if (frame->tf_rflags & PSL_NT) {
515                                 frame->tf_rflags &= ~PSL_NT;
516                                 goto out;
517                         }
518                         break;
519
520                 case T_TRCTRAP:  /* trace trap */
521                         /*
522                          * Ignore debug register trace traps due to
523                          * accesses in the user's address space, which
524                          * can happen under several conditions such as
525                          * if a user sets a watchpoint on a buffer and
526                          * then passes that buffer to a system call.
527                          * We still want to get TRCTRAPS for addresses
528                          * in kernel space because that is useful when
529                          * debugging the kernel.
530                          */
531                         if (user_dbreg_trap()) {
532                                 /*
533                                  * Reset breakpoint bits because the
534                                  * processor doesn't
535                                  */
536                                 /* XXX check upper bits here */
537                                 load_dr6(rdr6() & 0xfffffff0);
538                                 goto out;
539                         }
540                         /*
541                          * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
542                          */
543                 case T_BPTFLT:
544                         /*
545                          * If KDB is enabled, let it handle the debugger trap.
546                          * Otherwise, debugger traps "can't happen".
547                          */
548 #ifdef KDB
549                         if (kdb_trap(type, 0, frame))
550                                 goto out;
551 #endif
552                         break;
553
554 #ifdef DEV_ISA
555                 case T_NMI:
556                         /* machine/parity/power fail/"kitchen sink" faults */
557                         if (isa_nmi(code) == 0) {
558 #ifdef KDB
559                                 /*
560                                  * NMI can be hooked up to a pushbutton
561                                  * for debugging.
562                                  */
563                                 if (kdb_on_nmi) {
564                                         printf ("NMI ... going to debugger\n");
565                                         kdb_trap(type, 0, frame);
566                                 }
567 #endif /* KDB */
568                                 goto out;
569                         } else if (panic_on_nmi == 0)
570                                 goto out;
571                         /* FALLTHROUGH */
572 #endif /* DEV_ISA */
573                 }
574
575                 trap_fatal(frame, 0);
576                 goto out;
577         }
578
579         /* Translate fault for emulators (e.g. Linux) */
580         if (*p->p_sysent->sv_transtrap)
581                 i = (*p->p_sysent->sv_transtrap)(i, type);
582
583         ksiginfo_init_trap(&ksi);
584         ksi.ksi_signo = i;
585         ksi.ksi_code = ucode;
586         ksi.ksi_trapno = type;
587         ksi.ksi_addr = (void *)addr;
588         if (uprintf_signal) {
589                 uprintf("pid %d comm %s: signal %d err %lx code %d type %d "
590                     "addr 0x%lx rsp 0x%lx rip 0x%lx "
591                     "<%02x %02x %02x %02x %02x %02x %02x %02x>\n",
592                     p->p_pid, p->p_comm, i, frame->tf_err, ucode, type, addr,
593                     frame->tf_rsp, frame->tf_rip,
594                     fubyte((void *)(frame->tf_rip + 0)),
595                     fubyte((void *)(frame->tf_rip + 1)),
596                     fubyte((void *)(frame->tf_rip + 2)),
597                     fubyte((void *)(frame->tf_rip + 3)),
598                     fubyte((void *)(frame->tf_rip + 4)),
599                     fubyte((void *)(frame->tf_rip + 5)),
600                     fubyte((void *)(frame->tf_rip + 6)),
601                     fubyte((void *)(frame->tf_rip + 7)));
602         }
603         KASSERT((read_rflags() & PSL_I) != 0, ("interrupts disabled"));
604         trapsignal(td, &ksi);
605
606 user:
607         userret(td, frame);
608         KASSERT(PCB_USER_FPU(td->td_pcb),
609             ("Return from trap with kernel FPU ctx leaked"));
610 userout:
611 out:
612         return;
613 }
614
615 /*
616  * Ensure that we ignore any DTrace-induced faults. This function cannot
617  * be instrumented, so it cannot generate such faults itself.
618  */
619 void
620 trap_check(struct trapframe *frame)
621 {
622
623 #ifdef KDTRACE_HOOKS
624         if (dtrace_trap_func != NULL &&
625             (*dtrace_trap_func)(frame, frame->tf_trapno) != 0)
626                 return;
627 #endif
628         trap(frame);
629 }
630
631 static int
632 trap_pfault(frame, usermode)
633         struct trapframe *frame;
634         int usermode;
635 {
636         vm_offset_t va;
637         vm_map_t map;
638         int rv = 0;
639         vm_prot_t ftype;
640         struct thread *td = curthread;
641         struct proc *p = td->td_proc;
642         vm_offset_t eva = frame->tf_addr;
643
644         if (__predict_false((td->td_pflags & TDP_NOFAULTING) != 0)) {
645                 /*
646                  * Due to both processor errata and lazy TLB invalidation when
647                  * access restrictions are removed from virtual pages, memory
648                  * accesses that are allowed by the physical mapping layer may
649                  * nonetheless cause one spurious page fault per virtual page. 
650                  * When the thread is executing a "no faulting" section that
651                  * is bracketed by vm_fault_{disable,enable}_pagefaults(),
652                  * every page fault is treated as a spurious page fault,
653                  * unless it accesses the same virtual address as the most
654                  * recent page fault within the same "no faulting" section.
655                  */
656                 if (td->td_md.md_spurflt_addr != eva ||
657                     (td->td_pflags & TDP_RESETSPUR) != 0) {
658                         /*
659                          * Do nothing to the TLB.  A stale TLB entry is
660                          * flushed automatically by a page fault.
661                          */
662                         td->td_md.md_spurflt_addr = eva;
663                         td->td_pflags &= ~TDP_RESETSPUR;
664                         return (0);
665                 }
666         } else {
667                 /*
668                  * If we get a page fault while in a critical section, then
669                  * it is most likely a fatal kernel page fault.  The kernel
670                  * is already going to panic trying to get a sleep lock to
671                  * do the VM lookup, so just consider it a fatal trap so the
672                  * kernel can print out a useful trap message and even get
673                  * to the debugger.
674                  *
675                  * If we get a page fault while holding a non-sleepable
676                  * lock, then it is most likely a fatal kernel page fault.
677                  * If WITNESS is enabled, then it's going to whine about
678                  * bogus LORs with various VM locks, so just skip to the
679                  * fatal trap handling directly.
680                  */
681                 if (td->td_critnest != 0 ||
682                     WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
683                     "Kernel page fault") != 0) {
684                         trap_fatal(frame, eva);
685                         return (-1);
686                 }
687         }
688         va = trunc_page(eva);
689         if (va >= VM_MIN_KERNEL_ADDRESS) {
690                 /*
691                  * Don't allow user-mode faults in kernel address space.
692                  */
693                 if (usermode)
694                         goto nogo;
695
696                 map = kernel_map;
697         } else {
698                 map = &p->p_vmspace->vm_map;
699
700                 /*
701                  * When accessing a usermode address, kernel must be
702                  * ready to accept the page fault, and provide a
703                  * handling routine.  Since accessing the address
704                  * without the handler is a bug, do not try to handle
705                  * it normally, and panic immediately.
706                  */
707                 if (!usermode && (td->td_intr_nesting_level != 0 ||
708                     curpcb->pcb_onfault == NULL)) {
709                         trap_fatal(frame, eva);
710                         return (-1);
711                 }
712         }
713
714         /*
715          * If the trap was caused by errant bits in the PTE then panic.
716          */
717         if (frame->tf_err & PGEX_RSV) {
718                 trap_fatal(frame, eva);
719                 return (-1);
720         }
721
722         /*
723          * PGEX_I is defined only if the execute disable bit capability is
724          * supported and enabled.
725          */
726         if (frame->tf_err & PGEX_W)
727                 ftype = VM_PROT_WRITE;
728         else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
729                 ftype = VM_PROT_EXECUTE;
730         else
731                 ftype = VM_PROT_READ;
732
733         /* Fault in the page. */
734         rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
735         if (rv == KERN_SUCCESS) {
736 #ifdef HWPMC_HOOKS
737                 if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
738                         PMC_SOFT_CALL_TF( , , page_fault, all, frame);
739                         if (ftype == VM_PROT_READ)
740                                 PMC_SOFT_CALL_TF( , , page_fault, read,
741                                     frame);
742                         else
743                                 PMC_SOFT_CALL_TF( , , page_fault, write,
744                                     frame);
745                 }
746 #endif
747                 return (0);
748         }
749 nogo:
750         if (!usermode) {
751                 if (td->td_intr_nesting_level == 0 &&
752                     curpcb->pcb_onfault != NULL) {
753                         frame->tf_rip = (long)curpcb->pcb_onfault;
754                         return (0);
755                 }
756                 trap_fatal(frame, eva);
757                 return (-1);
758         }
759         return ((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
760 }
761
762 static void
763 trap_fatal(frame, eva)
764         struct trapframe *frame;
765         vm_offset_t eva;
766 {
767         int code, ss;
768         u_int type;
769         long esp;
770         struct soft_segment_descriptor softseg;
771         char *msg;
772
773         code = frame->tf_err;
774         type = frame->tf_trapno;
775         sdtossd(&gdt[NGDT * PCPU_GET(cpuid) + IDXSEL(frame->tf_cs & 0xffff)],
776             &softseg);
777
778         if (type <= MAX_TRAP_MSG)
779                 msg = trap_msg[type];
780         else
781                 msg = "UNKNOWN";
782         printf("\n\nFatal trap %d: %s while in %s mode\n", type, msg,
783             ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
784 #ifdef SMP
785         /* two separate prints in case of a trap on an unmapped page */
786         printf("cpuid = %d; ", PCPU_GET(cpuid));
787         printf("apic id = %02x\n", PCPU_GET(apic_id));
788 #endif
789         if (type == T_PAGEFLT) {
790                 printf("fault virtual address   = 0x%lx\n", eva);
791                 printf("fault code              = %s %s %s%s, %s\n",
792                         code & PGEX_U ? "user" : "supervisor",
793                         code & PGEX_W ? "write" : "read",
794                         code & PGEX_I ? "instruction" : "data",
795                         code & PGEX_RSV ? " rsv" : "",
796                         code & PGEX_P ? "protection violation" : "page not present");
797         }
798         printf("instruction pointer     = 0x%lx:0x%lx\n",
799                frame->tf_cs & 0xffff, frame->tf_rip);
800         if (ISPL(frame->tf_cs) == SEL_UPL) {
801                 ss = frame->tf_ss & 0xffff;
802                 esp = frame->tf_rsp;
803         } else {
804                 ss = GSEL(GDATA_SEL, SEL_KPL);
805                 esp = (long)&frame->tf_rsp;
806         }
807         printf("stack pointer           = 0x%x:0x%lx\n", ss, esp);
808         printf("frame pointer           = 0x%x:0x%lx\n", ss, frame->tf_rbp);
809         printf("code segment            = base 0x%lx, limit 0x%lx, type 0x%x\n",
810                softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
811         printf("                        = DPL %d, pres %d, long %d, def32 %d, gran %d\n",
812                softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
813                softseg.ssd_gran);
814         printf("processor eflags        = ");
815         if (frame->tf_rflags & PSL_T)
816                 printf("trace trap, ");
817         if (frame->tf_rflags & PSL_I)
818                 printf("interrupt enabled, ");
819         if (frame->tf_rflags & PSL_NT)
820                 printf("nested task, ");
821         if (frame->tf_rflags & PSL_RF)
822                 printf("resume, ");
823         printf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
824         printf("current process         = %d (%s)\n",
825             curproc->p_pid, curthread->td_name);
826
827 #ifdef KDB
828         if (debugger_on_panic || kdb_active)
829                 if (kdb_trap(type, 0, frame))
830                         return;
831 #endif
832         printf("trap number             = %d\n", type);
833         if (type <= MAX_TRAP_MSG)
834                 panic("%s", trap_msg[type]);
835         else
836                 panic("unknown/reserved trap");
837 }
838
839 /*
840  * Double fault handler. Called when a fault occurs while writing
841  * a frame for a trap/exception onto the stack. This usually occurs
842  * when the stack overflows (such is the case with infinite recursion,
843  * for example).
844  */
845 void
846 dblfault_handler(struct trapframe *frame)
847 {
848 #ifdef KDTRACE_HOOKS
849         if (dtrace_doubletrap_func != NULL)
850                 (*dtrace_doubletrap_func)();
851 #endif
852         printf("\nFatal double fault\n");
853         printf("rip = 0x%lx\n", frame->tf_rip);
854         printf("rsp = 0x%lx\n", frame->tf_rsp);
855         printf("rbp = 0x%lx\n", frame->tf_rbp);
856 #ifdef SMP
857         /* two separate prints in case of a trap on an unmapped page */
858         printf("cpuid = %d; ", PCPU_GET(cpuid));
859         printf("apic id = %02x\n", PCPU_GET(apic_id));
860 #endif
861         panic("double fault");
862 }
863
864 int
865 cpu_fetch_syscall_args(struct thread *td, struct syscall_args *sa)
866 {
867         struct proc *p;
868         struct trapframe *frame;
869         register_t *argp;
870         caddr_t params;
871         int reg, regcnt, error;
872
873         p = td->td_proc;
874         frame = td->td_frame;
875         reg = 0;
876         regcnt = 6;
877
878         params = (caddr_t)frame->tf_rsp + sizeof(register_t);
879         sa->code = frame->tf_rax;
880
881         if (sa->code == SYS_syscall || sa->code == SYS___syscall) {
882                 sa->code = frame->tf_rdi;
883                 reg++;
884                 regcnt--;
885         }
886         if (p->p_sysent->sv_mask)
887                 sa->code &= p->p_sysent->sv_mask;
888
889         if (sa->code >= p->p_sysent->sv_size)
890                 sa->callp = &p->p_sysent->sv_table[0];
891         else
892                 sa->callp = &p->p_sysent->sv_table[sa->code];
893
894         sa->narg = sa->callp->sy_narg;
895         KASSERT(sa->narg <= sizeof(sa->args) / sizeof(sa->args[0]),
896             ("Too many syscall arguments!"));
897         error = 0;
898         argp = &frame->tf_rdi;
899         argp += reg;
900         bcopy(argp, sa->args, sizeof(sa->args[0]) * regcnt);
901         if (sa->narg > regcnt) {
902                 KASSERT(params != NULL, ("copyin args with no params!"));
903                 error = copyin(params, &sa->args[regcnt],
904                     (sa->narg - regcnt) * sizeof(sa->args[0]));
905         }
906
907         if (error == 0) {
908                 td->td_retval[0] = 0;
909                 td->td_retval[1] = frame->tf_rdx;
910         }
911
912         return (error);
913 }
914
915 #include "../../kern/subr_syscall.c"
916
917 /*
918  * System call handler for native binaries.  The trap frame is already
919  * set up by the assembler trampoline and a pointer to it is saved in
920  * td_frame.
921  */
922 void
923 amd64_syscall(struct thread *td, int traced)
924 {
925         struct syscall_args sa;
926         int error;
927         ksiginfo_t ksi;
928
929 #ifdef DIAGNOSTIC
930         if (ISPL(td->td_frame->tf_cs) != SEL_UPL) {
931                 panic("syscall");
932                 /* NOT REACHED */
933         }
934 #endif
935         error = syscallenter(td, &sa);
936
937         /*
938          * Traced syscall.
939          */
940         if (__predict_false(traced)) {
941                 td->td_frame->tf_rflags &= ~PSL_T;
942                 ksiginfo_init_trap(&ksi);
943                 ksi.ksi_signo = SIGTRAP;
944                 ksi.ksi_code = TRAP_TRACE;
945                 ksi.ksi_addr = (void *)td->td_frame->tf_rip;
946                 trapsignal(td, &ksi);
947         }
948
949         KASSERT(PCB_USER_FPU(td->td_pcb),
950             ("System call %s returing with kernel FPU ctx leaked",
951              syscallname(td->td_proc, sa.code)));
952         KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td),
953             ("System call %s returning with mangled pcb_save",
954              syscallname(td->td_proc, sa.code)));
955
956         syscallret(td, error, &sa);
957
958         /*
959          * If the user-supplied value of %rip is not a canonical
960          * address, then some CPUs will trigger a ring 0 #GP during
961          * the sysret instruction.  However, the fault handler would
962          * execute in ring 0 with the user's %gs and %rsp which would
963          * not be safe.  Instead, use the full return path which
964          * catches the problem safely.
965          */
966         if (td->td_frame->tf_rip >= VM_MAXUSER_ADDRESS)
967                 set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
968 }