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