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