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