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