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