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