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