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