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 * Table of handlers for various segment load faults.
178 static const struct {
183 .faddr = (uintptr_t)ld_ds,
184 .fhandler = (uintptr_t)ds_load_fault,
187 .faddr = (uintptr_t)ld_es,
188 .fhandler = (uintptr_t)es_load_fault,
191 .faddr = (uintptr_t)ld_fs,
192 .fhandler = (uintptr_t)fs_load_fault,
195 .faddr = (uintptr_t)ld_gs,
196 .fhandler = (uintptr_t)gs_load_fault,
199 .faddr = (uintptr_t)ld_gsbase,
200 .fhandler = (uintptr_t)gsbase_load_fault
203 .faddr = (uintptr_t)ld_fsbase,
204 .fhandler = (uintptr_t)fsbase_load_fault,
209 * Exception, fault, and trap interface to the FreeBSD kernel.
210 * This common code is called from assembly language IDT gate entry
211 * routines that prepare a suitable stack frame, and restore this
212 * frame after the exception has been processed.
216 trap(struct trapframe *frame)
221 register_t addr, dr6;
223 int pf, signo, ucode;
231 type = frame->tf_trapno;
234 /* Handler for NMI IPIs used for stopping CPUs. */
235 if (type == T_NMI && ipi_nmi_handler() == 0)
246 if (type == T_RESERVED) {
247 trap_fatal(frame, 0);
254 * CPU PMCs interrupt using an NMI. If the PMC module is
255 * active, pass the 'rip' value to the PMC module's interrupt
256 * handler. A non-zero return value from the handler means that
257 * the NMI was consumed by it and we can return immediately.
259 if (pmc_intr != NULL &&
260 (*pmc_intr)(frame) != 0)
265 if ((frame->tf_rflags & PSL_I) == 0) {
267 * Buggy application or kernel code has disabled
268 * interrupts and then trapped. Enabling interrupts
269 * now is wrong, but it is better than running with
270 * interrupts disabled until they are accidentally
273 if (TRAPF_USERMODE(frame)) {
275 "pid %ld (%s): trap %d with interrupts disabled\n",
276 (long)curproc->p_pid, curthread->td_name, type);
288 "kernel trap %d with interrupts disabled\n",
292 * We shouldn't enable interrupts while holding a
295 if (td->td_md.md_spinlock_count == 0)
301 if (TRAPF_USERMODE(frame)) {
305 td->td_frame = frame;
306 addr = frame->tf_rip;
307 if (td->td_cowgen != p->p_cowgen)
308 thread_cow_update(td);
311 case T_PRIVINFLT: /* privileged instruction fault */
316 case T_BPTFLT: /* bpt instruction fault */
318 if (trap_user_dtrace(frame, &dtrace_pid_probe_ptr))
327 case T_TRCTRAP: /* debug exception */
332 if ((dr6 & DBREG_DR6_BS) != 0) {
333 PROC_LOCK(td->td_proc);
334 if ((td->td_dbgflags & TDB_STEP) != 0) {
335 td->td_frame->tf_rflags &= ~PSL_T;
336 td->td_dbgflags &= ~TDB_STEP;
338 PROC_UNLOCK(td->td_proc);
342 case T_ARITHTRAP: /* arithmetic trap */
343 ucode = fputrap_x87();
349 case T_PROTFLT: /* general protection fault */
353 case T_STKFLT: /* stack fault */
354 case T_SEGNPFLT: /* segment not present fault */
358 case T_TSSFLT: /* invalid TSS fault */
366 case T_DOUBLEFLT: /* double fault */
372 case T_PAGEFLT: /* page fault */
374 * Can emulator handle this trap?
376 if (*p->p_sysent->sv_trap != NULL &&
377 (*p->p_sysent->sv_trap)(td) == 0)
380 pf = trap_pfault(frame, true, &signo, &ucode);
385 addr = frame->tf_addr;
388 case T_DIVIDE: /* integer divide fault */
394 nmi_handle_intr(type, frame);
397 case T_OFLOW: /* integer overflow fault */
402 case T_BOUND: /* bounds check fault */
408 /* transparent fault (due to context switch "late") */
409 KASSERT(PCB_USER_FPU(td->td_pcb),
410 ("kernel FPU ctx has leaked"));
414 case T_FPOPFLT: /* FPU operand fetch fault */
419 case T_XMMFLT: /* SIMD floating-point exception */
420 ucode = fputrap_sse();
427 (void)trap_user_dtrace(frame, &dtrace_return_probe_ptr);
434 KASSERT(cold || td->td_ucred != NULL,
435 ("kernel trap doesn't have ucred"));
437 case T_PAGEFLT: /* page fault */
438 (void)trap_pfault(frame, false, NULL, NULL);
442 if (PCB_USER_FPU(td->td_pcb))
443 panic("Unregistered use of FPU in kernel");
447 case T_ARITHTRAP: /* arithmetic trap */
448 case T_XMMFLT: /* SIMD floating-point exception */
449 case T_FPOPFLT: /* FPU operand fetch fault */
451 * For now, supporting kernel handler
452 * registration for FPU traps is overkill.
454 trap_fatal(frame, 0);
457 case T_STKFLT: /* stack fault */
458 case T_PROTFLT: /* general protection fault */
459 case T_SEGNPFLT: /* segment not present fault */
460 if (td->td_intr_nesting_level != 0)
464 * Invalid segment selectors and out of bounds
465 * %rip's and %rsp's can be set up in user mode.
466 * This causes a fault in kernel mode when the
467 * kernel tries to return to user mode. We want
468 * to get this fault so that we can fix the
469 * problem here and not have to check all the
470 * selectors and pointers when the user changes
473 * In case of PTI, the IRETQ faulted while the
474 * kernel used the pti stack, and exception
475 * frame records %rsp value pointing to that
476 * stack. If we return normally to
477 * doreti_iret_fault, the trapframe is
478 * reconstructed on pti stack, and calltrap()
479 * called on it as well. Due to the very
480 * limited pti stack size, kernel does not
481 * survive for too long. Switch to the normal
482 * thread stack for the trap handling.
484 * Magic '5' is the number of qwords occupied by
485 * the hardware trap frame.
487 if (frame->tf_rip == (long)doreti_iret) {
488 KASSERT((read_rflags() & PSL_I) == 0,
489 ("interrupts enabled"));
490 frame->tf_rip = (long)doreti_iret_fault;
491 if ((PCPU_GET(curpmap)->pm_ucr3 !=
493 (frame->tf_rsp == (uintptr_t)PCPU_GET(
494 pti_rsp0) - 5 * sizeof(register_t))) {
495 frame->tf_rsp = PCPU_GET(rsp0) - 5 *
501 for (i = 0; i < nitems(sfhandlers); i++) {
502 if (frame->tf_rip == sfhandlers[i].faddr) {
503 KASSERT((read_rflags() & PSL_I) == 0,
504 ("interrupts enabled"));
505 frame->tf_rip = sfhandlers[i].fhandler;
510 if (curpcb->pcb_onfault != NULL) {
511 frame->tf_rip = (long)curpcb->pcb_onfault;
518 * PSL_NT can be set in user mode and isn't cleared
519 * automatically when the kernel is entered. This
520 * causes a TSS fault when the kernel attempts to
521 * `iret' because the TSS link is uninitialized. We
522 * want to get this fault so that we can fix the
523 * problem here and not every time the kernel is
526 if (frame->tf_rflags & PSL_NT) {
527 frame->tf_rflags &= ~PSL_NT;
532 case T_TRCTRAP: /* debug exception */
533 /* Clear any pending debug events. */
538 * Ignore debug register exceptions due to
539 * accesses in the user's address space, which
540 * can happen under several conditions such as
541 * if a user sets a watchpoint on a buffer and
542 * then passes that buffer to a system call.
543 * We still want to get TRCTRAPS for addresses
544 * in kernel space because that is useful when
545 * debugging the kernel.
547 if (user_dbreg_trap(dr6))
551 * Malicious user code can configure a debug
552 * register watchpoint to trap on data access
553 * to the top of stack and then execute 'pop
554 * %ss; int 3'. Due to exception deferral for
555 * 'pop %ss', the CPU will not interrupt 'int
556 * 3' to raise the DB# exception for the debug
557 * register but will postpone the DB# until
558 * execution of the first instruction of the
559 * BP# handler (in kernel mode). Normally the
560 * previous check would ignore DB# exceptions
561 * for watchpoints on user addresses raised in
562 * kernel mode. However, some CPU errata
563 * include cases where DB# exceptions do not
564 * properly set bits in %dr6, e.g. Haswell
565 * HSD23 and Skylake-X SKZ24.
567 * A deferred DB# can also be raised on the
568 * first instructions of system call entry
569 * points or single-step traps via similar use
570 * of 'pop %ss' or 'mov xxx, %ss'.
574 (uintptr_t)IDTVEC(fast_syscall_pti) ||
575 #ifdef COMPAT_FREEBSD32
577 (uintptr_t)IDTVEC(int0x80_syscall_pti) ||
579 frame->tf_rip == (uintptr_t)IDTVEC(bpt_pti))
583 (uintptr_t)IDTVEC(fast_syscall) ||
584 #ifdef COMPAT_FREEBSD32
586 (uintptr_t)IDTVEC(int0x80_syscall) ||
588 frame->tf_rip == (uintptr_t)IDTVEC(bpt))
591 if (frame->tf_rip == (uintptr_t)IDTVEC(dbg) ||
592 /* Needed for AMD. */
593 frame->tf_rip == (uintptr_t)IDTVEC(fast_syscall32))
596 * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
600 * If KDB is enabled, let it handle the debugger trap.
601 * Otherwise, debugger traps "can't happen".
604 if (kdb_trap(type, dr6, frame))
610 nmi_handle_intr(type, frame);
614 trap_fatal(frame, 0);
618 /* Translate fault for emulators (e.g. Linux) */
619 if (*p->p_sysent->sv_transtrap != NULL)
620 signo = (*p->p_sysent->sv_transtrap)(signo, type);
622 ksiginfo_init_trap(&ksi);
623 ksi.ksi_signo = signo;
624 ksi.ksi_code = ucode;
625 ksi.ksi_trapno = type;
626 ksi.ksi_addr = (void *)addr;
627 if (uprintf_signal) {
628 uprintf("pid %d comm %s: signal %d err %lx code %d type %d "
629 "addr 0x%lx rsp 0x%lx rip 0x%lx "
630 "<%02x %02x %02x %02x %02x %02x %02x %02x>\n",
631 p->p_pid, p->p_comm, signo, frame->tf_err, ucode, type,
632 addr, frame->tf_rsp, frame->tf_rip,
633 fubyte((void *)(frame->tf_rip + 0)),
634 fubyte((void *)(frame->tf_rip + 1)),
635 fubyte((void *)(frame->tf_rip + 2)),
636 fubyte((void *)(frame->tf_rip + 3)),
637 fubyte((void *)(frame->tf_rip + 4)),
638 fubyte((void *)(frame->tf_rip + 5)),
639 fubyte((void *)(frame->tf_rip + 6)),
640 fubyte((void *)(frame->tf_rip + 7)));
642 KASSERT((read_rflags() & PSL_I) != 0, ("interrupts disabled"));
643 trapsignal(td, &ksi);
647 KASSERT(PCB_USER_FPU(td->td_pcb),
648 ("Return from trap with kernel FPU ctx leaked"));
652 * Ensure that we ignore any DTrace-induced faults. This function cannot
653 * be instrumented, so it cannot generate such faults itself.
656 trap_check(struct trapframe *frame)
660 if (dtrace_trap_func != NULL &&
661 (*dtrace_trap_func)(frame, frame->tf_trapno) != 0)
668 trap_is_smap(struct trapframe *frame)
672 * A page fault on a userspace address is classified as
674 * - SMAP is supported;
675 * - kernel mode accessed present data page;
676 * - rflags.AC was cleared.
677 * Kernel must never access user space with rflags.AC cleared
678 * if SMAP is enabled.
680 return ((cpu_stdext_feature & CPUID_STDEXT_SMAP) != 0 &&
681 (frame->tf_err & (PGEX_P | PGEX_U | PGEX_I | PGEX_RSV)) ==
682 PGEX_P && (frame->tf_rflags & PSL_AC) == 0);
686 trap_is_pti(struct trapframe *frame)
689 return (PCPU_GET(curpmap)->pm_ucr3 != PMAP_NO_CR3 &&
690 pg_nx != 0 && (frame->tf_err & (PGEX_P | PGEX_W |
691 PGEX_U | PGEX_I)) == (PGEX_P | PGEX_U | PGEX_I) &&
692 (curpcb->pcb_saved_ucr3 & ~CR3_PCID_MASK) ==
693 (PCPU_GET(curpmap)->pm_cr3 & ~CR3_PCID_MASK));
697 * Handle all details of a page fault.
699 * -1 if this fault was fatal, typically from kernel mode
700 * (cannot happen, but we need to return something).
701 * 0 if this fault was handled by updating either the user or kernel
702 * page table, execution can continue.
703 * 1 if this fault was from usermode and it was not handled, a synchronous
704 * signal should be delivered to the thread. *signo returns the signal
705 * number, *ucode gives si_code.
708 trap_pfault(struct trapframe *frame, bool usermode, int *signo, int *ucode)
717 MPASS(!usermode || (signo != NULL && ucode != NULL));
721 eva = frame->tf_addr;
723 if (__predict_false((td->td_pflags & TDP_NOFAULTING) != 0)) {
725 * Due to both processor errata and lazy TLB invalidation when
726 * access restrictions are removed from virtual pages, memory
727 * accesses that are allowed by the physical mapping layer may
728 * nonetheless cause one spurious page fault per virtual page.
729 * When the thread is executing a "no faulting" section that
730 * is bracketed by vm_fault_{disable,enable}_pagefaults(),
731 * every page fault is treated as a spurious page fault,
732 * unless it accesses the same virtual address as the most
733 * recent page fault within the same "no faulting" section.
735 if (td->td_md.md_spurflt_addr != eva ||
736 (td->td_pflags & TDP_RESETSPUR) != 0) {
738 * Do nothing to the TLB. A stale TLB entry is
739 * flushed automatically by a page fault.
741 td->td_md.md_spurflt_addr = eva;
742 td->td_pflags &= ~TDP_RESETSPUR;
747 * If we get a page fault while in a critical section, then
748 * it is most likely a fatal kernel page fault. The kernel
749 * is already going to panic trying to get a sleep lock to
750 * do the VM lookup, so just consider it a fatal trap so the
751 * kernel can print out a useful trap message and even get
754 * If we get a page fault while holding a non-sleepable
755 * lock, then it is most likely a fatal kernel page fault.
756 * If WITNESS is enabled, then it's going to whine about
757 * bogus LORs with various VM locks, so just skip to the
758 * fatal trap handling directly.
760 if (td->td_critnest != 0 ||
761 WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
762 "Kernel page fault") != 0) {
763 trap_fatal(frame, eva);
767 if (eva >= VM_MIN_KERNEL_ADDRESS) {
769 * Don't allow user-mode faults in kernel address space.
773 *ucode = SEGV_MAPERR;
779 map = &p->p_vmspace->vm_map;
782 * When accessing a usermode address, kernel must be
783 * ready to accept the page fault, and provide a
784 * handling routine. Since accessing the address
785 * without the handler is a bug, do not try to handle
786 * it normally, and panic immediately.
788 * If SMAP is enabled, filter SMAP faults also,
789 * because illegal access might occur to the mapped
790 * user address, causing infinite loop.
792 if (!usermode && (td->td_intr_nesting_level != 0 ||
793 trap_is_smap(frame) || curpcb->pcb_onfault == NULL)) {
794 trap_fatal(frame, eva);
800 * If the trap was caused by errant bits in the PTE then panic.
802 if (frame->tf_err & PGEX_RSV) {
803 trap_fatal(frame, eva);
808 * User-mode protection key violation (PKU). May happen
809 * either from usermode or from kernel if copyin accessed
810 * key-protected mapping.
812 if ((frame->tf_err & PGEX_PK) != 0) {
813 if (eva > VM_MAXUSER_ADDRESS) {
814 trap_fatal(frame, eva);
819 *ucode = SEGV_PKUERR;
826 * If nx protection of the usermode portion of kernel page
827 * tables caused trap, panic.
829 if (usermode && trap_is_pti(frame))
830 panic("PTI: pid %d comm %s tf_err %#lx", p->p_pid,
831 p->p_comm, frame->tf_err);
834 * PGEX_I is defined only if the execute disable bit capability is
835 * supported and enabled.
837 if (frame->tf_err & PGEX_W)
838 ftype = VM_PROT_WRITE;
839 else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
840 ftype = VM_PROT_EXECUTE;
842 ftype = VM_PROT_READ;
844 /* Fault in the page. */
845 rv = vm_fault_trap(map, eva, ftype, VM_FAULT_NORMAL, signo, ucode);
846 if (rv == KERN_SUCCESS) {
848 if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
849 PMC_SOFT_CALL_TF( , , page_fault, all, frame);
850 if (ftype == VM_PROT_READ)
851 PMC_SOFT_CALL_TF( , , page_fault, read,
854 PMC_SOFT_CALL_TF( , , page_fault, write,
864 if (td->td_intr_nesting_level == 0 &&
865 curpcb->pcb_onfault != NULL) {
866 frame->tf_rip = (long)curpcb->pcb_onfault;
869 trap_fatal(frame, eva);
874 trap_fatal(frame, eva)
875 struct trapframe *frame;
880 struct soft_segment_descriptor softseg;
881 struct user_segment_descriptor *gdt;
886 code = frame->tf_err;
887 type = frame->tf_trapno;
888 gdt = *PCPU_PTR(gdt);
889 sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)], &softseg);
891 printf("\n\nFatal trap %d: %s while in %s mode\n", type,
892 type < nitems(trap_msg) ? trap_msg[type] : UNKNOWN,
893 TRAPF_USERMODE(frame) ? "user" : "kernel");
895 /* two separate prints in case of a trap on an unmapped page */
896 printf("cpuid = %d; ", PCPU_GET(cpuid));
897 printf("apic id = %02x\n", PCPU_GET(apic_id));
899 if (type == T_PAGEFLT) {
900 printf("fault virtual address = 0x%lx\n", eva);
901 printf("fault code = %s %s %s%s%s, %s\n",
902 code & PGEX_U ? "user" : "supervisor",
903 code & PGEX_W ? "write" : "read",
904 code & PGEX_I ? "instruction" : "data",
905 code & PGEX_PK ? " prot key" : "",
906 code & PGEX_SGX ? " SGX" : "",
907 code & PGEX_RSV ? "reserved bits in PTE" :
908 code & PGEX_P ? "protection violation" : "page not present");
910 printf("instruction pointer = 0x%lx:0x%lx\n",
911 frame->tf_cs & 0xffff, frame->tf_rip);
912 ss = frame->tf_ss & 0xffff;
913 printf("stack pointer = 0x%x:0x%lx\n", ss, frame->tf_rsp);
914 printf("frame pointer = 0x%x:0x%lx\n", ss, frame->tf_rbp);
915 printf("code segment = base 0x%lx, limit 0x%lx, type 0x%x\n",
916 softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
917 printf(" = DPL %d, pres %d, long %d, def32 %d, gran %d\n",
918 softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
920 printf("processor eflags = ");
921 if (frame->tf_rflags & PSL_T)
922 printf("trace trap, ");
923 if (frame->tf_rflags & PSL_I)
924 printf("interrupt enabled, ");
925 if (frame->tf_rflags & PSL_NT)
926 printf("nested task, ");
927 if (frame->tf_rflags & PSL_RF)
929 printf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
930 printf("current process = %d (%s)\n",
931 curproc->p_pid, curthread->td_name);
934 if (debugger_on_trap) {
935 kdb_why = KDB_WHY_TRAP;
936 handled = kdb_trap(type, 0, frame);
937 kdb_why = KDB_WHY_UNSET;
942 printf("trap number = %d\n", type);
943 panic("%s", type < nitems(trap_msg) ? trap_msg[type] :
944 "unknown/reserved trap");
949 * Invoke a userspace DTrace hook. The hook pointer is cleared when no
950 * userspace probes are enabled, so we must synchronize with DTrace to ensure
951 * that a trapping thread is able to call the hook before it is cleared.
954 trap_user_dtrace(struct trapframe *frame, int (**hookp)(struct trapframe *))
956 int (*hook)(struct trapframe *);
958 hook = atomic_load_ptr(hookp);
961 return ((hook)(frame) == 0);
967 * Double fault handler. Called when a fault occurs while writing
968 * a frame for a trap/exception onto the stack. This usually occurs
969 * when the stack overflows (such is the case with infinite recursion,
973 dblfault_handler(struct trapframe *frame)
976 if (dtrace_doubletrap_func != NULL)
977 (*dtrace_doubletrap_func)();
979 printf("\nFatal double fault\n"
980 "rip %#lx rsp %#lx rbp %#lx\n"
981 "rax %#lx rdx %#lx rbx %#lx\n"
982 "rcx %#lx rsi %#lx rdi %#lx\n"
983 "r8 %#lx r9 %#lx r10 %#lx\n"
984 "r11 %#lx r12 %#lx r13 %#lx\n"
985 "r14 %#lx r15 %#lx rflags %#lx\n"
986 "cs %#lx ss %#lx ds %#hx es %#hx fs %#hx gs %#hx\n"
987 "fsbase %#lx gsbase %#lx kgsbase %#lx\n",
988 frame->tf_rip, frame->tf_rsp, frame->tf_rbp,
989 frame->tf_rax, frame->tf_rdx, frame->tf_rbx,
990 frame->tf_rcx, frame->tf_rdi, frame->tf_rsi,
991 frame->tf_r8, frame->tf_r9, frame->tf_r10,
992 frame->tf_r11, frame->tf_r12, frame->tf_r13,
993 frame->tf_r14, frame->tf_r15, frame->tf_rflags,
994 frame->tf_cs, frame->tf_ss, frame->tf_ds, frame->tf_es,
995 frame->tf_fs, frame->tf_gs,
996 rdmsr(MSR_FSBASE), rdmsr(MSR_GSBASE), rdmsr(MSR_KGSBASE));
998 /* two separate prints in case of a trap on an unmapped page */
999 printf("cpuid = %d; ", PCPU_GET(cpuid));
1000 printf("apic id = %02x\n", PCPU_GET(apic_id));
1002 panic("double fault");
1005 static int __noinline
1006 cpu_fetch_syscall_args_fallback(struct thread *td, struct syscall_args *sa)
1009 struct trapframe *frame;
1012 int reg, regcnt, error;
1015 frame = td->td_frame;
1019 if (sa->code == SYS_syscall || sa->code == SYS___syscall) {
1020 sa->code = frame->tf_rdi;
1025 if (sa->code >= p->p_sysent->sv_size)
1026 sa->callp = &p->p_sysent->sv_table[0];
1028 sa->callp = &p->p_sysent->sv_table[sa->code];
1030 KASSERT(sa->callp->sy_narg <= nitems(sa->args),
1031 ("Too many syscall arguments!"));
1032 argp = &frame->tf_rdi;
1034 memcpy(sa->args, argp, sizeof(sa->args[0]) * NARGREGS);
1035 if (sa->callp->sy_narg > regcnt) {
1036 params = (caddr_t)frame->tf_rsp + sizeof(register_t);
1037 error = copyin(params, &sa->args[regcnt],
1038 (sa->callp->sy_narg - regcnt) * sizeof(sa->args[0]));
1039 if (__predict_false(error != 0))
1043 td->td_retval[0] = 0;
1044 td->td_retval[1] = frame->tf_rdx;
1050 cpu_fetch_syscall_args(struct thread *td)
1053 struct trapframe *frame;
1054 struct syscall_args *sa;
1057 frame = td->td_frame;
1060 sa->code = frame->tf_rax;
1062 if (__predict_false(sa->code == SYS_syscall ||
1063 sa->code == SYS___syscall ||
1064 sa->code >= p->p_sysent->sv_size))
1065 return (cpu_fetch_syscall_args_fallback(td, sa));
1067 sa->callp = &p->p_sysent->sv_table[sa->code];
1068 KASSERT(sa->callp->sy_narg <= nitems(sa->args),
1069 ("Too many syscall arguments!"));
1071 if (__predict_false(sa->callp->sy_narg > NARGREGS))
1072 return (cpu_fetch_syscall_args_fallback(td, sa));
1074 memcpy(sa->args, &frame->tf_rdi, sizeof(sa->args[0]) * NARGREGS);
1076 td->td_retval[0] = 0;
1077 td->td_retval[1] = frame->tf_rdx;
1082 #include "../../kern/subr_syscall.c"
1084 static void (*syscall_ret_l1d_flush)(void);
1085 int syscall_ret_l1d_flush_mode;
1091 wrmsr(MSR_IA32_FLUSH_CMD, IA32_FLUSH_CMD_L1D);
1094 static void __noinline
1095 amd64_syscall_ret_flush_l1d_check(int error)
1099 if (error != EEXIST && error != EAGAIN && error != EXDEV &&
1100 error != ENOENT && error != ENOTCONN && error != EINPROGRESS) {
1101 p = atomic_load_ptr(&syscall_ret_l1d_flush);
1107 static void __inline
1108 amd64_syscall_ret_flush_l1d_check_inline(int error)
1111 if (__predict_false(error != 0))
1112 amd64_syscall_ret_flush_l1d_check(error);
1116 amd64_syscall_ret_flush_l1d(int error)
1119 amd64_syscall_ret_flush_l1d_check_inline(error);
1123 amd64_syscall_ret_flush_l1d_recalc(void)
1127 l1d_hw = (cpu_stdext_feature3 & CPUID_STDEXT3_L1D_FLUSH) != 0;
1129 switch (syscall_ret_l1d_flush_mode) {
1131 syscall_ret_l1d_flush = NULL;
1134 syscall_ret_l1d_flush = l1d_hw ? flush_l1d_hw :
1138 syscall_ret_l1d_flush = l1d_hw ? flush_l1d_hw : NULL;
1141 syscall_ret_l1d_flush = flush_l1d_sw_abi;
1144 syscall_ret_l1d_flush_mode = 1;
1150 machdep_syscall_ret_flush_l1d(SYSCTL_HANDLER_ARGS)
1154 val = syscall_ret_l1d_flush_mode;
1155 error = sysctl_handle_int(oidp, &val, 0, req);
1156 if (error != 0 || req->newptr == NULL)
1158 syscall_ret_l1d_flush_mode = val;
1159 amd64_syscall_ret_flush_l1d_recalc();
1162 SYSCTL_PROC(_machdep, OID_AUTO, syscall_ret_flush_l1d, CTLTYPE_INT |
1163 CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
1164 machdep_syscall_ret_flush_l1d, "I",
1165 "Flush L1D on syscall return with error (0 - off, 1 - on, "
1166 "2 - use hw only, 3 - use sw only)");
1169 * System call handler for native binaries. The trap frame is already
1170 * set up by the assembler trampoline and a pointer to it is saved in
1174 amd64_syscall(struct thread *td, int traced)
1179 if (!TRAPF_USERMODE(td->td_frame)) {
1189 if (__predict_false(traced)) {
1190 td->td_frame->tf_rflags &= ~PSL_T;
1191 ksiginfo_init_trap(&ksi);
1192 ksi.ksi_signo = SIGTRAP;
1193 ksi.ksi_code = TRAP_TRACE;
1194 ksi.ksi_addr = (void *)td->td_frame->tf_rip;
1195 trapsignal(td, &ksi);
1198 KASSERT(PCB_USER_FPU(td->td_pcb),
1199 ("System call %s returning with kernel FPU ctx leaked",
1200 syscallname(td->td_proc, td->td_sa.code)));
1201 KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td),
1202 ("System call %s returning with mangled pcb_save",
1203 syscallname(td->td_proc, td->td_sa.code)));
1204 KASSERT(pmap_not_in_di(),
1205 ("System call %s returning with leaked invl_gen %lu",
1206 syscallname(td->td_proc, td->td_sa.code),
1207 td->td_md.md_invl_gen.gen));
1212 * If the user-supplied value of %rip is not a canonical
1213 * address, then some CPUs will trigger a ring 0 #GP during
1214 * the sysret instruction. However, the fault handler would
1215 * execute in ring 0 with the user's %gs and %rsp which would
1216 * not be safe. Instead, use the full return path which
1217 * catches the problem safely.
1219 if (__predict_false(td->td_frame->tf_rip >= (la57 ?
1220 VM_MAXUSER_ADDRESS_LA57 : VM_MAXUSER_ADDRESS_LA48)))
1221 set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
1223 amd64_syscall_ret_flush_l1d_check_inline(td->td_errno);