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