trap.c revision 308418
1/*-
2 * Copyright (C) 1994, David Greenman
3 * Copyright (c) 1990, 1993
4 *	The Regents of the University of California.  All rights reserved.
5 *
6 * This code is derived from software contributed to Berkeley by
7 * the University of Utah, and William Jolitz.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 *    must display the following acknowledgement:
19 *	This product includes software developed by the University of
20 *	California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 *    may be used to endorse or promote products derived from this software
23 *    without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
36 *
37 *	from: @(#)trap.c	7.4 (Berkeley) 5/13/91
38 */
39
40#include <sys/cdefs.h>
41__FBSDID("$FreeBSD: stable/11/sys/i386/i386/trap.c 308418 2016-11-07 12:10:17Z kib $");
42
43/*
44 * 386 Trap and System call handling
45 */
46
47#include "opt_clock.h"
48#include "opt_cpu.h"
49#include "opt_hwpmc_hooks.h"
50#include "opt_isa.h"
51#include "opt_kdb.h"
52#include "opt_npx.h"
53#include "opt_stack.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/pioctl.h>
61#include <sys/ptrace.h>
62#include <sys/kdb.h>
63#include <sys/kernel.h>
64#include <sys/ktr.h>
65#include <sys/lock.h>
66#include <sys/mutex.h>
67#include <sys/resourcevar.h>
68#include <sys/signalvar.h>
69#include <sys/syscall.h>
70#include <sys/sysctl.h>
71#include <sys/sysent.h>
72#include <sys/uio.h>
73#include <sys/vmmeter.h>
74#ifdef HWPMC_HOOKS
75#include <sys/pmckern.h>
76PMC_SOFT_DEFINE( , , page_fault, all);
77PMC_SOFT_DEFINE( , , page_fault, read);
78PMC_SOFT_DEFINE( , , page_fault, write);
79#endif
80#include <security/audit/audit.h>
81
82#include <vm/vm.h>
83#include <vm/vm_param.h>
84#include <vm/pmap.h>
85#include <vm/vm_kern.h>
86#include <vm/vm_map.h>
87#include <vm/vm_page.h>
88#include <vm/vm_extern.h>
89
90#include <machine/cpu.h>
91#include <machine/intr_machdep.h>
92#include <x86/mca.h>
93#include <machine/md_var.h>
94#include <machine/pcb.h>
95#ifdef SMP
96#include <machine/smp.h>
97#endif
98#include <machine/stack.h>
99#include <machine/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
111extern void trap(struct trapframe *frame);
112extern void syscall(struct trapframe *frame);
113
114static int trap_pfault(struct trapframe *, int, vm_offset_t);
115static void trap_fatal(struct trapframe *, vm_offset_t);
116void dblfault_handler(void);
117
118extern inthand_t IDTVEC(lcall_syscall);
119
120#define MAX_TRAP_MSG		32
121static char *trap_msg[] = {
122	"",					/*  0 unused */
123	"privileged instruction fault",		/*  1 T_PRIVINFLT */
124	"",					/*  2 unused */
125	"breakpoint instruction fault",		/*  3 T_BPTFLT */
126	"",					/*  4 unused */
127	"",					/*  5 unused */
128	"arithmetic trap",			/*  6 T_ARITHTRAP */
129	"",					/*  7 unused */
130	"",					/*  8 unused */
131	"general protection fault",		/*  9 T_PROTFLT */
132	"trace trap",				/* 10 T_TRCTRAP */
133	"",					/* 11 unused */
134	"page fault",				/* 12 T_PAGEFLT */
135	"",					/* 13 unused */
136	"alignment fault",			/* 14 T_ALIGNFLT */
137	"",					/* 15 unused */
138	"",					/* 16 unused */
139	"",					/* 17 unused */
140	"integer divide fault",			/* 18 T_DIVIDE */
141	"non-maskable interrupt trap",		/* 19 T_NMI */
142	"overflow trap",			/* 20 T_OFLOW */
143	"FPU bounds check fault",		/* 21 T_BOUND */
144	"FPU device not available",		/* 22 T_DNA */
145	"double fault",				/* 23 T_DOUBLEFLT */
146	"FPU operand fetch fault",		/* 24 T_FPOPFLT */
147	"invalid TSS fault",			/* 25 T_TSSFLT */
148	"segment not present fault",		/* 26 T_SEGNPFLT */
149	"stack fault",				/* 27 T_STKFLT */
150	"machine check trap",			/* 28 T_MCHK */
151	"SIMD floating-point exception",	/* 29 T_XMMFLT */
152	"reserved (unknown) fault",		/* 30 T_RESERVED */
153	"",					/* 31 unused (reserved) */
154	"DTrace pid return trap",               /* 32 T_DTRACE_RET */
155};
156
157#if defined(I586_CPU) && !defined(NO_F00F_HACK)
158int has_f00f_bug = 0;		/* Initialized so that it can be patched. */
159#endif
160
161#ifdef KDB
162static int kdb_on_nmi = 1;
163SYSCTL_INT(_machdep, OID_AUTO, kdb_on_nmi, CTLFLAG_RWTUN,
164	&kdb_on_nmi, 0, "Go to KDB on NMI");
165#endif
166static int panic_on_nmi = 1;
167SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RWTUN,
168	&panic_on_nmi, 0, "Panic on NMI");
169static int prot_fault_translation = 0;
170SYSCTL_INT(_machdep, OID_AUTO, prot_fault_translation, CTLFLAG_RW,
171	&prot_fault_translation, 0, "Select signal to deliver on protection fault");
172static int uprintf_signal;
173SYSCTL_INT(_machdep, OID_AUTO, uprintf_signal, CTLFLAG_RW,
174    &uprintf_signal, 0,
175    "Print debugging information on trap signal to ctty");
176
177/*
178 * Exception, fault, and trap interface to the FreeBSD kernel.
179 * This common code is called from assembly language IDT gate entry
180 * routines that prepare a suitable stack frame, and restore this
181 * frame after the exception has been processed.
182 */
183
184void
185trap(struct trapframe *frame)
186{
187#ifdef KDTRACE_HOOKS
188	struct reg regs;
189#endif
190	struct thread *td = curthread;
191	struct proc *p = td->td_proc;
192#ifdef KDB
193	register_t dr6;
194#endif
195	int i = 0, ucode = 0;
196	u_int type;
197	register_t addr = 0;
198	vm_offset_t eva;
199	ksiginfo_t ksi;
200#ifdef POWERFAIL_NMI
201	static int lastalert = 0;
202#endif
203
204	PCPU_INC(cnt.v_trap);
205	type = frame->tf_trapno;
206
207#ifdef SMP
208	/* Handler for NMI IPIs used for stopping CPUs. */
209	if (type == T_NMI) {
210	         if (ipi_nmi_handler() == 0)
211	                   goto out;
212	}
213#endif /* SMP */
214
215#ifdef KDB
216	if (kdb_active) {
217		kdb_reenter();
218		goto out;
219	}
220#endif
221
222	if (type == T_RESERVED) {
223		trap_fatal(frame, 0);
224		goto out;
225	}
226
227	if (type == T_NMI) {
228#ifdef HWPMC_HOOKS
229		/*
230		 * CPU PMCs interrupt using an NMI so we check for that first.
231		 * If the HWPMC module is active, 'pmc_hook' will point to
232		 * the function to be called.  A non-zero return value from the
233		 * hook means that the NMI was consumed by it and that we can
234		 * return immediately.
235		 */
236		if (pmc_intr != NULL &&
237		    (*pmc_intr)(PCPU_GET(cpuid), frame) != 0)
238			goto out;
239#endif
240
241#ifdef STACK
242		if (stack_nmi_handler(frame) != 0)
243			goto out;
244#endif
245	}
246
247	if (type == T_MCHK) {
248		mca_intr();
249		goto out;
250	}
251
252#ifdef KDTRACE_HOOKS
253	/*
254	 * A trap can occur while DTrace executes a probe. Before
255	 * executing the probe, DTrace blocks re-scheduling and sets
256	 * a flag in its per-cpu flags to indicate that it doesn't
257	 * want to fault. On returning from the probe, the no-fault
258	 * flag is cleared and finally re-scheduling is enabled.
259	 */
260	if ((type == T_PROTFLT || type == T_PAGEFLT) &&
261	    dtrace_trap_func != NULL && (*dtrace_trap_func)(frame, type))
262		goto out;
263#endif
264
265	if ((frame->tf_eflags & PSL_I) == 0) {
266		/*
267		 * Buggy application or kernel code has disabled
268		 * interrupts and then trapped.  Enabling interrupts
269		 * now is wrong, but it is better than running with
270		 * interrupts disabled until they are accidentally
271		 * enabled later.
272		 */
273		if (TRAPF_USERMODE(frame) &&
274		    (curpcb->pcb_flags & PCB_VM86CALL) == 0)
275			uprintf(
276			    "pid %ld (%s): trap %d with interrupts disabled\n",
277			    (long)curproc->p_pid, curthread->td_name, type);
278		else if (type != T_NMI && type != T_BPTFLT &&
279		    type != T_TRCTRAP &&
280		    frame->tf_eip != (int)cpu_switch_load_gs) {
281			/*
282			 * XXX not quite right, since this may be for a
283			 * multiple fault in user mode.
284			 */
285			printf("kernel trap %d with interrupts disabled\n",
286			    type);
287			/*
288			 * Page faults need interrupts disabled until later,
289			 * and we shouldn't enable interrupts while holding
290			 * a spin lock.
291			 */
292			if (type != T_PAGEFLT &&
293			    td->td_md.md_spinlock_count == 0)
294				enable_intr();
295		}
296	}
297	eva = 0;
298	if (type == T_PAGEFLT) {
299		/*
300		 * For some Cyrix CPUs, %cr2 is clobbered by
301		 * interrupts.  This problem is worked around by using
302		 * an interrupt gate for the pagefault handler.  We
303		 * are finally ready to read %cr2 and conditionally
304		 * reenable interrupts.  If we hold a spin lock, then
305		 * we must not reenable interrupts.  This might be a
306		 * spurious page fault.
307		 */
308		eva = rcr2();
309		if (td->td_md.md_spinlock_count == 0)
310			enable_intr();
311	}
312
313        if (TRAPF_USERMODE(frame) && (curpcb->pcb_flags & PCB_VM86CALL) == 0) {
314		/* user trap */
315
316		td->td_pticks = 0;
317		td->td_frame = frame;
318		addr = frame->tf_eip;
319		if (td->td_cowgen != p->p_cowgen)
320			thread_cow_update(td);
321
322		switch (type) {
323		case T_PRIVINFLT:	/* privileged instruction fault */
324			i = SIGILL;
325			ucode = ILL_PRVOPC;
326			break;
327
328		case T_BPTFLT:		/* bpt instruction fault */
329		case T_TRCTRAP:		/* trace trap */
330			enable_intr();
331#ifdef KDTRACE_HOOKS
332			if (type == T_BPTFLT) {
333				fill_frame_regs(frame, &regs);
334				if (dtrace_pid_probe_ptr != NULL &&
335				    dtrace_pid_probe_ptr(&regs) == 0)
336					goto out;
337			}
338#endif
339user_trctrap_out:
340			frame->tf_eflags &= ~PSL_T;
341			i = SIGTRAP;
342			ucode = (type == T_TRCTRAP ? TRAP_TRACE : TRAP_BRKPT);
343			break;
344
345		case T_ARITHTRAP:	/* arithmetic trap */
346#ifdef DEV_NPX
347			ucode = npxtrap_x87();
348			if (ucode == -1)
349				goto userout;
350#else
351			ucode = 0;
352#endif
353			i = SIGFPE;
354			break;
355
356			/*
357			 * The following two traps can happen in
358			 * vm86 mode, and, if so, we want to handle
359			 * them specially.
360			 */
361		case T_PROTFLT:		/* general protection fault */
362		case T_STKFLT:		/* stack fault */
363			if (frame->tf_eflags & PSL_VM) {
364				i = vm86_emulate((struct vm86frame *)frame);
365				if (i == SIGTRAP) {
366					type = T_TRCTRAP;
367					load_dr6(rdr6() | 0x4000);
368					goto user_trctrap_out;
369				}
370				if (i == 0)
371					goto user;
372				break;
373			}
374			i = SIGBUS;
375			ucode = (type == T_PROTFLT) ? BUS_OBJERR : BUS_ADRERR;
376			break;
377		case T_SEGNPFLT:	/* segment not present fault */
378			i = SIGBUS;
379			ucode = BUS_ADRERR;
380			break;
381		case T_TSSFLT:		/* invalid TSS fault */
382			i = SIGBUS;
383			ucode = BUS_OBJERR;
384			break;
385		case T_ALIGNFLT:
386			i = SIGBUS;
387			ucode = BUS_ADRALN;
388			break;
389		case T_DOUBLEFLT:	/* double fault */
390		default:
391			i = SIGBUS;
392			ucode = BUS_OBJERR;
393			break;
394
395		case T_PAGEFLT:		/* page fault */
396
397			i = trap_pfault(frame, TRUE, eva);
398#if defined(I586_CPU) && !defined(NO_F00F_HACK)
399			if (i == -2) {
400				/*
401				 * The f00f hack workaround has triggered, so
402				 * treat the fault as an illegal instruction
403				 * (T_PRIVINFLT) instead of a page fault.
404				 */
405				type = frame->tf_trapno = T_PRIVINFLT;
406
407				/* Proceed as in that case. */
408				ucode = ILL_PRVOPC;
409				i = SIGILL;
410				break;
411			}
412#endif
413			if (i == -1)
414				goto userout;
415			if (i == 0)
416				goto user;
417
418			if (i == SIGSEGV)
419				ucode = SEGV_MAPERR;
420			else {
421				if (prot_fault_translation == 0) {
422					/*
423					 * Autodetect.
424					 * This check also covers the images
425					 * without the ABI-tag ELF note.
426					 */
427					if (SV_CURPROC_ABI() == SV_ABI_FREEBSD
428					    && p->p_osrel >= P_OSREL_SIGSEGV) {
429						i = SIGSEGV;
430						ucode = SEGV_ACCERR;
431					} else {
432						i = SIGBUS;
433						ucode = BUS_PAGE_FAULT;
434					}
435				} else if (prot_fault_translation == 1) {
436					/*
437					 * Always compat mode.
438					 */
439					i = SIGBUS;
440					ucode = BUS_PAGE_FAULT;
441				} else {
442					/*
443					 * Always SIGSEGV mode.
444					 */
445					i = SIGSEGV;
446					ucode = SEGV_ACCERR;
447				}
448			}
449			addr = eva;
450			break;
451
452		case T_DIVIDE:		/* integer divide fault */
453			ucode = FPE_INTDIV;
454			i = SIGFPE;
455			break;
456
457#ifdef DEV_ISA
458		case T_NMI:
459#ifdef POWERFAIL_NMI
460#ifndef TIMER_FREQ
461#  define TIMER_FREQ 1193182
462#endif
463			if (time_second - lastalert > 10) {
464				log(LOG_WARNING, "NMI: power fail\n");
465				sysbeep(880, hz);
466				lastalert = time_second;
467			}
468			goto userout;
469#else /* !POWERFAIL_NMI */
470			/* machine/parity/power fail/"kitchen sink" faults */
471			if (isa_nmi(frame->tf_err) == 0) {
472#ifdef KDB
473				/*
474				 * NMI can be hooked up to a pushbutton
475				 * for debugging.
476				 */
477				if (kdb_on_nmi) {
478					printf ("NMI ... going to debugger\n");
479					kdb_trap(type, 0, frame);
480				}
481#endif /* KDB */
482				goto userout;
483			} else if (panic_on_nmi)
484				panic("NMI indicates hardware failure");
485			break;
486#endif /* POWERFAIL_NMI */
487#endif /* DEV_ISA */
488
489		case T_OFLOW:		/* integer overflow fault */
490			ucode = FPE_INTOVF;
491			i = SIGFPE;
492			break;
493
494		case T_BOUND:		/* bounds check fault */
495			ucode = FPE_FLTSUB;
496			i = SIGFPE;
497			break;
498
499		case T_DNA:
500#ifdef DEV_NPX
501			KASSERT(PCB_USER_FPU(td->td_pcb),
502			    ("kernel FPU ctx has leaked"));
503			/* transparent fault (due to context switch "late") */
504			if (npxdna())
505				goto userout;
506#endif
507			uprintf("pid %d killed due to lack of floating point\n",
508				p->p_pid);
509			i = SIGKILL;
510			ucode = 0;
511			break;
512
513		case T_FPOPFLT:		/* FPU operand fetch fault */
514			ucode = ILL_COPROC;
515			i = SIGILL;
516			break;
517
518		case T_XMMFLT:		/* SIMD floating-point exception */
519#if defined(DEV_NPX) && !defined(CPU_DISABLE_SSE) && defined(I686_CPU)
520			ucode = npxtrap_sse();
521			if (ucode == -1)
522				goto userout;
523#else
524			ucode = 0;
525#endif
526			i = SIGFPE;
527			break;
528#ifdef KDTRACE_HOOKS
529		case T_DTRACE_RET:
530			enable_intr();
531			fill_frame_regs(frame, &regs);
532			if (dtrace_return_probe_ptr != NULL &&
533			    dtrace_return_probe_ptr(&regs) == 0)
534				goto out;
535			break;
536#endif
537		}
538	} else {
539		/* kernel trap */
540
541		KASSERT(cold || td->td_ucred != NULL,
542		    ("kernel trap doesn't have ucred"));
543		switch (type) {
544		case T_PAGEFLT:			/* page fault */
545			(void) trap_pfault(frame, FALSE, eva);
546			goto out;
547
548		case T_DNA:
549#ifdef DEV_NPX
550			if (PCB_USER_FPU(td->td_pcb))
551				panic("Unregistered use of FPU in kernel");
552			if (npxdna())
553				goto out;
554#endif
555			break;
556
557		case T_ARITHTRAP:	/* arithmetic trap */
558		case T_XMMFLT:		/* SIMD floating-point exception */
559		case T_FPOPFLT:		/* FPU operand fetch fault */
560			/*
561			 * XXXKIB for now disable any FPU traps in kernel
562			 * handler registration seems to be overkill
563			 */
564			trap_fatal(frame, 0);
565			goto out;
566
567			/*
568			 * The following two traps can happen in
569			 * vm86 mode, and, if so, we want to handle
570			 * them specially.
571			 */
572		case T_PROTFLT:		/* general protection fault */
573		case T_STKFLT:		/* stack fault */
574			if (frame->tf_eflags & PSL_VM) {
575				i = vm86_emulate((struct vm86frame *)frame);
576				if (i == SIGTRAP) {
577					type = T_TRCTRAP;
578					load_dr6(rdr6() | 0x4000);
579					goto kernel_trctrap;
580				}
581				if (i != 0)
582					/*
583					 * returns to original process
584					 */
585					vm86_trap((struct vm86frame *)frame);
586				goto out;
587			}
588			if (type == T_STKFLT)
589				break;
590
591			/* FALL THROUGH */
592
593		case T_SEGNPFLT:	/* segment not present fault */
594			if (curpcb->pcb_flags & PCB_VM86CALL)
595				break;
596
597			/*
598			 * Invalid %fs's and %gs's can be created using
599			 * procfs or PT_SETREGS or by invalidating the
600			 * underlying LDT entry.  This causes a fault
601			 * in kernel mode when the kernel attempts to
602			 * switch contexts.  Lose the bad context
603			 * (XXX) so that we can continue, and generate
604			 * a signal.
605			 */
606			if (frame->tf_eip == (int)cpu_switch_load_gs) {
607				curpcb->pcb_gs = 0;
608#if 0
609				PROC_LOCK(p);
610				kern_psignal(p, SIGBUS);
611				PROC_UNLOCK(p);
612#endif
613				goto out;
614			}
615
616			if (td->td_intr_nesting_level != 0)
617				break;
618
619			/*
620			 * Invalid segment selectors and out of bounds
621			 * %eip's and %esp's can be set up in user mode.
622			 * This causes a fault in kernel mode when the
623			 * kernel tries to return to user mode.  We want
624			 * to get this fault so that we can fix the
625			 * problem here and not have to check all the
626			 * selectors and pointers when the user changes
627			 * them.
628			 */
629			if (frame->tf_eip == (int)doreti_iret) {
630				frame->tf_eip = (int)doreti_iret_fault;
631				goto out;
632			}
633			if (frame->tf_eip == (int)doreti_popl_ds) {
634				frame->tf_eip = (int)doreti_popl_ds_fault;
635				goto out;
636			}
637			if (frame->tf_eip == (int)doreti_popl_es) {
638				frame->tf_eip = (int)doreti_popl_es_fault;
639				goto out;
640			}
641			if (frame->tf_eip == (int)doreti_popl_fs) {
642				frame->tf_eip = (int)doreti_popl_fs_fault;
643				goto out;
644			}
645			if (curpcb->pcb_onfault != NULL) {
646				frame->tf_eip =
647				    (int)curpcb->pcb_onfault;
648				goto out;
649			}
650			break;
651
652		case T_TSSFLT:
653			/*
654			 * PSL_NT can be set in user mode and isn't cleared
655			 * automatically when the kernel is entered.  This
656			 * causes a TSS fault when the kernel attempts to
657			 * `iret' because the TSS link is uninitialized.  We
658			 * want to get this fault so that we can fix the
659			 * problem here and not every time the kernel is
660			 * entered.
661			 */
662			if (frame->tf_eflags & PSL_NT) {
663				frame->tf_eflags &= ~PSL_NT;
664				goto out;
665			}
666			break;
667
668		case T_TRCTRAP:	 /* trace trap */
669kernel_trctrap:
670			if (frame->tf_eip == (int)IDTVEC(lcall_syscall)) {
671				/*
672				 * We've just entered system mode via the
673				 * syscall lcall.  Continue single stepping
674				 * silently until the syscall handler has
675				 * saved the flags.
676				 */
677				goto out;
678			}
679			if (frame->tf_eip == (int)IDTVEC(lcall_syscall) + 1) {
680				/*
681				 * The syscall handler has now saved the
682				 * flags.  Stop single stepping it.
683				 */
684				frame->tf_eflags &= ~PSL_T;
685				goto out;
686			}
687			/*
688			 * Ignore debug register trace traps due to
689			 * accesses in the user's address space, which
690			 * can happen under several conditions such as
691			 * if a user sets a watchpoint on a buffer and
692			 * then passes that buffer to a system call.
693			 * We still want to get TRCTRAPS for addresses
694			 * in kernel space because that is useful when
695			 * debugging the kernel.
696			 */
697			if (user_dbreg_trap() &&
698			   !(curpcb->pcb_flags & PCB_VM86CALL)) {
699				/*
700				 * Reset breakpoint bits because the
701				 * processor doesn't
702				 */
703				load_dr6(rdr6() & ~0xf);
704				goto out;
705			}
706			/*
707			 * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
708			 */
709		case T_BPTFLT:
710			/*
711			 * If KDB is enabled, let it handle the debugger trap.
712			 * Otherwise, debugger traps "can't happen".
713			 */
714#ifdef KDB
715			/* XXX %dr6 is not quite reentrant. */
716			dr6 = rdr6();
717			load_dr6(dr6 & ~0x4000);
718			if (kdb_trap(type, dr6, frame))
719				goto out;
720#endif
721			break;
722
723#ifdef DEV_ISA
724		case T_NMI:
725#ifdef POWERFAIL_NMI
726			if (time_second - lastalert > 10) {
727				log(LOG_WARNING, "NMI: power fail\n");
728				sysbeep(880, hz);
729				lastalert = time_second;
730			}
731			goto out;
732#else /* !POWERFAIL_NMI */
733			/* machine/parity/power fail/"kitchen sink" faults */
734			if (isa_nmi(frame->tf_err) == 0) {
735#ifdef KDB
736				/*
737				 * NMI can be hooked up to a pushbutton
738				 * for debugging.
739				 */
740				if (kdb_on_nmi) {
741					printf ("NMI ... going to debugger\n");
742					kdb_trap(type, 0, frame);
743				}
744#endif /* KDB */
745				goto out;
746			} else if (panic_on_nmi == 0)
747				goto out;
748			/* FALLTHROUGH */
749#endif /* POWERFAIL_NMI */
750#endif /* DEV_ISA */
751		}
752
753		trap_fatal(frame, eva);
754		goto out;
755	}
756
757	/* Translate fault for emulators (e.g. Linux) */
758	if (*p->p_sysent->sv_transtrap)
759		i = (*p->p_sysent->sv_transtrap)(i, type);
760
761	ksiginfo_init_trap(&ksi);
762	ksi.ksi_signo = i;
763	ksi.ksi_code = ucode;
764	ksi.ksi_addr = (void *)addr;
765	ksi.ksi_trapno = type;
766	if (uprintf_signal) {
767		uprintf("pid %d comm %s: signal %d err %x code %d type %d "
768		    "addr 0x%x esp 0x%08x eip 0x%08x "
769		    "<%02x %02x %02x %02x %02x %02x %02x %02x>\n",
770		    p->p_pid, p->p_comm, i, frame->tf_err, ucode, type, addr,
771		    frame->tf_esp, frame->tf_eip,
772		    fubyte((void *)(frame->tf_eip + 0)),
773		    fubyte((void *)(frame->tf_eip + 1)),
774		    fubyte((void *)(frame->tf_eip + 2)),
775		    fubyte((void *)(frame->tf_eip + 3)),
776		    fubyte((void *)(frame->tf_eip + 4)),
777		    fubyte((void *)(frame->tf_eip + 5)),
778		    fubyte((void *)(frame->tf_eip + 6)),
779		    fubyte((void *)(frame->tf_eip + 7)));
780	}
781	KASSERT((read_eflags() & PSL_I) != 0, ("interrupts disabled"));
782	trapsignal(td, &ksi);
783
784#ifdef DEBUG
785	if (type <= MAX_TRAP_MSG) {
786		uprintf("fatal process exception: %s",
787			trap_msg[type]);
788		if ((type == T_PAGEFLT) || (type == T_PROTFLT))
789			uprintf(", fault VA = 0x%lx", (u_long)eva);
790		uprintf("\n");
791	}
792#endif
793
794user:
795	userret(td, frame);
796	KASSERT(PCB_USER_FPU(td->td_pcb),
797	    ("Return from trap with kernel FPU ctx leaked"));
798userout:
799out:
800	return;
801}
802
803static int
804trap_pfault(frame, usermode, eva)
805	struct trapframe *frame;
806	int usermode;
807	vm_offset_t eva;
808{
809	vm_offset_t va;
810	vm_map_t map;
811	int rv = 0;
812	vm_prot_t ftype;
813	struct thread *td = curthread;
814	struct proc *p = td->td_proc;
815
816	if (__predict_false((td->td_pflags & TDP_NOFAULTING) != 0)) {
817		/*
818		 * Due to both processor errata and lazy TLB invalidation when
819		 * access restrictions are removed from virtual pages, memory
820		 * accesses that are allowed by the physical mapping layer may
821		 * nonetheless cause one spurious page fault per virtual page.
822		 * When the thread is executing a "no faulting" section that
823		 * is bracketed by vm_fault_{disable,enable}_pagefaults(),
824		 * every page fault is treated as a spurious page fault,
825		 * unless it accesses the same virtual address as the most
826		 * recent page fault within the same "no faulting" section.
827		 */
828		if (td->td_md.md_spurflt_addr != eva ||
829		    (td->td_pflags & TDP_RESETSPUR) != 0) {
830			/*
831			 * Do nothing to the TLB.  A stale TLB entry is
832			 * flushed automatically by a page fault.
833			 */
834			td->td_md.md_spurflt_addr = eva;
835			td->td_pflags &= ~TDP_RESETSPUR;
836			return (0);
837		}
838	} else {
839		/*
840		 * If we get a page fault while in a critical section, then
841		 * it is most likely a fatal kernel page fault.  The kernel
842		 * is already going to panic trying to get a sleep lock to
843		 * do the VM lookup, so just consider it a fatal trap so the
844		 * kernel can print out a useful trap message and even get
845		 * to the debugger.
846		 *
847		 * If we get a page fault while holding a non-sleepable
848		 * lock, then it is most likely a fatal kernel page fault.
849		 * If WITNESS is enabled, then it's going to whine about
850		 * bogus LORs with various VM locks, so just skip to the
851		 * fatal trap handling directly.
852		 */
853		if (td->td_critnest != 0 ||
854		    WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
855		    "Kernel page fault") != 0) {
856			trap_fatal(frame, eva);
857			return (-1);
858		}
859	}
860	va = trunc_page(eva);
861	if (va >= KERNBASE) {
862		/*
863		 * Don't allow user-mode faults in kernel address space.
864		 * An exception:  if the faulting address is the invalid
865		 * instruction entry in the IDT, then the Intel Pentium
866		 * F00F bug workaround was triggered, and we need to
867		 * treat it is as an illegal instruction, and not a page
868		 * fault.
869		 */
870#if defined(I586_CPU) && !defined(NO_F00F_HACK)
871		if ((eva == (unsigned int)&idt[6]) && has_f00f_bug)
872			return (-2);
873#endif
874		if (usermode)
875			goto nogo;
876
877		map = kernel_map;
878	} else {
879		map = &p->p_vmspace->vm_map;
880
881		/*
882		 * When accessing a user-space address, kernel must be
883		 * ready to accept the page fault, and provide a
884		 * handling routine.  Since accessing the address
885		 * without the handler is a bug, do not try to handle
886		 * it normally, and panic immediately.
887		 */
888		if (!usermode && (td->td_intr_nesting_level != 0 ||
889		    curpcb->pcb_onfault == NULL)) {
890			trap_fatal(frame, eva);
891			return (-1);
892		}
893	}
894
895	/*
896	 * PGEX_I is defined only if the execute disable bit capability is
897	 * supported and enabled.
898	 */
899	if (frame->tf_err & PGEX_W)
900		ftype = VM_PROT_WRITE;
901#if defined(PAE) || defined(PAE_TABLES)
902	else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
903		ftype = VM_PROT_EXECUTE;
904#endif
905	else
906		ftype = VM_PROT_READ;
907
908	/* Fault in the page. */
909	rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
910	if (rv == KERN_SUCCESS) {
911#ifdef HWPMC_HOOKS
912		if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
913			PMC_SOFT_CALL_TF( , , page_fault, all, frame);
914			if (ftype == VM_PROT_READ)
915				PMC_SOFT_CALL_TF( , , page_fault, read,
916				    frame);
917			else
918				PMC_SOFT_CALL_TF( , , page_fault, write,
919				    frame);
920		}
921#endif
922		return (0);
923	}
924nogo:
925	if (!usermode) {
926		if (td->td_intr_nesting_level == 0 &&
927		    curpcb->pcb_onfault != NULL) {
928			frame->tf_eip = (int)curpcb->pcb_onfault;
929			return (0);
930		}
931		trap_fatal(frame, eva);
932		return (-1);
933	}
934	return ((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
935}
936
937static void
938trap_fatal(frame, eva)
939	struct trapframe *frame;
940	vm_offset_t eva;
941{
942	int code, ss, esp;
943	u_int type;
944	struct soft_segment_descriptor softseg;
945	char *msg;
946
947	code = frame->tf_err;
948	type = frame->tf_trapno;
949	sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)].sd, &softseg);
950
951	if (type <= MAX_TRAP_MSG)
952		msg = trap_msg[type];
953	else
954		msg = "UNKNOWN";
955	printf("\n\nFatal trap %d: %s while in %s mode\n", type, msg,
956	    frame->tf_eflags & PSL_VM ? "vm86" :
957	    ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
958#ifdef SMP
959	/* two separate prints in case of a trap on an unmapped page */
960	printf("cpuid = %d; ", PCPU_GET(cpuid));
961	printf("apic id = %02x\n", PCPU_GET(apic_id));
962#endif
963	if (type == T_PAGEFLT) {
964		printf("fault virtual address	= 0x%x\n", eva);
965		printf("fault code		= %s %s, %s\n",
966			code & PGEX_U ? "user" : "supervisor",
967			code & PGEX_W ? "write" : "read",
968			code & PGEX_P ? "protection violation" : "page not present");
969	}
970	printf("instruction pointer	= 0x%x:0x%x\n",
971	       frame->tf_cs & 0xffff, frame->tf_eip);
972        if (TF_HAS_STACKREGS(frame)) {
973		ss = frame->tf_ss & 0xffff;
974		esp = frame->tf_esp;
975	} else {
976		ss = GSEL(GDATA_SEL, SEL_KPL);
977		esp = (int)&frame->tf_esp;
978	}
979	printf("stack pointer	        = 0x%x:0x%x\n", ss, esp);
980	printf("frame pointer	        = 0x%x:0x%x\n", ss, frame->tf_ebp);
981	printf("code segment		= base 0x%x, limit 0x%x, type 0x%x\n",
982	       softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
983	printf("			= DPL %d, pres %d, def32 %d, gran %d\n",
984	       softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_def32,
985	       softseg.ssd_gran);
986	printf("processor eflags	= ");
987	if (frame->tf_eflags & PSL_T)
988		printf("trace trap, ");
989	if (frame->tf_eflags & PSL_I)
990		printf("interrupt enabled, ");
991	if (frame->tf_eflags & PSL_NT)
992		printf("nested task, ");
993	if (frame->tf_eflags & PSL_RF)
994		printf("resume, ");
995	if (frame->tf_eflags & PSL_VM)
996		printf("vm86, ");
997	printf("IOPL = %d\n", (frame->tf_eflags & PSL_IOPL) >> 12);
998	printf("current process		= %d (%s)\n",
999	    curproc->p_pid, curthread->td_name);
1000
1001#ifdef KDB
1002	if (debugger_on_panic || kdb_active) {
1003		frame->tf_err = eva;	/* smuggle fault address to ddb */
1004		if (kdb_trap(type, 0, frame)) {
1005			frame->tf_err = code;	/* restore error code */
1006			return;
1007		}
1008		frame->tf_err = code;		/* restore error code */
1009	}
1010#endif
1011	printf("trap number		= %d\n", type);
1012	if (type <= MAX_TRAP_MSG)
1013		panic("%s", trap_msg[type]);
1014	else
1015		panic("unknown/reserved trap");
1016}
1017
1018/*
1019 * Double fault handler. Called when a fault occurs while writing
1020 * a frame for a trap/exception onto the stack. This usually occurs
1021 * when the stack overflows (such is the case with infinite recursion,
1022 * for example).
1023 *
1024 * XXX Note that the current PTD gets replaced by IdlePTD when the
1025 * task switch occurs. This means that the stack that was active at
1026 * the time of the double fault is not available at <kstack> unless
1027 * the machine was idle when the double fault occurred. The downside
1028 * of this is that "trace <ebp>" in ddb won't work.
1029 */
1030void
1031dblfault_handler()
1032{
1033#ifdef KDTRACE_HOOKS
1034	if (dtrace_doubletrap_func != NULL)
1035		(*dtrace_doubletrap_func)();
1036#endif
1037	printf("\nFatal double fault:\n");
1038	printf("eip = 0x%x\n", PCPU_GET(common_tss.tss_eip));
1039	printf("esp = 0x%x\n", PCPU_GET(common_tss.tss_esp));
1040	printf("ebp = 0x%x\n", PCPU_GET(common_tss.tss_ebp));
1041#ifdef SMP
1042	/* two separate prints in case of a trap on an unmapped page */
1043	printf("cpuid = %d; ", PCPU_GET(cpuid));
1044	printf("apic id = %02x\n", PCPU_GET(apic_id));
1045#endif
1046	panic("double fault");
1047}
1048
1049int
1050cpu_fetch_syscall_args(struct thread *td, struct syscall_args *sa)
1051{
1052	struct proc *p;
1053	struct trapframe *frame;
1054	caddr_t params;
1055	long tmp;
1056	int error;
1057
1058	p = td->td_proc;
1059	frame = td->td_frame;
1060
1061	params = (caddr_t)frame->tf_esp + sizeof(int);
1062	sa->code = frame->tf_eax;
1063
1064	/*
1065	 * Need to check if this is a 32 bit or 64 bit syscall.
1066	 */
1067	if (sa->code == SYS_syscall) {
1068		/*
1069		 * Code is first argument, followed by actual args.
1070		 */
1071		error = fueword(params, &tmp);
1072		if (error == -1)
1073			return (EFAULT);
1074		sa->code = tmp;
1075		params += sizeof(int);
1076	} else if (sa->code == SYS___syscall) {
1077		/*
1078		 * Like syscall, but code is a quad, so as to maintain
1079		 * quad alignment for the rest of the arguments.
1080		 */
1081		error = fueword(params, &tmp);
1082		if (error == -1)
1083			return (EFAULT);
1084		sa->code = tmp;
1085		params += sizeof(quad_t);
1086	}
1087
1088 	if (p->p_sysent->sv_mask)
1089 		sa->code &= p->p_sysent->sv_mask;
1090 	if (sa->code >= p->p_sysent->sv_size)
1091 		sa->callp = &p->p_sysent->sv_table[0];
1092  	else
1093 		sa->callp = &p->p_sysent->sv_table[sa->code];
1094	sa->narg = sa->callp->sy_narg;
1095
1096	if (params != NULL && sa->narg != 0)
1097		error = copyin(params, (caddr_t)sa->args,
1098		    (u_int)(sa->narg * sizeof(int)));
1099	else
1100		error = 0;
1101
1102	if (error == 0) {
1103		td->td_retval[0] = 0;
1104		td->td_retval[1] = frame->tf_edx;
1105	}
1106
1107	return (error);
1108}
1109
1110#include "../../kern/subr_syscall.c"
1111
1112/*
1113 * syscall - system call request C handler.  A system call is
1114 * essentially treated as a trap by reusing the frame layout.
1115 */
1116void
1117syscall(struct trapframe *frame)
1118{
1119	struct thread *td;
1120	struct syscall_args sa;
1121	register_t orig_tf_eflags;
1122	int error;
1123	ksiginfo_t ksi;
1124
1125#ifdef DIAGNOSTIC
1126	if (!(TRAPF_USERMODE(frame) &&
1127	    (curpcb->pcb_flags & PCB_VM86CALL) == 0)) {
1128		panic("syscall");
1129		/* NOT REACHED */
1130	}
1131#endif
1132	orig_tf_eflags = frame->tf_eflags;
1133
1134	td = curthread;
1135	td->td_frame = frame;
1136
1137	error = syscallenter(td, &sa);
1138
1139	/*
1140	 * Traced syscall.
1141	 */
1142	if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1143		frame->tf_eflags &= ~PSL_T;
1144		ksiginfo_init_trap(&ksi);
1145		ksi.ksi_signo = SIGTRAP;
1146		ksi.ksi_code = TRAP_TRACE;
1147		ksi.ksi_addr = (void *)frame->tf_eip;
1148		trapsignal(td, &ksi);
1149	}
1150
1151	KASSERT(PCB_USER_FPU(td->td_pcb),
1152	    ("System call %s returning with kernel FPU ctx leaked",
1153	     syscallname(td->td_proc, sa.code)));
1154	KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td),
1155	    ("System call %s returning with mangled pcb_save",
1156	     syscallname(td->td_proc, sa.code)));
1157
1158	syscallret(td, error, &sa);
1159}
1160