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