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