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