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