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