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