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