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