xref: /freebsd/sys/i386/i386/trap.c (revision 4d3fc8b0)
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  * 386 Trap and System call handling
47  */
48 
49 #include "opt_clock.h"
50 #include "opt_cpu.h"
51 #include "opt_hwpmc_hooks.h"
52 #include "opt_isa.h"
53 #include "opt_kdb.h"
54 #include "opt_trap.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 #include <security/audit/audit.h>
80 
81 #include <vm/vm.h>
82 #include <vm/vm_param.h>
83 #include <vm/pmap.h>
84 #include <vm/vm_kern.h>
85 #include <vm/vm_map.h>
86 #include <vm/vm_page.h>
87 #include <vm/vm_extern.h>
88 
89 #include <machine/cpu.h>
90 #include <machine/intr_machdep.h>
91 #include <x86/mca.h>
92 #include <machine/md_var.h>
93 #include <machine/pcb.h>
94 #ifdef SMP
95 #include <machine/smp.h>
96 #endif
97 #include <machine/stack.h>
98 #include <machine/trap.h>
99 #include <machine/tss.h>
100 #include <machine/vm86.h>
101 
102 #ifdef POWERFAIL_NMI
103 #include <sys/syslog.h>
104 #include <machine/clock.h>
105 #endif
106 
107 #ifdef KDTRACE_HOOKS
108 #include <sys/dtrace_bsd.h>
109 #endif
110 
111 void trap(struct trapframe *frame);
112 void syscall(struct trapframe *frame);
113 
114 static int trap_pfault(struct trapframe *, bool, vm_offset_t, 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 void dblfault_handler(void);
121 
122 extern inthand_t IDTVEC(bpt), IDTVEC(dbg), IDTVEC(int0x80_syscall);
123 extern uint64_t pg_nx;
124 
125 struct trap_data {
126 	bool		ei;
127 	const char	*msg;
128 };
129 
130 static const struct trap_data trap_data[] = {
131 	[T_PRIVINFLT] =	{ .ei = true,	.msg = "privileged instruction fault" },
132 	[T_BPTFLT] =	{ .ei = false,	.msg = "breakpoint instruction fault" },
133 	[T_ARITHTRAP] =	{ .ei = true,	.msg = "arithmetic trap" },
134 	[T_PROTFLT] =	{ .ei = true,	.msg = "general protection fault" },
135 	[T_TRCTRAP] =	{ .ei = false,	.msg = "debug exception" },
136 	[T_PAGEFLT] =	{ .ei = true,	.msg = "page fault" },
137 	[T_ALIGNFLT] = 	{ .ei = true,	.msg = "alignment fault" },
138 	[T_DIVIDE] =	{ .ei = true,	.msg = "integer divide fault" },
139 	[T_NMI] =	{ .ei = false,	.msg = "non-maskable interrupt trap" },
140 	[T_OFLOW] =	{ .ei = true,	.msg = "overflow trap" },
141 	[T_BOUND] =	{ .ei = true,	.msg = "FPU bounds check fault" },
142 	[T_DNA] =	{ .ei = true,	.msg = "FPU device not available" },
143 	[T_DOUBLEFLT] =	{ .ei = false,	.msg = "double fault" },
144 	[T_FPOPFLT] =	{ .ei = true,	.msg = "FPU operand fetch fault" },
145 	[T_TSSFLT] =	{ .ei = true,	.msg = "invalid TSS fault" },
146 	[T_SEGNPFLT] =	{ .ei = true,	.msg = "segment not present fault" },
147 	[T_STKFLT] =	{ .ei = true,	.msg = "stack fault" },
148 	[T_MCHK] =	{ .ei = true,	.msg = "machine check trap" },
149 	[T_XMMFLT] =	{ .ei = true,	.msg = "SIMD floating-point exception" },
150 	[T_DTRACE_RET] ={ .ei = true,	.msg = "DTrace pid return trap" },
151 };
152 
153 static bool
154 trap_enable_intr(int trapno)
155 {
156 
157 	MPASS(trapno > 0);
158 	if (trapno < nitems(trap_data) && trap_data[trapno].msg != NULL)
159 		return (trap_data[trapno].ei);
160 	return (false);
161 }
162 
163 static const char *
164 trap_msg(int trapno)
165 {
166 	const char *res;
167 	static const char unkn[] = "UNKNOWN";
168 
169 	res = NULL;
170 	if (trapno < nitems(trap_data))
171 		res = trap_data[trapno].msg;
172 	if (res == NULL)
173 		res = unkn;
174 	return (res);
175 }
176 
177 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
178 int has_f00f_bug = 0;		/* Initialized so that it can be patched. */
179 #endif
180 
181 static int uprintf_signal;
182 SYSCTL_INT(_machdep, OID_AUTO, uprintf_signal, CTLFLAG_RW,
183     &uprintf_signal, 0,
184     "Print debugging information on trap signal to ctty");
185 
186 
187 #ifdef INVARIANTS
188 static __inline register_t
189 read_esp(void)
190 {
191 	register_t res;
192 
193 	__asm __volatile("movl\t%%esp,%0" : "=r" (res));
194 	return (res);
195 }
196 
197 void
198 trap_check_kstack(void)
199 {
200 	struct thread *td;
201 	vm_offset_t stk;
202 
203 	td = curthread;
204 	stk = read_esp();
205 	if (stk >= PMAP_TRM_MIN_ADDRESS)
206 		panic("td %p stack %#x in trampoline", td, stk);
207 	if (!kstack_contains(td, stk, 0))
208 		panic("td %p stack %#x not in kstack VA %#x %d",
209 		    td, stk, td->td_kstack, td->td_kstack_pages);
210 }
211 #endif
212 
213 /*
214  * Exception, fault, and trap interface to the FreeBSD kernel.
215  * This common code is called from assembly language IDT gate entry
216  * routines that prepare a suitable stack frame, and restore this
217  * frame after the exception has been processed.
218  */
219 
220 void
221 trap(struct trapframe *frame)
222 {
223 	ksiginfo_t ksi;
224 	struct thread *td;
225 	struct proc *p;
226 	int pf, signo, ucode;
227 	u_int type;
228 	register_t addr, dr6;
229 	vm_offset_t eva;
230 #ifdef POWERFAIL_NMI
231 	static int lastalert = 0;
232 #endif
233 
234 	td = curthread;
235 	p = td->td_proc;
236 	dr6 = 0;
237 
238 	VM_CNT_INC(v_trap);
239 	type = frame->tf_trapno;
240 
241 	KASSERT((read_eflags() & PSL_I) == 0,
242 	    ("trap: interrupts enabled, type %d frame %p", type, frame));
243 
244 #ifdef SMP
245 	/* Handler for NMI IPIs used for stopping CPUs. */
246 	if (type == T_NMI && ipi_nmi_handler() == 0)
247 		return;
248 #endif /* SMP */
249 
250 #ifdef KDB
251 	if (kdb_active) {
252 		kdb_reenter();
253 		return;
254 	}
255 #endif
256 	trap_check_kstack();
257 
258 	if (type == T_RESERVED) {
259 		trap_fatal(frame, 0);
260 		return;
261 	}
262 
263 	if (type == T_NMI) {
264 #ifdef HWPMC_HOOKS
265 		/*
266 		 * CPU PMCs interrupt using an NMI so we check for that first.
267 		 * If the HWPMC module is active, 'pmc_hook' will point to
268 		 * the function to be called.  A non-zero return value from the
269 		 * hook means that the NMI was consumed by it and that we can
270 		 * return immediately.
271 		 */
272 		if (pmc_intr != NULL &&
273 		    (*pmc_intr)(frame) != 0)
274 			return;
275 #endif
276 	}
277 
278 	if (type == T_MCHK) {
279 		mca_intr();
280 		return;
281 	}
282 
283 #ifdef KDTRACE_HOOKS
284 	/*
285 	 * A trap can occur while DTrace executes a probe. Before
286 	 * executing the probe, DTrace blocks re-scheduling and sets
287 	 * a flag in its per-cpu flags to indicate that it doesn't
288 	 * want to fault. On returning from the probe, the no-fault
289 	 * flag is cleared and finally re-scheduling is enabled.
290 	 */
291 	if ((type == T_PROTFLT || type == T_PAGEFLT) &&
292 	    dtrace_trap_func != NULL && (*dtrace_trap_func)(frame, type))
293 		return;
294 #endif
295 
296 	/*
297 	 * We must not allow context switches until %cr2 is read.
298 	 * Also, for some Cyrix CPUs, %cr2 is clobbered by interrupts.
299 	 * All faults use interrupt gates, so %cr2 can be safely read
300 	 * now, before optional enable of the interrupts below.
301 	 */
302 	if (type == T_PAGEFLT)
303 		eva = rcr2();
304 
305 	/*
306 	 * Buggy application or kernel code has disabled interrupts
307 	 * and then trapped.  Enabling interrupts now is wrong, but it
308 	 * is better than running with interrupts disabled until they
309 	 * are accidentally enabled later.
310 	 */
311 	if ((frame->tf_eflags & PSL_I) == 0 && TRAPF_USERMODE(frame) &&
312 	    (curpcb->pcb_flags & PCB_VM86CALL) == 0)
313 		uprintf("pid %ld (%s): usermode trap %d (%s) with "
314 		    "interrupts disabled\n",
315 		    (long)curproc->p_pid, curthread->td_name, type,
316 		    trap_data[type].msg);
317 
318 	/*
319 	 * Conditionally reenable interrupts.  If we hold a spin lock,
320 	 * then we must not reenable interrupts.  This might be a
321 	 * spurious page fault.
322 	 */
323 	if (trap_enable_intr(type) && td->td_md.md_spinlock_count == 0 &&
324 	    frame->tf_eip != (int)cpu_switch_load_gs)
325 		enable_intr();
326 
327         if (TRAPF_USERMODE(frame) && (curpcb->pcb_flags & PCB_VM86CALL) == 0) {
328 		/* user trap */
329 
330 		td->td_pticks = 0;
331 		td->td_frame = frame;
332 		addr = frame->tf_eip;
333 		if (td->td_cowgen != atomic_load_int(&p->p_cowgen))
334 			thread_cow_update(td);
335 
336 		switch (type) {
337 		case T_PRIVINFLT:	/* privileged instruction fault */
338 			signo = SIGILL;
339 			ucode = ILL_PRVOPC;
340 			break;
341 
342 		case T_BPTFLT:		/* bpt instruction fault */
343 #ifdef KDTRACE_HOOKS
344 			if (trap_user_dtrace(frame, &dtrace_pid_probe_ptr))
345 				return;
346 #else
347 			enable_intr();
348 #endif
349 			signo = SIGTRAP;
350 			ucode = TRAP_BRKPT;
351 			break;
352 
353 		case T_TRCTRAP:		/* debug exception */
354 			enable_intr();
355 user_trctrap_out:
356 			signo = SIGTRAP;
357 			ucode = TRAP_TRACE;
358 			dr6 = rdr6();
359 			if ((dr6 & DBREG_DR6_BS) != 0) {
360 				PROC_LOCK(td->td_proc);
361 				if ((td->td_dbgflags & TDB_STEP) != 0) {
362 					td->td_frame->tf_eflags &= ~PSL_T;
363 					td->td_dbgflags &= ~TDB_STEP;
364 				}
365 				PROC_UNLOCK(td->td_proc);
366 			}
367 			break;
368 
369 		case T_ARITHTRAP:	/* arithmetic trap */
370 			ucode = npxtrap_x87();
371 			if (ucode == -1)
372 				return;
373 			signo = SIGFPE;
374 			break;
375 
376 		/*
377 		 * The following two traps can happen in vm86 mode,
378 		 * and, if so, we want to handle them specially.
379 		 */
380 		case T_PROTFLT:		/* general protection fault */
381 		case T_STKFLT:		/* stack fault */
382 			if (frame->tf_eflags & PSL_VM) {
383 				signo = vm86_emulate((struct vm86frame *)frame);
384 				ucode = 0;	/* XXXKIB: better code ? */
385 				if (signo == SIGTRAP) {
386 					load_dr6(rdr6() | 0x4000);
387 					goto user_trctrap_out;
388 				}
389 				if (signo == 0)
390 					goto user;
391 				break;
392 			}
393 			signo = SIGBUS;
394 			ucode = (type == T_PROTFLT) ? BUS_OBJERR : BUS_ADRERR;
395 			break;
396 		case T_SEGNPFLT:	/* segment not present fault */
397 			signo = SIGBUS;
398 			ucode = BUS_ADRERR;
399 			break;
400 		case T_TSSFLT:		/* invalid TSS fault */
401 			signo = SIGBUS;
402 			ucode = BUS_OBJERR;
403 			break;
404 		case T_ALIGNFLT:
405 			signo = SIGBUS;
406 			ucode = BUS_ADRALN;
407 			break;
408 		case T_DOUBLEFLT:	/* double fault */
409 		default:
410 			signo = SIGBUS;
411 			ucode = BUS_OBJERR;
412 			break;
413 
414 		case T_PAGEFLT:		/* page fault */
415 			addr = eva;
416 			pf = trap_pfault(frame, true, eva, &signo, &ucode);
417 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
418 			if (pf == -2) {
419 				/*
420 				 * The f00f hack workaround has triggered, so
421 				 * treat the fault as an illegal instruction
422 				 * (T_PRIVINFLT) instead of a page fault.
423 				 */
424 				type = frame->tf_trapno = T_PRIVINFLT;
425 				break;
426 			}
427 #endif
428 			if (pf == -1)
429 				return;
430 			if (pf == 0)
431 				goto user;
432 			break;
433 
434 		case T_DIVIDE:		/* integer divide fault */
435 			ucode = FPE_INTDIV;
436 			signo = SIGFPE;
437 			break;
438 
439 		case T_NMI:
440 #ifdef POWERFAIL_NMI
441 #ifndef TIMER_FREQ
442 #  define TIMER_FREQ 1193182
443 #endif
444 			if (time_second - lastalert > 10) {
445 				log(LOG_WARNING, "NMI: power fail\n");
446 				sysbeep(880, SBT_1S);
447 				lastalert = time_second;
448 			}
449 			return;
450 #else /* !POWERFAIL_NMI */
451 			nmi_handle_intr(type, frame);
452 			return;
453 #endif /* POWERFAIL_NMI */
454 
455 		case T_OFLOW:		/* integer overflow fault */
456 			ucode = FPE_INTOVF;
457 			signo = SIGFPE;
458 			break;
459 
460 		case T_BOUND:		/* bounds check fault */
461 			ucode = FPE_FLTSUB;
462 			signo = SIGFPE;
463 			break;
464 
465 		case T_DNA:
466 			KASSERT(PCB_USER_FPU(td->td_pcb),
467 			    ("kernel FPU ctx has leaked"));
468 			/* transparent fault (due to context switch "late") */
469 			if (npxdna())
470 				return;
471 			uprintf("pid %d killed due to lack of floating point\n",
472 				p->p_pid);
473 			signo = SIGKILL;
474 			ucode = 0;
475 			break;
476 
477 		case T_FPOPFLT:		/* FPU operand fetch fault */
478 			ucode = ILL_COPROC;
479 			signo = SIGILL;
480 			break;
481 
482 		case T_XMMFLT:		/* SIMD floating-point exception */
483 			ucode = npxtrap_sse();
484 			if (ucode == -1)
485 				return;
486 			signo = SIGFPE;
487 			break;
488 #ifdef KDTRACE_HOOKS
489 		case T_DTRACE_RET:
490 			(void)trap_user_dtrace(frame, &dtrace_return_probe_ptr);
491 			return;
492 #endif
493 		}
494 	} else {
495 		/* kernel trap */
496 
497 		KASSERT(cold || td->td_ucred != NULL,
498 		    ("kernel trap doesn't have ucred"));
499 		switch (type) {
500 		case T_PAGEFLT:			/* page fault */
501 			(void)trap_pfault(frame, false, eva, NULL, NULL);
502 			return;
503 
504 		case T_DNA:
505 			if (PCB_USER_FPU(td->td_pcb))
506 				panic("Unregistered use of FPU in kernel");
507 			if (npxdna())
508 				return;
509 			break;
510 
511 		case T_ARITHTRAP:	/* arithmetic trap */
512 		case T_XMMFLT:		/* SIMD floating-point exception */
513 		case T_FPOPFLT:		/* FPU operand fetch fault */
514 			/*
515 			 * XXXKIB for now disable any FPU traps in kernel
516 			 * handler registration seems to be overkill
517 			 */
518 			trap_fatal(frame, 0);
519 			return;
520 
521 			/*
522 			 * The following two traps can happen in
523 			 * vm86 mode, and, if so, we want to handle
524 			 * them specially.
525 			 */
526 		case T_PROTFLT:		/* general protection fault */
527 		case T_STKFLT:		/* stack fault */
528 			if (frame->tf_eflags & PSL_VM) {
529 				signo = vm86_emulate((struct vm86frame *)frame);
530 				if (signo == SIGTRAP) {
531 					type = T_TRCTRAP;
532 					load_dr6(rdr6() | 0x4000);
533 					goto kernel_trctrap;
534 				}
535 				if (signo != 0)
536 					/*
537 					 * returns to original process
538 					 */
539 					vm86_trap((struct vm86frame *)frame);
540 				return;
541 			}
542 			/* FALL THROUGH */
543 		case T_SEGNPFLT:	/* segment not present fault */
544 			if (curpcb->pcb_flags & PCB_VM86CALL)
545 				break;
546 
547 			/*
548 			 * Invalid %fs's and %gs's can be created using
549 			 * procfs or PT_SETREGS or by invalidating the
550 			 * underlying LDT entry.  This causes a fault
551 			 * in kernel mode when the kernel attempts to
552 			 * switch contexts.  Lose the bad context
553 			 * (XXX) so that we can continue, and generate
554 			 * a signal.
555 			 */
556 			if (frame->tf_eip == (int)cpu_switch_load_gs) {
557 				curpcb->pcb_gs = 0;
558 #if 0
559 				PROC_LOCK(p);
560 				kern_psignal(p, SIGBUS);
561 				PROC_UNLOCK(p);
562 #endif
563 				return;
564 			}
565 
566 			if (td->td_intr_nesting_level != 0)
567 				break;
568 
569 			/*
570 			 * Invalid segment selectors and out of bounds
571 			 * %eip's and %esp's can be set up in user mode.
572 			 * This causes a fault in kernel mode when the
573 			 * kernel tries to return to user mode.  We want
574 			 * to get this fault so that we can fix the
575 			 * problem here and not have to check all the
576 			 * selectors and pointers when the user changes
577 			 * them.
578 			 *
579 			 * N.B. Comparing to long mode, 32-bit mode
580 			 * does not push %esp on the trap frame,
581 			 * because iretl faulted while in ring 0.  As
582 			 * the consequence, there is no need to fixup
583 			 * the stack pointer for doreti_iret_fault,
584 			 * the fixup and the complimentary trap() call
585 			 * are executed on the main thread stack, not
586 			 * on the trampoline stack.
587 			 */
588 			if (frame->tf_eip == (int)doreti_iret + setidt_disp) {
589 				frame->tf_eip = (int)doreti_iret_fault +
590 				    setidt_disp;
591 				return;
592 			}
593 			if (type == T_STKFLT)
594 				break;
595 
596 			if (frame->tf_eip == (int)doreti_popl_ds +
597 			    setidt_disp) {
598 				frame->tf_eip = (int)doreti_popl_ds_fault +
599 				    setidt_disp;
600 				return;
601 			}
602 			if (frame->tf_eip == (int)doreti_popl_es +
603 			    setidt_disp) {
604 				frame->tf_eip = (int)doreti_popl_es_fault +
605 				    setidt_disp;
606 				return;
607 			}
608 			if (frame->tf_eip == (int)doreti_popl_fs +
609 			    setidt_disp) {
610 				frame->tf_eip = (int)doreti_popl_fs_fault +
611 				    setidt_disp;
612 				return;
613 			}
614 			if (curpcb->pcb_onfault != NULL) {
615 				frame->tf_eip = (int)curpcb->pcb_onfault;
616 				return;
617 			}
618 			break;
619 
620 		case T_TSSFLT:
621 			/*
622 			 * PSL_NT can be set in user mode and isn't cleared
623 			 * automatically when the kernel is entered.  This
624 			 * causes a TSS fault when the kernel attempts to
625 			 * `iret' because the TSS link is uninitialized.  We
626 			 * want to get this fault so that we can fix the
627 			 * problem here and not every time the kernel is
628 			 * entered.
629 			 */
630 			if (frame->tf_eflags & PSL_NT) {
631 				frame->tf_eflags &= ~PSL_NT;
632 				return;
633 			}
634 			break;
635 
636 		case T_TRCTRAP:	 /* debug exception */
637 kernel_trctrap:
638 			/* Clear any pending debug events. */
639 			dr6 = rdr6();
640 			load_dr6(0);
641 
642 			/*
643 			 * Ignore debug register exceptions due to
644 			 * accesses in the user's address space, which
645 			 * can happen under several conditions such as
646 			 * if a user sets a watchpoint on a buffer and
647 			 * then passes that buffer to a system call.
648 			 * We still want to get TRCTRAPS for addresses
649 			 * in kernel space because that is useful when
650 			 * debugging the kernel.
651 			 */
652 			if (user_dbreg_trap(dr6) &&
653 			   !(curpcb->pcb_flags & PCB_VM86CALL))
654 				return;
655 
656 			/*
657 			 * Malicious user code can configure a debug
658 			 * register watchpoint to trap on data access
659 			 * to the top of stack and then execute 'pop
660 			 * %ss; int 3'.  Due to exception deferral for
661 			 * 'pop %ss', the CPU will not interrupt 'int
662 			 * 3' to raise the DB# exception for the debug
663 			 * register but will postpone the DB# until
664 			 * execution of the first instruction of the
665 			 * BP# handler (in kernel mode).  Normally the
666 			 * previous check would ignore DB# exceptions
667 			 * for watchpoints on user addresses raised in
668 			 * kernel mode.  However, some CPU errata
669 			 * include cases where DB# exceptions do not
670 			 * properly set bits in %dr6, e.g. Haswell
671 			 * HSD23 and Skylake-X SKZ24.
672 			 *
673 			 * A deferred DB# can also be raised on the
674 			 * first instructions of system call entry
675 			 * points or single-step traps via similar use
676 			 * of 'pop %ss' or 'mov xxx, %ss'.
677 			 */
678 			if (frame->tf_eip ==
679 			    (uintptr_t)IDTVEC(int0x80_syscall) + setidt_disp ||
680 			    frame->tf_eip == (uintptr_t)IDTVEC(bpt) +
681 			    setidt_disp ||
682 			    frame->tf_eip == (uintptr_t)IDTVEC(dbg) +
683 			    setidt_disp)
684 				return;
685 			/*
686 			 * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
687 			 */
688 		case T_BPTFLT:
689 			/*
690 			 * If KDB is enabled, let it handle the debugger trap.
691 			 * Otherwise, debugger traps "can't happen".
692 			 */
693 #ifdef KDB
694 			if (kdb_trap(type, dr6, frame))
695 				return;
696 #endif
697 			break;
698 
699 		case T_NMI:
700 #ifdef POWERFAIL_NMI
701 			if (time_second - lastalert > 10) {
702 				log(LOG_WARNING, "NMI: power fail\n");
703 				sysbeep(880, SBT_1S);
704 				lastalert = time_second;
705 			}
706 			return;
707 #else /* !POWERFAIL_NMI */
708 			nmi_handle_intr(type, frame);
709 			return;
710 #endif /* POWERFAIL_NMI */
711 		}
712 
713 		trap_fatal(frame, eva);
714 		return;
715 	}
716 
717 	ksiginfo_init_trap(&ksi);
718 	ksi.ksi_signo = signo;
719 	ksi.ksi_code = ucode;
720 	ksi.ksi_addr = (void *)addr;
721 	ksi.ksi_trapno = type;
722 	if (uprintf_signal) {
723 		uprintf("pid %d comm %s: signal %d err %#x code %d type %d "
724 		    "addr %#x ss %#04x esp %#08x cs %#04x eip %#08x eax %#08x"
725 		    "<%02x %02x %02x %02x %02x %02x %02x %02x>\n",
726 		    p->p_pid, p->p_comm, signo, frame->tf_err, ucode, type,
727 		    addr, frame->tf_ss, frame->tf_esp, frame->tf_cs,
728 		    frame->tf_eip, frame->tf_eax,
729 		    fubyte((void *)(frame->tf_eip + 0)),
730 		    fubyte((void *)(frame->tf_eip + 1)),
731 		    fubyte((void *)(frame->tf_eip + 2)),
732 		    fubyte((void *)(frame->tf_eip + 3)),
733 		    fubyte((void *)(frame->tf_eip + 4)),
734 		    fubyte((void *)(frame->tf_eip + 5)),
735 		    fubyte((void *)(frame->tf_eip + 6)),
736 		    fubyte((void *)(frame->tf_eip + 7)));
737 	}
738 	KASSERT((read_eflags() & PSL_I) != 0, ("interrupts disabled"));
739 	trapsignal(td, &ksi);
740 
741 user:
742 	userret(td, frame);
743 	KASSERT(PCB_USER_FPU(td->td_pcb),
744 	    ("Return from trap with kernel FPU ctx leaked"));
745 }
746 
747 /*
748  * Handle all details of a page fault.
749  * Returns:
750  * -2 if the fault was caused by triggered workaround for Intel Pentium
751  *    0xf00f bug.
752  * -1 if this fault was fatal, typically from kernel mode
753  *    (cannot happen, but we need to return something).
754  * 0  if this fault was handled by updating either the user or kernel
755  *    page table, execution can continue.
756  * 1  if this fault was from usermode and it was not handled, a synchronous
757  *    signal should be delivered to the thread.  *signo returns the signal
758  *    number, *ucode gives si_code.
759  */
760 static int
761 trap_pfault(struct trapframe *frame, bool usermode, vm_offset_t eva,
762     int *signo, int *ucode)
763 {
764 	struct thread *td;
765 	struct proc *p;
766 	vm_map_t map;
767 	int rv;
768 	vm_prot_t ftype;
769 
770 	MPASS(!usermode || (signo != NULL && ucode != NULL));
771 
772 	td = curthread;
773 	p = td->td_proc;
774 
775 	if (__predict_false((td->td_pflags & TDP_NOFAULTING) != 0)) {
776 		/*
777 		 * Due to both processor errata and lazy TLB invalidation when
778 		 * access restrictions are removed from virtual pages, memory
779 		 * accesses that are allowed by the physical mapping layer may
780 		 * nonetheless cause one spurious page fault per virtual page.
781 		 * When the thread is executing a "no faulting" section that
782 		 * is bracketed by vm_fault_{disable,enable}_pagefaults(),
783 		 * every page fault is treated as a spurious page fault,
784 		 * unless it accesses the same virtual address as the most
785 		 * recent page fault within the same "no faulting" section.
786 		 */
787 		if (td->td_md.md_spurflt_addr != eva ||
788 		    (td->td_pflags & TDP_RESETSPUR) != 0) {
789 			/*
790 			 * Do nothing to the TLB.  A stale TLB entry is
791 			 * flushed automatically by a page fault.
792 			 */
793 			td->td_md.md_spurflt_addr = eva;
794 			td->td_pflags &= ~TDP_RESETSPUR;
795 			return (0);
796 		}
797 	} else {
798 		/*
799 		 * If we get a page fault while in a critical section, then
800 		 * it is most likely a fatal kernel page fault.  The kernel
801 		 * is already going to panic trying to get a sleep lock to
802 		 * do the VM lookup, so just consider it a fatal trap so the
803 		 * kernel can print out a useful trap message and even get
804 		 * to the debugger.
805 		 *
806 		 * If we get a page fault while holding a non-sleepable
807 		 * lock, then it is most likely a fatal kernel page fault.
808 		 * If WITNESS is enabled, then it's going to whine about
809 		 * bogus LORs with various VM locks, so just skip to the
810 		 * fatal trap handling directly.
811 		 */
812 		if (td->td_critnest != 0 ||
813 		    WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
814 		    "Kernel page fault") != 0) {
815 			trap_fatal(frame, eva);
816 			return (-1);
817 		}
818 	}
819 	if (eva >= PMAP_TRM_MIN_ADDRESS) {
820 		/*
821 		 * Don't allow user-mode faults in kernel address space.
822 		 * An exception:  if the faulting address is the invalid
823 		 * instruction entry in the IDT, then the Intel Pentium
824 		 * F00F bug workaround was triggered, and we need to
825 		 * treat it is as an illegal instruction, and not a page
826 		 * fault.
827 		 */
828 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
829 		if ((eva == (unsigned int)&idt[6]) && has_f00f_bug) {
830 			*ucode = ILL_PRVOPC;
831 			*signo = SIGILL;
832 			return (-2);
833 		}
834 #endif
835 		if (usermode) {
836 			*signo = SIGSEGV;
837 			*ucode = SEGV_MAPERR;
838 			return (1);
839 		}
840 		trap_fatal(frame, eva);
841 		return (-1);
842 	} else {
843 		map = usermode ? &p->p_vmspace->vm_map : kernel_map;
844 
845 		/*
846 		 * Kernel cannot access a user-space address directly
847 		 * because user pages are not mapped.  Also, page
848 		 * faults must not be caused during the interrupts.
849 		 */
850 		if (!usermode && td->td_intr_nesting_level != 0) {
851 			trap_fatal(frame, eva);
852 			return (-1);
853 		}
854 	}
855 
856 	/*
857 	 * If the trap was caused by errant bits in the PTE then panic.
858 	 */
859 	if (frame->tf_err & PGEX_RSV) {
860 		trap_fatal(frame, eva);
861 		return (-1);
862 	}
863 
864 	/*
865 	 * PGEX_I is defined only if the execute disable bit capability is
866 	 * supported and enabled.
867 	 */
868 	if (frame->tf_err & PGEX_W)
869 		ftype = VM_PROT_WRITE;
870 	else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
871 		ftype = VM_PROT_EXECUTE;
872 	else
873 		ftype = VM_PROT_READ;
874 
875 	/* Fault in the page. */
876 	rv = vm_fault_trap(map, eva, ftype, VM_FAULT_NORMAL, signo, ucode);
877 	if (rv == KERN_SUCCESS) {
878 #ifdef HWPMC_HOOKS
879 		if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
880 			PMC_SOFT_CALL_TF( , , page_fault, all, frame);
881 			if (ftype == VM_PROT_READ)
882 				PMC_SOFT_CALL_TF( , , page_fault, read,
883 				    frame);
884 			else
885 				PMC_SOFT_CALL_TF( , , page_fault, write,
886 				    frame);
887 		}
888 #endif
889 		return (0);
890 	}
891 	if (usermode)
892 		return (1);
893 	if (td->td_intr_nesting_level == 0 &&
894 	    curpcb->pcb_onfault != NULL) {
895 		frame->tf_eip = (int)curpcb->pcb_onfault;
896 		return (0);
897 	}
898 	trap_fatal(frame, eva);
899 	return (-1);
900 }
901 
902 static void
903 trap_fatal(struct trapframe *frame, vm_offset_t eva)
904 {
905 	int code, ss, esp;
906 	u_int type;
907 	struct soft_segment_descriptor softseg;
908 #ifdef KDB
909 	bool handled;
910 #endif
911 
912 	code = frame->tf_err;
913 	type = frame->tf_trapno;
914 	sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)].sd, &softseg);
915 
916 	printf("\n\nFatal trap %d: %s while in %s mode\n", type, trap_msg(type),
917 	    frame->tf_eflags & PSL_VM ? "vm86" :
918 	    ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
919 #ifdef SMP
920 	/* two separate prints in case of a trap on an unmapped page */
921 	printf("cpuid = %d; ", PCPU_GET(cpuid));
922 	printf("apic id = %02x\n", PCPU_GET(apic_id));
923 #endif
924 	if (type == T_PAGEFLT) {
925 		printf("fault virtual address	= 0x%x\n", eva);
926 		printf("fault code		= %s %s%s, %s\n",
927 			code & PGEX_U ? "user" : "supervisor",
928 			code & PGEX_W ? "write" : "read",
929 			pg_nx != 0 ?
930 			(code & PGEX_I ? " instruction" : " data") :
931 			"",
932 			code & PGEX_RSV ? "reserved bits in PTE" :
933 			code & PGEX_P ? "protection violation" : "page not present");
934 	} else {
935 		printf("error code		= %#x\n", code);
936 	}
937 	printf("instruction pointer	= 0x%x:0x%x\n",
938 	       frame->tf_cs & 0xffff, frame->tf_eip);
939         if (TF_HAS_STACKREGS(frame)) {
940 		ss = frame->tf_ss & 0xffff;
941 		esp = frame->tf_esp;
942 	} else {
943 		ss = GSEL(GDATA_SEL, SEL_KPL);
944 		esp = (int)&frame->tf_esp;
945 	}
946 	printf("stack pointer	        = 0x%x:0x%x\n", ss, esp);
947 	printf("frame pointer	        = 0x%x:0x%x\n", ss, frame->tf_ebp);
948 	printf("code segment		= base 0x%x, limit 0x%x, type 0x%x\n",
949 	       softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
950 	printf("			= DPL %d, pres %d, def32 %d, gran %d\n",
951 	       softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_def32,
952 	       softseg.ssd_gran);
953 	printf("processor eflags	= ");
954 	if (frame->tf_eflags & PSL_T)
955 		printf("trace trap, ");
956 	if (frame->tf_eflags & PSL_I)
957 		printf("interrupt enabled, ");
958 	if (frame->tf_eflags & PSL_NT)
959 		printf("nested task, ");
960 	if (frame->tf_eflags & PSL_RF)
961 		printf("resume, ");
962 	if (frame->tf_eflags & PSL_VM)
963 		printf("vm86, ");
964 	printf("IOPL = %d\n", (frame->tf_eflags & PSL_IOPL) >> 12);
965 	printf("current process		= %d (%s)\n",
966 	    curproc->p_pid, curthread->td_name);
967 
968 #ifdef KDB
969 	if (debugger_on_trap) {
970 		kdb_why = KDB_WHY_TRAP;
971 		frame->tf_err = eva;	/* smuggle fault address to ddb */
972 		handled = kdb_trap(type, 0, frame);
973 		frame->tf_err = code;	/* restore error code */
974 		kdb_why = KDB_WHY_UNSET;
975 		if (handled)
976 			return;
977 	}
978 #endif
979 	printf("trap number		= %d\n", type);
980 	if (trap_msg(type) != NULL)
981 		panic("%s", trap_msg(type));
982 	else
983 		panic("unknown/reserved trap");
984 }
985 
986 #ifdef KDTRACE_HOOKS
987 /*
988  * Invoke a userspace DTrace hook.  The hook pointer is cleared when no
989  * userspace probes are enabled, so we must synchronize with DTrace to ensure
990  * that a trapping thread is able to call the hook before it is cleared.
991  */
992 static bool
993 trap_user_dtrace(struct trapframe *frame, int (**hookp)(struct trapframe *))
994 {
995 	int (*hook)(struct trapframe *);
996 
997 	hook = atomic_load_ptr(hookp);
998 	enable_intr();
999 	if (hook != NULL)
1000 		return ((hook)(frame) == 0);
1001 	return (false);
1002 }
1003 #endif
1004 
1005 /*
1006  * Double fault handler. Called when a fault occurs while writing
1007  * a frame for a trap/exception onto the stack. This usually occurs
1008  * when the stack overflows (such is the case with infinite recursion,
1009  * for example).
1010  *
1011  * XXX Note that the current PTD gets replaced by IdlePTD when the
1012  * task switch occurs. This means that the stack that was active at
1013  * the time of the double fault is not available at <kstack> unless
1014  * the machine was idle when the double fault occurred. The downside
1015  * of this is that "trace <ebp>" in ddb won't work.
1016  */
1017 void
1018 dblfault_handler(void)
1019 {
1020 	struct i386tss *t;
1021 
1022 #ifdef KDTRACE_HOOKS
1023 	if (dtrace_doubletrap_func != NULL)
1024 		(*dtrace_doubletrap_func)();
1025 #endif
1026 	printf("\nFatal double fault:\n");
1027 	t = PCPU_GET(common_tssp);
1028 	printf(
1029 	    "eip = %#08x esp = %#08x ebp = %#08x eax = %#08x\n"
1030 	    "edx = %#08x ecx = %#08x edi = %#08x esi = %#08x\n"
1031 	    "ebx = %#08x\n"
1032 	    "psl = %#08x cs  = %#08x ss  = %#08x ds  = %#08x\n"
1033 	    "es  = %#08x fs  = %#08x gs  = %#08x cr3 = %#08x\n",
1034 	    t->tss_eip, t->tss_esp, t->tss_ebp, t->tss_eax,
1035 	    t->tss_edx, t->tss_ecx, t->tss_edi, t->tss_esi,
1036 	    t->tss_ebx,
1037 	    t->tss_eflags, t->tss_cs, t->tss_ss, t->tss_ds,
1038 	    t->tss_es, t->tss_fs, t->tss_gs, t->tss_cr3);
1039 #ifdef SMP
1040 	printf("cpuid = %d; apic id = %02x\n", PCPU_GET(cpuid),
1041 	    PCPU_GET(apic_id));
1042 #endif
1043 	panic("double fault");
1044 }
1045 
1046 int
1047 cpu_fetch_syscall_args(struct thread *td)
1048 {
1049 	struct proc *p;
1050 	struct trapframe *frame;
1051 	struct syscall_args *sa;
1052 	caddr_t params;
1053 	long tmp;
1054 	int error;
1055 #ifdef COMPAT_43
1056 	u_int32_t eip;
1057 	int cs;
1058 #endif
1059 
1060 	p = td->td_proc;
1061 	frame = td->td_frame;
1062 	sa = &td->td_sa;
1063 
1064 #ifdef COMPAT_43
1065 	if (__predict_false(frame->tf_cs == 7 && frame->tf_eip == 2)) {
1066 		/*
1067 		 * In lcall $7,$0 after int $0x80.  Convert the user
1068 		 * frame to what it would be for a direct int 0x80 instead
1069 		 * of lcall $7,$0, by popping the lcall return address.
1070 		 */
1071 		error = fueword32((void *)frame->tf_esp, &eip);
1072 		if (error == -1)
1073 			return (EFAULT);
1074 		cs = fuword16((void *)(frame->tf_esp + sizeof(u_int32_t)));
1075 		if (cs == -1)
1076 			return (EFAULT);
1077 
1078 		/*
1079 		 * Unwind in-kernel frame after all stack frame pieces
1080 		 * were successfully read.
1081 		 */
1082 		frame->tf_eip = eip;
1083 		frame->tf_cs = cs;
1084 		frame->tf_esp += 2 * sizeof(u_int32_t);
1085 		frame->tf_err = 7;	/* size of lcall $7,$0 */
1086 	}
1087 #endif
1088 
1089 	sa->code = frame->tf_eax;
1090 	sa->original_code = sa->code;
1091 	params = (caddr_t)frame->tf_esp + sizeof(uint32_t);
1092 
1093 	/*
1094 	 * Need to check if this is a 32 bit or 64 bit syscall.
1095 	 */
1096 	if (sa->code == SYS_syscall) {
1097 		/*
1098 		 * Code is first argument, followed by actual args.
1099 		 */
1100 		error = fueword(params, &tmp);
1101 		if (error == -1)
1102 			return (EFAULT);
1103 		sa->code = tmp;
1104 		params += sizeof(uint32_t);
1105 	} else if (sa->code == SYS___syscall) {
1106 		/*
1107 		 * Like syscall, but code is a quad, so as to maintain
1108 		 * quad alignment for the rest of the arguments.
1109 		 */
1110 		error = fueword(params, &tmp);
1111 		if (error == -1)
1112 			return (EFAULT);
1113 		sa->code = tmp;
1114 		params += sizeof(quad_t);
1115 	}
1116 
1117  	if (sa->code >= p->p_sysent->sv_size)
1118  		sa->callp = &p->p_sysent->sv_table[0];
1119   	else
1120  		sa->callp = &p->p_sysent->sv_table[sa->code];
1121 
1122 	if (params != NULL && sa->callp->sy_narg != 0)
1123 		error = copyin(params, (caddr_t)sa->args,
1124 		    (u_int)(sa->callp->sy_narg * sizeof(uint32_t)));
1125 	else
1126 		error = 0;
1127 
1128 	if (error == 0) {
1129 		td->td_retval[0] = 0;
1130 		td->td_retval[1] = frame->tf_edx;
1131 	}
1132 
1133 	return (error);
1134 }
1135 
1136 #include "../../kern/subr_syscall.c"
1137 
1138 /*
1139  * syscall - system call request C handler.  A system call is
1140  * essentially treated as a trap by reusing the frame layout.
1141  */
1142 void
1143 syscall(struct trapframe *frame)
1144 {
1145 	struct thread *td;
1146 	register_t orig_tf_eflags;
1147 	ksiginfo_t ksi;
1148 
1149 #ifdef DIAGNOSTIC
1150 	if (!(TRAPF_USERMODE(frame) &&
1151 	    (curpcb->pcb_flags & PCB_VM86CALL) == 0)) {
1152 		panic("syscall");
1153 		/* NOT REACHED */
1154 	}
1155 #endif
1156 	trap_check_kstack();
1157 	orig_tf_eflags = frame->tf_eflags;
1158 
1159 	td = curthread;
1160 	td->td_frame = frame;
1161 
1162 	syscallenter(td);
1163 
1164 	/*
1165 	 * Traced syscall.
1166 	 */
1167 	if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1168 		frame->tf_eflags &= ~PSL_T;
1169 		ksiginfo_init_trap(&ksi);
1170 		ksi.ksi_signo = SIGTRAP;
1171 		ksi.ksi_code = TRAP_TRACE;
1172 		ksi.ksi_addr = (void *)frame->tf_eip;
1173 		trapsignal(td, &ksi);
1174 	}
1175 
1176 	KASSERT(PCB_USER_FPU(td->td_pcb),
1177 	    ("System call %s returning with kernel FPU ctx leaked",
1178 	     syscallname(td->td_proc, td->td_sa.code)));
1179 	KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td),
1180 	    ("System call %s returning with mangled pcb_save",
1181 	     syscallname(td->td_proc, td->td_sa.code)));
1182 
1183 	syscallret(td);
1184 }
1185