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"
55 #include "opt_stack.h"
57 #include <sys/param.h>
59 #include <sys/systm.h>
61 #include <sys/pioctl.h>
62 #include <sys/ptrace.h>
64 #include <sys/kernel.h>
67 #include <sys/mutex.h>
68 #include <sys/resourcevar.h>
69 #include <sys/signalvar.h>
70 #include <sys/syscall.h>
71 #include <sys/sysctl.h>
72 #include <sys/sysent.h>
74 #include <sys/vmmeter.h>
76 #include <sys/pmckern.h>
77 PMC_SOFT_DEFINE( , , page_fault, all);
78 PMC_SOFT_DEFINE( , , page_fault, read);
79 PMC_SOFT_DEFINE( , , page_fault, write);
83 #include <vm/vm_param.h>
85 #include <vm/vm_kern.h>
86 #include <vm/vm_map.h>
87 #include <vm/vm_page.h>
88 #include <vm/vm_extern.h>
90 #include <machine/cpu.h>
91 #include <machine/intr_machdep.h>
93 #include <machine/md_var.h>
94 #include <machine/pcb.h>
96 #include <machine/smp.h>
98 #include <machine/stack.h>
99 #include <machine/trap.h>
100 #include <machine/tss.h>
103 #include <sys/dtrace_bsd.h>
106 extern inthand_t IDTVEC(bpt), IDTVEC(bpt_pti), IDTVEC(dbg),
107 IDTVEC(fast_syscall), IDTVEC(fast_syscall_pti), IDTVEC(fast_syscall32),
108 IDTVEC(int0x80_syscall_pti), IDTVEC(int0x80_syscall);
110 void __noinline trap(struct trapframe *frame);
111 void trap_check(struct trapframe *frame);
112 void dblfault_handler(struct trapframe *frame);
114 static int trap_pfault(struct trapframe *, bool, int *, int *);
115 static void trap_fatal(struct trapframe *, vm_offset_t);
117 static bool trap_user_dtrace(struct trapframe *,
118 int (**hook)(struct trapframe *));
121 static const char UNKNOWN[] = "unknown";
122 static const char *const trap_msg[] = {
123 [0] = UNKNOWN, /* unused */
124 [T_PRIVINFLT] = "privileged instruction fault",
125 [2] = UNKNOWN, /* unused */
126 [T_BPTFLT] = "breakpoint instruction fault",
127 [4] = UNKNOWN, /* unused */
128 [5] = UNKNOWN, /* unused */
129 [T_ARITHTRAP] = "arithmetic trap",
130 [7] = UNKNOWN, /* unused */
131 [8] = UNKNOWN, /* unused */
132 [T_PROTFLT] = "general protection fault",
133 [T_TRCTRAP] = "debug exception",
134 [11] = UNKNOWN, /* unused */
135 [T_PAGEFLT] = "page fault",
136 [13] = UNKNOWN, /* unused */
137 [T_ALIGNFLT] = "alignment fault",
138 [15] = UNKNOWN, /* unused */
139 [16] = UNKNOWN, /* unused */
140 [17] = UNKNOWN, /* unused */
141 [T_DIVIDE] = "integer divide fault",
142 [T_NMI] = "non-maskable interrupt trap",
143 [T_OFLOW] = "overflow trap",
144 [T_BOUND] = "FPU bounds check fault",
145 [T_DNA] = "FPU device not available",
146 [T_DOUBLEFLT] = "double fault",
147 [T_FPOPFLT] = "FPU operand fetch fault",
148 [T_TSSFLT] = "invalid TSS fault",
149 [T_SEGNPFLT] = "segment not present fault",
150 [T_STKFLT] = "stack fault",
151 [T_MCHK] = "machine check trap",
152 [T_XMMFLT] = "SIMD floating-point exception",
153 [T_RESERVED] = "reserved (unknown) fault",
154 [31] = UNKNOWN, /* reserved */
155 [T_DTRACE_RET] = "DTrace pid return trap",
158 static int uprintf_signal;
159 SYSCTL_INT(_machdep, OID_AUTO, uprintf_signal, CTLFLAG_RWTUN,
161 "Print debugging information on trap signal to ctty");
164 * Control L1D flush on return from NMI.
166 * Tunable can be set to the following values:
167 * 0 - only enable flush on return from NMI if required by vmm.ko (default)
168 * >1 - always flush on return from NMI.
170 * Post-boot, the sysctl indicates if flushing is currently enabled.
172 int nmi_flush_l1d_sw;
173 SYSCTL_INT(_machdep, OID_AUTO, nmi_flush_l1d_sw, CTLFLAG_RWTUN,
174 &nmi_flush_l1d_sw, 0,
175 "Flush L1 Data Cache on NMI exit, software bhyve L1TF mitigation assist");
178 * Exception, fault, and trap interface to the FreeBSD kernel.
179 * This common code is called from assembly language IDT gate entry
180 * routines that prepare a suitable stack frame, and restore this
181 * frame after the exception has been processed.
185 trap(struct trapframe *frame)
190 register_t addr, dr6;
191 int pf, signo, ucode;
199 type = frame->tf_trapno;
202 /* Handler for NMI IPIs used for stopping CPUs. */
203 if (type == T_NMI && ipi_nmi_handler() == 0)
214 if (type == T_RESERVED) {
215 trap_fatal(frame, 0);
222 * CPU PMCs interrupt using an NMI. If the PMC module is
223 * active, pass the 'rip' value to the PMC module's interrupt
224 * handler. A non-zero return value from the handler means that
225 * the NMI was consumed by it and we can return immediately.
227 if (pmc_intr != NULL &&
228 (*pmc_intr)(frame) != 0)
233 if (stack_nmi_handler(frame) != 0)
238 if ((frame->tf_rflags & PSL_I) == 0) {
240 * Buggy application or kernel code has disabled
241 * interrupts and then trapped. Enabling interrupts
242 * now is wrong, but it is better than running with
243 * interrupts disabled until they are accidentally
246 if (TRAPF_USERMODE(frame))
248 "pid %ld (%s): trap %d with interrupts disabled\n",
249 (long)curproc->p_pid, curthread->td_name, type);
250 else if (type != T_NMI && type != T_BPTFLT &&
253 * XXX not quite right, since this may be for a
254 * multiple fault in user mode.
256 printf("kernel trap %d with interrupts disabled\n",
260 * We shouldn't enable interrupts while holding a
263 if (td->td_md.md_spinlock_count == 0)
268 if (TRAPF_USERMODE(frame)) {
272 td->td_frame = frame;
273 addr = frame->tf_rip;
274 if (td->td_cowgen != p->p_cowgen)
275 thread_cow_update(td);
278 case T_PRIVINFLT: /* privileged instruction fault */
283 case T_BPTFLT: /* bpt instruction fault */
285 if (trap_user_dtrace(frame, &dtrace_pid_probe_ptr))
294 case T_TRCTRAP: /* debug exception */
299 if ((dr6 & DBREG_DR6_BS) != 0) {
300 PROC_LOCK(td->td_proc);
301 if ((td->td_dbgflags & TDB_STEP) != 0) {
302 td->td_frame->tf_rflags &= ~PSL_T;
303 td->td_dbgflags &= ~TDB_STEP;
305 PROC_UNLOCK(td->td_proc);
309 case T_ARITHTRAP: /* arithmetic trap */
310 ucode = fputrap_x87();
316 case T_PROTFLT: /* general protection fault */
320 case T_STKFLT: /* stack fault */
321 case T_SEGNPFLT: /* segment not present fault */
325 case T_TSSFLT: /* invalid TSS fault */
333 case T_DOUBLEFLT: /* double fault */
339 case T_PAGEFLT: /* page fault */
341 * Can emulator handle this trap?
343 if (*p->p_sysent->sv_trap != NULL &&
344 (*p->p_sysent->sv_trap)(td) == 0)
347 pf = trap_pfault(frame, true, &signo, &ucode);
352 addr = frame->tf_addr;
355 case T_DIVIDE: /* integer divide fault */
362 nmi_handle_intr(type, frame);
366 case T_OFLOW: /* integer overflow fault */
371 case T_BOUND: /* bounds check fault */
377 /* transparent fault (due to context switch "late") */
378 KASSERT(PCB_USER_FPU(td->td_pcb),
379 ("kernel FPU ctx has leaked"));
383 case T_FPOPFLT: /* FPU operand fetch fault */
388 case T_XMMFLT: /* SIMD floating-point exception */
389 ucode = fputrap_sse();
396 (void)trap_user_dtrace(frame, &dtrace_return_probe_ptr);
403 KASSERT(cold || td->td_ucred != NULL,
404 ("kernel trap doesn't have ucred"));
406 case T_PAGEFLT: /* page fault */
407 (void)trap_pfault(frame, false, NULL, NULL);
411 if (PCB_USER_FPU(td->td_pcb))
412 panic("Unregistered use of FPU in kernel");
416 case T_ARITHTRAP: /* arithmetic trap */
417 case T_XMMFLT: /* SIMD floating-point exception */
418 case T_FPOPFLT: /* FPU operand fetch fault */
420 * For now, supporting kernel handler
421 * registration for FPU traps is overkill.
423 trap_fatal(frame, 0);
426 case T_STKFLT: /* stack fault */
427 case T_PROTFLT: /* general protection fault */
428 case T_SEGNPFLT: /* segment not present fault */
429 if (td->td_intr_nesting_level != 0)
433 * Invalid segment selectors and out of bounds
434 * %rip's and %rsp's can be set up in user mode.
435 * This causes a fault in kernel mode when the
436 * kernel tries to return to user mode. We want
437 * to get this fault so that we can fix the
438 * problem here and not have to check all the
439 * selectors and pointers when the user changes
442 * In case of PTI, the IRETQ faulted while the
443 * kernel used the pti stack, and exception
444 * frame records %rsp value pointing to that
445 * stack. If we return normally to
446 * doreti_iret_fault, the trapframe is
447 * reconstructed on pti stack, and calltrap()
448 * called on it as well. Due to the very
449 * limited pti stack size, kernel does not
450 * survive for too long. Switch to the normal
451 * thread stack for the trap handling.
453 * Magic '5' is the number of qwords occupied by
454 * the hardware trap frame.
456 if (frame->tf_rip == (long)doreti_iret) {
457 frame->tf_rip = (long)doreti_iret_fault;
458 if ((PCPU_GET(curpmap)->pm_ucr3 !=
460 (frame->tf_rsp == (uintptr_t)PCPU_GET(
461 pti_rsp0) - 5 * sizeof(register_t))) {
462 frame->tf_rsp = PCPU_GET(rsp0) - 5 *
467 if (frame->tf_rip == (long)ld_ds) {
468 frame->tf_rip = (long)ds_load_fault;
471 if (frame->tf_rip == (long)ld_es) {
472 frame->tf_rip = (long)es_load_fault;
475 if (frame->tf_rip == (long)ld_fs) {
476 frame->tf_rip = (long)fs_load_fault;
479 if (frame->tf_rip == (long)ld_gs) {
480 frame->tf_rip = (long)gs_load_fault;
483 if (frame->tf_rip == (long)ld_gsbase) {
484 frame->tf_rip = (long)gsbase_load_fault;
487 if (frame->tf_rip == (long)ld_fsbase) {
488 frame->tf_rip = (long)fsbase_load_fault;
491 if (curpcb->pcb_onfault != NULL) {
492 frame->tf_rip = (long)curpcb->pcb_onfault;
499 * PSL_NT can be set in user mode and isn't cleared
500 * automatically when the kernel is entered. This
501 * causes a TSS fault when the kernel attempts to
502 * `iret' because the TSS link is uninitialized. We
503 * want to get this fault so that we can fix the
504 * problem here and not every time the kernel is
507 if (frame->tf_rflags & PSL_NT) {
508 frame->tf_rflags &= ~PSL_NT;
513 case T_TRCTRAP: /* debug exception */
514 /* Clear any pending debug events. */
519 * Ignore debug register exceptions due to
520 * accesses in the user's address space, which
521 * can happen under several conditions such as
522 * if a user sets a watchpoint on a buffer and
523 * then passes that buffer to a system call.
524 * We still want to get TRCTRAPS for addresses
525 * in kernel space because that is useful when
526 * debugging the kernel.
528 if (user_dbreg_trap(dr6))
532 * Malicious user code can configure a debug
533 * register watchpoint to trap on data access
534 * to the top of stack and then execute 'pop
535 * %ss; int 3'. Due to exception deferral for
536 * 'pop %ss', the CPU will not interrupt 'int
537 * 3' to raise the DB# exception for the debug
538 * register but will postpone the DB# until
539 * execution of the first instruction of the
540 * BP# handler (in kernel mode). Normally the
541 * previous check would ignore DB# exceptions
542 * for watchpoints on user addresses raised in
543 * kernel mode. However, some CPU errata
544 * include cases where DB# exceptions do not
545 * properly set bits in %dr6, e.g. Haswell
546 * HSD23 and Skylake-X SKZ24.
548 * A deferred DB# can also be raised on the
549 * first instructions of system call entry
550 * points or single-step traps via similar use
551 * of 'pop %ss' or 'mov xxx, %ss'.
555 (uintptr_t)IDTVEC(fast_syscall_pti) ||
556 #ifdef COMPAT_FREEBSD32
558 (uintptr_t)IDTVEC(int0x80_syscall_pti) ||
560 frame->tf_rip == (uintptr_t)IDTVEC(bpt_pti))
564 (uintptr_t)IDTVEC(fast_syscall) ||
565 #ifdef COMPAT_FREEBSD32
567 (uintptr_t)IDTVEC(int0x80_syscall) ||
569 frame->tf_rip == (uintptr_t)IDTVEC(bpt))
572 if (frame->tf_rip == (uintptr_t)IDTVEC(dbg) ||
573 /* Needed for AMD. */
574 frame->tf_rip == (uintptr_t)IDTVEC(fast_syscall32))
577 * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
581 * If KDB is enabled, let it handle the debugger trap.
582 * Otherwise, debugger traps "can't happen".
585 if (kdb_trap(type, dr6, frame))
592 nmi_handle_intr(type, frame);
597 trap_fatal(frame, 0);
601 /* Translate fault for emulators (e.g. Linux) */
602 if (*p->p_sysent->sv_transtrap != NULL)
603 signo = (*p->p_sysent->sv_transtrap)(signo, type);
605 ksiginfo_init_trap(&ksi);
606 ksi.ksi_signo = signo;
607 ksi.ksi_code = ucode;
608 ksi.ksi_trapno = type;
609 ksi.ksi_addr = (void *)addr;
610 if (uprintf_signal) {
611 uprintf("pid %d comm %s: signal %d err %lx code %d type %d "
612 "addr 0x%lx rsp 0x%lx rip 0x%lx "
613 "<%02x %02x %02x %02x %02x %02x %02x %02x>\n",
614 p->p_pid, p->p_comm, signo, frame->tf_err, ucode, type,
615 addr, frame->tf_rsp, frame->tf_rip,
616 fubyte((void *)(frame->tf_rip + 0)),
617 fubyte((void *)(frame->tf_rip + 1)),
618 fubyte((void *)(frame->tf_rip + 2)),
619 fubyte((void *)(frame->tf_rip + 3)),
620 fubyte((void *)(frame->tf_rip + 4)),
621 fubyte((void *)(frame->tf_rip + 5)),
622 fubyte((void *)(frame->tf_rip + 6)),
623 fubyte((void *)(frame->tf_rip + 7)));
625 KASSERT((read_rflags() & PSL_I) != 0, ("interrupts disabled"));
626 trapsignal(td, &ksi);
630 KASSERT(PCB_USER_FPU(td->td_pcb),
631 ("Return from trap with kernel FPU ctx leaked"));
635 * Ensure that we ignore any DTrace-induced faults. This function cannot
636 * be instrumented, so it cannot generate such faults itself.
639 trap_check(struct trapframe *frame)
643 if (dtrace_trap_func != NULL &&
644 (*dtrace_trap_func)(frame, frame->tf_trapno) != 0)
651 trap_is_smap(struct trapframe *frame)
655 * A page fault on a userspace address is classified as
657 * - SMAP is supported;
658 * - kernel mode accessed present data page;
659 * - rflags.AC was cleared.
660 * Kernel must never access user space with rflags.AC cleared
661 * if SMAP is enabled.
663 return ((cpu_stdext_feature & CPUID_STDEXT_SMAP) != 0 &&
664 (frame->tf_err & (PGEX_P | PGEX_U | PGEX_I | PGEX_RSV)) ==
665 PGEX_P && (frame->tf_rflags & PSL_AC) == 0);
669 trap_is_pti(struct trapframe *frame)
672 return (PCPU_GET(curpmap)->pm_ucr3 != PMAP_NO_CR3 &&
673 pg_nx != 0 && (frame->tf_err & (PGEX_P | PGEX_W |
674 PGEX_U | PGEX_I)) == (PGEX_P | PGEX_U | PGEX_I) &&
675 (curpcb->pcb_saved_ucr3 & ~CR3_PCID_MASK) ==
676 (PCPU_GET(curpmap)->pm_cr3 & ~CR3_PCID_MASK));
680 * Handle all details of a page fault.
682 * -1 if this fault was fatal, typically from kernel mode
683 * (cannot happen, but we need to return something).
684 * 0 if this fault was handled by updating either the user or kernel
685 * page table, execution can continue.
686 * 1 if this fault was from usermode and it was not handled, a synchronous
687 * signal should be delivered to the thread. *signo returns the signal
688 * number, *ucode gives si_code.
691 trap_pfault(struct trapframe *frame, bool usermode, int *signo, int *ucode)
700 MPASS(!usermode || (signo != NULL && ucode != NULL));
704 eva = frame->tf_addr;
706 if (__predict_false((td->td_pflags & TDP_NOFAULTING) != 0)) {
708 * Due to both processor errata and lazy TLB invalidation when
709 * access restrictions are removed from virtual pages, memory
710 * accesses that are allowed by the physical mapping layer may
711 * nonetheless cause one spurious page fault per virtual page.
712 * When the thread is executing a "no faulting" section that
713 * is bracketed by vm_fault_{disable,enable}_pagefaults(),
714 * every page fault is treated as a spurious page fault,
715 * unless it accesses the same virtual address as the most
716 * recent page fault within the same "no faulting" section.
718 if (td->td_md.md_spurflt_addr != eva ||
719 (td->td_pflags & TDP_RESETSPUR) != 0) {
721 * Do nothing to the TLB. A stale TLB entry is
722 * flushed automatically by a page fault.
724 td->td_md.md_spurflt_addr = eva;
725 td->td_pflags &= ~TDP_RESETSPUR;
730 * If we get a page fault while in a critical section, then
731 * it is most likely a fatal kernel page fault. The kernel
732 * is already going to panic trying to get a sleep lock to
733 * do the VM lookup, so just consider it a fatal trap so the
734 * kernel can print out a useful trap message and even get
737 * If we get a page fault while holding a non-sleepable
738 * lock, then it is most likely a fatal kernel page fault.
739 * If WITNESS is enabled, then it's going to whine about
740 * bogus LORs with various VM locks, so just skip to the
741 * fatal trap handling directly.
743 if (td->td_critnest != 0 ||
744 WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
745 "Kernel page fault") != 0) {
746 trap_fatal(frame, eva);
750 if (eva >= VM_MIN_KERNEL_ADDRESS) {
752 * Don't allow user-mode faults in kernel address space.
756 *ucode = SEGV_MAPERR;
762 map = &p->p_vmspace->vm_map;
765 * When accessing a usermode address, kernel must be
766 * ready to accept the page fault, and provide a
767 * handling routine. Since accessing the address
768 * without the handler is a bug, do not try to handle
769 * it normally, and panic immediately.
771 * If SMAP is enabled, filter SMAP faults also,
772 * because illegal access might occur to the mapped
773 * user address, causing infinite loop.
775 if (!usermode && (td->td_intr_nesting_level != 0 ||
776 trap_is_smap(frame) || curpcb->pcb_onfault == NULL)) {
777 trap_fatal(frame, eva);
783 * If the trap was caused by errant bits in the PTE then panic.
785 if (frame->tf_err & PGEX_RSV) {
786 trap_fatal(frame, eva);
791 * User-mode protection key violation (PKU). May happen
792 * either from usermode or from kernel if copyin accessed
793 * key-protected mapping.
795 if ((frame->tf_err & PGEX_PK) != 0) {
796 if (eva > VM_MAXUSER_ADDRESS) {
797 trap_fatal(frame, eva);
802 *ucode = SEGV_PKUERR;
809 * If nx protection of the usermode portion of kernel page
810 * tables caused trap, panic.
812 if (usermode && trap_is_pti(frame))
813 panic("PTI: pid %d comm %s tf_err %#lx", p->p_pid,
814 p->p_comm, frame->tf_err);
817 * PGEX_I is defined only if the execute disable bit capability is
818 * supported and enabled.
820 if (frame->tf_err & PGEX_W)
821 ftype = VM_PROT_WRITE;
822 else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
823 ftype = VM_PROT_EXECUTE;
825 ftype = VM_PROT_READ;
827 /* Fault in the page. */
828 rv = vm_fault_trap(map, eva, ftype, VM_FAULT_NORMAL, signo, ucode);
829 if (rv == KERN_SUCCESS) {
831 if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
832 PMC_SOFT_CALL_TF( , , page_fault, all, frame);
833 if (ftype == VM_PROT_READ)
834 PMC_SOFT_CALL_TF( , , page_fault, read,
837 PMC_SOFT_CALL_TF( , , page_fault, write,
847 if (td->td_intr_nesting_level == 0 &&
848 curpcb->pcb_onfault != NULL) {
849 frame->tf_rip = (long)curpcb->pcb_onfault;
852 trap_fatal(frame, eva);
857 trap_fatal(frame, eva)
858 struct trapframe *frame;
863 struct soft_segment_descriptor softseg;
868 code = frame->tf_err;
869 type = frame->tf_trapno;
870 sdtossd(&gdt[NGDT * PCPU_GET(cpuid) + IDXSEL(frame->tf_cs & 0xffff)],
873 printf("\n\nFatal trap %d: %s while in %s mode\n", type,
874 type < nitems(trap_msg) ? trap_msg[type] : UNKNOWN,
875 TRAPF_USERMODE(frame) ? "user" : "kernel");
877 /* two separate prints in case of a trap on an unmapped page */
878 printf("cpuid = %d; ", PCPU_GET(cpuid));
879 printf("apic id = %02x\n", PCPU_GET(apic_id));
881 if (type == T_PAGEFLT) {
882 printf("fault virtual address = 0x%lx\n", eva);
883 printf("fault code = %s %s %s%s%s, %s\n",
884 code & PGEX_U ? "user" : "supervisor",
885 code & PGEX_W ? "write" : "read",
886 code & PGEX_I ? "instruction" : "data",
887 code & PGEX_PK ? " prot key" : "",
888 code & PGEX_SGX ? " SGX" : "",
889 code & PGEX_RSV ? "reserved bits in PTE" :
890 code & PGEX_P ? "protection violation" : "page not present");
892 printf("instruction pointer = 0x%lx:0x%lx\n",
893 frame->tf_cs & 0xffff, frame->tf_rip);
894 ss = frame->tf_ss & 0xffff;
895 printf("stack pointer = 0x%x:0x%lx\n", ss, frame->tf_rsp);
896 printf("frame pointer = 0x%x:0x%lx\n", ss, frame->tf_rbp);
897 printf("code segment = base 0x%lx, limit 0x%lx, type 0x%x\n",
898 softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
899 printf(" = DPL %d, pres %d, long %d, def32 %d, gran %d\n",
900 softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
902 printf("processor eflags = ");
903 if (frame->tf_rflags & PSL_T)
904 printf("trace trap, ");
905 if (frame->tf_rflags & PSL_I)
906 printf("interrupt enabled, ");
907 if (frame->tf_rflags & PSL_NT)
908 printf("nested task, ");
909 if (frame->tf_rflags & PSL_RF)
911 printf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
912 printf("current process = %d (%s)\n",
913 curproc->p_pid, curthread->td_name);
916 if (debugger_on_trap) {
917 kdb_why = KDB_WHY_TRAP;
918 handled = kdb_trap(type, 0, frame);
919 kdb_why = KDB_WHY_UNSET;
924 printf("trap number = %d\n", type);
925 panic("%s", type < nitems(trap_msg) ? trap_msg[type] :
926 "unknown/reserved trap");
931 * Invoke a userspace DTrace hook. The hook pointer is cleared when no
932 * userspace probes are enabled, so we must synchronize with DTrace to ensure
933 * that a trapping thread is able to call the hook before it is cleared.
936 trap_user_dtrace(struct trapframe *frame, int (**hookp)(struct trapframe *))
938 int (*hook)(struct trapframe *);
940 hook = (int (*)(struct trapframe *))atomic_load_ptr(hookp);
943 return ((hook)(frame) == 0);
949 * Double fault handler. Called when a fault occurs while writing
950 * a frame for a trap/exception onto the stack. This usually occurs
951 * when the stack overflows (such is the case with infinite recursion,
955 dblfault_handler(struct trapframe *frame)
958 if (dtrace_doubletrap_func != NULL)
959 (*dtrace_doubletrap_func)();
961 printf("\nFatal double fault\n"
962 "rip %#lx rsp %#lx rbp %#lx\n"
963 "rax %#lx rdx %#lx rbx %#lx\n"
964 "rcx %#lx rsi %#lx rdi %#lx\n"
965 "r8 %#lx r9 %#lx r10 %#lx\n"
966 "r11 %#lx r12 %#lx r13 %#lx\n"
967 "r14 %#lx r15 %#lx rflags %#lx\n"
968 "cs %#lx ss %#lx ds %#hx es %#hx fs %#hx gs %#hx\n"
969 "fsbase %#lx gsbase %#lx kgsbase %#lx\n",
970 frame->tf_rip, frame->tf_rsp, frame->tf_rbp,
971 frame->tf_rax, frame->tf_rdx, frame->tf_rbx,
972 frame->tf_rcx, frame->tf_rdi, frame->tf_rsi,
973 frame->tf_r8, frame->tf_r9, frame->tf_r10,
974 frame->tf_r11, frame->tf_r12, frame->tf_r13,
975 frame->tf_r14, frame->tf_r15, frame->tf_rflags,
976 frame->tf_cs, frame->tf_ss, frame->tf_ds, frame->tf_es,
977 frame->tf_fs, frame->tf_gs,
978 rdmsr(MSR_FSBASE), rdmsr(MSR_GSBASE), rdmsr(MSR_KGSBASE));
980 /* two separate prints in case of a trap on an unmapped page */
981 printf("cpuid = %d; ", PCPU_GET(cpuid));
982 printf("apic id = %02x\n", PCPU_GET(apic_id));
984 panic("double fault");
987 static int __noinline
988 cpu_fetch_syscall_args_fallback(struct thread *td, struct syscall_args *sa)
991 struct trapframe *frame;
994 int reg, regcnt, error;
997 frame = td->td_frame;
1001 sa->code = frame->tf_rax;
1003 if (sa->code == SYS_syscall || sa->code == SYS___syscall) {
1004 sa->code = frame->tf_rdi;
1009 if (sa->code >= p->p_sysent->sv_size)
1010 sa->callp = &p->p_sysent->sv_table[0];
1012 sa->callp = &p->p_sysent->sv_table[sa->code];
1014 sa->narg = sa->callp->sy_narg;
1015 KASSERT(sa->narg <= nitems(sa->args), ("Too many syscall arguments!"));
1016 argp = &frame->tf_rdi;
1018 memcpy(sa->args, argp, sizeof(sa->args[0]) * NARGREGS);
1019 if (sa->narg > regcnt) {
1020 params = (caddr_t)frame->tf_rsp + sizeof(register_t);
1021 error = copyin(params, &sa->args[regcnt],
1022 (sa->narg - regcnt) * sizeof(sa->args[0]));
1023 if (__predict_false(error != 0))
1027 td->td_retval[0] = 0;
1028 td->td_retval[1] = frame->tf_rdx;
1034 cpu_fetch_syscall_args(struct thread *td)
1037 struct trapframe *frame;
1038 struct syscall_args *sa;
1041 frame = td->td_frame;
1044 sa->code = frame->tf_rax;
1046 if (__predict_false(sa->code == SYS_syscall ||
1047 sa->code == SYS___syscall ||
1048 sa->code >= p->p_sysent->sv_size))
1049 return (cpu_fetch_syscall_args_fallback(td, sa));
1051 sa->callp = &p->p_sysent->sv_table[sa->code];
1052 sa->narg = sa->callp->sy_narg;
1053 KASSERT(sa->narg <= nitems(sa->args), ("Too many syscall arguments!"));
1055 if (__predict_false(sa->narg > NARGREGS))
1056 return (cpu_fetch_syscall_args_fallback(td, sa));
1058 memcpy(sa->args, &frame->tf_rdi, sizeof(sa->args[0]) * NARGREGS);
1060 td->td_retval[0] = 0;
1061 td->td_retval[1] = frame->tf_rdx;
1066 #include "../../kern/subr_syscall.c"
1068 static void (*syscall_ret_l1d_flush)(void);
1069 int syscall_ret_l1d_flush_mode;
1075 wrmsr(MSR_IA32_FLUSH_CMD, IA32_FLUSH_CMD_L1D);
1078 static void __inline
1079 amd64_syscall_ret_flush_l1d_inline(int error)
1083 if (error != 0 && error != EEXIST && error != EAGAIN &&
1084 error != EXDEV && error != ENOENT && error != ENOTCONN &&
1085 error != EINPROGRESS) {
1086 p = syscall_ret_l1d_flush;
1093 amd64_syscall_ret_flush_l1d(int error)
1096 amd64_syscall_ret_flush_l1d_inline(error);
1100 amd64_syscall_ret_flush_l1d_recalc(void)
1104 l1d_hw = (cpu_stdext_feature3 & CPUID_STDEXT3_L1D_FLUSH) != 0;
1106 switch (syscall_ret_l1d_flush_mode) {
1108 syscall_ret_l1d_flush = NULL;
1111 syscall_ret_l1d_flush = l1d_hw ? flush_l1d_hw :
1115 syscall_ret_l1d_flush = l1d_hw ? flush_l1d_hw : NULL;
1118 syscall_ret_l1d_flush = flush_l1d_sw_abi;
1121 syscall_ret_l1d_flush_mode = 1;
1127 machdep_syscall_ret_flush_l1d(SYSCTL_HANDLER_ARGS)
1131 val = syscall_ret_l1d_flush_mode;
1132 error = sysctl_handle_int(oidp, &val, 0, req);
1133 if (error != 0 || req->newptr == NULL)
1135 syscall_ret_l1d_flush_mode = val;
1136 amd64_syscall_ret_flush_l1d_recalc();
1139 SYSCTL_PROC(_machdep, OID_AUTO, syscall_ret_flush_l1d, CTLTYPE_INT |
1140 CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
1141 machdep_syscall_ret_flush_l1d, "I",
1142 "Flush L1D on syscall return with error (0 - off, 1 - on, "
1143 "2 - use hw only, 3 - use sw only");
1147 * System call handler for native binaries. The trap frame is already
1148 * set up by the assembler trampoline and a pointer to it is saved in
1152 amd64_syscall(struct thread *td, int traced)
1157 if (!TRAPF_USERMODE(td->td_frame)) {
1167 if (__predict_false(traced)) {
1168 td->td_frame->tf_rflags &= ~PSL_T;
1169 ksiginfo_init_trap(&ksi);
1170 ksi.ksi_signo = SIGTRAP;
1171 ksi.ksi_code = TRAP_TRACE;
1172 ksi.ksi_addr = (void *)td->td_frame->tf_rip;
1173 trapsignal(td, &ksi);
1176 KASSERT(PCB_USER_FPU(td->td_pcb),
1177 ("System call %s returning with kernel FPU ctx leaked",
1178 syscallname(td->td_proc, td->td_sa.code)));
1179 KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td),
1180 ("System call %s returning with mangled pcb_save",
1181 syscallname(td->td_proc, td->td_sa.code)));
1182 KASSERT(pmap_not_in_di(),
1183 ("System call %s returning with leaked invl_gen %lu",
1184 syscallname(td->td_proc, td->td_sa.code),
1185 td->td_md.md_invl_gen.gen));
1190 * If the user-supplied value of %rip is not a canonical
1191 * address, then some CPUs will trigger a ring 0 #GP during
1192 * the sysret instruction. However, the fault handler would
1193 * execute in ring 0 with the user's %gs and %rsp which would
1194 * not be safe. Instead, use the full return path which
1195 * catches the problem safely.
1197 if (__predict_false(td->td_frame->tf_rip >= VM_MAXUSER_ADDRESS))
1198 set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
1200 amd64_syscall_ret_flush_l1d_inline(td->td_errno);