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