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>
59 #include <sys/systm.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 * Table of handlers for various segment load faults.
179 static const struct {
184 .faddr = (uintptr_t)ld_ds,
185 .fhandler = (uintptr_t)ds_load_fault,
188 .faddr = (uintptr_t)ld_es,
189 .fhandler = (uintptr_t)es_load_fault,
192 .faddr = (uintptr_t)ld_fs,
193 .fhandler = (uintptr_t)fs_load_fault,
196 .faddr = (uintptr_t)ld_gs,
197 .fhandler = (uintptr_t)gs_load_fault,
200 .faddr = (uintptr_t)ld_gsbase,
201 .fhandler = (uintptr_t)gsbase_load_fault
204 .faddr = (uintptr_t)ld_fsbase,
205 .fhandler = (uintptr_t)fsbase_load_fault,
210 * Exception, fault, and trap interface to the FreeBSD kernel.
211 * This common code is called from assembly language IDT gate entry
212 * routines that prepare a suitable stack frame, and restore this
213 * frame after the exception has been processed.
217 trap(struct trapframe *frame)
222 register_t addr, dr6;
224 int pf, signo, ucode;
231 kasan_mark(frame, sizeof(*frame), sizeof(*frame), 0);
234 type = frame->tf_trapno;
237 /* Handler for NMI IPIs used for stopping CPUs. */
238 if (type == T_NMI && ipi_nmi_handler() == 0)
249 if (type == T_RESERVED) {
250 trap_fatal(frame, 0);
257 * CPU PMCs interrupt using an NMI. If the PMC module is
258 * active, pass the 'rip' value to the PMC module's interrupt
259 * handler. A non-zero return value from the handler means that
260 * the NMI was consumed by it and we can return immediately.
262 if (pmc_intr != NULL &&
263 (*pmc_intr)(frame) != 0)
268 if ((frame->tf_rflags & PSL_I) == 0) {
270 * Buggy application or kernel code has disabled
271 * interrupts and then trapped. Enabling interrupts
272 * now is wrong, but it is better than running with
273 * interrupts disabled until they are accidentally
276 if (TRAPF_USERMODE(frame)) {
278 "pid %ld (%s): trap %d (%s) "
279 "with interrupts disabled\n",
280 (long)curproc->p_pid, curthread->td_name, type,
293 "kernel trap %d with interrupts disabled\n",
297 * We shouldn't enable interrupts while holding a
300 if (td->td_md.md_spinlock_count == 0)
306 if (TRAPF_USERMODE(frame)) {
310 td->td_frame = frame;
311 addr = frame->tf_rip;
312 if (td->td_cowgen != p->p_cowgen)
313 thread_cow_update(td);
316 case T_PRIVINFLT: /* privileged instruction fault */
321 case T_BPTFLT: /* bpt instruction fault */
323 if (trap_user_dtrace(frame, &dtrace_pid_probe_ptr))
332 case T_TRCTRAP: /* debug exception */
337 if ((dr6 & DBREG_DR6_BS) != 0) {
338 PROC_LOCK(td->td_proc);
339 if ((td->td_dbgflags & TDB_STEP) != 0) {
340 td->td_frame->tf_rflags &= ~PSL_T;
341 td->td_dbgflags &= ~TDB_STEP;
343 PROC_UNLOCK(td->td_proc);
347 case T_ARITHTRAP: /* arithmetic trap */
348 ucode = fputrap_x87();
354 case T_PROTFLT: /* general protection fault */
358 case T_STKFLT: /* stack fault */
359 case T_SEGNPFLT: /* segment not present fault */
363 case T_TSSFLT: /* invalid TSS fault */
371 case T_DOUBLEFLT: /* double fault */
377 case T_PAGEFLT: /* page fault */
379 * Can emulator handle this trap?
381 if (*p->p_sysent->sv_trap != NULL &&
382 (*p->p_sysent->sv_trap)(td) == 0)
385 pf = trap_pfault(frame, true, &signo, &ucode);
390 addr = frame->tf_addr;
393 case T_DIVIDE: /* integer divide fault */
399 nmi_handle_intr(type, frame);
402 case T_OFLOW: /* integer overflow fault */
407 case T_BOUND: /* bounds check fault */
413 /* transparent fault (due to context switch "late") */
414 KASSERT(PCB_USER_FPU(td->td_pcb),
415 ("kernel FPU ctx has leaked"));
419 case T_FPOPFLT: /* FPU operand fetch fault */
424 case T_XMMFLT: /* SIMD floating-point exception */
425 ucode = fputrap_sse();
432 (void)trap_user_dtrace(frame, &dtrace_return_probe_ptr);
439 KASSERT(cold || td->td_ucred != NULL,
440 ("kernel trap doesn't have ucred"));
442 case T_PAGEFLT: /* page fault */
443 (void)trap_pfault(frame, false, NULL, NULL);
447 if (PCB_USER_FPU(td->td_pcb))
448 panic("Unregistered use of FPU in kernel");
452 case T_ARITHTRAP: /* arithmetic trap */
453 case T_XMMFLT: /* SIMD floating-point exception */
454 case T_FPOPFLT: /* FPU operand fetch fault */
456 * For now, supporting kernel handler
457 * registration for FPU traps is overkill.
459 trap_fatal(frame, 0);
462 case T_STKFLT: /* stack fault */
463 case T_PROTFLT: /* general protection fault */
464 case T_SEGNPFLT: /* segment not present fault */
465 if (td->td_intr_nesting_level != 0)
469 * Invalid segment selectors and out of bounds
470 * %rip's and %rsp's can be set up in user mode.
471 * This causes a fault in kernel mode when the
472 * kernel tries to return to user mode. We want
473 * to get this fault so that we can fix the
474 * problem here and not have to check all the
475 * selectors and pointers when the user changes
478 * In case of PTI, the IRETQ faulted while the
479 * kernel used the pti stack, and exception
480 * frame records %rsp value pointing to that
481 * stack. If we return normally to
482 * doreti_iret_fault, the trapframe is
483 * reconstructed on pti stack, and calltrap()
484 * called on it as well. Due to the very
485 * limited pti stack size, kernel does not
486 * survive for too long. Switch to the normal
487 * thread stack for the trap handling.
489 * Magic '5' is the number of qwords occupied by
490 * the hardware trap frame.
492 if (frame->tf_rip == (long)doreti_iret) {
493 KASSERT((read_rflags() & PSL_I) == 0,
494 ("interrupts enabled"));
495 frame->tf_rip = (long)doreti_iret_fault;
496 if ((PCPU_GET(curpmap)->pm_ucr3 !=
498 (frame->tf_rsp == (uintptr_t)PCPU_GET(
499 pti_rsp0) - 5 * sizeof(register_t))) {
500 frame->tf_rsp = PCPU_GET(rsp0) - 5 *
506 for (i = 0; i < nitems(sfhandlers); i++) {
507 if (frame->tf_rip == sfhandlers[i].faddr) {
508 KASSERT((read_rflags() & PSL_I) == 0,
509 ("interrupts enabled"));
510 frame->tf_rip = sfhandlers[i].fhandler;
515 if (curpcb->pcb_onfault != NULL) {
516 frame->tf_rip = (long)curpcb->pcb_onfault;
523 * PSL_NT can be set in user mode and isn't cleared
524 * automatically when the kernel is entered. This
525 * causes a TSS fault when the kernel attempts to
526 * `iret' because the TSS link is uninitialized. We
527 * want to get this fault so that we can fix the
528 * problem here and not every time the kernel is
531 if (frame->tf_rflags & PSL_NT) {
532 frame->tf_rflags &= ~PSL_NT;
537 case T_TRCTRAP: /* debug exception */
538 /* Clear any pending debug events. */
543 * Ignore debug register exceptions due to
544 * accesses in the user's address space, which
545 * can happen under several conditions such as
546 * if a user sets a watchpoint on a buffer and
547 * then passes that buffer to a system call.
548 * We still want to get TRCTRAPS for addresses
549 * in kernel space because that is useful when
550 * debugging the kernel.
552 if (user_dbreg_trap(dr6))
556 * Malicious user code can configure a debug
557 * register watchpoint to trap on data access
558 * to the top of stack and then execute 'pop
559 * %ss; int 3'. Due to exception deferral for
560 * 'pop %ss', the CPU will not interrupt 'int
561 * 3' to raise the DB# exception for the debug
562 * register but will postpone the DB# until
563 * execution of the first instruction of the
564 * BP# handler (in kernel mode). Normally the
565 * previous check would ignore DB# exceptions
566 * for watchpoints on user addresses raised in
567 * kernel mode. However, some CPU errata
568 * include cases where DB# exceptions do not
569 * properly set bits in %dr6, e.g. Haswell
570 * HSD23 and Skylake-X SKZ24.
572 * A deferred DB# can also be raised on the
573 * first instructions of system call entry
574 * points or single-step traps via similar use
575 * of 'pop %ss' or 'mov xxx, %ss'.
579 (uintptr_t)IDTVEC(fast_syscall_pti) ||
580 #ifdef COMPAT_FREEBSD32
582 (uintptr_t)IDTVEC(int0x80_syscall_pti) ||
584 frame->tf_rip == (uintptr_t)IDTVEC(bpt_pti))
588 (uintptr_t)IDTVEC(fast_syscall) ||
589 #ifdef COMPAT_FREEBSD32
591 (uintptr_t)IDTVEC(int0x80_syscall) ||
593 frame->tf_rip == (uintptr_t)IDTVEC(bpt))
596 if (frame->tf_rip == (uintptr_t)IDTVEC(dbg) ||
597 /* Needed for AMD. */
598 frame->tf_rip == (uintptr_t)IDTVEC(fast_syscall32))
601 * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
605 * If KDB is enabled, let it handle the debugger trap.
606 * Otherwise, debugger traps "can't happen".
609 if (kdb_trap(type, dr6, frame))
615 nmi_handle_intr(type, frame);
619 trap_fatal(frame, 0);
623 ksiginfo_init_trap(&ksi);
624 ksi.ksi_signo = signo;
625 ksi.ksi_code = ucode;
626 ksi.ksi_trapno = type;
627 ksi.ksi_addr = (void *)addr;
628 if (uprintf_signal) {
629 uprintf("pid %d comm %s: signal %d err %#lx code %d type %d "
630 "addr %#lx rsp %#lx rip %#lx rax %#lx"
631 "<%02x %02x %02x %02x %02x %02x %02x %02x>\n",
632 p->p_pid, p->p_comm, signo, frame->tf_err, ucode, type,
633 addr, frame->tf_rsp, frame->tf_rip, frame->tf_rax,
634 fubyte((void *)(frame->tf_rip + 0)),
635 fubyte((void *)(frame->tf_rip + 1)),
636 fubyte((void *)(frame->tf_rip + 2)),
637 fubyte((void *)(frame->tf_rip + 3)),
638 fubyte((void *)(frame->tf_rip + 4)),
639 fubyte((void *)(frame->tf_rip + 5)),
640 fubyte((void *)(frame->tf_rip + 6)),
641 fubyte((void *)(frame->tf_rip + 7)));
643 KASSERT((read_rflags() & PSL_I) != 0, ("interrupts disabled"));
644 trapsignal(td, &ksi);
648 KASSERT(PCB_USER_FPU(td->td_pcb),
649 ("Return from trap with kernel FPU ctx leaked"));
653 * Ensure that we ignore any DTrace-induced faults. This function cannot
654 * be instrumented, so it cannot generate such faults itself.
657 trap_check(struct trapframe *frame)
661 if (dtrace_trap_func != NULL &&
662 (*dtrace_trap_func)(frame, frame->tf_trapno) != 0)
669 trap_is_smap(struct trapframe *frame)
673 * A page fault on a userspace address is classified as
675 * - SMAP is supported;
676 * - kernel mode accessed present data page;
677 * - rflags.AC was cleared.
678 * Kernel must never access user space with rflags.AC cleared
679 * if SMAP is enabled.
681 return ((cpu_stdext_feature & CPUID_STDEXT_SMAP) != 0 &&
682 (frame->tf_err & (PGEX_P | PGEX_U | PGEX_I | PGEX_RSV)) ==
683 PGEX_P && (frame->tf_rflags & PSL_AC) == 0);
687 trap_is_pti(struct trapframe *frame)
690 return (PCPU_GET(curpmap)->pm_ucr3 != PMAP_NO_CR3 &&
691 pg_nx != 0 && (frame->tf_err & (PGEX_P | PGEX_W |
692 PGEX_U | PGEX_I)) == (PGEX_P | PGEX_U | PGEX_I) &&
693 (curpcb->pcb_saved_ucr3 & ~CR3_PCID_MASK) ==
694 (PCPU_GET(curpmap)->pm_cr3 & ~CR3_PCID_MASK));
698 * Handle all details of a page fault.
700 * -1 if this fault was fatal, typically from kernel mode
701 * (cannot happen, but we need to return something).
702 * 0 if this fault was handled by updating either the user or kernel
703 * page table, execution can continue.
704 * 1 if this fault was from usermode and it was not handled, a synchronous
705 * signal should be delivered to the thread. *signo returns the signal
706 * number, *ucode gives si_code.
709 trap_pfault(struct trapframe *frame, bool usermode, int *signo, int *ucode)
718 MPASS(!usermode || (signo != NULL && ucode != NULL));
722 eva = frame->tf_addr;
724 if (__predict_false((td->td_pflags & TDP_NOFAULTING) != 0)) {
726 * Due to both processor errata and lazy TLB invalidation when
727 * access restrictions are removed from virtual pages, memory
728 * accesses that are allowed by the physical mapping layer may
729 * nonetheless cause one spurious page fault per virtual page.
730 * When the thread is executing a "no faulting" section that
731 * is bracketed by vm_fault_{disable,enable}_pagefaults(),
732 * every page fault is treated as a spurious page fault,
733 * unless it accesses the same virtual address as the most
734 * recent page fault within the same "no faulting" section.
736 if (td->td_md.md_spurflt_addr != eva ||
737 (td->td_pflags & TDP_RESETSPUR) != 0) {
739 * Do nothing to the TLB. A stale TLB entry is
740 * flushed automatically by a page fault.
742 td->td_md.md_spurflt_addr = eva;
743 td->td_pflags &= ~TDP_RESETSPUR;
748 * If we get a page fault while in a critical section, then
749 * it is most likely a fatal kernel page fault. The kernel
750 * is already going to panic trying to get a sleep lock to
751 * do the VM lookup, so just consider it a fatal trap so the
752 * kernel can print out a useful trap message and even get
755 * If we get a page fault while holding a non-sleepable
756 * lock, then it is most likely a fatal kernel page fault.
757 * If WITNESS is enabled, then it's going to whine about
758 * bogus LORs with various VM locks, so just skip to the
759 * fatal trap handling directly.
761 if (td->td_critnest != 0 ||
762 WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
763 "Kernel page fault") != 0) {
764 trap_fatal(frame, eva);
768 if (eva >= VM_MIN_KERNEL_ADDRESS) {
770 * Don't allow user-mode faults in kernel address space.
774 *ucode = SEGV_MAPERR;
780 map = &p->p_vmspace->vm_map;
783 * When accessing a usermode address, kernel must be
784 * ready to accept the page fault, and provide a
785 * handling routine. Since accessing the address
786 * without the handler is a bug, do not try to handle
787 * it normally, and panic immediately.
789 * If SMAP is enabled, filter SMAP faults also,
790 * because illegal access might occur to the mapped
791 * user address, causing infinite loop.
793 if (!usermode && (td->td_intr_nesting_level != 0 ||
794 trap_is_smap(frame) || curpcb->pcb_onfault == NULL)) {
795 trap_fatal(frame, eva);
801 * If the trap was caused by errant bits in the PTE then panic.
803 if (frame->tf_err & PGEX_RSV) {
804 trap_fatal(frame, eva);
809 * User-mode protection key violation (PKU). May happen
810 * either from usermode or from kernel if copyin accessed
811 * key-protected mapping.
813 if ((frame->tf_err & PGEX_PK) != 0) {
814 if (eva > VM_MAXUSER_ADDRESS) {
815 trap_fatal(frame, eva);
820 *ucode = SEGV_PKUERR;
827 * If nx protection of the usermode portion of kernel page
828 * tables caused trap, panic.
830 if (usermode && trap_is_pti(frame))
831 panic("PTI: pid %d comm %s tf_err %#lx", p->p_pid,
832 p->p_comm, frame->tf_err);
835 * PGEX_I is defined only if the execute disable bit capability is
836 * supported and enabled.
838 if (frame->tf_err & PGEX_W)
839 ftype = VM_PROT_WRITE;
840 else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
841 ftype = VM_PROT_EXECUTE;
843 ftype = VM_PROT_READ;
845 /* Fault in the page. */
846 rv = vm_fault_trap(map, eva, ftype, VM_FAULT_NORMAL, signo, ucode);
847 if (rv == KERN_SUCCESS) {
849 if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
850 PMC_SOFT_CALL_TF( , , page_fault, all, frame);
851 if (ftype == VM_PROT_READ)
852 PMC_SOFT_CALL_TF( , , page_fault, read,
855 PMC_SOFT_CALL_TF( , , page_fault, write,
865 if (td->td_intr_nesting_level == 0 &&
866 curpcb->pcb_onfault != NULL) {
867 frame->tf_rip = (long)curpcb->pcb_onfault;
870 trap_fatal(frame, eva);
875 trap_fatal(struct trapframe *frame, vm_offset_t eva)
879 struct soft_segment_descriptor softseg;
880 struct user_segment_descriptor *gdt;
885 code = frame->tf_err;
886 type = frame->tf_trapno;
887 gdt = *PCPU_PTR(gdt);
888 sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)], &softseg);
890 printf("\n\nFatal trap %d: %s while in %s mode\n", type,
891 type < nitems(trap_msg) ? trap_msg[type] : UNKNOWN,
892 TRAPF_USERMODE(frame) ? "user" : "kernel");
894 /* two separate prints in case of a trap on an unmapped page */
895 printf("cpuid = %d; ", PCPU_GET(cpuid));
896 printf("apic id = %02x\n", PCPU_GET(apic_id));
898 if (type == T_PAGEFLT) {
899 printf("fault virtual address = 0x%lx\n", eva);
900 printf("fault code = %s %s %s%s%s, %s\n",
901 code & PGEX_U ? "user" : "supervisor",
902 code & PGEX_W ? "write" : "read",
903 code & PGEX_I ? "instruction" : "data",
904 code & PGEX_PK ? " prot key" : "",
905 code & PGEX_SGX ? " SGX" : "",
906 code & PGEX_RSV ? "reserved bits in PTE" :
907 code & PGEX_P ? "protection violation" : "page not present");
909 printf("instruction pointer = 0x%lx:0x%lx\n",
910 frame->tf_cs & 0xffff, frame->tf_rip);
911 ss = frame->tf_ss & 0xffff;
912 printf("stack pointer = 0x%x:0x%lx\n", ss, frame->tf_rsp);
913 printf("frame pointer = 0x%x:0x%lx\n", ss, frame->tf_rbp);
914 printf("code segment = base 0x%lx, limit 0x%lx, type 0x%x\n",
915 softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
916 printf(" = DPL %d, pres %d, long %d, def32 %d, gran %d\n",
917 softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
919 printf("processor eflags = ");
920 if (frame->tf_rflags & PSL_T)
921 printf("trace trap, ");
922 if (frame->tf_rflags & PSL_I)
923 printf("interrupt enabled, ");
924 if (frame->tf_rflags & PSL_NT)
925 printf("nested task, ");
926 if (frame->tf_rflags & PSL_RF)
928 printf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
929 printf("current process = %d (%s)\n",
930 curproc->p_pid, curthread->td_name);
933 if (debugger_on_trap) {
934 kdb_why = KDB_WHY_TRAP;
935 handled = kdb_trap(type, 0, frame);
936 kdb_why = KDB_WHY_UNSET;
941 printf("trap number = %d\n", type);
942 panic("%s", type < nitems(trap_msg) ? trap_msg[type] :
943 "unknown/reserved trap");
948 * Invoke a userspace DTrace hook. The hook pointer is cleared when no
949 * userspace probes are enabled, so we must synchronize with DTrace to ensure
950 * that a trapping thread is able to call the hook before it is cleared.
953 trap_user_dtrace(struct trapframe *frame, int (**hookp)(struct trapframe *))
955 int (*hook)(struct trapframe *);
957 hook = atomic_load_ptr(hookp);
960 return ((hook)(frame) == 0);
966 * Double fault handler. Called when a fault occurs while writing
967 * a frame for a trap/exception onto the stack. This usually occurs
968 * when the stack overflows (such is the case with infinite recursion,
972 dblfault_handler(struct trapframe *frame)
975 if (dtrace_doubletrap_func != NULL)
976 (*dtrace_doubletrap_func)();
978 printf("\nFatal double fault\n"
979 "rip %#lx rsp %#lx rbp %#lx\n"
980 "rax %#lx rdx %#lx rbx %#lx\n"
981 "rcx %#lx rsi %#lx rdi %#lx\n"
982 "r8 %#lx r9 %#lx r10 %#lx\n"
983 "r11 %#lx r12 %#lx r13 %#lx\n"
984 "r14 %#lx r15 %#lx rflags %#lx\n"
985 "cs %#lx ss %#lx ds %#hx es %#hx fs %#hx gs %#hx\n"
986 "fsbase %#lx gsbase %#lx kgsbase %#lx\n",
987 frame->tf_rip, frame->tf_rsp, frame->tf_rbp,
988 frame->tf_rax, frame->tf_rdx, frame->tf_rbx,
989 frame->tf_rcx, frame->tf_rdi, frame->tf_rsi,
990 frame->tf_r8, frame->tf_r9, frame->tf_r10,
991 frame->tf_r11, frame->tf_r12, frame->tf_r13,
992 frame->tf_r14, frame->tf_r15, frame->tf_rflags,
993 frame->tf_cs, frame->tf_ss, frame->tf_ds, frame->tf_es,
994 frame->tf_fs, frame->tf_gs,
995 rdmsr(MSR_FSBASE), rdmsr(MSR_GSBASE), rdmsr(MSR_KGSBASE));
997 /* two separate prints in case of a trap on an unmapped page */
998 printf("cpuid = %d; ", PCPU_GET(cpuid));
999 printf("apic id = %02x\n", PCPU_GET(apic_id));
1001 panic("double fault");
1004 static int __noinline
1005 cpu_fetch_syscall_args_fallback(struct thread *td, struct syscall_args *sa)
1008 struct trapframe *frame;
1011 int reg, regcnt, error;
1014 frame = td->td_frame;
1018 if (sa->code == SYS_syscall || sa->code == SYS___syscall) {
1019 sa->code = frame->tf_rdi;
1024 if (sa->code >= p->p_sysent->sv_size)
1025 sa->callp = &p->p_sysent->sv_table[0];
1027 sa->callp = &p->p_sysent->sv_table[sa->code];
1029 KASSERT(sa->callp->sy_narg <= nitems(sa->args),
1030 ("Too many syscall arguments!"));
1031 argp = &frame->tf_rdi;
1033 memcpy(sa->args, argp, sizeof(sa->args[0]) * NARGREGS);
1034 if (sa->callp->sy_narg > regcnt) {
1035 params = (caddr_t)frame->tf_rsp + sizeof(register_t);
1036 error = copyin(params, &sa->args[regcnt],
1037 (sa->callp->sy_narg - regcnt) * sizeof(sa->args[0]));
1038 if (__predict_false(error != 0))
1042 td->td_retval[0] = 0;
1043 td->td_retval[1] = frame->tf_rdx;
1049 cpu_fetch_syscall_args(struct thread *td)
1052 struct trapframe *frame;
1053 struct syscall_args *sa;
1056 frame = td->td_frame;
1059 sa->code = frame->tf_rax;
1061 if (__predict_false(sa->code == SYS_syscall ||
1062 sa->code == SYS___syscall ||
1063 sa->code >= p->p_sysent->sv_size))
1064 return (cpu_fetch_syscall_args_fallback(td, sa));
1066 sa->callp = &p->p_sysent->sv_table[sa->code];
1067 KASSERT(sa->callp->sy_narg <= nitems(sa->args),
1068 ("Too many syscall arguments!"));
1070 if (__predict_false(sa->callp->sy_narg > NARGREGS))
1071 return (cpu_fetch_syscall_args_fallback(td, sa));
1073 memcpy(sa->args, &frame->tf_rdi, sizeof(sa->args[0]) * NARGREGS);
1075 td->td_retval[0] = 0;
1076 td->td_retval[1] = frame->tf_rdx;
1081 #include "../../kern/subr_syscall.c"
1083 static void (*syscall_ret_l1d_flush)(void);
1084 int syscall_ret_l1d_flush_mode;
1090 wrmsr(MSR_IA32_FLUSH_CMD, IA32_FLUSH_CMD_L1D);
1093 static void __noinline
1094 amd64_syscall_ret_flush_l1d_check(int error)
1098 if (error != EEXIST && error != EAGAIN && error != EXDEV &&
1099 error != ENOENT && error != ENOTCONN && error != EINPROGRESS) {
1100 p = atomic_load_ptr(&syscall_ret_l1d_flush);
1106 static void __inline
1107 amd64_syscall_ret_flush_l1d_check_inline(int error)
1110 if (__predict_false(error != 0))
1111 amd64_syscall_ret_flush_l1d_check(error);
1115 amd64_syscall_ret_flush_l1d(int error)
1118 amd64_syscall_ret_flush_l1d_check_inline(error);
1122 amd64_syscall_ret_flush_l1d_recalc(void)
1126 l1d_hw = (cpu_stdext_feature3 & CPUID_STDEXT3_L1D_FLUSH) != 0;
1128 switch (syscall_ret_l1d_flush_mode) {
1130 syscall_ret_l1d_flush = NULL;
1133 syscall_ret_l1d_flush = l1d_hw ? flush_l1d_hw :
1137 syscall_ret_l1d_flush = l1d_hw ? flush_l1d_hw : NULL;
1140 syscall_ret_l1d_flush = flush_l1d_sw_abi;
1143 syscall_ret_l1d_flush_mode = 1;
1149 machdep_syscall_ret_flush_l1d(SYSCTL_HANDLER_ARGS)
1153 val = syscall_ret_l1d_flush_mode;
1154 error = sysctl_handle_int(oidp, &val, 0, req);
1155 if (error != 0 || req->newptr == NULL)
1157 syscall_ret_l1d_flush_mode = val;
1158 amd64_syscall_ret_flush_l1d_recalc();
1161 SYSCTL_PROC(_machdep, OID_AUTO, syscall_ret_flush_l1d, CTLTYPE_INT |
1162 CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
1163 machdep_syscall_ret_flush_l1d, "I",
1164 "Flush L1D on syscall return with error (0 - off, 1 - on, "
1165 "2 - use hw only, 3 - use sw only)");
1168 * System call handler for native binaries. The trap frame is already
1169 * set up by the assembler trampoline and a pointer to it is saved in
1173 amd64_syscall(struct thread *td, int traced)
1178 if (!TRAPF_USERMODE(td->td_frame)) {
1188 if (__predict_false(traced)) {
1189 td->td_frame->tf_rflags &= ~PSL_T;
1190 ksiginfo_init_trap(&ksi);
1191 ksi.ksi_signo = SIGTRAP;
1192 ksi.ksi_code = TRAP_TRACE;
1193 ksi.ksi_addr = (void *)td->td_frame->tf_rip;
1194 trapsignal(td, &ksi);
1197 KASSERT(PCB_USER_FPU(td->td_pcb),
1198 ("System call %s returning with kernel FPU ctx leaked",
1199 syscallname(td->td_proc, td->td_sa.code)));
1200 KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td),
1201 ("System call %s returning with mangled pcb_save",
1202 syscallname(td->td_proc, td->td_sa.code)));
1203 KASSERT(pmap_not_in_di(),
1204 ("System call %s returning with leaked invl_gen %lu",
1205 syscallname(td->td_proc, td->td_sa.code),
1206 td->td_md.md_invl_gen.gen));
1211 * If the user-supplied value of %rip is not a canonical
1212 * address, then some CPUs will trigger a ring 0 #GP during
1213 * the sysret instruction. However, the fault handler would
1214 * execute in ring 0 with the user's %gs and %rsp which would
1215 * not be safe. Instead, use the full return path which
1216 * catches the problem safely.
1218 if (__predict_false(td->td_frame->tf_rip >= (la57 ?
1219 VM_MAXUSER_ADDRESS_LA57 : VM_MAXUSER_ADDRESS_LA48)))
1220 set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
1222 amd64_syscall_ret_flush_l1d_check_inline(td->td_errno);