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