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