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