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 */
354 nmi_handle_intr(type, frame);
357 case T_OFLOW: /* integer overflow fault */
362 case T_BOUND: /* bounds check fault */
368 /* transparent fault (due to context switch "late") */
369 KASSERT(PCB_USER_FPU(td->td_pcb),
370 ("kernel FPU ctx has leaked"));
374 case T_FPOPFLT: /* FPU operand fetch fault */
379 case T_XMMFLT: /* SIMD floating-point exception */
380 ucode = fputrap_sse();
387 (void)trap_user_dtrace(frame, &dtrace_return_probe_ptr);
394 KASSERT(cold || td->td_ucred != NULL,
395 ("kernel trap doesn't have ucred"));
397 case T_PAGEFLT: /* page fault */
398 (void)trap_pfault(frame, false, NULL, NULL);
402 if (PCB_USER_FPU(td->td_pcb))
403 panic("Unregistered use of FPU in kernel");
407 case T_ARITHTRAP: /* arithmetic trap */
408 case T_XMMFLT: /* SIMD floating-point exception */
409 case T_FPOPFLT: /* FPU operand fetch fault */
411 * For now, supporting kernel handler
412 * registration for FPU traps is overkill.
414 trap_fatal(frame, 0);
417 case T_STKFLT: /* stack fault */
418 case T_PROTFLT: /* general protection fault */
419 case T_SEGNPFLT: /* segment not present fault */
420 if (td->td_intr_nesting_level != 0)
424 * Invalid segment selectors and out of bounds
425 * %rip's and %rsp's can be set up in user mode.
426 * This causes a fault in kernel mode when the
427 * kernel tries to return to user mode. We want
428 * to get this fault so that we can fix the
429 * problem here and not have to check all the
430 * selectors and pointers when the user changes
433 * In case of PTI, the IRETQ faulted while the
434 * kernel used the pti stack, and exception
435 * frame records %rsp value pointing to that
436 * stack. If we return normally to
437 * doreti_iret_fault, the trapframe is
438 * reconstructed on pti stack, and calltrap()
439 * called on it as well. Due to the very
440 * limited pti stack size, kernel does not
441 * survive for too long. Switch to the normal
442 * thread stack for the trap handling.
444 * Magic '5' is the number of qwords occupied by
445 * the hardware trap frame.
447 if (frame->tf_rip == (long)doreti_iret) {
448 frame->tf_rip = (long)doreti_iret_fault;
449 if ((PCPU_GET(curpmap)->pm_ucr3 !=
451 (frame->tf_rsp == (uintptr_t)PCPU_GET(
452 pti_rsp0) - 5 * sizeof(register_t))) {
453 frame->tf_rsp = PCPU_GET(rsp0) - 5 *
458 if (frame->tf_rip == (long)ld_ds) {
459 frame->tf_rip = (long)ds_load_fault;
462 if (frame->tf_rip == (long)ld_es) {
463 frame->tf_rip = (long)es_load_fault;
466 if (frame->tf_rip == (long)ld_fs) {
467 frame->tf_rip = (long)fs_load_fault;
470 if (frame->tf_rip == (long)ld_gs) {
471 frame->tf_rip = (long)gs_load_fault;
474 if (frame->tf_rip == (long)ld_gsbase) {
475 frame->tf_rip = (long)gsbase_load_fault;
478 if (frame->tf_rip == (long)ld_fsbase) {
479 frame->tf_rip = (long)fsbase_load_fault;
482 if (curpcb->pcb_onfault != NULL) {
483 frame->tf_rip = (long)curpcb->pcb_onfault;
490 * PSL_NT can be set in user mode and isn't cleared
491 * automatically when the kernel is entered. This
492 * causes a TSS fault when the kernel attempts to
493 * `iret' because the TSS link is uninitialized. We
494 * want to get this fault so that we can fix the
495 * problem here and not every time the kernel is
498 if (frame->tf_rflags & PSL_NT) {
499 frame->tf_rflags &= ~PSL_NT;
504 case T_TRCTRAP: /* debug exception */
505 /* Clear any pending debug events. */
510 * Ignore debug register exceptions due to
511 * accesses in the user's address space, which
512 * can happen under several conditions such as
513 * if a user sets a watchpoint on a buffer and
514 * then passes that buffer to a system call.
515 * We still want to get TRCTRAPS for addresses
516 * in kernel space because that is useful when
517 * debugging the kernel.
519 if (user_dbreg_trap(dr6))
523 * Malicious user code can configure a debug
524 * register watchpoint to trap on data access
525 * to the top of stack and then execute 'pop
526 * %ss; int 3'. Due to exception deferral for
527 * 'pop %ss', the CPU will not interrupt 'int
528 * 3' to raise the DB# exception for the debug
529 * register but will postpone the DB# until
530 * execution of the first instruction of the
531 * BP# handler (in kernel mode). Normally the
532 * previous check would ignore DB# exceptions
533 * for watchpoints on user addresses raised in
534 * kernel mode. However, some CPU errata
535 * include cases where DB# exceptions do not
536 * properly set bits in %dr6, e.g. Haswell
537 * HSD23 and Skylake-X SKZ24.
539 * A deferred DB# can also be raised on the
540 * first instructions of system call entry
541 * points or single-step traps via similar use
542 * of 'pop %ss' or 'mov xxx, %ss'.
546 (uintptr_t)IDTVEC(fast_syscall_pti) ||
547 #ifdef COMPAT_FREEBSD32
549 (uintptr_t)IDTVEC(int0x80_syscall_pti) ||
551 frame->tf_rip == (uintptr_t)IDTVEC(bpt_pti))
555 (uintptr_t)IDTVEC(fast_syscall) ||
556 #ifdef COMPAT_FREEBSD32
558 (uintptr_t)IDTVEC(int0x80_syscall) ||
560 frame->tf_rip == (uintptr_t)IDTVEC(bpt))
563 if (frame->tf_rip == (uintptr_t)IDTVEC(dbg) ||
564 /* Needed for AMD. */
565 frame->tf_rip == (uintptr_t)IDTVEC(fast_syscall32))
568 * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
572 * If KDB is enabled, let it handle the debugger trap.
573 * Otherwise, debugger traps "can't happen".
576 if (kdb_trap(type, dr6, frame))
582 nmi_handle_intr(type, frame);
586 trap_fatal(frame, 0);
590 /* Translate fault for emulators (e.g. Linux) */
591 if (*p->p_sysent->sv_transtrap != NULL)
592 signo = (*p->p_sysent->sv_transtrap)(signo, type);
594 ksiginfo_init_trap(&ksi);
595 ksi.ksi_signo = signo;
596 ksi.ksi_code = ucode;
597 ksi.ksi_trapno = type;
598 ksi.ksi_addr = (void *)addr;
599 if (uprintf_signal) {
600 uprintf("pid %d comm %s: signal %d err %lx code %d type %d "
601 "addr 0x%lx rsp 0x%lx rip 0x%lx "
602 "<%02x %02x %02x %02x %02x %02x %02x %02x>\n",
603 p->p_pid, p->p_comm, signo, frame->tf_err, ucode, type,
604 addr, frame->tf_rsp, frame->tf_rip,
605 fubyte((void *)(frame->tf_rip + 0)),
606 fubyte((void *)(frame->tf_rip + 1)),
607 fubyte((void *)(frame->tf_rip + 2)),
608 fubyte((void *)(frame->tf_rip + 3)),
609 fubyte((void *)(frame->tf_rip + 4)),
610 fubyte((void *)(frame->tf_rip + 5)),
611 fubyte((void *)(frame->tf_rip + 6)),
612 fubyte((void *)(frame->tf_rip + 7)));
614 KASSERT((read_rflags() & PSL_I) != 0, ("interrupts disabled"));
615 trapsignal(td, &ksi);
619 KASSERT(PCB_USER_FPU(td->td_pcb),
620 ("Return from trap with kernel FPU ctx leaked"));
624 * Ensure that we ignore any DTrace-induced faults. This function cannot
625 * be instrumented, so it cannot generate such faults itself.
628 trap_check(struct trapframe *frame)
632 if (dtrace_trap_func != NULL &&
633 (*dtrace_trap_func)(frame, frame->tf_trapno) != 0)
640 trap_is_smap(struct trapframe *frame)
644 * A page fault on a userspace address is classified as
646 * - SMAP is supported;
647 * - kernel mode accessed present data page;
648 * - rflags.AC was cleared.
649 * Kernel must never access user space with rflags.AC cleared
650 * if SMAP is enabled.
652 return ((cpu_stdext_feature & CPUID_STDEXT_SMAP) != 0 &&
653 (frame->tf_err & (PGEX_P | PGEX_U | PGEX_I | PGEX_RSV)) ==
654 PGEX_P && (frame->tf_rflags & PSL_AC) == 0);
658 trap_is_pti(struct trapframe *frame)
661 return (PCPU_GET(curpmap)->pm_ucr3 != PMAP_NO_CR3 &&
662 pg_nx != 0 && (frame->tf_err & (PGEX_P | PGEX_W |
663 PGEX_U | PGEX_I)) == (PGEX_P | PGEX_U | PGEX_I) &&
664 (curpcb->pcb_saved_ucr3 & ~CR3_PCID_MASK) ==
665 (PCPU_GET(curpmap)->pm_cr3 & ~CR3_PCID_MASK));
669 * Handle all details of a page fault.
671 * -1 if this fault was fatal, typically from kernel mode
672 * (cannot happen, but we need to return something).
673 * 0 if this fault was handled by updating either the user or kernel
674 * page table, execution can continue.
675 * 1 if this fault was from usermode and it was not handled, a synchronous
676 * signal should be delivered to the thread. *signo returns the signal
677 * number, *ucode gives si_code.
680 trap_pfault(struct trapframe *frame, bool usermode, int *signo, int *ucode)
689 MPASS(!usermode || (signo != NULL && ucode != NULL));
693 eva = frame->tf_addr;
695 if (__predict_false((td->td_pflags & TDP_NOFAULTING) != 0)) {
697 * Due to both processor errata and lazy TLB invalidation when
698 * access restrictions are removed from virtual pages, memory
699 * accesses that are allowed by the physical mapping layer may
700 * nonetheless cause one spurious page fault per virtual page.
701 * When the thread is executing a "no faulting" section that
702 * is bracketed by vm_fault_{disable,enable}_pagefaults(),
703 * every page fault is treated as a spurious page fault,
704 * unless it accesses the same virtual address as the most
705 * recent page fault within the same "no faulting" section.
707 if (td->td_md.md_spurflt_addr != eva ||
708 (td->td_pflags & TDP_RESETSPUR) != 0) {
710 * Do nothing to the TLB. A stale TLB entry is
711 * flushed automatically by a page fault.
713 td->td_md.md_spurflt_addr = eva;
714 td->td_pflags &= ~TDP_RESETSPUR;
719 * If we get a page fault while in a critical section, then
720 * it is most likely a fatal kernel page fault. The kernel
721 * is already going to panic trying to get a sleep lock to
722 * do the VM lookup, so just consider it a fatal trap so the
723 * kernel can print out a useful trap message and even get
726 * If we get a page fault while holding a non-sleepable
727 * lock, then it is most likely a fatal kernel page fault.
728 * If WITNESS is enabled, then it's going to whine about
729 * bogus LORs with various VM locks, so just skip to the
730 * fatal trap handling directly.
732 if (td->td_critnest != 0 ||
733 WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
734 "Kernel page fault") != 0) {
735 trap_fatal(frame, eva);
739 if (eva >= VM_MIN_KERNEL_ADDRESS) {
741 * Don't allow user-mode faults in kernel address space.
745 *ucode = SEGV_MAPERR;
751 map = &p->p_vmspace->vm_map;
754 * When accessing a usermode address, kernel must be
755 * ready to accept the page fault, and provide a
756 * handling routine. Since accessing the address
757 * without the handler is a bug, do not try to handle
758 * it normally, and panic immediately.
760 * If SMAP is enabled, filter SMAP faults also,
761 * because illegal access might occur to the mapped
762 * user address, causing infinite loop.
764 if (!usermode && (td->td_intr_nesting_level != 0 ||
765 trap_is_smap(frame) || curpcb->pcb_onfault == NULL)) {
766 trap_fatal(frame, eva);
772 * If the trap was caused by errant bits in the PTE then panic.
774 if (frame->tf_err & PGEX_RSV) {
775 trap_fatal(frame, eva);
780 * User-mode protection key violation (PKU). May happen
781 * either from usermode or from kernel if copyin accessed
782 * key-protected mapping.
784 if ((frame->tf_err & PGEX_PK) != 0) {
785 if (eva > VM_MAXUSER_ADDRESS) {
786 trap_fatal(frame, eva);
791 *ucode = SEGV_PKUERR;
798 * If nx protection of the usermode portion of kernel page
799 * tables caused trap, panic.
801 if (usermode && trap_is_pti(frame))
802 panic("PTI: pid %d comm %s tf_err %#lx", p->p_pid,
803 p->p_comm, frame->tf_err);
806 * PGEX_I is defined only if the execute disable bit capability is
807 * supported and enabled.
809 if (frame->tf_err & PGEX_W)
810 ftype = VM_PROT_WRITE;
811 else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
812 ftype = VM_PROT_EXECUTE;
814 ftype = VM_PROT_READ;
816 /* Fault in the page. */
817 rv = vm_fault_trap(map, eva, ftype, VM_FAULT_NORMAL, signo, ucode);
818 if (rv == KERN_SUCCESS) {
820 if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
821 PMC_SOFT_CALL_TF( , , page_fault, all, frame);
822 if (ftype == VM_PROT_READ)
823 PMC_SOFT_CALL_TF( , , page_fault, read,
826 PMC_SOFT_CALL_TF( , , page_fault, write,
836 if (td->td_intr_nesting_level == 0 &&
837 curpcb->pcb_onfault != NULL) {
838 frame->tf_rip = (long)curpcb->pcb_onfault;
841 trap_fatal(frame, eva);
846 trap_fatal(frame, eva)
847 struct trapframe *frame;
852 struct soft_segment_descriptor softseg;
853 struct user_segment_descriptor *gdt;
858 code = frame->tf_err;
859 type = frame->tf_trapno;
860 gdt = *PCPU_PTR(gdt);
861 sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)], &softseg);
863 printf("\n\nFatal trap %d: %s while in %s mode\n", type,
864 type < nitems(trap_msg) ? trap_msg[type] : UNKNOWN,
865 TRAPF_USERMODE(frame) ? "user" : "kernel");
867 /* two separate prints in case of a trap on an unmapped page */
868 printf("cpuid = %d; ", PCPU_GET(cpuid));
869 printf("apic id = %02x\n", PCPU_GET(apic_id));
871 if (type == T_PAGEFLT) {
872 printf("fault virtual address = 0x%lx\n", eva);
873 printf("fault code = %s %s %s%s%s, %s\n",
874 code & PGEX_U ? "user" : "supervisor",
875 code & PGEX_W ? "write" : "read",
876 code & PGEX_I ? "instruction" : "data",
877 code & PGEX_PK ? " prot key" : "",
878 code & PGEX_SGX ? " SGX" : "",
879 code & PGEX_RSV ? "reserved bits in PTE" :
880 code & PGEX_P ? "protection violation" : "page not present");
882 printf("instruction pointer = 0x%lx:0x%lx\n",
883 frame->tf_cs & 0xffff, frame->tf_rip);
884 ss = frame->tf_ss & 0xffff;
885 printf("stack pointer = 0x%x:0x%lx\n", ss, frame->tf_rsp);
886 printf("frame pointer = 0x%x:0x%lx\n", ss, frame->tf_rbp);
887 printf("code segment = base 0x%lx, limit 0x%lx, type 0x%x\n",
888 softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
889 printf(" = DPL %d, pres %d, long %d, def32 %d, gran %d\n",
890 softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
892 printf("processor eflags = ");
893 if (frame->tf_rflags & PSL_T)
894 printf("trace trap, ");
895 if (frame->tf_rflags & PSL_I)
896 printf("interrupt enabled, ");
897 if (frame->tf_rflags & PSL_NT)
898 printf("nested task, ");
899 if (frame->tf_rflags & PSL_RF)
901 printf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
902 printf("current process = %d (%s)\n",
903 curproc->p_pid, curthread->td_name);
906 if (debugger_on_trap) {
907 kdb_why = KDB_WHY_TRAP;
908 handled = kdb_trap(type, 0, frame);
909 kdb_why = KDB_WHY_UNSET;
914 printf("trap number = %d\n", type);
915 panic("%s", type < nitems(trap_msg) ? trap_msg[type] :
916 "unknown/reserved trap");
921 * Invoke a userspace DTrace hook. The hook pointer is cleared when no
922 * userspace probes are enabled, so we must synchronize with DTrace to ensure
923 * that a trapping thread is able to call the hook before it is cleared.
926 trap_user_dtrace(struct trapframe *frame, int (**hookp)(struct trapframe *))
928 int (*hook)(struct trapframe *);
930 hook = atomic_load_ptr(hookp);
933 return ((hook)(frame) == 0);
939 * Double fault handler. Called when a fault occurs while writing
940 * a frame for a trap/exception onto the stack. This usually occurs
941 * when the stack overflows (such is the case with infinite recursion,
945 dblfault_handler(struct trapframe *frame)
948 if (dtrace_doubletrap_func != NULL)
949 (*dtrace_doubletrap_func)();
951 printf("\nFatal double fault\n"
952 "rip %#lx rsp %#lx rbp %#lx\n"
953 "rax %#lx rdx %#lx rbx %#lx\n"
954 "rcx %#lx rsi %#lx rdi %#lx\n"
955 "r8 %#lx r9 %#lx r10 %#lx\n"
956 "r11 %#lx r12 %#lx r13 %#lx\n"
957 "r14 %#lx r15 %#lx rflags %#lx\n"
958 "cs %#lx ss %#lx ds %#hx es %#hx fs %#hx gs %#hx\n"
959 "fsbase %#lx gsbase %#lx kgsbase %#lx\n",
960 frame->tf_rip, frame->tf_rsp, frame->tf_rbp,
961 frame->tf_rax, frame->tf_rdx, frame->tf_rbx,
962 frame->tf_rcx, frame->tf_rdi, frame->tf_rsi,
963 frame->tf_r8, frame->tf_r9, frame->tf_r10,
964 frame->tf_r11, frame->tf_r12, frame->tf_r13,
965 frame->tf_r14, frame->tf_r15, frame->tf_rflags,
966 frame->tf_cs, frame->tf_ss, frame->tf_ds, frame->tf_es,
967 frame->tf_fs, frame->tf_gs,
968 rdmsr(MSR_FSBASE), rdmsr(MSR_GSBASE), rdmsr(MSR_KGSBASE));
970 /* two separate prints in case of a trap on an unmapped page */
971 printf("cpuid = %d; ", PCPU_GET(cpuid));
972 printf("apic id = %02x\n", PCPU_GET(apic_id));
974 panic("double fault");
977 static int __noinline
978 cpu_fetch_syscall_args_fallback(struct thread *td, struct syscall_args *sa)
981 struct trapframe *frame;
984 int reg, regcnt, error;
987 frame = td->td_frame;
991 if (sa->code == SYS_syscall || sa->code == SYS___syscall) {
992 sa->code = frame->tf_rdi;
997 if (sa->code >= p->p_sysent->sv_size)
998 sa->callp = &p->p_sysent->sv_table[0];
1000 sa->callp = &p->p_sysent->sv_table[sa->code];
1002 KASSERT(sa->callp->sy_narg <= nitems(sa->args),
1003 ("Too many syscall arguments!"));
1004 argp = &frame->tf_rdi;
1006 memcpy(sa->args, argp, sizeof(sa->args[0]) * NARGREGS);
1007 if (sa->callp->sy_narg > regcnt) {
1008 params = (caddr_t)frame->tf_rsp + sizeof(register_t);
1009 error = copyin(params, &sa->args[regcnt],
1010 (sa->callp->sy_narg - regcnt) * sizeof(sa->args[0]));
1011 if (__predict_false(error != 0))
1015 td->td_retval[0] = 0;
1016 td->td_retval[1] = frame->tf_rdx;
1022 cpu_fetch_syscall_args(struct thread *td)
1025 struct trapframe *frame;
1026 struct syscall_args *sa;
1029 frame = td->td_frame;
1032 sa->code = frame->tf_rax;
1034 if (__predict_false(sa->code == SYS_syscall ||
1035 sa->code == SYS___syscall ||
1036 sa->code >= p->p_sysent->sv_size))
1037 return (cpu_fetch_syscall_args_fallback(td, sa));
1039 sa->callp = &p->p_sysent->sv_table[sa->code];
1040 KASSERT(sa->callp->sy_narg <= nitems(sa->args),
1041 ("Too many syscall arguments!"));
1043 if (__predict_false(sa->callp->sy_narg > NARGREGS))
1044 return (cpu_fetch_syscall_args_fallback(td, sa));
1046 memcpy(sa->args, &frame->tf_rdi, sizeof(sa->args[0]) * NARGREGS);
1048 td->td_retval[0] = 0;
1049 td->td_retval[1] = frame->tf_rdx;
1054 #include "../../kern/subr_syscall.c"
1056 static void (*syscall_ret_l1d_flush)(void);
1057 int syscall_ret_l1d_flush_mode;
1063 wrmsr(MSR_IA32_FLUSH_CMD, IA32_FLUSH_CMD_L1D);
1066 static void __noinline
1067 amd64_syscall_ret_flush_l1d_check(int error)
1071 if (error != EEXIST && error != EAGAIN && error != EXDEV &&
1072 error != ENOENT && error != ENOTCONN && error != EINPROGRESS) {
1073 p = atomic_load_ptr(&syscall_ret_l1d_flush);
1079 static void __inline
1080 amd64_syscall_ret_flush_l1d_check_inline(int error)
1083 if (__predict_false(error != 0))
1084 amd64_syscall_ret_flush_l1d_check(error);
1088 amd64_syscall_ret_flush_l1d(int error)
1091 amd64_syscall_ret_flush_l1d_check_inline(error);
1095 amd64_syscall_ret_flush_l1d_recalc(void)
1099 l1d_hw = (cpu_stdext_feature3 & CPUID_STDEXT3_L1D_FLUSH) != 0;
1101 switch (syscall_ret_l1d_flush_mode) {
1103 syscall_ret_l1d_flush = NULL;
1106 syscall_ret_l1d_flush = l1d_hw ? flush_l1d_hw :
1110 syscall_ret_l1d_flush = l1d_hw ? flush_l1d_hw : NULL;
1113 syscall_ret_l1d_flush = flush_l1d_sw_abi;
1116 syscall_ret_l1d_flush_mode = 1;
1122 machdep_syscall_ret_flush_l1d(SYSCTL_HANDLER_ARGS)
1126 val = syscall_ret_l1d_flush_mode;
1127 error = sysctl_handle_int(oidp, &val, 0, req);
1128 if (error != 0 || req->newptr == NULL)
1130 syscall_ret_l1d_flush_mode = val;
1131 amd64_syscall_ret_flush_l1d_recalc();
1134 SYSCTL_PROC(_machdep, OID_AUTO, syscall_ret_flush_l1d, CTLTYPE_INT |
1135 CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
1136 machdep_syscall_ret_flush_l1d, "I",
1137 "Flush L1D on syscall return with error (0 - off, 1 - on, "
1138 "2 - use hw only, 3 - use sw only");
1141 * System call handler for native binaries. The trap frame is already
1142 * set up by the assembler trampoline and a pointer to it is saved in
1146 amd64_syscall(struct thread *td, int traced)
1151 if (!TRAPF_USERMODE(td->td_frame)) {
1161 if (__predict_false(traced)) {
1162 td->td_frame->tf_rflags &= ~PSL_T;
1163 ksiginfo_init_trap(&ksi);
1164 ksi.ksi_signo = SIGTRAP;
1165 ksi.ksi_code = TRAP_TRACE;
1166 ksi.ksi_addr = (void *)td->td_frame->tf_rip;
1167 trapsignal(td, &ksi);
1170 KASSERT(PCB_USER_FPU(td->td_pcb),
1171 ("System call %s returning with kernel FPU ctx leaked",
1172 syscallname(td->td_proc, td->td_sa.code)));
1173 KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td),
1174 ("System call %s returning with mangled pcb_save",
1175 syscallname(td->td_proc, td->td_sa.code)));
1176 KASSERT(pmap_not_in_di(),
1177 ("System call %s returning with leaked invl_gen %lu",
1178 syscallname(td->td_proc, td->td_sa.code),
1179 td->td_md.md_invl_gen.gen));
1184 * If the user-supplied value of %rip is not a canonical
1185 * address, then some CPUs will trigger a ring 0 #GP during
1186 * the sysret instruction. However, the fault handler would
1187 * execute in ring 0 with the user's %gs and %rsp which would
1188 * not be safe. Instead, use the full return path which
1189 * catches the problem safely.
1191 if (__predict_false(td->td_frame->tf_rip >= (la57 ?
1192 VM_MAXUSER_ADDRESS_LA57 : VM_MAXUSER_ADDRESS_LA48)))
1193 set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
1195 amd64_syscall_ret_flush_l1d_check_inline(td->td_errno);