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