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