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