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/pioctl.h>
61 #include <sys/ptrace.h>
63 #include <sys/kernel.h>
66 #include <sys/mutex.h>
67 #include <sys/resourcevar.h>
68 #include <sys/signalvar.h>
69 #include <sys/syscall.h>
70 #include <sys/sysctl.h>
71 #include <sys/sysent.h>
73 #include <sys/vmmeter.h>
75 #include <sys/pmckern.h>
76 PMC_SOFT_DEFINE( , , page_fault, all);
77 PMC_SOFT_DEFINE( , , page_fault, read);
78 PMC_SOFT_DEFINE( , , page_fault, write);
82 #include <vm/vm_param.h>
84 #include <vm/vm_kern.h>
85 #include <vm/vm_map.h>
86 #include <vm/vm_page.h>
87 #include <vm/vm_extern.h>
89 #include <machine/cpu.h>
90 #include <machine/intr_machdep.h>
92 #include <machine/md_var.h>
93 #include <machine/pcb.h>
95 #include <machine/smp.h>
97 #include <machine/stack.h>
98 #include <machine/trap.h>
99 #include <machine/tss.h>
102 #include <sys/dtrace_bsd.h>
105 extern inthand_t IDTVEC(bpt), IDTVEC(bpt_pti), IDTVEC(dbg),
106 IDTVEC(fast_syscall), IDTVEC(fast_syscall_pti), IDTVEC(fast_syscall32),
107 IDTVEC(int0x80_syscall_pti), IDTVEC(int0x80_syscall);
109 void __noinline trap(struct trapframe *frame);
110 void trap_check(struct trapframe *frame);
111 void dblfault_handler(struct trapframe *frame);
113 static int trap_pfault(struct trapframe *, bool, int *, int *);
114 static void trap_fatal(struct trapframe *, vm_offset_t);
116 static bool trap_user_dtrace(struct trapframe *,
117 int (**hook)(struct trapframe *));
120 static const char UNKNOWN[] = "unknown";
121 static const char *const trap_msg[] = {
122 [0] = UNKNOWN, /* unused */
123 [T_PRIVINFLT] = "privileged instruction fault",
124 [2] = UNKNOWN, /* unused */
125 [T_BPTFLT] = "breakpoint instruction fault",
126 [4] = UNKNOWN, /* unused */
127 [5] = UNKNOWN, /* unused */
128 [T_ARITHTRAP] = "arithmetic trap",
129 [7] = UNKNOWN, /* unused */
130 [8] = UNKNOWN, /* unused */
131 [T_PROTFLT] = "general protection fault",
132 [T_TRCTRAP] = "debug exception",
133 [11] = UNKNOWN, /* unused */
134 [T_PAGEFLT] = "page fault",
135 [13] = UNKNOWN, /* unused */
136 [T_ALIGNFLT] = "alignment fault",
137 [15] = UNKNOWN, /* unused */
138 [16] = UNKNOWN, /* unused */
139 [17] = UNKNOWN, /* unused */
140 [T_DIVIDE] = "integer divide fault",
141 [T_NMI] = "non-maskable interrupt trap",
142 [T_OFLOW] = "overflow trap",
143 [T_BOUND] = "FPU bounds check fault",
144 [T_DNA] = "FPU device not available",
145 [T_DOUBLEFLT] = "double fault",
146 [T_FPOPFLT] = "FPU operand fetch fault",
147 [T_TSSFLT] = "invalid TSS fault",
148 [T_SEGNPFLT] = "segment not present fault",
149 [T_STKFLT] = "stack fault",
150 [T_MCHK] = "machine check trap",
151 [T_XMMFLT] = "SIMD floating-point exception",
152 [T_RESERVED] = "reserved (unknown) fault",
153 [31] = UNKNOWN, /* reserved */
154 [T_DTRACE_RET] = "DTrace pid return trap",
157 static int uprintf_signal;
158 SYSCTL_INT(_machdep, OID_AUTO, uprintf_signal, CTLFLAG_RWTUN,
160 "Print debugging information on trap signal to ctty");
163 * Control L1D flush on return from NMI.
165 * Tunable can be set to the following values:
166 * 0 - only enable flush on return from NMI if required by vmm.ko (default)
167 * >1 - always flush on return from NMI.
169 * Post-boot, the sysctl indicates if flushing is currently enabled.
171 int nmi_flush_l1d_sw;
172 SYSCTL_INT(_machdep, OID_AUTO, nmi_flush_l1d_sw, CTLFLAG_RWTUN,
173 &nmi_flush_l1d_sw, 0,
174 "Flush L1 Data Cache on NMI exit, software bhyve L1TF mitigation assist");
177 * Exception, fault, and trap interface to the FreeBSD kernel.
178 * This common code is called from assembly language IDT gate entry
179 * routines that prepare a suitable stack frame, and restore this
180 * frame after the exception has been processed.
184 trap(struct trapframe *frame)
189 register_t addr, dr6;
190 int pf, signo, ucode;
198 type = frame->tf_trapno;
201 /* Handler for NMI IPIs used for stopping CPUs. */
202 if (type == T_NMI && ipi_nmi_handler() == 0)
213 if (type == T_RESERVED) {
214 trap_fatal(frame, 0);
221 * CPU PMCs interrupt using an NMI. If the PMC module is
222 * active, pass the 'rip' value to the PMC module's interrupt
223 * handler. A non-zero return value from the handler means that
224 * the NMI was consumed by it and we can return immediately.
226 if (pmc_intr != NULL &&
227 (*pmc_intr)(frame) != 0)
232 if ((frame->tf_rflags & PSL_I) == 0) {
234 * Buggy application or kernel code has disabled
235 * interrupts and then trapped. Enabling interrupts
236 * now is wrong, but it is better than running with
237 * interrupts disabled until they are accidentally
240 if (TRAPF_USERMODE(frame))
242 "pid %ld (%s): trap %d with interrupts disabled\n",
243 (long)curproc->p_pid, curthread->td_name, type);
244 else if (type != T_NMI && type != T_BPTFLT &&
247 * XXX not quite right, since this may be for a
248 * multiple fault in user mode.
250 printf("kernel trap %d with interrupts disabled\n",
254 * We shouldn't enable interrupts while holding a
257 if (td->td_md.md_spinlock_count == 0)
262 if (TRAPF_USERMODE(frame)) {
266 td->td_frame = frame;
267 addr = frame->tf_rip;
268 if (td->td_cowgen != p->p_cowgen)
269 thread_cow_update(td);
272 case T_PRIVINFLT: /* privileged instruction fault */
277 case T_BPTFLT: /* bpt instruction fault */
279 if (trap_user_dtrace(frame, &dtrace_pid_probe_ptr))
288 case T_TRCTRAP: /* debug exception */
293 if ((dr6 & DBREG_DR6_BS) != 0) {
294 PROC_LOCK(td->td_proc);
295 if ((td->td_dbgflags & TDB_STEP) != 0) {
296 td->td_frame->tf_rflags &= ~PSL_T;
297 td->td_dbgflags &= ~TDB_STEP;
299 PROC_UNLOCK(td->td_proc);
303 case T_ARITHTRAP: /* arithmetic trap */
304 ucode = fputrap_x87();
310 case T_PROTFLT: /* general protection fault */
314 case T_STKFLT: /* stack fault */
315 case T_SEGNPFLT: /* segment not present fault */
319 case T_TSSFLT: /* invalid TSS fault */
327 case T_DOUBLEFLT: /* double fault */
333 case T_PAGEFLT: /* page fault */
335 * Can emulator handle this trap?
337 if (*p->p_sysent->sv_trap != NULL &&
338 (*p->p_sysent->sv_trap)(td) == 0)
341 pf = trap_pfault(frame, true, &signo, &ucode);
346 addr = frame->tf_addr;
349 case T_DIVIDE: /* integer divide fault */
356 nmi_handle_intr(type, frame);
360 case T_OFLOW: /* integer overflow fault */
365 case T_BOUND: /* bounds check fault */
371 /* transparent fault (due to context switch "late") */
372 KASSERT(PCB_USER_FPU(td->td_pcb),
373 ("kernel FPU ctx has leaked"));
377 case T_FPOPFLT: /* FPU operand fetch fault */
382 case T_XMMFLT: /* SIMD floating-point exception */
383 ucode = fputrap_sse();
390 (void)trap_user_dtrace(frame, &dtrace_return_probe_ptr);
397 KASSERT(cold || td->td_ucred != NULL,
398 ("kernel trap doesn't have ucred"));
400 case T_PAGEFLT: /* page fault */
401 (void)trap_pfault(frame, false, NULL, NULL);
405 if (PCB_USER_FPU(td->td_pcb))
406 panic("Unregistered use of FPU in kernel");
410 case T_ARITHTRAP: /* arithmetic trap */
411 case T_XMMFLT: /* SIMD floating-point exception */
412 case T_FPOPFLT: /* FPU operand fetch fault */
414 * For now, supporting kernel handler
415 * registration for FPU traps is overkill.
417 trap_fatal(frame, 0);
420 case T_STKFLT: /* stack fault */
421 case T_PROTFLT: /* general protection fault */
422 case T_SEGNPFLT: /* segment not present fault */
423 if (td->td_intr_nesting_level != 0)
427 * Invalid segment selectors and out of bounds
428 * %rip's and %rsp's can be set up in user mode.
429 * This causes a fault in kernel mode when the
430 * kernel tries to return to user mode. We want
431 * to get this fault so that we can fix the
432 * problem here and not have to check all the
433 * selectors and pointers when the user changes
436 * In case of PTI, the IRETQ faulted while the
437 * kernel used the pti stack, and exception
438 * frame records %rsp value pointing to that
439 * stack. If we return normally to
440 * doreti_iret_fault, the trapframe is
441 * reconstructed on pti stack, and calltrap()
442 * called on it as well. Due to the very
443 * limited pti stack size, kernel does not
444 * survive for too long. Switch to the normal
445 * thread stack for the trap handling.
447 * Magic '5' is the number of qwords occupied by
448 * the hardware trap frame.
450 if (frame->tf_rip == (long)doreti_iret) {
451 frame->tf_rip = (long)doreti_iret_fault;
452 if ((PCPU_GET(curpmap)->pm_ucr3 !=
454 (frame->tf_rsp == (uintptr_t)PCPU_GET(
455 pti_rsp0) - 5 * sizeof(register_t))) {
456 frame->tf_rsp = PCPU_GET(rsp0) - 5 *
461 if (frame->tf_rip == (long)ld_ds) {
462 frame->tf_rip = (long)ds_load_fault;
465 if (frame->tf_rip == (long)ld_es) {
466 frame->tf_rip = (long)es_load_fault;
469 if (frame->tf_rip == (long)ld_fs) {
470 frame->tf_rip = (long)fs_load_fault;
473 if (frame->tf_rip == (long)ld_gs) {
474 frame->tf_rip = (long)gs_load_fault;
477 if (frame->tf_rip == (long)ld_gsbase) {
478 frame->tf_rip = (long)gsbase_load_fault;
481 if (frame->tf_rip == (long)ld_fsbase) {
482 frame->tf_rip = (long)fsbase_load_fault;
485 if (curpcb->pcb_onfault != NULL) {
486 frame->tf_rip = (long)curpcb->pcb_onfault;
493 * PSL_NT can be set in user mode and isn't cleared
494 * automatically when the kernel is entered. This
495 * causes a TSS fault when the kernel attempts to
496 * `iret' because the TSS link is uninitialized. We
497 * want to get this fault so that we can fix the
498 * problem here and not every time the kernel is
501 if (frame->tf_rflags & PSL_NT) {
502 frame->tf_rflags &= ~PSL_NT;
507 case T_TRCTRAP: /* debug exception */
508 /* Clear any pending debug events. */
513 * Ignore debug register exceptions due to
514 * accesses in the user's address space, which
515 * can happen under several conditions such as
516 * if a user sets a watchpoint on a buffer and
517 * then passes that buffer to a system call.
518 * We still want to get TRCTRAPS for addresses
519 * in kernel space because that is useful when
520 * debugging the kernel.
522 if (user_dbreg_trap(dr6))
526 * Malicious user code can configure a debug
527 * register watchpoint to trap on data access
528 * to the top of stack and then execute 'pop
529 * %ss; int 3'. Due to exception deferral for
530 * 'pop %ss', the CPU will not interrupt 'int
531 * 3' to raise the DB# exception for the debug
532 * register but will postpone the DB# until
533 * execution of the first instruction of the
534 * BP# handler (in kernel mode). Normally the
535 * previous check would ignore DB# exceptions
536 * for watchpoints on user addresses raised in
537 * kernel mode. However, some CPU errata
538 * include cases where DB# exceptions do not
539 * properly set bits in %dr6, e.g. Haswell
540 * HSD23 and Skylake-X SKZ24.
542 * A deferred DB# can also be raised on the
543 * first instructions of system call entry
544 * points or single-step traps via similar use
545 * of 'pop %ss' or 'mov xxx, %ss'.
549 (uintptr_t)IDTVEC(fast_syscall_pti) ||
550 #ifdef COMPAT_FREEBSD32
552 (uintptr_t)IDTVEC(int0x80_syscall_pti) ||
554 frame->tf_rip == (uintptr_t)IDTVEC(bpt_pti))
558 (uintptr_t)IDTVEC(fast_syscall) ||
559 #ifdef COMPAT_FREEBSD32
561 (uintptr_t)IDTVEC(int0x80_syscall) ||
563 frame->tf_rip == (uintptr_t)IDTVEC(bpt))
566 if (frame->tf_rip == (uintptr_t)IDTVEC(dbg) ||
567 /* Needed for AMD. */
568 frame->tf_rip == (uintptr_t)IDTVEC(fast_syscall32))
571 * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
575 * If KDB is enabled, let it handle the debugger trap.
576 * Otherwise, debugger traps "can't happen".
579 if (kdb_trap(type, dr6, frame))
586 nmi_handle_intr(type, frame);
591 trap_fatal(frame, 0);
595 /* Translate fault for emulators (e.g. Linux) */
596 if (*p->p_sysent->sv_transtrap != NULL)
597 signo = (*p->p_sysent->sv_transtrap)(signo, type);
599 ksiginfo_init_trap(&ksi);
600 ksi.ksi_signo = signo;
601 ksi.ksi_code = ucode;
602 ksi.ksi_trapno = type;
603 ksi.ksi_addr = (void *)addr;
604 if (uprintf_signal) {
605 uprintf("pid %d comm %s: signal %d err %lx code %d type %d "
606 "addr 0x%lx rsp 0x%lx rip 0x%lx "
607 "<%02x %02x %02x %02x %02x %02x %02x %02x>\n",
608 p->p_pid, p->p_comm, signo, frame->tf_err, ucode, type,
609 addr, frame->tf_rsp, frame->tf_rip,
610 fubyte((void *)(frame->tf_rip + 0)),
611 fubyte((void *)(frame->tf_rip + 1)),
612 fubyte((void *)(frame->tf_rip + 2)),
613 fubyte((void *)(frame->tf_rip + 3)),
614 fubyte((void *)(frame->tf_rip + 4)),
615 fubyte((void *)(frame->tf_rip + 5)),
616 fubyte((void *)(frame->tf_rip + 6)),
617 fubyte((void *)(frame->tf_rip + 7)));
619 KASSERT((read_rflags() & PSL_I) != 0, ("interrupts disabled"));
620 trapsignal(td, &ksi);
624 KASSERT(PCB_USER_FPU(td->td_pcb),
625 ("Return from trap with kernel FPU ctx leaked"));
629 * Ensure that we ignore any DTrace-induced faults. This function cannot
630 * be instrumented, so it cannot generate such faults itself.
633 trap_check(struct trapframe *frame)
637 if (dtrace_trap_func != NULL &&
638 (*dtrace_trap_func)(frame, frame->tf_trapno) != 0)
645 trap_is_smap(struct trapframe *frame)
649 * A page fault on a userspace address is classified as
651 * - SMAP is supported;
652 * - kernel mode accessed present data page;
653 * - rflags.AC was cleared.
654 * Kernel must never access user space with rflags.AC cleared
655 * if SMAP is enabled.
657 return ((cpu_stdext_feature & CPUID_STDEXT_SMAP) != 0 &&
658 (frame->tf_err & (PGEX_P | PGEX_U | PGEX_I | PGEX_RSV)) ==
659 PGEX_P && (frame->tf_rflags & PSL_AC) == 0);
663 trap_is_pti(struct trapframe *frame)
666 return (PCPU_GET(curpmap)->pm_ucr3 != PMAP_NO_CR3 &&
667 pg_nx != 0 && (frame->tf_err & (PGEX_P | PGEX_W |
668 PGEX_U | PGEX_I)) == (PGEX_P | PGEX_U | PGEX_I) &&
669 (curpcb->pcb_saved_ucr3 & ~CR3_PCID_MASK) ==
670 (PCPU_GET(curpmap)->pm_cr3 & ~CR3_PCID_MASK));
674 * Handle all details of a page fault.
676 * -1 if this fault was fatal, typically from kernel mode
677 * (cannot happen, but we need to return something).
678 * 0 if this fault was handled by updating either the user or kernel
679 * page table, execution can continue.
680 * 1 if this fault was from usermode and it was not handled, a synchronous
681 * signal should be delivered to the thread. *signo returns the signal
682 * number, *ucode gives si_code.
685 trap_pfault(struct trapframe *frame, bool usermode, int *signo, int *ucode)
694 MPASS(!usermode || (signo != NULL && ucode != NULL));
698 eva = frame->tf_addr;
700 if (__predict_false((td->td_pflags & TDP_NOFAULTING) != 0)) {
702 * Due to both processor errata and lazy TLB invalidation when
703 * access restrictions are removed from virtual pages, memory
704 * accesses that are allowed by the physical mapping layer may
705 * nonetheless cause one spurious page fault per virtual page.
706 * When the thread is executing a "no faulting" section that
707 * is bracketed by vm_fault_{disable,enable}_pagefaults(),
708 * every page fault is treated as a spurious page fault,
709 * unless it accesses the same virtual address as the most
710 * recent page fault within the same "no faulting" section.
712 if (td->td_md.md_spurflt_addr != eva ||
713 (td->td_pflags & TDP_RESETSPUR) != 0) {
715 * Do nothing to the TLB. A stale TLB entry is
716 * flushed automatically by a page fault.
718 td->td_md.md_spurflt_addr = eva;
719 td->td_pflags &= ~TDP_RESETSPUR;
724 * If we get a page fault while in a critical section, then
725 * it is most likely a fatal kernel page fault. The kernel
726 * is already going to panic trying to get a sleep lock to
727 * do the VM lookup, so just consider it a fatal trap so the
728 * kernel can print out a useful trap message and even get
731 * If we get a page fault while holding a non-sleepable
732 * lock, then it is most likely a fatal kernel page fault.
733 * If WITNESS is enabled, then it's going to whine about
734 * bogus LORs with various VM locks, so just skip to the
735 * fatal trap handling directly.
737 if (td->td_critnest != 0 ||
738 WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
739 "Kernel page fault") != 0) {
740 trap_fatal(frame, eva);
744 if (eva >= VM_MIN_KERNEL_ADDRESS) {
746 * Don't allow user-mode faults in kernel address space.
750 *ucode = SEGV_MAPERR;
756 map = &p->p_vmspace->vm_map;
759 * When accessing a usermode address, kernel must be
760 * ready to accept the page fault, and provide a
761 * handling routine. Since accessing the address
762 * without the handler is a bug, do not try to handle
763 * it normally, and panic immediately.
765 * If SMAP is enabled, filter SMAP faults also,
766 * because illegal access might occur to the mapped
767 * user address, causing infinite loop.
769 if (!usermode && (td->td_intr_nesting_level != 0 ||
770 trap_is_smap(frame) || curpcb->pcb_onfault == NULL)) {
771 trap_fatal(frame, eva);
777 * If the trap was caused by errant bits in the PTE then panic.
779 if (frame->tf_err & PGEX_RSV) {
780 trap_fatal(frame, eva);
785 * User-mode protection key violation (PKU). May happen
786 * either from usermode or from kernel if copyin accessed
787 * key-protected mapping.
789 if ((frame->tf_err & PGEX_PK) != 0) {
790 if (eva > VM_MAXUSER_ADDRESS) {
791 trap_fatal(frame, eva);
796 *ucode = SEGV_PKUERR;
803 * If nx protection of the usermode portion of kernel page
804 * tables caused trap, panic.
806 if (usermode && trap_is_pti(frame))
807 panic("PTI: pid %d comm %s tf_err %#lx", p->p_pid,
808 p->p_comm, frame->tf_err);
811 * PGEX_I is defined only if the execute disable bit capability is
812 * supported and enabled.
814 if (frame->tf_err & PGEX_W)
815 ftype = VM_PROT_WRITE;
816 else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
817 ftype = VM_PROT_EXECUTE;
819 ftype = VM_PROT_READ;
821 /* Fault in the page. */
822 rv = vm_fault_trap(map, eva, ftype, VM_FAULT_NORMAL, signo, ucode);
823 if (rv == KERN_SUCCESS) {
825 if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
826 PMC_SOFT_CALL_TF( , , page_fault, all, frame);
827 if (ftype == VM_PROT_READ)
828 PMC_SOFT_CALL_TF( , , page_fault, read,
831 PMC_SOFT_CALL_TF( , , page_fault, write,
841 if (td->td_intr_nesting_level == 0 &&
842 curpcb->pcb_onfault != NULL) {
843 frame->tf_rip = (long)curpcb->pcb_onfault;
846 trap_fatal(frame, eva);
851 trap_fatal(frame, eva)
852 struct trapframe *frame;
857 struct soft_segment_descriptor softseg;
858 struct user_segment_descriptor *gdt;
863 code = frame->tf_err;
864 type = frame->tf_trapno;
865 gdt = *PCPU_PTR(gdt);
866 sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)], &softseg);
868 printf("\n\nFatal trap %d: %s while in %s mode\n", type,
869 type < nitems(trap_msg) ? trap_msg[type] : UNKNOWN,
870 TRAPF_USERMODE(frame) ? "user" : "kernel");
872 /* two separate prints in case of a trap on an unmapped page */
873 printf("cpuid = %d; ", PCPU_GET(cpuid));
874 printf("apic id = %02x\n", PCPU_GET(apic_id));
876 if (type == T_PAGEFLT) {
877 printf("fault virtual address = 0x%lx\n", eva);
878 printf("fault code = %s %s %s%s%s, %s\n",
879 code & PGEX_U ? "user" : "supervisor",
880 code & PGEX_W ? "write" : "read",
881 code & PGEX_I ? "instruction" : "data",
882 code & PGEX_PK ? " prot key" : "",
883 code & PGEX_SGX ? " SGX" : "",
884 code & PGEX_RSV ? "reserved bits in PTE" :
885 code & PGEX_P ? "protection violation" : "page not present");
887 printf("instruction pointer = 0x%lx:0x%lx\n",
888 frame->tf_cs & 0xffff, frame->tf_rip);
889 ss = frame->tf_ss & 0xffff;
890 printf("stack pointer = 0x%x:0x%lx\n", ss, frame->tf_rsp);
891 printf("frame pointer = 0x%x:0x%lx\n", ss, frame->tf_rbp);
892 printf("code segment = base 0x%lx, limit 0x%lx, type 0x%x\n",
893 softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
894 printf(" = DPL %d, pres %d, long %d, def32 %d, gran %d\n",
895 softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
897 printf("processor eflags = ");
898 if (frame->tf_rflags & PSL_T)
899 printf("trace trap, ");
900 if (frame->tf_rflags & PSL_I)
901 printf("interrupt enabled, ");
902 if (frame->tf_rflags & PSL_NT)
903 printf("nested task, ");
904 if (frame->tf_rflags & PSL_RF)
906 printf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
907 printf("current process = %d (%s)\n",
908 curproc->p_pid, curthread->td_name);
911 if (debugger_on_trap) {
912 kdb_why = KDB_WHY_TRAP;
913 handled = kdb_trap(type, 0, frame);
914 kdb_why = KDB_WHY_UNSET;
919 printf("trap number = %d\n", type);
920 panic("%s", type < nitems(trap_msg) ? trap_msg[type] :
921 "unknown/reserved trap");
926 * Invoke a userspace DTrace hook. The hook pointer is cleared when no
927 * userspace probes are enabled, so we must synchronize with DTrace to ensure
928 * that a trapping thread is able to call the hook before it is cleared.
931 trap_user_dtrace(struct trapframe *frame, int (**hookp)(struct trapframe *))
933 int (*hook)(struct trapframe *);
935 hook = (int (*)(struct trapframe *))atomic_load_ptr(hookp);
938 return ((hook)(frame) == 0);
944 * Double fault handler. Called when a fault occurs while writing
945 * a frame for a trap/exception onto the stack. This usually occurs
946 * when the stack overflows (such is the case with infinite recursion,
950 dblfault_handler(struct trapframe *frame)
953 if (dtrace_doubletrap_func != NULL)
954 (*dtrace_doubletrap_func)();
956 printf("\nFatal double fault\n"
957 "rip %#lx rsp %#lx rbp %#lx\n"
958 "rax %#lx rdx %#lx rbx %#lx\n"
959 "rcx %#lx rsi %#lx rdi %#lx\n"
960 "r8 %#lx r9 %#lx r10 %#lx\n"
961 "r11 %#lx r12 %#lx r13 %#lx\n"
962 "r14 %#lx r15 %#lx rflags %#lx\n"
963 "cs %#lx ss %#lx ds %#hx es %#hx fs %#hx gs %#hx\n"
964 "fsbase %#lx gsbase %#lx kgsbase %#lx\n",
965 frame->tf_rip, frame->tf_rsp, frame->tf_rbp,
966 frame->tf_rax, frame->tf_rdx, frame->tf_rbx,
967 frame->tf_rcx, frame->tf_rdi, frame->tf_rsi,
968 frame->tf_r8, frame->tf_r9, frame->tf_r10,
969 frame->tf_r11, frame->tf_r12, frame->tf_r13,
970 frame->tf_r14, frame->tf_r15, frame->tf_rflags,
971 frame->tf_cs, frame->tf_ss, frame->tf_ds, frame->tf_es,
972 frame->tf_fs, frame->tf_gs,
973 rdmsr(MSR_FSBASE), rdmsr(MSR_GSBASE), rdmsr(MSR_KGSBASE));
975 /* two separate prints in case of a trap on an unmapped page */
976 printf("cpuid = %d; ", PCPU_GET(cpuid));
977 printf("apic id = %02x\n", PCPU_GET(apic_id));
979 panic("double fault");
982 static int __noinline
983 cpu_fetch_syscall_args_fallback(struct thread *td, struct syscall_args *sa)
986 struct trapframe *frame;
989 int reg, regcnt, error;
992 frame = td->td_frame;
996 sa->code = frame->tf_rax;
998 if (sa->code == SYS_syscall || sa->code == SYS___syscall) {
999 sa->code = frame->tf_rdi;
1004 if (sa->code >= p->p_sysent->sv_size)
1005 sa->callp = &p->p_sysent->sv_table[0];
1007 sa->callp = &p->p_sysent->sv_table[sa->code];
1009 sa->narg = sa->callp->sy_narg;
1010 KASSERT(sa->narg <= nitems(sa->args), ("Too many syscall arguments!"));
1011 argp = &frame->tf_rdi;
1013 memcpy(sa->args, argp, sizeof(sa->args[0]) * NARGREGS);
1014 if (sa->narg > regcnt) {
1015 params = (caddr_t)frame->tf_rsp + sizeof(register_t);
1016 error = copyin(params, &sa->args[regcnt],
1017 (sa->narg - regcnt) * sizeof(sa->args[0]));
1018 if (__predict_false(error != 0))
1022 td->td_retval[0] = 0;
1023 td->td_retval[1] = frame->tf_rdx;
1029 cpu_fetch_syscall_args(struct thread *td)
1032 struct trapframe *frame;
1033 struct syscall_args *sa;
1036 frame = td->td_frame;
1039 sa->code = frame->tf_rax;
1041 if (__predict_false(sa->code == SYS_syscall ||
1042 sa->code == SYS___syscall ||
1043 sa->code >= p->p_sysent->sv_size))
1044 return (cpu_fetch_syscall_args_fallback(td, sa));
1046 sa->callp = &p->p_sysent->sv_table[sa->code];
1047 sa->narg = sa->callp->sy_narg;
1048 KASSERT(sa->narg <= nitems(sa->args), ("Too many syscall arguments!"));
1050 if (__predict_false(sa->narg > NARGREGS))
1051 return (cpu_fetch_syscall_args_fallback(td, sa));
1053 memcpy(sa->args, &frame->tf_rdi, sizeof(sa->args[0]) * NARGREGS);
1055 td->td_retval[0] = 0;
1056 td->td_retval[1] = frame->tf_rdx;
1061 #include "../../kern/subr_syscall.c"
1063 static void (*syscall_ret_l1d_flush)(void);
1064 int syscall_ret_l1d_flush_mode;
1070 wrmsr(MSR_IA32_FLUSH_CMD, IA32_FLUSH_CMD_L1D);
1073 static void __inline
1074 amd64_syscall_ret_flush_l1d_inline(int error)
1078 if (error != 0 && error != EEXIST && error != EAGAIN &&
1079 error != EXDEV && error != ENOENT && error != ENOTCONN &&
1080 error != EINPROGRESS) {
1081 p = syscall_ret_l1d_flush;
1088 amd64_syscall_ret_flush_l1d(int error)
1091 amd64_syscall_ret_flush_l1d_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");
1142 * System call handler for native binaries. The trap frame is already
1143 * set up by the assembler trampoline and a pointer to it is saved in
1147 amd64_syscall(struct thread *td, int traced)
1152 if (!TRAPF_USERMODE(td->td_frame)) {
1162 if (__predict_false(traced)) {
1163 td->td_frame->tf_rflags &= ~PSL_T;
1164 ksiginfo_init_trap(&ksi);
1165 ksi.ksi_signo = SIGTRAP;
1166 ksi.ksi_code = TRAP_TRACE;
1167 ksi.ksi_addr = (void *)td->td_frame->tf_rip;
1168 trapsignal(td, &ksi);
1171 KASSERT(PCB_USER_FPU(td->td_pcb),
1172 ("System call %s returning with kernel FPU ctx leaked",
1173 syscallname(td->td_proc, td->td_sa.code)));
1174 KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td),
1175 ("System call %s returning with mangled pcb_save",
1176 syscallname(td->td_proc, td->td_sa.code)));
1177 KASSERT(pmap_not_in_di(),
1178 ("System call %s returning with leaked invl_gen %lu",
1179 syscallname(td->td_proc, td->td_sa.code),
1180 td->td_md.md_invl_gen.gen));
1185 * If the user-supplied value of %rip is not a canonical
1186 * address, then some CPUs will trigger a ring 0 #GP during
1187 * the sysret instruction. However, the fault handler would
1188 * execute in ring 0 with the user's %gs and %rsp which would
1189 * not be safe. Instead, use the full return path which
1190 * catches the problem safely.
1192 if (__predict_false(td->td_frame->tf_rip >= VM_MAXUSER_ADDRESS))
1193 set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
1195 amd64_syscall_ret_flush_l1d_inline(td->td_errno);