1 /*- 2 * SPDX-License-Identifier: BSD-4-Clause 3 * 4 * Copyright (C) 1994, David Greenman 5 * Copyright (c) 1990, 1993 6 * The Regents of the University of California. All rights reserved. 7 * 8 * This code is derived from software contributed to Berkeley by 9 * the University of Utah, and William Jolitz. 10 * 11 * Redistribution and use in source and binary forms, with or without 12 * modification, are permitted provided that the following conditions 13 * are met: 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. 26 * 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 37 * SUCH DAMAGE. 38 * 39 * from: @(#)trap.c 7.4 (Berkeley) 5/13/91 40 */ 41 42 #include <sys/cdefs.h> 43 /* 44 * AMD64 Trap and System call handling 45 */ 46 47 #include "opt_clock.h" 48 #include "opt_cpu.h" 49 #include "opt_hwpmc_hooks.h" 50 #include "opt_isa.h" 51 #include "opt_kdb.h" 52 53 #include <sys/param.h> 54 #include <sys/asan.h> 55 #include <sys/bus.h> 56 #include <sys/systm.h> 57 #include <sys/proc.h> 58 #include <sys/ptrace.h> 59 #include <sys/kdb.h> 60 #include <sys/kernel.h> 61 #include <sys/ktr.h> 62 #include <sys/lock.h> 63 #include <sys/msan.h> 64 #include <sys/mutex.h> 65 #include <sys/resourcevar.h> 66 #include <sys/signalvar.h> 67 #include <sys/syscall.h> 68 #include <sys/sysctl.h> 69 #include <sys/sysent.h> 70 #include <sys/uio.h> 71 #include <sys/vmmeter.h> 72 #ifdef HWPMC_HOOKS 73 #include <sys/pmckern.h> 74 PMC_SOFT_DEFINE( , , page_fault, all); 75 PMC_SOFT_DEFINE( , , page_fault, read); 76 PMC_SOFT_DEFINE( , , page_fault, write); 77 #endif 78 79 #include <vm/vm.h> 80 #include <vm/vm_param.h> 81 #include <vm/pmap.h> 82 #include <vm/vm_kern.h> 83 #include <vm/vm_map.h> 84 #include <vm/vm_page.h> 85 #include <vm/vm_extern.h> 86 87 #include <machine/cpu.h> 88 #include <machine/intr_machdep.h> 89 #include <x86/mca.h> 90 #include <machine/md_var.h> 91 #include <machine/pcb.h> 92 #ifdef SMP 93 #include <machine/smp.h> 94 #endif 95 #include <machine/stack.h> 96 #include <machine/trap.h> 97 #include <machine/tss.h> 98 99 #ifdef KDTRACE_HOOKS 100 #include <sys/dtrace_bsd.h> 101 #endif 102 103 extern inthand_t IDTVEC(bpt), IDTVEC(bpt_pti), IDTVEC(dbg), 104 IDTVEC(fast_syscall), IDTVEC(fast_syscall_pti), IDTVEC(fast_syscall32), 105 IDTVEC(int0x80_syscall_pti), IDTVEC(int0x80_syscall); 106 107 void __noinline trap(struct trapframe *frame); 108 void trap_check(struct trapframe *frame); 109 void dblfault_handler(struct trapframe *frame); 110 111 static int trap_pfault(struct trapframe *, bool, int *, int *); 112 static void trap_fatal(struct trapframe *, vm_offset_t); 113 #ifdef KDTRACE_HOOKS 114 static bool trap_user_dtrace(struct trapframe *, 115 int (**hook)(struct trapframe *)); 116 #endif 117 118 static const char UNKNOWN[] = "unknown"; 119 static const char *const trap_msg[] = { 120 [0] = UNKNOWN, /* unused */ 121 [T_PRIVINFLT] = "privileged instruction fault", 122 [2] = UNKNOWN, /* unused */ 123 [T_BPTFLT] = "breakpoint instruction fault", 124 [4] = UNKNOWN, /* unused */ 125 [5] = UNKNOWN, /* unused */ 126 [T_ARITHTRAP] = "arithmetic trap", 127 [7] = UNKNOWN, /* unused */ 128 [8] = UNKNOWN, /* unused */ 129 [T_PROTFLT] = "general protection fault", 130 [T_TRCTRAP] = "debug exception", 131 [11] = UNKNOWN, /* unused */ 132 [T_PAGEFLT] = "page fault", 133 [13] = UNKNOWN, /* unused */ 134 [T_ALIGNFLT] = "alignment fault", 135 [15] = UNKNOWN, /* unused */ 136 [16] = UNKNOWN, /* unused */ 137 [17] = UNKNOWN, /* unused */ 138 [T_DIVIDE] = "integer divide fault", 139 [T_NMI] = "non-maskable interrupt trap", 140 [T_OFLOW] = "overflow trap", 141 [T_BOUND] = "FPU bounds check fault", 142 [T_DNA] = "FPU device not available", 143 [T_DOUBLEFLT] = "double fault", 144 [T_FPOPFLT] = "FPU operand fetch fault", 145 [T_TSSFLT] = "invalid TSS fault", 146 [T_SEGNPFLT] = "segment not present fault", 147 [T_STKFLT] = "stack fault", 148 [T_MCHK] = "machine check trap", 149 [T_XMMFLT] = "SIMD floating-point exception", 150 [T_RESERVED] = "reserved (unknown) fault", 151 [31] = UNKNOWN, /* reserved */ 152 [T_DTRACE_RET] = "DTrace pid return trap", 153 }; 154 155 static int uprintf_signal; 156 SYSCTL_INT(_machdep, OID_AUTO, uprintf_signal, CTLFLAG_RWTUN, 157 &uprintf_signal, 0, 158 "Print debugging information on trap signal to ctty"); 159 160 /* 161 * Control L1D flush on return from NMI. 162 * 163 * Tunable can be set to the following values: 164 * 0 - only enable flush on return from NMI if required by vmm.ko (default) 165 * >1 - always flush on return from NMI. 166 * 167 * Post-boot, the sysctl indicates if flushing is currently enabled. 168 */ 169 int nmi_flush_l1d_sw; 170 SYSCTL_INT(_machdep, OID_AUTO, nmi_flush_l1d_sw, CTLFLAG_RWTUN, 171 &nmi_flush_l1d_sw, 0, 172 "Flush L1 Data Cache on NMI exit, software bhyve L1TF mitigation assist"); 173 174 /* 175 * Table of handlers for various segment load faults. 176 */ 177 static const struct { 178 uintptr_t faddr; 179 uintptr_t fhandler; 180 } sfhandlers[] = { 181 { 182 .faddr = (uintptr_t)ld_ds, 183 .fhandler = (uintptr_t)ds_load_fault, 184 }, 185 { 186 .faddr = (uintptr_t)ld_es, 187 .fhandler = (uintptr_t)es_load_fault, 188 }, 189 { 190 .faddr = (uintptr_t)ld_fs, 191 .fhandler = (uintptr_t)fs_load_fault, 192 }, 193 { 194 .faddr = (uintptr_t)ld_gs, 195 .fhandler = (uintptr_t)gs_load_fault, 196 }, 197 { 198 .faddr = (uintptr_t)ld_gsbase, 199 .fhandler = (uintptr_t)gsbase_load_fault 200 }, 201 { 202 .faddr = (uintptr_t)ld_fsbase, 203 .fhandler = (uintptr_t)fsbase_load_fault, 204 }, 205 }; 206 207 /* 208 * Exception, fault, and trap interface to the FreeBSD kernel. 209 * This common code is called from assembly language IDT gate entry 210 * routines that prepare a suitable stack frame, and restore this 211 * frame after the exception has been processed. 212 */ 213 214 void 215 trap(struct trapframe *frame) 216 { 217 ksiginfo_t ksi; 218 struct thread *td; 219 struct proc *p; 220 register_t addr, dr6; 221 size_t i; 222 int pf, signo, ucode; 223 u_int type; 224 225 td = curthread; 226 p = td->td_proc; 227 dr6 = 0; 228 229 kasan_mark(frame, sizeof(*frame), sizeof(*frame), 0); 230 kmsan_mark(frame, sizeof(*frame), KMSAN_STATE_INITED); 231 232 VM_CNT_INC(v_trap); 233 type = frame->tf_trapno; 234 235 #ifdef SMP 236 /* Handler for NMI IPIs used for stopping CPUs. */ 237 if (type == T_NMI && ipi_nmi_handler() == 0) 238 return; 239 #endif 240 241 #ifdef KDB 242 if (kdb_active) { 243 kdb_reenter(); 244 return; 245 } 246 #endif 247 248 if (type == T_RESERVED) { 249 trap_fatal(frame, 0); 250 return; 251 } 252 253 if (type == T_NMI) { 254 #ifdef HWPMC_HOOKS 255 /* 256 * CPU PMCs interrupt using an NMI. If the PMC module is 257 * active, pass the 'rip' value to the PMC module's interrupt 258 * handler. A non-zero return value from the handler means that 259 * the NMI was consumed by it and we can return immediately. 260 */ 261 if (pmc_intr != NULL && 262 (*pmc_intr)(frame) != 0) 263 return; 264 #endif 265 } 266 267 if ((frame->tf_rflags & PSL_I) == 0) { 268 /* 269 * Buggy application or kernel code has disabled 270 * interrupts and then trapped. Enabling interrupts 271 * now is wrong, but it is better than running with 272 * interrupts disabled until they are accidentally 273 * enabled later. 274 */ 275 if (TRAPF_USERMODE(frame)) { 276 uprintf( 277 "pid %ld (%s): trap %d (%s) " 278 "with interrupts disabled\n", 279 (long)curproc->p_pid, curthread->td_name, type, 280 trap_msg[type]); 281 } else { 282 switch (type) { 283 case T_NMI: 284 case T_BPTFLT: 285 case T_TRCTRAP: 286 case T_PROTFLT: 287 case T_SEGNPFLT: 288 case T_STKFLT: 289 break; 290 default: 291 printf( 292 "kernel trap %d with interrupts disabled\n", 293 type); 294 295 /* 296 * We shouldn't enable interrupts while holding a 297 * spin lock. 298 */ 299 if (td->td_md.md_spinlock_count == 0) 300 enable_intr(); 301 } 302 } 303 } 304 305 if (TRAPF_USERMODE(frame)) { 306 /* user trap */ 307 308 td->td_pticks = 0; 309 td->td_frame = frame; 310 addr = frame->tf_rip; 311 if (td->td_cowgen != atomic_load_int(&p->p_cowgen)) 312 thread_cow_update(td); 313 314 switch (type) { 315 case T_PRIVINFLT: /* privileged instruction fault */ 316 signo = SIGILL; 317 ucode = ILL_PRVOPC; 318 break; 319 320 case T_BPTFLT: /* bpt instruction fault */ 321 #ifdef KDTRACE_HOOKS 322 if (trap_user_dtrace(frame, &dtrace_pid_probe_ptr)) 323 return; 324 #else 325 enable_intr(); 326 #endif 327 signo = SIGTRAP; 328 ucode = TRAP_BRKPT; 329 break; 330 331 case T_TRCTRAP: /* debug exception */ 332 enable_intr(); 333 signo = SIGTRAP; 334 ucode = TRAP_TRACE; 335 dr6 = rdr6(); 336 if ((dr6 & DBREG_DR6_BS) != 0) { 337 PROC_LOCK(td->td_proc); 338 if ((td->td_dbgflags & TDB_STEP) != 0) { 339 td->td_frame->tf_rflags &= ~PSL_T; 340 td->td_dbgflags &= ~TDB_STEP; 341 } 342 PROC_UNLOCK(td->td_proc); 343 } 344 break; 345 346 case T_ARITHTRAP: /* arithmetic trap */ 347 ucode = fputrap_x87(); 348 if (ucode == -1) 349 return; 350 signo = SIGFPE; 351 break; 352 353 case T_PROTFLT: /* general protection fault */ 354 signo = SIGBUS; 355 ucode = BUS_OBJERR; 356 break; 357 case T_STKFLT: /* stack fault */ 358 case T_SEGNPFLT: /* segment not present fault */ 359 signo = SIGBUS; 360 ucode = BUS_ADRERR; 361 break; 362 case T_TSSFLT: /* invalid TSS fault */ 363 signo = SIGBUS; 364 ucode = BUS_OBJERR; 365 break; 366 case T_ALIGNFLT: 367 signo = SIGBUS; 368 ucode = BUS_ADRALN; 369 break; 370 case T_DOUBLEFLT: /* double fault */ 371 default: 372 signo = SIGBUS; 373 ucode = BUS_OBJERR; 374 break; 375 376 case T_PAGEFLT: /* page fault */ 377 /* 378 * Can emulator handle this trap? 379 */ 380 if (*p->p_sysent->sv_trap != NULL && 381 (*p->p_sysent->sv_trap)(td) == 0) 382 return; 383 384 pf = trap_pfault(frame, true, &signo, &ucode); 385 if (pf == -1) 386 return; 387 if (pf == 0) 388 goto userret; 389 addr = frame->tf_addr; 390 break; 391 392 case T_DIVIDE: /* integer divide fault */ 393 ucode = FPE_INTDIV; 394 signo = SIGFPE; 395 break; 396 397 case T_NMI: 398 nmi_handle_intr(type, frame); 399 return; 400 401 case T_OFLOW: /* integer overflow fault */ 402 ucode = FPE_INTOVF; 403 signo = SIGFPE; 404 break; 405 406 case T_BOUND: /* bounds check fault */ 407 ucode = FPE_FLTSUB; 408 signo = SIGFPE; 409 break; 410 411 case T_DNA: 412 /* transparent fault (due to context switch "late") */ 413 KASSERT(PCB_USER_FPU(td->td_pcb), 414 ("kernel FPU ctx has leaked")); 415 fpudna(); 416 return; 417 418 case T_FPOPFLT: /* FPU operand fetch fault */ 419 ucode = ILL_COPROC; 420 signo = SIGILL; 421 break; 422 423 case T_XMMFLT: /* SIMD floating-point exception */ 424 ucode = fputrap_sse(); 425 if (ucode == -1) 426 return; 427 signo = SIGFPE; 428 break; 429 #ifdef KDTRACE_HOOKS 430 case T_DTRACE_RET: 431 (void)trap_user_dtrace(frame, &dtrace_return_probe_ptr); 432 return; 433 #endif 434 } 435 } else { 436 /* kernel trap */ 437 438 KASSERT(cold || td->td_ucred != NULL, 439 ("kernel trap doesn't have ucred")); 440 switch (type) { 441 case T_PAGEFLT: /* page fault */ 442 (void)trap_pfault(frame, false, NULL, NULL); 443 return; 444 445 case T_DNA: 446 if (PCB_USER_FPU(td->td_pcb)) 447 panic("Unregistered use of FPU in kernel"); 448 fpudna(); 449 return; 450 451 case T_ARITHTRAP: /* arithmetic trap */ 452 case T_XMMFLT: /* SIMD floating-point exception */ 453 case T_FPOPFLT: /* FPU operand fetch fault */ 454 /* 455 * For now, supporting kernel handler 456 * registration for FPU traps is overkill. 457 */ 458 trap_fatal(frame, 0); 459 return; 460 461 case T_STKFLT: /* stack fault */ 462 case T_PROTFLT: /* general protection fault */ 463 case T_SEGNPFLT: /* segment not present fault */ 464 if (td->td_intr_nesting_level != 0) 465 break; 466 467 /* 468 * Invalid segment selectors and out of bounds 469 * %rip's and %rsp's can be set up in user mode. 470 * This causes a fault in kernel mode when the 471 * kernel tries to return to user mode. We want 472 * to get this fault so that we can fix the 473 * problem here and not have to check all the 474 * selectors and pointers when the user changes 475 * them. 476 * 477 * In case of PTI, the IRETQ faulted while the 478 * kernel used the pti stack, and exception 479 * frame records %rsp value pointing to that 480 * stack. If we return normally to 481 * doreti_iret_fault, the trapframe is 482 * reconstructed on pti stack, and calltrap() 483 * called on it as well. Due to the very 484 * limited pti stack size, kernel does not 485 * survive for too long. Switch to the normal 486 * thread stack for the trap handling. 487 * 488 * Magic '5' is the number of qwords occupied by 489 * the hardware trap frame. 490 */ 491 if (frame->tf_rip == (long)doreti_iret) { 492 KASSERT((read_rflags() & PSL_I) == 0, 493 ("interrupts enabled")); 494 frame->tf_rip = (long)doreti_iret_fault; 495 if ((PCPU_GET(curpmap)->pm_ucr3 != 496 PMAP_NO_CR3) && 497 (frame->tf_rsp == (uintptr_t)PCPU_GET( 498 pti_rsp0) - 5 * sizeof(register_t))) { 499 frame->tf_rsp = PCPU_GET(rsp0) - 5 * 500 sizeof(register_t); 501 } 502 return; 503 } 504 505 for (i = 0; i < nitems(sfhandlers); i++) { 506 if (frame->tf_rip == sfhandlers[i].faddr) { 507 KASSERT((read_rflags() & PSL_I) == 0, 508 ("interrupts enabled")); 509 frame->tf_rip = sfhandlers[i].fhandler; 510 return; 511 } 512 } 513 514 if (curpcb->pcb_onfault != NULL) { 515 frame->tf_rip = (long)curpcb->pcb_onfault; 516 return; 517 } 518 break; 519 520 case T_TSSFLT: 521 /* 522 * PSL_NT can be set in user mode and isn't cleared 523 * automatically when the kernel is entered. This 524 * causes a TSS fault when the kernel attempts to 525 * `iret' because the TSS link is uninitialized. We 526 * want to get this fault so that we can fix the 527 * problem here and not every time the kernel is 528 * entered. 529 */ 530 if (frame->tf_rflags & PSL_NT) { 531 frame->tf_rflags &= ~PSL_NT; 532 return; 533 } 534 break; 535 536 case T_TRCTRAP: /* debug exception */ 537 /* Clear any pending debug events. */ 538 dr6 = rdr6(); 539 load_dr6(0); 540 541 /* 542 * Ignore debug register exceptions due to 543 * accesses in the user's address space, which 544 * can happen under several conditions such as 545 * if a user sets a watchpoint on a buffer and 546 * then passes that buffer to a system call. 547 * We still want to get TRCTRAPS for addresses 548 * in kernel space because that is useful when 549 * debugging the kernel. 550 */ 551 if (user_dbreg_trap(dr6)) 552 return; 553 554 /* 555 * Malicious user code can configure a debug 556 * register watchpoint to trap on data access 557 * to the top of stack and then execute 'pop 558 * %ss; int 3'. Due to exception deferral for 559 * 'pop %ss', the CPU will not interrupt 'int 560 * 3' to raise the DB# exception for the debug 561 * register but will postpone the DB# until 562 * execution of the first instruction of the 563 * BP# handler (in kernel mode). Normally the 564 * previous check would ignore DB# exceptions 565 * for watchpoints on user addresses raised in 566 * kernel mode. However, some CPU errata 567 * include cases where DB# exceptions do not 568 * properly set bits in %dr6, e.g. Haswell 569 * HSD23 and Skylake-X SKZ24. 570 * 571 * A deferred DB# can also be raised on the 572 * first instructions of system call entry 573 * points or single-step traps via similar use 574 * of 'pop %ss' or 'mov xxx, %ss'. 575 */ 576 if (pti) { 577 if (frame->tf_rip == 578 (uintptr_t)IDTVEC(fast_syscall_pti) || 579 #ifdef COMPAT_FREEBSD32 580 frame->tf_rip == 581 (uintptr_t)IDTVEC(int0x80_syscall_pti) || 582 #endif 583 frame->tf_rip == (uintptr_t)IDTVEC(bpt_pti)) 584 return; 585 } else { 586 if (frame->tf_rip == 587 (uintptr_t)IDTVEC(fast_syscall) || 588 #ifdef COMPAT_FREEBSD32 589 frame->tf_rip == 590 (uintptr_t)IDTVEC(int0x80_syscall) || 591 #endif 592 frame->tf_rip == (uintptr_t)IDTVEC(bpt)) 593 return; 594 } 595 if (frame->tf_rip == (uintptr_t)IDTVEC(dbg) || 596 /* Needed for AMD. */ 597 frame->tf_rip == (uintptr_t)IDTVEC(fast_syscall32)) 598 return; 599 /* 600 * FALLTHROUGH (TRCTRAP kernel mode, kernel address) 601 */ 602 case T_BPTFLT: 603 /* 604 * If KDB is enabled, let it handle the debugger trap. 605 * Otherwise, debugger traps "can't happen". 606 */ 607 #ifdef KDB 608 if (kdb_trap(type, dr6, frame)) 609 return; 610 #endif 611 break; 612 613 case T_NMI: 614 nmi_handle_intr(type, frame); 615 return; 616 } 617 618 trap_fatal(frame, 0); 619 return; 620 } 621 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 %#lx rsp %#lx rip %#lx rax %#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, frame->tf_rax, 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))); 641 } 642 KASSERT((read_rflags() & PSL_I) != 0, ("interrupts disabled")); 643 trapsignal(td, &ksi); 644 645 userret: 646 userret(td, frame); 647 KASSERT(PCB_USER_FPU(td->td_pcb), 648 ("Return from trap with kernel FPU ctx leaked")); 649 } 650 651 /* 652 * Ensure that we ignore any DTrace-induced faults. This function cannot 653 * be instrumented, so it cannot generate such faults itself. 654 */ 655 void 656 trap_check(struct trapframe *frame) 657 { 658 659 #ifdef KDTRACE_HOOKS 660 if (dtrace_trap_func != NULL && 661 (*dtrace_trap_func)(frame, frame->tf_trapno) != 0) 662 return; 663 #endif 664 trap(frame); 665 } 666 667 static bool 668 trap_is_smap(struct trapframe *frame) 669 { 670 671 /* 672 * A page fault on a userspace address is classified as 673 * SMAP-induced if: 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. 679 */ 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); 683 } 684 685 static bool 686 trap_is_pti(struct trapframe *frame) 687 { 688 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)); 694 } 695 696 /* 697 * Handle all details of a page fault. 698 * Returns: 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. 706 */ 707 static int 708 trap_pfault(struct trapframe *frame, bool usermode, int *signo, int *ucode) 709 { 710 struct thread *td; 711 struct proc *p; 712 vm_map_t map; 713 vm_offset_t eva; 714 int rv; 715 vm_prot_t ftype; 716 717 MPASS(!usermode || (signo != NULL && ucode != NULL)); 718 719 td = curthread; 720 p = td->td_proc; 721 eva = frame->tf_addr; 722 723 if (__predict_false((td->td_pflags & TDP_NOFAULTING) != 0)) { 724 /* 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. 734 */ 735 if (td->td_md.md_spurflt_addr != eva || 736 (td->td_pflags & TDP_RESETSPUR) != 0) { 737 /* 738 * Do nothing to the TLB. A stale TLB entry is 739 * flushed automatically by a page fault. 740 */ 741 td->td_md.md_spurflt_addr = eva; 742 td->td_pflags &= ~TDP_RESETSPUR; 743 return (0); 744 } 745 } else { 746 /* 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 752 * to the debugger. 753 * 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. 759 */ 760 if (td->td_critnest != 0 || 761 WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL, 762 "Kernel page fault") != 0) { 763 trap_fatal(frame, eva); 764 return (-1); 765 } 766 } 767 if (eva >= VM_MIN_KERNEL_ADDRESS) { 768 /* 769 * Don't allow user-mode faults in kernel address space. 770 */ 771 if (usermode) { 772 *signo = SIGSEGV; 773 *ucode = SEGV_MAPERR; 774 return (1); 775 } 776 777 map = kernel_map; 778 } else { 779 map = &p->p_vmspace->vm_map; 780 781 /* 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. 787 * 788 * If SMAP is enabled, filter SMAP faults also, 789 * because illegal access might occur to the mapped 790 * user address, causing infinite loop. 791 */ 792 if (!usermode && (td->td_intr_nesting_level != 0 || 793 trap_is_smap(frame) || curpcb->pcb_onfault == NULL)) { 794 trap_fatal(frame, eva); 795 return (-1); 796 } 797 } 798 799 /* 800 * If the trap was caused by errant bits in the PTE then panic. 801 */ 802 if (frame->tf_err & PGEX_RSV) { 803 trap_fatal(frame, eva); 804 return (-1); 805 } 806 807 /* 808 * User-mode protection key violation (PKU). May happen 809 * either from usermode or from kernel if copyin accessed 810 * key-protected mapping. 811 */ 812 if ((frame->tf_err & PGEX_PK) != 0) { 813 if (eva > VM_MAXUSER_ADDRESS) { 814 trap_fatal(frame, eva); 815 return (-1); 816 } 817 if (usermode) { 818 *signo = SIGSEGV; 819 *ucode = SEGV_PKUERR; 820 return (1); 821 } 822 goto after_vmfault; 823 } 824 825 /* 826 * If nx protection of the usermode portion of kernel page 827 * tables caused trap, panic. 828 */ 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); 832 833 /* 834 * PGEX_I is defined only if the execute disable bit capability is 835 * supported and enabled. 836 */ 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; 841 else 842 ftype = VM_PROT_READ; 843 844 /* Fault in the page. */ 845 rv = vm_fault_trap(map, eva, ftype, VM_FAULT_NORMAL, signo, ucode); 846 if (rv == KERN_SUCCESS) { 847 #ifdef HWPMC_HOOKS 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, 852 frame); 853 else 854 PMC_SOFT_CALL_TF( , , page_fault, write, 855 frame); 856 } 857 #endif 858 return (0); 859 } 860 861 if (usermode) 862 return (1); 863 after_vmfault: 864 if (td->td_intr_nesting_level == 0 && 865 curpcb->pcb_onfault != NULL) { 866 frame->tf_rip = (long)curpcb->pcb_onfault; 867 return (0); 868 } 869 trap_fatal(frame, eva); 870 return (-1); 871 } 872 873 static void 874 trap_fatal(struct trapframe *frame, vm_offset_t eva) 875 { 876 int code, ss; 877 u_int type; 878 struct soft_segment_descriptor softseg; 879 struct user_segment_descriptor *gdt; 880 #ifdef KDB 881 bool handled; 882 #endif 883 884 code = frame->tf_err; 885 type = frame->tf_trapno; 886 gdt = *PCPU_PTR(gdt); 887 sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)], &softseg); 888 889 printf("\n\nFatal trap %d: %s while in %s mode\n", type, 890 type < nitems(trap_msg) ? trap_msg[type] : UNKNOWN, 891 TRAPF_USERMODE(frame) ? "user" : "kernel"); 892 #ifdef SMP 893 /* two separate prints in case of a trap on an unmapped page */ 894 printf("cpuid = %d; ", PCPU_GET(cpuid)); 895 printf("apic id = %02x\n", PCPU_GET(apic_id)); 896 #endif 897 if (type == T_PAGEFLT) { 898 printf("fault virtual address = 0x%lx\n", eva); 899 printf("fault code = %s %s %s%s%s, %s\n", 900 code & PGEX_U ? "user" : "supervisor", 901 code & PGEX_W ? "write" : "read", 902 code & PGEX_I ? "instruction" : "data", 903 code & PGEX_PK ? " prot key" : "", 904 code & PGEX_SGX ? " SGX" : "", 905 code & PGEX_RSV ? "reserved bits in PTE" : 906 code & PGEX_P ? "protection violation" : "page not present"); 907 } 908 printf("instruction pointer = 0x%lx:0x%lx\n", 909 frame->tf_cs & 0xffff, frame->tf_rip); 910 ss = frame->tf_ss & 0xffff; 911 printf("stack pointer = 0x%x:0x%lx\n", ss, frame->tf_rsp); 912 printf("frame pointer = 0x%x:0x%lx\n", ss, frame->tf_rbp); 913 printf("code segment = base 0x%lx, limit 0x%lx, type 0x%x\n", 914 softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type); 915 printf(" = DPL %d, pres %d, long %d, def32 %d, gran %d\n", 916 softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32, 917 softseg.ssd_gran); 918 printf("processor eflags = "); 919 if (frame->tf_rflags & PSL_T) 920 printf("trace trap, "); 921 if (frame->tf_rflags & PSL_I) 922 printf("interrupt enabled, "); 923 if (frame->tf_rflags & PSL_NT) 924 printf("nested task, "); 925 if (frame->tf_rflags & PSL_RF) 926 printf("resume, "); 927 printf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12); 928 printf("current process = %d (%s)\n", 929 curproc->p_pid, curthread->td_name); 930 931 printf("rdi: %016lx rsi: %016lx rdx: %016lx\n", frame->tf_rdi, 932 frame->tf_rsi, frame->tf_rdx); 933 printf("rcx: %016lx r8: %016lx r9: %016lx\n", frame->tf_rcx, 934 frame->tf_r8, frame->tf_r9); 935 printf("rax: %016lx rbx: %016lx rbp: %016lx\n", frame->tf_rax, 936 frame->tf_rbx, frame->tf_rbp); 937 printf("r10: %016lx r11: %016lx r12: %016lx\n", frame->tf_r10, 938 frame->tf_r11, frame->tf_r12); 939 printf("r13: %016lx r14: %016lx r15: %016lx\n", frame->tf_r13, 940 frame->tf_r14, frame->tf_r15); 941 942 #ifdef KDB 943 if (debugger_on_trap) { 944 kdb_why = KDB_WHY_TRAP; 945 handled = kdb_trap(type, 0, frame); 946 kdb_why = KDB_WHY_UNSET; 947 if (handled) 948 return; 949 } 950 #endif 951 printf("trap number = %d\n", type); 952 panic("%s", type < nitems(trap_msg) ? trap_msg[type] : 953 "unknown/reserved trap"); 954 } 955 956 #ifdef KDTRACE_HOOKS 957 /* 958 * Invoke a userspace DTrace hook. The hook pointer is cleared when no 959 * userspace probes are enabled, so we must synchronize with DTrace to ensure 960 * that a trapping thread is able to call the hook before it is cleared. 961 */ 962 static bool 963 trap_user_dtrace(struct trapframe *frame, int (**hookp)(struct trapframe *)) 964 { 965 int (*hook)(struct trapframe *); 966 967 hook = atomic_load_ptr(hookp); 968 enable_intr(); 969 if (hook != NULL) 970 return ((hook)(frame) == 0); 971 return (false); 972 } 973 #endif 974 975 /* 976 * Double fault handler. Called when a fault occurs while writing 977 * a frame for a trap/exception onto the stack. This usually occurs 978 * when the stack overflows (such is the case with infinite recursion, 979 * for example). 980 */ 981 void 982 dblfault_handler(struct trapframe *frame) 983 { 984 kmsan_mark(frame, sizeof(*frame), KMSAN_STATE_INITED); 985 #ifdef KDTRACE_HOOKS 986 if (dtrace_doubletrap_func != NULL) 987 (*dtrace_doubletrap_func)(); 988 #endif 989 printf("\nFatal double fault\n" 990 "rip %#lx rsp %#lx rbp %#lx\n" 991 "rax %#lx rdx %#lx rbx %#lx\n" 992 "rcx %#lx rsi %#lx rdi %#lx\n" 993 "r8 %#lx r9 %#lx r10 %#lx\n" 994 "r11 %#lx r12 %#lx r13 %#lx\n" 995 "r14 %#lx r15 %#lx rflags %#lx\n" 996 "cs %#lx ss %#lx ds %#hx es %#hx fs %#hx gs %#hx\n" 997 "fsbase %#lx gsbase %#lx kgsbase %#lx\n", 998 frame->tf_rip, frame->tf_rsp, frame->tf_rbp, 999 frame->tf_rax, frame->tf_rdx, frame->tf_rbx, 1000 frame->tf_rcx, frame->tf_rdi, frame->tf_rsi, 1001 frame->tf_r8, frame->tf_r9, frame->tf_r10, 1002 frame->tf_r11, frame->tf_r12, frame->tf_r13, 1003 frame->tf_r14, frame->tf_r15, frame->tf_rflags, 1004 frame->tf_cs, frame->tf_ss, frame->tf_ds, frame->tf_es, 1005 frame->tf_fs, frame->tf_gs, 1006 rdmsr(MSR_FSBASE), rdmsr(MSR_GSBASE), rdmsr(MSR_KGSBASE)); 1007 #ifdef SMP 1008 /* two separate prints in case of a trap on an unmapped page */ 1009 printf("cpuid = %d; ", PCPU_GET(cpuid)); 1010 printf("apic id = %02x\n", PCPU_GET(apic_id)); 1011 #endif 1012 panic("double fault"); 1013 } 1014 1015 static int __noinline 1016 cpu_fetch_syscall_args_fallback(struct thread *td, struct syscall_args *sa) 1017 { 1018 struct proc *p; 1019 struct trapframe *frame; 1020 syscallarg_t *argp; 1021 caddr_t params; 1022 int reg, regcnt, error; 1023 1024 p = td->td_proc; 1025 frame = td->td_frame; 1026 reg = 0; 1027 regcnt = NARGREGS; 1028 1029 if (sa->code == SYS_syscall || sa->code == SYS___syscall) { 1030 sa->code = frame->tf_rdi; 1031 reg++; 1032 regcnt--; 1033 } 1034 1035 if (sa->code >= p->p_sysent->sv_size) 1036 sa->callp = &p->p_sysent->sv_table[0]; 1037 else 1038 sa->callp = &p->p_sysent->sv_table[sa->code]; 1039 1040 KASSERT(sa->callp->sy_narg <= nitems(sa->args), 1041 ("Too many syscall arguments!")); 1042 argp = &frame->tf_rdi; 1043 argp += reg; 1044 memcpy(sa->args, argp, sizeof(sa->args[0]) * NARGREGS); 1045 if (sa->callp->sy_narg > regcnt) { 1046 params = (caddr_t)frame->tf_rsp + sizeof(register_t); 1047 error = copyin(params, &sa->args[regcnt], 1048 (sa->callp->sy_narg - regcnt) * sizeof(sa->args[0])); 1049 if (__predict_false(error != 0)) 1050 return (error); 1051 } 1052 1053 td->td_retval[0] = 0; 1054 td->td_retval[1] = frame->tf_rdx; 1055 1056 return (0); 1057 } 1058 1059 int 1060 cpu_fetch_syscall_args(struct thread *td) 1061 { 1062 struct proc *p; 1063 struct trapframe *frame; 1064 struct syscall_args *sa; 1065 1066 p = td->td_proc; 1067 frame = td->td_frame; 1068 sa = &td->td_sa; 1069 1070 sa->code = frame->tf_rax; 1071 sa->original_code = sa->code; 1072 1073 if (__predict_false(sa->code == SYS_syscall || 1074 sa->code == SYS___syscall || 1075 sa->code >= p->p_sysent->sv_size)) 1076 return (cpu_fetch_syscall_args_fallback(td, sa)); 1077 1078 sa->callp = &p->p_sysent->sv_table[sa->code]; 1079 KASSERT(sa->callp->sy_narg <= nitems(sa->args), 1080 ("Too many syscall arguments!")); 1081 1082 if (__predict_false(sa->callp->sy_narg > NARGREGS)) 1083 return (cpu_fetch_syscall_args_fallback(td, sa)); 1084 1085 memcpy(sa->args, &frame->tf_rdi, sizeof(sa->args[0]) * NARGREGS); 1086 1087 td->td_retval[0] = 0; 1088 td->td_retval[1] = frame->tf_rdx; 1089 1090 return (0); 1091 } 1092 1093 #include "../../kern/subr_syscall.c" 1094 1095 static void (*syscall_ret_l1d_flush)(void); 1096 int syscall_ret_l1d_flush_mode; 1097 1098 static void 1099 flush_l1d_hw(void) 1100 { 1101 1102 wrmsr(MSR_IA32_FLUSH_CMD, IA32_FLUSH_CMD_L1D); 1103 } 1104 1105 static void __noinline 1106 amd64_syscall_ret_flush_l1d_check(int error) 1107 { 1108 void (*p)(void); 1109 1110 if (error != EEXIST && error != EAGAIN && error != EXDEV && 1111 error != ENOENT && error != ENOTCONN && error != EINPROGRESS) { 1112 p = atomic_load_ptr(&syscall_ret_l1d_flush); 1113 if (p != NULL) 1114 p(); 1115 } 1116 } 1117 1118 static void __inline 1119 amd64_syscall_ret_flush_l1d_check_inline(int error) 1120 { 1121 1122 if (__predict_false(error != 0)) 1123 amd64_syscall_ret_flush_l1d_check(error); 1124 } 1125 1126 void 1127 amd64_syscall_ret_flush_l1d(int error) 1128 { 1129 1130 amd64_syscall_ret_flush_l1d_check_inline(error); 1131 } 1132 1133 void 1134 amd64_syscall_ret_flush_l1d_recalc(void) 1135 { 1136 bool l1d_hw; 1137 1138 l1d_hw = (cpu_stdext_feature3 & CPUID_STDEXT3_L1D_FLUSH) != 0; 1139 again: 1140 switch (syscall_ret_l1d_flush_mode) { 1141 case 0: 1142 syscall_ret_l1d_flush = NULL; 1143 break; 1144 case 1: 1145 syscall_ret_l1d_flush = l1d_hw ? flush_l1d_hw : 1146 flush_l1d_sw_abi; 1147 break; 1148 case 2: 1149 syscall_ret_l1d_flush = l1d_hw ? flush_l1d_hw : NULL; 1150 break; 1151 case 3: 1152 syscall_ret_l1d_flush = flush_l1d_sw_abi; 1153 break; 1154 default: 1155 syscall_ret_l1d_flush_mode = 1; 1156 goto again; 1157 } 1158 } 1159 1160 static int 1161 machdep_syscall_ret_flush_l1d(SYSCTL_HANDLER_ARGS) 1162 { 1163 int error, val; 1164 1165 val = syscall_ret_l1d_flush_mode; 1166 error = sysctl_handle_int(oidp, &val, 0, req); 1167 if (error != 0 || req->newptr == NULL) 1168 return (error); 1169 syscall_ret_l1d_flush_mode = val; 1170 amd64_syscall_ret_flush_l1d_recalc(); 1171 return (0); 1172 } 1173 SYSCTL_PROC(_machdep, OID_AUTO, syscall_ret_flush_l1d, CTLTYPE_INT | 1174 CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0, 1175 machdep_syscall_ret_flush_l1d, "I", 1176 "Flush L1D on syscall return with error (0 - off, 1 - on, " 1177 "2 - use hw only, 3 - use sw only)"); 1178 1179 /* 1180 * System call handler for native binaries. The trap frame is already 1181 * set up by the assembler trampoline and a pointer to it is saved in 1182 * td_frame. 1183 */ 1184 void 1185 amd64_syscall(struct thread *td, int traced) 1186 { 1187 ksiginfo_t ksi; 1188 1189 kmsan_mark(td->td_frame, sizeof(*td->td_frame), KMSAN_STATE_INITED); 1190 1191 KASSERT(TRAPF_USERMODE(td->td_frame), 1192 ("%s: not from user mode", __func__)); 1193 1194 syscallenter(td); 1195 1196 /* 1197 * Traced syscall. 1198 */ 1199 if (__predict_false(traced)) { 1200 td->td_frame->tf_rflags &= ~PSL_T; 1201 ksiginfo_init_trap(&ksi); 1202 ksi.ksi_signo = SIGTRAP; 1203 ksi.ksi_code = TRAP_TRACE; 1204 ksi.ksi_addr = (void *)td->td_frame->tf_rip; 1205 trapsignal(td, &ksi); 1206 } 1207 1208 KASSERT(PCB_USER_FPU(td->td_pcb), 1209 ("System call %s returning with kernel FPU ctx leaked", 1210 syscallname(td->td_proc, td->td_sa.code))); 1211 KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td), 1212 ("System call %s returning with mangled pcb_save", 1213 syscallname(td->td_proc, td->td_sa.code))); 1214 KASSERT(pmap_not_in_di(), 1215 ("System call %s returning with leaked invl_gen %lu", 1216 syscallname(td->td_proc, td->td_sa.code), 1217 td->td_md.md_invl_gen.gen)); 1218 1219 syscallret(td); 1220 1221 /* 1222 * If the user-supplied value of %rip is not a canonical 1223 * address, then some CPUs will trigger a ring 0 #GP during 1224 * the sysret instruction. However, the fault handler would 1225 * execute in ring 0 with the user's %gs and %rsp which would 1226 * not be safe. Instead, use the full return path which 1227 * catches the problem safely. 1228 */ 1229 if (__predict_false(td->td_frame->tf_rip >= (la57 ? 1230 VM_MAXUSER_ADDRESS_LA57 : VM_MAXUSER_ADDRESS_LA48))) 1231 set_pcb_flags(td->td_pcb, PCB_FULL_IRET); 1232 1233 amd64_syscall_ret_flush_l1d_check_inline(td->td_errno); 1234 } 1235