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