2 * SPDX-License-Identifier: BSD-4-Clause
4 * Copyright (C) 1994, David Greenman
5 * Copyright (c) 1990, 1993
6 * The Regents of the University of California. All rights reserved.
8 * This code is derived from software contributed to Berkeley by
9 * the University of Utah, and William Jolitz.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
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.
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
39 * from: @(#)trap.c 7.4 (Berkeley) 5/13/91
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
46 * AMD64 Trap and System call handling
49 #include "opt_clock.h"
50 #include "opt_compat.h"
52 #include "opt_hwpmc_hooks.h"
56 #include <sys/param.h>
58 #include <sys/systm.h>
60 #include <sys/ptrace.h>
62 #include <sys/kernel.h>
65 #include <sys/mutex.h>
66 #include <sys/resourcevar.h>
67 #include <sys/signalvar.h>
68 #include <sys/syscall.h>
69 #include <sys/sysctl.h>
70 #include <sys/sysent.h>
72 #include <sys/vmmeter.h>
74 #include <sys/pmckern.h>
75 PMC_SOFT_DEFINE( , , page_fault, all);
76 PMC_SOFT_DEFINE( , , page_fault, read);
77 PMC_SOFT_DEFINE( , , page_fault, write);
81 #include <vm/vm_param.h>
83 #include <vm/vm_kern.h>
84 #include <vm/vm_map.h>
85 #include <vm/vm_page.h>
86 #include <vm/vm_extern.h>
88 #include <machine/cpu.h>
89 #include <machine/intr_machdep.h>
91 #include <machine/md_var.h>
92 #include <machine/pcb.h>
94 #include <machine/smp.h>
96 #include <machine/stack.h>
97 #include <machine/trap.h>
98 #include <machine/tss.h>
101 #include <sys/dtrace_bsd.h>
104 extern inthand_t IDTVEC(bpt), IDTVEC(bpt_pti), IDTVEC(dbg),
105 IDTVEC(fast_syscall), IDTVEC(fast_syscall_pti), IDTVEC(fast_syscall32),
106 IDTVEC(int0x80_syscall_pti), IDTVEC(int0x80_syscall);
108 void __noinline trap(struct trapframe *frame);
109 void trap_check(struct trapframe *frame);
110 void dblfault_handler(struct trapframe *frame);
112 static int trap_pfault(struct trapframe *, bool, int *, int *);
113 static void trap_fatal(struct trapframe *, vm_offset_t);
115 static bool trap_user_dtrace(struct trapframe *,
116 int (**hook)(struct trapframe *));
119 static const char UNKNOWN[] = "unknown";
120 static const char *const trap_msg[] = {
121 [0] = UNKNOWN, /* unused */
122 [T_PRIVINFLT] = "privileged instruction fault",
123 [2] = UNKNOWN, /* unused */
124 [T_BPTFLT] = "breakpoint instruction fault",
125 [4] = UNKNOWN, /* unused */
126 [5] = UNKNOWN, /* unused */
127 [T_ARITHTRAP] = "arithmetic trap",
128 [7] = UNKNOWN, /* unused */
129 [8] = UNKNOWN, /* unused */
130 [T_PROTFLT] = "general protection fault",
131 [T_TRCTRAP] = "debug exception",
132 [11] = UNKNOWN, /* unused */
133 [T_PAGEFLT] = "page fault",
134 [13] = UNKNOWN, /* unused */
135 [T_ALIGNFLT] = "alignment fault",
136 [15] = UNKNOWN, /* unused */
137 [16] = UNKNOWN, /* unused */
138 [17] = UNKNOWN, /* unused */
139 [T_DIVIDE] = "integer divide fault",
140 [T_NMI] = "non-maskable interrupt trap",
141 [T_OFLOW] = "overflow trap",
142 [T_BOUND] = "FPU bounds check fault",
143 [T_DNA] = "FPU device not available",
144 [T_DOUBLEFLT] = "double fault",
145 [T_FPOPFLT] = "FPU operand fetch fault",
146 [T_TSSFLT] = "invalid TSS fault",
147 [T_SEGNPFLT] = "segment not present fault",
148 [T_STKFLT] = "stack fault",
149 [T_MCHK] = "machine check trap",
150 [T_XMMFLT] = "SIMD floating-point exception",
151 [T_RESERVED] = "reserved (unknown) fault",
152 [31] = UNKNOWN, /* reserved */
153 [T_DTRACE_RET] = "DTrace pid return trap",
156 static int uprintf_signal;
157 SYSCTL_INT(_machdep, OID_AUTO, uprintf_signal, CTLFLAG_RWTUN,
159 "Print debugging information on trap signal to ctty");
162 * Control L1D flush on return from NMI.
164 * Tunable can be set to the following values:
165 * 0 - only enable flush on return from NMI if required by vmm.ko (default)
166 * >1 - always flush on return from NMI.
168 * Post-boot, the sysctl indicates if flushing is currently enabled.
170 int nmi_flush_l1d_sw;
171 SYSCTL_INT(_machdep, OID_AUTO, nmi_flush_l1d_sw, CTLFLAG_RWTUN,
172 &nmi_flush_l1d_sw, 0,
173 "Flush L1 Data Cache on NMI exit, software bhyve L1TF mitigation assist");
176 * Exception, fault, and trap interface to the FreeBSD kernel.
177 * This common code is called from assembly language IDT gate entry
178 * routines that prepare a suitable stack frame, and restore this
179 * frame after the exception has been processed.
183 trap(struct trapframe *frame)
188 register_t addr, dr6;
189 int pf, signo, ucode;
197 type = frame->tf_trapno;
200 /* Handler for NMI IPIs used for stopping CPUs. */
201 if (type == T_NMI && ipi_nmi_handler() == 0)
212 if (type == T_RESERVED) {
213 trap_fatal(frame, 0);
220 * CPU PMCs interrupt using an NMI. If the PMC module is
221 * active, pass the 'rip' value to the PMC module's interrupt
222 * handler. A non-zero return value from the handler means that
223 * the NMI was consumed by it and we can return immediately.
225 if (pmc_intr != NULL &&
226 (*pmc_intr)(frame) != 0)
231 if ((frame->tf_rflags & PSL_I) == 0) {
233 * Buggy application or kernel code has disabled
234 * interrupts and then trapped. Enabling interrupts
235 * now is wrong, but it is better than running with
236 * interrupts disabled until they are accidentally
239 if (TRAPF_USERMODE(frame))
241 "pid %ld (%s): trap %d with interrupts disabled\n",
242 (long)curproc->p_pid, curthread->td_name, type);
243 else if (type != T_NMI && type != T_BPTFLT &&
246 * XXX not quite right, since this may be for a
247 * multiple fault in user mode.
249 printf("kernel trap %d with interrupts disabled\n",
253 * We shouldn't enable interrupts while holding a
256 if (td->td_md.md_spinlock_count == 0)
261 if (TRAPF_USERMODE(frame)) {
265 td->td_frame = frame;
266 addr = frame->tf_rip;
267 if (td->td_cowgen != p->p_cowgen)
268 thread_cow_update(td);
271 case T_PRIVINFLT: /* privileged instruction fault */
276 case T_BPTFLT: /* bpt instruction fault */
278 if (trap_user_dtrace(frame, &dtrace_pid_probe_ptr))
287 case T_TRCTRAP: /* debug exception */
292 if ((dr6 & DBREG_DR6_BS) != 0) {
293 PROC_LOCK(td->td_proc);
294 if ((td->td_dbgflags & TDB_STEP) != 0) {
295 td->td_frame->tf_rflags &= ~PSL_T;
296 td->td_dbgflags &= ~TDB_STEP;
298 PROC_UNLOCK(td->td_proc);
302 case T_ARITHTRAP: /* arithmetic trap */
303 ucode = fputrap_x87();
309 case T_PROTFLT: /* general protection fault */
313 case T_STKFLT: /* stack fault */
314 case T_SEGNPFLT: /* segment not present fault */
318 case T_TSSFLT: /* invalid TSS fault */
326 case T_DOUBLEFLT: /* double fault */
332 case T_PAGEFLT: /* page fault */
334 * Can emulator handle this trap?
336 if (*p->p_sysent->sv_trap != NULL &&
337 (*p->p_sysent->sv_trap)(td) == 0)
340 pf = trap_pfault(frame, true, &signo, &ucode);
345 addr = frame->tf_addr;
348 case T_DIVIDE: /* integer divide fault */
355 nmi_handle_intr(type, frame);
359 case T_OFLOW: /* integer overflow fault */
364 case T_BOUND: /* bounds check fault */
370 /* transparent fault (due to context switch "late") */
371 KASSERT(PCB_USER_FPU(td->td_pcb),
372 ("kernel FPU ctx has leaked"));
376 case T_FPOPFLT: /* FPU operand fetch fault */
381 case T_XMMFLT: /* SIMD floating-point exception */
382 ucode = fputrap_sse();
389 (void)trap_user_dtrace(frame, &dtrace_return_probe_ptr);
396 KASSERT(cold || td->td_ucred != NULL,
397 ("kernel trap doesn't have ucred"));
399 case T_PAGEFLT: /* page fault */
400 (void)trap_pfault(frame, false, NULL, NULL);
404 if (PCB_USER_FPU(td->td_pcb))
405 panic("Unregistered use of FPU in kernel");
409 case T_ARITHTRAP: /* arithmetic trap */
410 case T_XMMFLT: /* SIMD floating-point exception */
411 case T_FPOPFLT: /* FPU operand fetch fault */
413 * For now, supporting kernel handler
414 * registration for FPU traps is overkill.
416 trap_fatal(frame, 0);
419 case T_STKFLT: /* stack fault */
420 case T_PROTFLT: /* general protection fault */
421 case T_SEGNPFLT: /* segment not present fault */
422 if (td->td_intr_nesting_level != 0)
426 * Invalid segment selectors and out of bounds
427 * %rip's and %rsp's can be set up in user mode.
428 * This causes a fault in kernel mode when the
429 * kernel tries to return to user mode. We want
430 * to get this fault so that we can fix the
431 * problem here and not have to check all the
432 * selectors and pointers when the user changes
435 * In case of PTI, the IRETQ faulted while the
436 * kernel used the pti stack, and exception
437 * frame records %rsp value pointing to that
438 * stack. If we return normally to
439 * doreti_iret_fault, the trapframe is
440 * reconstructed on pti stack, and calltrap()
441 * called on it as well. Due to the very
442 * limited pti stack size, kernel does not
443 * survive for too long. Switch to the normal
444 * thread stack for the trap handling.
446 * Magic '5' is the number of qwords occupied by
447 * the hardware trap frame.
449 if (frame->tf_rip == (long)doreti_iret) {
450 frame->tf_rip = (long)doreti_iret_fault;
451 if ((PCPU_GET(curpmap)->pm_ucr3 !=
453 (frame->tf_rsp == (uintptr_t)PCPU_GET(
454 pti_rsp0) - 5 * sizeof(register_t))) {
455 frame->tf_rsp = PCPU_GET(rsp0) - 5 *
460 if (frame->tf_rip == (long)ld_ds) {
461 frame->tf_rip = (long)ds_load_fault;
464 if (frame->tf_rip == (long)ld_es) {
465 frame->tf_rip = (long)es_load_fault;
468 if (frame->tf_rip == (long)ld_fs) {
469 frame->tf_rip = (long)fs_load_fault;
472 if (frame->tf_rip == (long)ld_gs) {
473 frame->tf_rip = (long)gs_load_fault;
476 if (frame->tf_rip == (long)ld_gsbase) {
477 frame->tf_rip = (long)gsbase_load_fault;
480 if (frame->tf_rip == (long)ld_fsbase) {
481 frame->tf_rip = (long)fsbase_load_fault;
484 if (curpcb->pcb_onfault != NULL) {
485 frame->tf_rip = (long)curpcb->pcb_onfault;
492 * PSL_NT can be set in user mode and isn't cleared
493 * automatically when the kernel is entered. This
494 * causes a TSS fault when the kernel attempts to
495 * `iret' because the TSS link is uninitialized. We
496 * want to get this fault so that we can fix the
497 * problem here and not every time the kernel is
500 if (frame->tf_rflags & PSL_NT) {
501 frame->tf_rflags &= ~PSL_NT;
506 case T_TRCTRAP: /* debug exception */
507 /* Clear any pending debug events. */
512 * Ignore debug register exceptions due to
513 * accesses in the user's address space, which
514 * can happen under several conditions such as
515 * if a user sets a watchpoint on a buffer and
516 * then passes that buffer to a system call.
517 * We still want to get TRCTRAPS for addresses
518 * in kernel space because that is useful when
519 * debugging the kernel.
521 if (user_dbreg_trap(dr6))
525 * Malicious user code can configure a debug
526 * register watchpoint to trap on data access
527 * to the top of stack and then execute 'pop
528 * %ss; int 3'. Due to exception deferral for
529 * 'pop %ss', the CPU will not interrupt 'int
530 * 3' to raise the DB# exception for the debug
531 * register but will postpone the DB# until
532 * execution of the first instruction of the
533 * BP# handler (in kernel mode). Normally the
534 * previous check would ignore DB# exceptions
535 * for watchpoints on user addresses raised in
536 * kernel mode. However, some CPU errata
537 * include cases where DB# exceptions do not
538 * properly set bits in %dr6, e.g. Haswell
539 * HSD23 and Skylake-X SKZ24.
541 * A deferred DB# can also be raised on the
542 * first instructions of system call entry
543 * points or single-step traps via similar use
544 * of 'pop %ss' or 'mov xxx, %ss'.
548 (uintptr_t)IDTVEC(fast_syscall_pti) ||
549 #ifdef COMPAT_FREEBSD32
551 (uintptr_t)IDTVEC(int0x80_syscall_pti) ||
553 frame->tf_rip == (uintptr_t)IDTVEC(bpt_pti))
557 (uintptr_t)IDTVEC(fast_syscall) ||
558 #ifdef COMPAT_FREEBSD32
560 (uintptr_t)IDTVEC(int0x80_syscall) ||
562 frame->tf_rip == (uintptr_t)IDTVEC(bpt))
565 if (frame->tf_rip == (uintptr_t)IDTVEC(dbg) ||
566 /* Needed for AMD. */
567 frame->tf_rip == (uintptr_t)IDTVEC(fast_syscall32))
570 * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
574 * If KDB is enabled, let it handle the debugger trap.
575 * Otherwise, debugger traps "can't happen".
578 if (kdb_trap(type, dr6, frame))
585 nmi_handle_intr(type, frame);
590 trap_fatal(frame, 0);
594 /* Translate fault for emulators (e.g. Linux) */
595 if (*p->p_sysent->sv_transtrap != NULL)
596 signo = (*p->p_sysent->sv_transtrap)(signo, type);
598 ksiginfo_init_trap(&ksi);
599 ksi.ksi_signo = signo;
600 ksi.ksi_code = ucode;
601 ksi.ksi_trapno = type;
602 ksi.ksi_addr = (void *)addr;
603 if (uprintf_signal) {
604 uprintf("pid %d comm %s: signal %d err %lx code %d type %d "
605 "addr 0x%lx rsp 0x%lx rip 0x%lx "
606 "<%02x %02x %02x %02x %02x %02x %02x %02x>\n",
607 p->p_pid, p->p_comm, signo, frame->tf_err, ucode, type,
608 addr, frame->tf_rsp, frame->tf_rip,
609 fubyte((void *)(frame->tf_rip + 0)),
610 fubyte((void *)(frame->tf_rip + 1)),
611 fubyte((void *)(frame->tf_rip + 2)),
612 fubyte((void *)(frame->tf_rip + 3)),
613 fubyte((void *)(frame->tf_rip + 4)),
614 fubyte((void *)(frame->tf_rip + 5)),
615 fubyte((void *)(frame->tf_rip + 6)),
616 fubyte((void *)(frame->tf_rip + 7)));
618 KASSERT((read_rflags() & PSL_I) != 0, ("interrupts disabled"));
619 trapsignal(td, &ksi);
623 KASSERT(PCB_USER_FPU(td->td_pcb),
624 ("Return from trap with kernel FPU ctx leaked"));
628 * Ensure that we ignore any DTrace-induced faults. This function cannot
629 * be instrumented, so it cannot generate such faults itself.
632 trap_check(struct trapframe *frame)
636 if (dtrace_trap_func != NULL &&
637 (*dtrace_trap_func)(frame, frame->tf_trapno) != 0)
644 trap_is_smap(struct trapframe *frame)
648 * A page fault on a userspace address is classified as
650 * - SMAP is supported;
651 * - kernel mode accessed present data page;
652 * - rflags.AC was cleared.
653 * Kernel must never access user space with rflags.AC cleared
654 * if SMAP is enabled.
656 return ((cpu_stdext_feature & CPUID_STDEXT_SMAP) != 0 &&
657 (frame->tf_err & (PGEX_P | PGEX_U | PGEX_I | PGEX_RSV)) ==
658 PGEX_P && (frame->tf_rflags & PSL_AC) == 0);
662 trap_is_pti(struct trapframe *frame)
665 return (PCPU_GET(curpmap)->pm_ucr3 != PMAP_NO_CR3 &&
666 pg_nx != 0 && (frame->tf_err & (PGEX_P | PGEX_W |
667 PGEX_U | PGEX_I)) == (PGEX_P | PGEX_U | PGEX_I) &&
668 (curpcb->pcb_saved_ucr3 & ~CR3_PCID_MASK) ==
669 (PCPU_GET(curpmap)->pm_cr3 & ~CR3_PCID_MASK));
673 * Handle all details of a page fault.
675 * -1 if this fault was fatal, typically from kernel mode
676 * (cannot happen, but we need to return something).
677 * 0 if this fault was handled by updating either the user or kernel
678 * page table, execution can continue.
679 * 1 if this fault was from usermode and it was not handled, a synchronous
680 * signal should be delivered to the thread. *signo returns the signal
681 * number, *ucode gives si_code.
684 trap_pfault(struct trapframe *frame, bool usermode, int *signo, int *ucode)
693 MPASS(!usermode || (signo != NULL && ucode != NULL));
697 eva = frame->tf_addr;
699 if (__predict_false((td->td_pflags & TDP_NOFAULTING) != 0)) {
701 * Due to both processor errata and lazy TLB invalidation when
702 * access restrictions are removed from virtual pages, memory
703 * accesses that are allowed by the physical mapping layer may
704 * nonetheless cause one spurious page fault per virtual page.
705 * When the thread is executing a "no faulting" section that
706 * is bracketed by vm_fault_{disable,enable}_pagefaults(),
707 * every page fault is treated as a spurious page fault,
708 * unless it accesses the same virtual address as the most
709 * recent page fault within the same "no faulting" section.
711 if (td->td_md.md_spurflt_addr != eva ||
712 (td->td_pflags & TDP_RESETSPUR) != 0) {
714 * Do nothing to the TLB. A stale TLB entry is
715 * flushed automatically by a page fault.
717 td->td_md.md_spurflt_addr = eva;
718 td->td_pflags &= ~TDP_RESETSPUR;
723 * If we get a page fault while in a critical section, then
724 * it is most likely a fatal kernel page fault. The kernel
725 * is already going to panic trying to get a sleep lock to
726 * do the VM lookup, so just consider it a fatal trap so the
727 * kernel can print out a useful trap message and even get
730 * If we get a page fault while holding a non-sleepable
731 * lock, then it is most likely a fatal kernel page fault.
732 * If WITNESS is enabled, then it's going to whine about
733 * bogus LORs with various VM locks, so just skip to the
734 * fatal trap handling directly.
736 if (td->td_critnest != 0 ||
737 WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
738 "Kernel page fault") != 0) {
739 trap_fatal(frame, eva);
743 if (eva >= VM_MIN_KERNEL_ADDRESS) {
745 * Don't allow user-mode faults in kernel address space.
749 *ucode = SEGV_MAPERR;
755 map = &p->p_vmspace->vm_map;
758 * When accessing a usermode address, kernel must be
759 * ready to accept the page fault, and provide a
760 * handling routine. Since accessing the address
761 * without the handler is a bug, do not try to handle
762 * it normally, and panic immediately.
764 * If SMAP is enabled, filter SMAP faults also,
765 * because illegal access might occur to the mapped
766 * user address, causing infinite loop.
768 if (!usermode && (td->td_intr_nesting_level != 0 ||
769 trap_is_smap(frame) || curpcb->pcb_onfault == NULL)) {
770 trap_fatal(frame, eva);
776 * If the trap was caused by errant bits in the PTE then panic.
778 if (frame->tf_err & PGEX_RSV) {
779 trap_fatal(frame, eva);
784 * User-mode protection key violation (PKU). May happen
785 * either from usermode or from kernel if copyin accessed
786 * key-protected mapping.
788 if ((frame->tf_err & PGEX_PK) != 0) {
789 if (eva > VM_MAXUSER_ADDRESS) {
790 trap_fatal(frame, eva);
795 *ucode = SEGV_PKUERR;
802 * If nx protection of the usermode portion of kernel page
803 * tables caused trap, panic.
805 if (usermode && trap_is_pti(frame))
806 panic("PTI: pid %d comm %s tf_err %#lx", p->p_pid,
807 p->p_comm, frame->tf_err);
810 * PGEX_I is defined only if the execute disable bit capability is
811 * supported and enabled.
813 if (frame->tf_err & PGEX_W)
814 ftype = VM_PROT_WRITE;
815 else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
816 ftype = VM_PROT_EXECUTE;
818 ftype = VM_PROT_READ;
820 /* Fault in the page. */
821 rv = vm_fault_trap(map, eva, ftype, VM_FAULT_NORMAL, signo, ucode);
822 if (rv == KERN_SUCCESS) {
824 if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
825 PMC_SOFT_CALL_TF( , , page_fault, all, frame);
826 if (ftype == VM_PROT_READ)
827 PMC_SOFT_CALL_TF( , , page_fault, read,
830 PMC_SOFT_CALL_TF( , , page_fault, write,
840 if (td->td_intr_nesting_level == 0 &&
841 curpcb->pcb_onfault != NULL) {
842 frame->tf_rip = (long)curpcb->pcb_onfault;
845 trap_fatal(frame, eva);
850 trap_fatal(frame, eva)
851 struct trapframe *frame;
856 struct soft_segment_descriptor softseg;
857 struct user_segment_descriptor *gdt;
862 code = frame->tf_err;
863 type = frame->tf_trapno;
864 gdt = *PCPU_PTR(gdt);
865 sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)], &softseg);
867 printf("\n\nFatal trap %d: %s while in %s mode\n", type,
868 type < nitems(trap_msg) ? trap_msg[type] : UNKNOWN,
869 TRAPF_USERMODE(frame) ? "user" : "kernel");
871 /* two separate prints in case of a trap on an unmapped page */
872 printf("cpuid = %d; ", PCPU_GET(cpuid));
873 printf("apic id = %02x\n", PCPU_GET(apic_id));
875 if (type == T_PAGEFLT) {
876 printf("fault virtual address = 0x%lx\n", eva);
877 printf("fault code = %s %s %s%s%s, %s\n",
878 code & PGEX_U ? "user" : "supervisor",
879 code & PGEX_W ? "write" : "read",
880 code & PGEX_I ? "instruction" : "data",
881 code & PGEX_PK ? " prot key" : "",
882 code & PGEX_SGX ? " SGX" : "",
883 code & PGEX_RSV ? "reserved bits in PTE" :
884 code & PGEX_P ? "protection violation" : "page not present");
886 printf("instruction pointer = 0x%lx:0x%lx\n",
887 frame->tf_cs & 0xffff, frame->tf_rip);
888 ss = frame->tf_ss & 0xffff;
889 printf("stack pointer = 0x%x:0x%lx\n", ss, frame->tf_rsp);
890 printf("frame pointer = 0x%x:0x%lx\n", ss, frame->tf_rbp);
891 printf("code segment = base 0x%lx, limit 0x%lx, type 0x%x\n",
892 softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
893 printf(" = DPL %d, pres %d, long %d, def32 %d, gran %d\n",
894 softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
896 printf("processor eflags = ");
897 if (frame->tf_rflags & PSL_T)
898 printf("trace trap, ");
899 if (frame->tf_rflags & PSL_I)
900 printf("interrupt enabled, ");
901 if (frame->tf_rflags & PSL_NT)
902 printf("nested task, ");
903 if (frame->tf_rflags & PSL_RF)
905 printf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
906 printf("current process = %d (%s)\n",
907 curproc->p_pid, curthread->td_name);
910 if (debugger_on_trap) {
911 kdb_why = KDB_WHY_TRAP;
912 handled = kdb_trap(type, 0, frame);
913 kdb_why = KDB_WHY_UNSET;
918 printf("trap number = %d\n", type);
919 panic("%s", type < nitems(trap_msg) ? trap_msg[type] :
920 "unknown/reserved trap");
925 * Invoke a userspace DTrace hook. The hook pointer is cleared when no
926 * userspace probes are enabled, so we must synchronize with DTrace to ensure
927 * that a trapping thread is able to call the hook before it is cleared.
930 trap_user_dtrace(struct trapframe *frame, int (**hookp)(struct trapframe *))
932 int (*hook)(struct trapframe *);
934 hook = atomic_load_ptr(hookp);
937 return ((hook)(frame) == 0);
943 * Double fault handler. Called when a fault occurs while writing
944 * a frame for a trap/exception onto the stack. This usually occurs
945 * when the stack overflows (such is the case with infinite recursion,
949 dblfault_handler(struct trapframe *frame)
952 if (dtrace_doubletrap_func != NULL)
953 (*dtrace_doubletrap_func)();
955 printf("\nFatal double fault\n"
956 "rip %#lx rsp %#lx rbp %#lx\n"
957 "rax %#lx rdx %#lx rbx %#lx\n"
958 "rcx %#lx rsi %#lx rdi %#lx\n"
959 "r8 %#lx r9 %#lx r10 %#lx\n"
960 "r11 %#lx r12 %#lx r13 %#lx\n"
961 "r14 %#lx r15 %#lx rflags %#lx\n"
962 "cs %#lx ss %#lx ds %#hx es %#hx fs %#hx gs %#hx\n"
963 "fsbase %#lx gsbase %#lx kgsbase %#lx\n",
964 frame->tf_rip, frame->tf_rsp, frame->tf_rbp,
965 frame->tf_rax, frame->tf_rdx, frame->tf_rbx,
966 frame->tf_rcx, frame->tf_rdi, frame->tf_rsi,
967 frame->tf_r8, frame->tf_r9, frame->tf_r10,
968 frame->tf_r11, frame->tf_r12, frame->tf_r13,
969 frame->tf_r14, frame->tf_r15, frame->tf_rflags,
970 frame->tf_cs, frame->tf_ss, frame->tf_ds, frame->tf_es,
971 frame->tf_fs, frame->tf_gs,
972 rdmsr(MSR_FSBASE), rdmsr(MSR_GSBASE), rdmsr(MSR_KGSBASE));
974 /* two separate prints in case of a trap on an unmapped page */
975 printf("cpuid = %d; ", PCPU_GET(cpuid));
976 printf("apic id = %02x\n", PCPU_GET(apic_id));
978 panic("double fault");
981 static int __noinline
982 cpu_fetch_syscall_args_fallback(struct thread *td, struct syscall_args *sa)
985 struct trapframe *frame;
988 int reg, regcnt, error;
991 frame = td->td_frame;
995 if (sa->code == SYS_syscall || sa->code == SYS___syscall) {
996 sa->code = frame->tf_rdi;
1001 if (sa->code >= p->p_sysent->sv_size)
1002 sa->callp = &p->p_sysent->sv_table[0];
1004 sa->callp = &p->p_sysent->sv_table[sa->code];
1006 sa->narg = sa->callp->sy_narg;
1007 KASSERT(sa->narg <= nitems(sa->args), ("Too many syscall arguments!"));
1008 argp = &frame->tf_rdi;
1010 memcpy(sa->args, argp, sizeof(sa->args[0]) * NARGREGS);
1011 if (sa->narg > regcnt) {
1012 params = (caddr_t)frame->tf_rsp + sizeof(register_t);
1013 error = copyin(params, &sa->args[regcnt],
1014 (sa->narg - regcnt) * sizeof(sa->args[0]));
1015 if (__predict_false(error != 0))
1019 td->td_retval[0] = 0;
1020 td->td_retval[1] = frame->tf_rdx;
1026 cpu_fetch_syscall_args(struct thread *td)
1029 struct trapframe *frame;
1030 struct syscall_args *sa;
1033 frame = td->td_frame;
1036 sa->code = frame->tf_rax;
1038 if (__predict_false(sa->code == SYS_syscall ||
1039 sa->code == SYS___syscall ||
1040 sa->code >= p->p_sysent->sv_size))
1041 return (cpu_fetch_syscall_args_fallback(td, sa));
1043 sa->callp = &p->p_sysent->sv_table[sa->code];
1044 sa->narg = sa->callp->sy_narg;
1045 KASSERT(sa->narg <= nitems(sa->args), ("Too many syscall arguments!"));
1047 if (__predict_false(sa->narg > NARGREGS))
1048 return (cpu_fetch_syscall_args_fallback(td, sa));
1050 memcpy(sa->args, &frame->tf_rdi, sizeof(sa->args[0]) * NARGREGS);
1052 td->td_retval[0] = 0;
1053 td->td_retval[1] = frame->tf_rdx;
1058 #include "../../kern/subr_syscall.c"
1060 static void (*syscall_ret_l1d_flush)(void);
1061 int syscall_ret_l1d_flush_mode;
1067 wrmsr(MSR_IA32_FLUSH_CMD, IA32_FLUSH_CMD_L1D);
1070 static void __noinline
1071 amd64_syscall_ret_flush_l1d_check(int error)
1075 if (error != EEXIST && error != EAGAIN && error != EXDEV &&
1076 error != ENOENT && error != ENOTCONN && error != EINPROGRESS) {
1077 p = atomic_load_ptr(&syscall_ret_l1d_flush);
1083 static void __inline
1084 amd64_syscall_ret_flush_l1d_check_inline(int error)
1087 if (__predict_false(error != 0))
1088 amd64_syscall_ret_flush_l1d_check(error);
1092 amd64_syscall_ret_flush_l1d(int error)
1095 amd64_syscall_ret_flush_l1d_check_inline(error);
1099 amd64_syscall_ret_flush_l1d_recalc(void)
1103 l1d_hw = (cpu_stdext_feature3 & CPUID_STDEXT3_L1D_FLUSH) != 0;
1105 switch (syscall_ret_l1d_flush_mode) {
1107 syscall_ret_l1d_flush = NULL;
1110 syscall_ret_l1d_flush = l1d_hw ? flush_l1d_hw :
1114 syscall_ret_l1d_flush = l1d_hw ? flush_l1d_hw : NULL;
1117 syscall_ret_l1d_flush = flush_l1d_sw_abi;
1120 syscall_ret_l1d_flush_mode = 1;
1126 machdep_syscall_ret_flush_l1d(SYSCTL_HANDLER_ARGS)
1130 val = syscall_ret_l1d_flush_mode;
1131 error = sysctl_handle_int(oidp, &val, 0, req);
1132 if (error != 0 || req->newptr == NULL)
1134 syscall_ret_l1d_flush_mode = val;
1135 amd64_syscall_ret_flush_l1d_recalc();
1138 SYSCTL_PROC(_machdep, OID_AUTO, syscall_ret_flush_l1d, CTLTYPE_INT |
1139 CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
1140 machdep_syscall_ret_flush_l1d, "I",
1141 "Flush L1D on syscall return with error (0 - off, 1 - on, "
1142 "2 - use hw only, 3 - use sw only");
1146 * System call handler for native binaries. The trap frame is already
1147 * set up by the assembler trampoline and a pointer to it is saved in
1151 amd64_syscall(struct thread *td, int traced)
1156 if (!TRAPF_USERMODE(td->td_frame)) {
1166 if (__predict_false(traced)) {
1167 td->td_frame->tf_rflags &= ~PSL_T;
1168 ksiginfo_init_trap(&ksi);
1169 ksi.ksi_signo = SIGTRAP;
1170 ksi.ksi_code = TRAP_TRACE;
1171 ksi.ksi_addr = (void *)td->td_frame->tf_rip;
1172 trapsignal(td, &ksi);
1175 KASSERT(PCB_USER_FPU(td->td_pcb),
1176 ("System call %s returning with kernel FPU ctx leaked",
1177 syscallname(td->td_proc, td->td_sa.code)));
1178 KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td),
1179 ("System call %s returning with mangled pcb_save",
1180 syscallname(td->td_proc, td->td_sa.code)));
1181 KASSERT(pmap_not_in_di(),
1182 ("System call %s returning with leaked invl_gen %lu",
1183 syscallname(td->td_proc, td->td_sa.code),
1184 td->td_md.md_invl_gen.gen));
1189 * If the user-supplied value of %rip is not a canonical
1190 * address, then some CPUs will trigger a ring 0 #GP during
1191 * the sysret instruction. However, the fault handler would
1192 * execute in ring 0 with the user's %gs and %rsp which would
1193 * not be safe. Instead, use the full return path which
1194 * catches the problem safely.
1196 if (__predict_false(td->td_frame->tf_rip >= VM_MAXUSER_ADDRESS))
1197 set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
1199 amd64_syscall_ret_flush_l1d_check_inline(td->td_errno);