subr_syscall.c revision 72911
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 * $FreeBSD: head/sys/kern/subr_trap.c 72911 2001-02-22 18:05:15Z jhb $
39 */
40
41/*
42 * 386 Trap and System call handling
43 */
44
45#include "opt_clock.h"
46#include "opt_cpu.h"
47#include "opt_ddb.h"
48#include "opt_isa.h"
49#include "opt_ktrace.h"
50#include "opt_npx.h"
51#include "opt_trap.h"
52
53#include <sys/param.h>
54#include <sys/bus.h>
55#include <sys/systm.h>
56#include <sys/proc.h>
57#include <sys/pioctl.h>
58#include <sys/ipl.h>
59#include <sys/kernel.h>
60#include <sys/ktr.h>
61#include <sys/mutex.h>
62#include <sys/resourcevar.h>
63#include <sys/signalvar.h>
64#include <sys/syscall.h>
65#include <sys/sysctl.h>
66#include <sys/sysent.h>
67#include <sys/uio.h>
68#include <sys/vmmeter.h>
69#ifdef KTRACE
70#include <sys/ktrace.h>
71#endif
72
73#include <vm/vm.h>
74#include <vm/vm_param.h>
75#include <sys/lock.h>
76#include <vm/pmap.h>
77#include <vm/vm_kern.h>
78#include <vm/vm_map.h>
79#include <vm/vm_page.h>
80#include <vm/vm_extern.h>
81
82#include <machine/cpu.h>
83#include <machine/md_var.h>
84#include <machine/pcb.h>
85#ifdef SMP
86#include <machine/smp.h>
87#endif
88#include <machine/tss.h>
89
90#include <i386/isa/icu.h>
91#include <i386/isa/intr_machdep.h>
92
93#ifdef POWERFAIL_NMI
94#include <sys/syslog.h>
95#include <machine/clock.h>
96#endif
97
98#include <machine/vm86.h>
99
100#include <ddb/ddb.h>
101
102#include <sys/sysctl.h>
103
104int (*pmath_emulate) __P((struct trapframe *));
105
106extern void trap __P((struct trapframe frame));
107extern int trapwrite __P((unsigned addr));
108extern void syscall __P((struct trapframe frame));
109extern void ast __P((struct trapframe *framep));
110
111static int trap_pfault __P((struct trapframe *, int, vm_offset_t));
112static void trap_fatal __P((struct trapframe *, vm_offset_t));
113void dblfault_handler __P((void));
114
115extern inthand_t IDTVEC(syscall);
116
117#define MAX_TRAP_MSG		28
118static char *trap_msg[] = {
119	"",					/*  0 unused */
120	"privileged instruction fault",		/*  1 T_PRIVINFLT */
121	"",					/*  2 unused */
122	"breakpoint instruction fault",		/*  3 T_BPTFLT */
123	"",					/*  4 unused */
124	"",					/*  5 unused */
125	"arithmetic trap",			/*  6 T_ARITHTRAP */
126	"",					/*  7 unused */
127	"",					/*  8 unused */
128	"general protection fault",		/*  9 T_PROTFLT */
129	"trace trap",				/* 10 T_TRCTRAP */
130	"",					/* 11 unused */
131	"page fault",				/* 12 T_PAGEFLT */
132	"",					/* 13 unused */
133	"alignment fault",			/* 14 T_ALIGNFLT */
134	"",					/* 15 unused */
135	"",					/* 16 unused */
136	"",					/* 17 unused */
137	"integer divide fault",			/* 18 T_DIVIDE */
138	"non-maskable interrupt trap",		/* 19 T_NMI */
139	"overflow trap",			/* 20 T_OFLOW */
140	"FPU bounds check fault",		/* 21 T_BOUND */
141	"FPU device not available",		/* 22 T_DNA */
142	"double fault",				/* 23 T_DOUBLEFLT */
143	"FPU operand fetch fault",		/* 24 T_FPOPFLT */
144	"invalid TSS fault",			/* 25 T_TSSFLT */
145	"segment not present fault",		/* 26 T_SEGNPFLT */
146	"stack fault",				/* 27 T_STKFLT */
147	"machine check trap",			/* 28 T_MCHK */
148};
149
150#if defined(I586_CPU) && !defined(NO_F00F_HACK)
151extern int has_f00f_bug;
152#endif
153
154#ifdef DDB
155static int ddb_on_nmi = 1;
156SYSCTL_INT(_machdep, OID_AUTO, ddb_on_nmi, CTLFLAG_RW,
157	&ddb_on_nmi, 0, "Go to DDB on NMI");
158#endif
159static int panic_on_nmi = 1;
160SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
161	&panic_on_nmi, 0, "Panic on NMI");
162
163#ifdef WITNESS
164extern char *syscallnames[];
165#endif
166
167void
168userret(p, frame, oticks)
169	struct proc *p;
170	struct trapframe *frame;
171	u_quad_t oticks;
172{
173	int sig;
174
175	while ((sig = CURSIG(p)) != 0) {
176		if (!mtx_owned(&Giant))
177			mtx_lock(&Giant);
178		postsig(sig);
179	}
180
181	mtx_lock_spin(&sched_lock);
182	p->p_pri.pri_level = p->p_pri.pri_user;
183	if (resched_wanted()) {
184		/*
185		 * Since we are curproc, clock will normally just change
186		 * our priority without moving us from one queue to another
187		 * (since the running process is not on a queue.)
188		 * If that happened after we setrunqueue ourselves but before we
189		 * mi_switch()'ed, we might not be on the queue indicated by
190		 * our priority.
191		 */
192		DROP_GIANT_NOSWITCH();
193		setrunqueue(p);
194		p->p_stats->p_ru.ru_nivcsw++;
195		mi_switch();
196		mtx_unlock_spin(&sched_lock);
197		PICKUP_GIANT();
198		while ((sig = CURSIG(p)) != 0) {
199			if (!mtx_owned(&Giant))
200				mtx_lock(&Giant);
201			postsig(sig);
202		}
203		mtx_lock_spin(&sched_lock);
204	}
205
206	/*
207	 * Charge system time if profiling.
208	 */
209	if (p->p_sflag & PS_PROFIL) {
210		mtx_unlock_spin(&sched_lock);
211		/* XXX - do we need Giant? */
212		if (!mtx_owned(&Giant))
213			mtx_lock(&Giant);
214		addupc_task(p, TRAPF_PC(frame),
215			    (u_int)(p->p_sticks - oticks) * psratio);
216	} else
217		mtx_unlock_spin(&sched_lock);
218}
219
220/*
221 * Exception, fault, and trap interface to the FreeBSD kernel.
222 * This common code is called from assembly language IDT gate entry
223 * routines that prepare a suitable stack frame, and restore this
224 * frame after the exception has been processed.
225 */
226
227void
228trap(frame)
229	struct trapframe frame;
230{
231	struct proc *p = curproc;
232	u_quad_t sticks = 0;
233	int i = 0, ucode = 0, type, code;
234	vm_offset_t eva;
235#ifdef POWERFAIL_NMI
236	static int lastalert = 0;
237#endif
238
239	atomic_add_int(&cnt.v_trap, 1);
240
241	if ((frame.tf_eflags & PSL_I) == 0) {
242		/*
243		 * Buggy application or kernel code has disabled
244		 * interrupts and then trapped.  Enabling interrupts
245		 * now is wrong, but it is better than running with
246		 * interrupts disabled until they are accidentally
247		 * enabled later.  XXX This is really bad if we trap
248		 * while holding a spin lock.
249		 */
250		type = frame.tf_trapno;
251		if (ISPL(frame.tf_cs) == SEL_UPL || (frame.tf_eflags & PSL_VM))
252			printf(
253			    "pid %ld (%s): trap %d with interrupts disabled\n",
254			    (long)curproc->p_pid, curproc->p_comm, type);
255		else if (type != T_BPTFLT && type != T_TRCTRAP) {
256			/*
257			 * XXX not quite right, since this may be for a
258			 * multiple fault in user mode.
259			 */
260			printf("kernel trap %d with interrupts disabled\n",
261			    type);
262			/*
263			 * We should walk p_heldmtx here and see if any are
264			 * spin mutexes, and not do this if so.
265			 */
266			enable_intr();
267		}
268	}
269
270	eva = 0;
271
272#if defined(I586_CPU) && !defined(NO_F00F_HACK)
273restart:
274#endif
275
276	type = frame.tf_trapno;
277	code = frame.tf_err;
278
279        if ((ISPL(frame.tf_cs) == SEL_UPL) ||
280	    ((frame.tf_eflags & PSL_VM) && !in_vm86call)) {
281		/* user trap */
282
283		mtx_lock_spin(&sched_lock);
284		sticks = p->p_sticks;
285		mtx_unlock_spin(&sched_lock);
286		p->p_md.md_regs = &frame;
287
288		switch (type) {
289		case T_PRIVINFLT:	/* privileged instruction fault */
290			ucode = type;
291			i = SIGILL;
292			break;
293
294		case T_BPTFLT:		/* bpt instruction fault */
295		case T_TRCTRAP:		/* trace trap */
296			frame.tf_eflags &= ~PSL_T;
297			i = SIGTRAP;
298			break;
299
300		case T_ARITHTRAP:	/* arithmetic trap */
301			ucode = code;
302			i = SIGFPE;
303			break;
304
305			/*
306			 * The following two traps can happen in
307			 * vm86 mode, and, if so, we want to handle
308			 * them specially.
309			 */
310		case T_PROTFLT:		/* general protection fault */
311		case T_STKFLT:		/* stack fault */
312			if (frame.tf_eflags & PSL_VM) {
313				mtx_lock(&Giant);
314				i = vm86_emulate((struct vm86frame *)&frame);
315				mtx_unlock(&Giant);
316				if (i == 0)
317					goto user;
318				break;
319			}
320			/* FALL THROUGH */
321
322		case T_SEGNPFLT:	/* segment not present fault */
323		case T_TSSFLT:		/* invalid TSS fault */
324		case T_DOUBLEFLT:	/* double fault */
325		default:
326			ucode = code + BUS_SEGM_FAULT ;
327			i = SIGBUS;
328			break;
329
330		case T_PAGEFLT:		/* page fault */
331			/*
332			 * For some Cyrix CPUs, %cr2 is clobbered by
333			 * interrupts.  This problem is worked around by using
334			 * an interrupt gate for the pagefault handler.  We
335			 * are finally ready to read %cr2 and then must
336			 * reenable interrupts.
337			 */
338			eva = rcr2();
339			enable_intr();
340			mtx_lock(&Giant);
341			i = trap_pfault(&frame, TRUE, eva);
342			mtx_unlock(&Giant);
343#if defined(I586_CPU) && !defined(NO_F00F_HACK)
344			if (i == -2) {
345				/*
346				 * f00f hack workaround has triggered, treat
347				 * as illegal instruction not page fault.
348				 */
349				frame.tf_trapno = T_PRIVINFLT;
350				goto restart;
351			}
352#endif
353			if (i == -1)
354				goto out;
355			if (i == 0)
356				goto user;
357
358			ucode = T_PAGEFLT;
359			break;
360
361		case T_DIVIDE:		/* integer divide fault */
362			ucode = FPE_INTDIV;
363			i = SIGFPE;
364			break;
365
366#ifdef DEV_ISA
367		case T_NMI:
368#ifdef POWERFAIL_NMI
369#ifndef TIMER_FREQ
370#  define TIMER_FREQ 1193182
371#endif
372			mtx_lock(&Giant);
373			if (time_second - lastalert > 10) {
374				log(LOG_WARNING, "NMI: power fail\n");
375				sysbeep(TIMER_FREQ/880, hz);
376				lastalert = time_second;
377			}
378			mtx_unlock(&Giant);
379			goto out;
380#else /* !POWERFAIL_NMI */
381			/* machine/parity/power fail/"kitchen sink" faults */
382			/* XXX Giant */
383			if (isa_nmi(code) == 0) {
384#ifdef DDB
385				/*
386				 * NMI can be hooked up to a pushbutton
387				 * for debugging.
388				 */
389				if (ddb_on_nmi) {
390					printf ("NMI ... going to debugger\n");
391					kdb_trap (type, 0, &frame);
392				}
393#endif /* DDB */
394				goto out;
395			} else if (panic_on_nmi)
396				panic("NMI indicates hardware failure");
397			break;
398#endif /* POWERFAIL_NMI */
399#endif /* DEV_ISA */
400
401		case T_OFLOW:		/* integer overflow fault */
402			ucode = FPE_INTOVF;
403			i = SIGFPE;
404			break;
405
406		case T_BOUND:		/* bounds check fault */
407			ucode = FPE_FLTSUB;
408			i = SIGFPE;
409			break;
410
411		case T_DNA:
412#ifdef DEV_NPX
413			/* transparent fault (due to context switch "late") */
414			if (npxdna())
415				goto out;
416#endif
417			if (!pmath_emulate) {
418				i = SIGFPE;
419				ucode = FPE_FPU_NP_TRAP;
420				break;
421			}
422			mtx_lock(&Giant);
423			i = (*pmath_emulate)(&frame);
424			mtx_unlock(&Giant);
425			if (i == 0) {
426				if (!(frame.tf_eflags & PSL_T))
427					goto out;
428				frame.tf_eflags &= ~PSL_T;
429				i = SIGTRAP;
430			}
431			/* else ucode = emulator_only_knows() XXX */
432			break;
433
434		case T_FPOPFLT:		/* FPU operand fetch fault */
435			ucode = T_FPOPFLT;
436			i = SIGILL;
437			break;
438		}
439	} else {
440		/* kernel trap */
441
442		switch (type) {
443		case T_PAGEFLT:			/* page fault */
444			/*
445			 * For some Cyrix CPUs, %cr2 is clobbered by
446			 * interrupts.  This problem is worked around by using
447			 * an interrupt gate for the pagefault handler.  We
448			 * are finally ready to read %cr2 and then must
449			 * reenable interrupts.
450			 */
451			eva = rcr2();
452			enable_intr();
453			mtx_lock(&Giant);
454			(void) trap_pfault(&frame, FALSE, eva);
455			mtx_unlock(&Giant);
456			goto out;
457
458		case T_DNA:
459#ifdef DEV_NPX
460			/*
461			 * The kernel is apparently using npx for copying.
462			 * XXX this should be fatal unless the kernel has
463			 * registered such use.
464			 */
465			if (npxdna())
466				goto out;
467#endif
468			break;
469
470			/*
471			 * The following two traps can happen in
472			 * vm86 mode, and, if so, we want to handle
473			 * them specially.
474			 */
475		case T_PROTFLT:		/* general protection fault */
476		case T_STKFLT:		/* stack fault */
477			if (frame.tf_eflags & PSL_VM) {
478				mtx_lock(&Giant);
479				i = vm86_emulate((struct vm86frame *)&frame);
480				mtx_unlock(&Giant);
481				if (i != 0)
482					/*
483					 * returns to original process
484					 */
485					vm86_trap((struct vm86frame *)&frame);
486				goto out;
487			}
488			if (type == T_STKFLT)
489				break;
490
491			/* FALL THROUGH */
492
493		case T_SEGNPFLT:	/* segment not present fault */
494			if (in_vm86call)
495				break;
496
497			if (p->p_intr_nesting_level != 0)
498				break;
499
500			/*
501			 * Invalid %fs's and %gs's can be created using
502			 * procfs or PT_SETREGS or by invalidating the
503			 * underlying LDT entry.  This causes a fault
504			 * in kernel mode when the kernel attempts to
505			 * switch contexts.  Lose the bad context
506			 * (XXX) so that we can continue, and generate
507			 * a signal.
508			 */
509			if (frame.tf_eip == (int)cpu_switch_load_gs) {
510				PCPU_GET(curpcb)->pcb_gs = 0;
511				mtx_lock(&Giant);
512				psignal(p, SIGBUS);
513				mtx_unlock(&Giant);
514				goto out;
515			}
516
517			/*
518			 * Invalid segment selectors and out of bounds
519			 * %eip's and %esp's can be set up in user mode.
520			 * This causes a fault in kernel mode when the
521			 * kernel tries to return to user mode.  We want
522			 * to get this fault so that we can fix the
523			 * problem here and not have to check all the
524			 * selectors and pointers when the user changes
525			 * them.
526			 */
527			if (frame.tf_eip == (int)doreti_iret) {
528				frame.tf_eip = (int)doreti_iret_fault;
529				goto out;
530			}
531			if (frame.tf_eip == (int)doreti_popl_ds) {
532				frame.tf_eip = (int)doreti_popl_ds_fault;
533				goto out;
534			}
535			if (frame.tf_eip == (int)doreti_popl_es) {
536				frame.tf_eip = (int)doreti_popl_es_fault;
537				goto out;
538			}
539			if (frame.tf_eip == (int)doreti_popl_fs) {
540				frame.tf_eip = (int)doreti_popl_fs_fault;
541				goto out;
542			}
543			if (PCPU_GET(curpcb) != NULL &&
544			    PCPU_GET(curpcb)->pcb_onfault != NULL) {
545				frame.tf_eip =
546				    (int)PCPU_GET(curpcb)->pcb_onfault;
547				goto out;
548			}
549			break;
550
551		case T_TSSFLT:
552			/*
553			 * PSL_NT can be set in user mode and isn't cleared
554			 * automatically when the kernel is entered.  This
555			 * causes a TSS fault when the kernel attempts to
556			 * `iret' because the TSS link is uninitialized.  We
557			 * want to get this fault so that we can fix the
558			 * problem here and not every time the kernel is
559			 * entered.
560			 */
561			if (frame.tf_eflags & PSL_NT) {
562				frame.tf_eflags &= ~PSL_NT;
563				goto out;
564			}
565			break;
566
567		case T_TRCTRAP:	 /* trace trap */
568			if (frame.tf_eip == (int)IDTVEC(syscall)) {
569				/*
570				 * We've just entered system mode via the
571				 * syscall lcall.  Continue single stepping
572				 * silently until the syscall handler has
573				 * saved the flags.
574				 */
575				goto out;
576			}
577			if (frame.tf_eip == (int)IDTVEC(syscall) + 1) {
578				/*
579				 * The syscall handler has now saved the
580				 * flags.  Stop single stepping it.
581				 */
582				frame.tf_eflags &= ~PSL_T;
583				goto out;
584			}
585			/*
586			 * Ignore debug register trace traps due to
587			 * accesses in the user's address space, which
588			 * can happen under several conditions such as
589			 * if a user sets a watchpoint on a buffer and
590			 * then passes that buffer to a system call.
591			 * We still want to get TRCTRAPS for addresses
592			 * in kernel space because that is useful when
593			 * debugging the kernel.
594			 */
595			/* XXX Giant */
596			if (user_dbreg_trap() && !in_vm86call) {
597				/*
598				 * Reset breakpoint bits because the
599				 * processor doesn't
600				 */
601				load_dr6(rdr6() & 0xfffffff0);
602				goto out;
603			}
604			/*
605			 * Fall through (TRCTRAP kernel mode, kernel address)
606			 */
607		case T_BPTFLT:
608			/*
609			 * If DDB is enabled, let it handle the debugger trap.
610			 * Otherwise, debugger traps "can't happen".
611			 */
612#ifdef DDB
613			/* XXX Giant */
614			if (kdb_trap (type, 0, &frame))
615				goto out;
616#endif
617			break;
618
619#ifdef DEV_ISA
620		case T_NMI:
621#ifdef POWERFAIL_NMI
622			mtx_lock(&Giant);
623			if (time_second - lastalert > 10) {
624				log(LOG_WARNING, "NMI: power fail\n");
625				sysbeep(TIMER_FREQ/880, hz);
626				lastalert = time_second;
627			}
628			mtx_unlock(&Giant);
629			goto out;
630#else /* !POWERFAIL_NMI */
631			/* XXX Giant */
632			/* machine/parity/power fail/"kitchen sink" faults */
633			if (isa_nmi(code) == 0) {
634#ifdef DDB
635				/*
636				 * NMI can be hooked up to a pushbutton
637				 * for debugging.
638				 */
639				if (ddb_on_nmi) {
640					printf ("NMI ... going to debugger\n");
641					kdb_trap (type, 0, &frame);
642				}
643#endif /* DDB */
644				goto out;
645			} else if (panic_on_nmi == 0)
646				goto out;
647			/* FALL THROUGH */
648#endif /* POWERFAIL_NMI */
649#endif /* DEV_ISA */
650		}
651
652		mtx_lock(&Giant);
653		trap_fatal(&frame, eva);
654		mtx_unlock(&Giant);
655		goto out;
656	}
657
658	mtx_lock(&Giant);
659	/* Translate fault for emulators (e.g. Linux) */
660	if (*p->p_sysent->sv_transtrap)
661		i = (*p->p_sysent->sv_transtrap)(i, type);
662
663	trapsignal(p, i, ucode);
664
665#ifdef DEBUG
666	if (type <= MAX_TRAP_MSG) {
667		uprintf("fatal process exception: %s",
668			trap_msg[type]);
669		if ((type == T_PAGEFLT) || (type == T_PROTFLT))
670			uprintf(", fault VA = 0x%lx", (u_long)eva);
671		uprintf("\n");
672	}
673#endif
674	mtx_unlock(&Giant);
675
676user:
677	userret(p, &frame, sticks);
678	if (mtx_owned(&Giant))
679		mtx_unlock(&Giant);
680out:
681	return;
682}
683
684#ifdef notyet
685/*
686 * This version doesn't allow a page fault to user space while
687 * in the kernel. The rest of the kernel needs to be made "safe"
688 * before this can be used. I think the only things remaining
689 * to be made safe are the iBCS2 code and the process tracing/
690 * debugging code.
691 */
692static int
693trap_pfault(frame, usermode, eva)
694	struct trapframe *frame;
695	int usermode;
696	vm_offset_t eva;
697{
698	vm_offset_t va;
699	struct vmspace *vm = NULL;
700	vm_map_t map = 0;
701	int rv = 0;
702	vm_prot_t ftype;
703	struct proc *p = curproc;
704
705	if (frame->tf_err & PGEX_W)
706		ftype = VM_PROT_WRITE;
707	else
708		ftype = VM_PROT_READ;
709
710	va = trunc_page(eva);
711	if (va < VM_MIN_KERNEL_ADDRESS) {
712		vm_offset_t v;
713		vm_page_t mpte;
714
715		if (p == NULL ||
716		    (!usermode && va < VM_MAXUSER_ADDRESS &&
717		     (p->p_intr_nesting_level != 0 ||
718		      PCPU_GET(curpcb) == NULL ||
719		      PCPU_GET(curpcb)->pcb_onfault == NULL))) {
720			trap_fatal(frame, eva);
721			return (-1);
722		}
723
724		/*
725		 * This is a fault on non-kernel virtual memory.
726		 * vm is initialized above to NULL. If curproc is NULL
727		 * or curproc->p_vmspace is NULL the fault is fatal.
728		 */
729		vm = p->p_vmspace;
730		if (vm == NULL)
731			goto nogo;
732
733		map = &vm->vm_map;
734
735		/*
736		 * Keep swapout from messing with us during this
737		 *	critical time.
738		 */
739		PROC_LOCK(p);
740		++p->p_lock;
741		PROC_UNLOCK(p);
742
743		/*
744		 * Grow the stack if necessary
745		 */
746		/* grow_stack returns false only if va falls into
747		 * a growable stack region and the stack growth
748		 * fails.  It returns true if va was not within
749		 * a growable stack region, or if the stack
750		 * growth succeeded.
751		 */
752		if (!grow_stack (p, va)) {
753			rv = KERN_FAILURE;
754			PROC_LOCK(p);
755			--p->p_lock;
756			PROC_UNLOCK(p);
757			goto nogo;
758		}
759
760		/* Fault in the user page: */
761		rv = vm_fault(map, va, ftype,
762			      (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
763						      : VM_FAULT_NORMAL);
764
765		PROC_LOCK(p);
766		--p->p_lock;
767		PROC_UNLOCK(p);
768	} else {
769		/*
770		 * Don't allow user-mode faults in kernel address space.
771		 */
772		if (usermode)
773			goto nogo;
774
775		/*
776		 * Since we know that kernel virtual address addresses
777		 * always have pte pages mapped, we just have to fault
778		 * the page.
779		 */
780		rv = vm_fault(kernel_map, va, ftype, VM_FAULT_NORMAL);
781	}
782
783	if (rv == KERN_SUCCESS)
784		return (0);
785nogo:
786	if (!usermode) {
787		if (p->p_intr_nesting_level == 0 &&
788		    PCPU_GET(curpcb) != NULL &&
789		    PCPU_GET(curpcb)->pcb_onfault != NULL) {
790			frame->tf_eip = (int)PCPU_GET(curpcb)->pcb_onfault;
791			return (0);
792		}
793		trap_fatal(frame, eva);
794		return (-1);
795	}
796
797	/* kludge to pass faulting virtual address to sendsig */
798	frame->tf_err = eva;
799
800	return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
801}
802#endif
803
804int
805trap_pfault(frame, usermode, eva)
806	struct trapframe *frame;
807	int usermode;
808	vm_offset_t eva;
809{
810	vm_offset_t va;
811	struct vmspace *vm = NULL;
812	vm_map_t map = 0;
813	int rv = 0;
814	vm_prot_t ftype;
815	struct proc *p = curproc;
816
817	va = trunc_page(eva);
818	if (va >= KERNBASE) {
819		/*
820		 * Don't allow user-mode faults in kernel address space.
821		 * An exception:  if the faulting address is the invalid
822		 * instruction entry in the IDT, then the Intel Pentium
823		 * F00F bug workaround was triggered, and we need to
824		 * treat it is as an illegal instruction, and not a page
825		 * fault.
826		 */
827#if defined(I586_CPU) && !defined(NO_F00F_HACK)
828		if ((eva == (unsigned int)&idt[6]) && has_f00f_bug)
829			return -2;
830#endif
831		if (usermode)
832			goto nogo;
833
834		map = kernel_map;
835	} else {
836		/*
837		 * This is a fault on non-kernel virtual memory.
838		 * vm is initialized above to NULL. If curproc is NULL
839		 * or curproc->p_vmspace is NULL the fault is fatal.
840		 */
841		if (p != NULL)
842			vm = p->p_vmspace;
843
844		if (vm == NULL)
845			goto nogo;
846
847		map = &vm->vm_map;
848	}
849
850	if (frame->tf_err & PGEX_W)
851		ftype = VM_PROT_WRITE;
852	else
853		ftype = VM_PROT_READ;
854
855	if (map != kernel_map) {
856		/*
857		 * Keep swapout from messing with us during this
858		 *	critical time.
859		 */
860		PROC_LOCK(p);
861		++p->p_lock;
862		PROC_UNLOCK(p);
863
864		/*
865		 * Grow the stack if necessary
866		 */
867		/* grow_stack returns false only if va falls into
868		 * a growable stack region and the stack growth
869		 * fails.  It returns true if va was not within
870		 * a growable stack region, or if the stack
871		 * growth succeeded.
872		 */
873		if (!grow_stack (p, va)) {
874			rv = KERN_FAILURE;
875			PROC_LOCK(p);
876			--p->p_lock;
877			PROC_UNLOCK(p);
878			goto nogo;
879		}
880
881		/* Fault in the user page: */
882		rv = vm_fault(map, va, ftype,
883			      (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
884						      : VM_FAULT_NORMAL);
885
886		PROC_LOCK(p);
887		--p->p_lock;
888		PROC_UNLOCK(p);
889	} else {
890		/*
891		 * Don't have to worry about process locking or stacks in the
892		 * kernel.
893		 */
894		rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
895	}
896
897	if (rv == KERN_SUCCESS)
898		return (0);
899nogo:
900	if (!usermode) {
901		if (p->p_intr_nesting_level == 0 &&
902		    PCPU_GET(curpcb) != NULL &&
903		    PCPU_GET(curpcb)->pcb_onfault != NULL) {
904			frame->tf_eip = (int)PCPU_GET(curpcb)->pcb_onfault;
905			return (0);
906		}
907		trap_fatal(frame, eva);
908		return (-1);
909	}
910
911	/* kludge to pass faulting virtual address to sendsig */
912	frame->tf_err = eva;
913
914	return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
915}
916
917static void
918trap_fatal(frame, eva)
919	struct trapframe *frame;
920	vm_offset_t eva;
921{
922	int code, type, ss, esp;
923	struct soft_segment_descriptor softseg;
924
925	code = frame->tf_err;
926	type = frame->tf_trapno;
927	sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)].sd, &softseg);
928
929	if (type <= MAX_TRAP_MSG)
930		printf("\n\nFatal trap %d: %s while in %s mode\n",
931			type, trap_msg[type],
932        		frame->tf_eflags & PSL_VM ? "vm86" :
933			ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
934#ifdef SMP
935	/* two separate prints in case of a trap on an unmapped page */
936	printf("cpuid = %d; ", PCPU_GET(cpuid));
937	printf("lapic.id = %08x\n", lapic.id);
938#endif
939	if (type == T_PAGEFLT) {
940		printf("fault virtual address	= 0x%x\n", eva);
941		printf("fault code		= %s %s, %s\n",
942			code & PGEX_U ? "user" : "supervisor",
943			code & PGEX_W ? "write" : "read",
944			code & PGEX_P ? "protection violation" : "page not present");
945	}
946	printf("instruction pointer	= 0x%x:0x%x\n",
947	       frame->tf_cs & 0xffff, frame->tf_eip);
948        if ((ISPL(frame->tf_cs) == SEL_UPL) || (frame->tf_eflags & PSL_VM)) {
949		ss = frame->tf_ss & 0xffff;
950		esp = frame->tf_esp;
951	} else {
952		ss = GSEL(GDATA_SEL, SEL_KPL);
953		esp = (int)&frame->tf_esp;
954	}
955	printf("stack pointer	        = 0x%x:0x%x\n", ss, esp);
956	printf("frame pointer	        = 0x%x:0x%x\n", ss, frame->tf_ebp);
957	printf("code segment		= base 0x%x, limit 0x%x, type 0x%x\n",
958	       softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
959	printf("			= DPL %d, pres %d, def32 %d, gran %d\n",
960	       softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_def32,
961	       softseg.ssd_gran);
962	printf("processor eflags	= ");
963	if (frame->tf_eflags & PSL_T)
964		printf("trace trap, ");
965	if (frame->tf_eflags & PSL_I)
966		printf("interrupt enabled, ");
967	if (frame->tf_eflags & PSL_NT)
968		printf("nested task, ");
969	if (frame->tf_eflags & PSL_RF)
970		printf("resume, ");
971	if (frame->tf_eflags & PSL_VM)
972		printf("vm86, ");
973	printf("IOPL = %d\n", (frame->tf_eflags & PSL_IOPL) >> 12);
974	printf("current process		= ");
975	if (curproc) {
976		printf("%lu (%s)\n",
977		    (u_long)curproc->p_pid, curproc->p_comm ?
978		    curproc->p_comm : "");
979	} else {
980		printf("Idle\n");
981	}
982
983#ifdef KDB
984	if (kdb_trap(&psl))
985		return;
986#endif
987#ifdef DDB
988	if ((debugger_on_panic || db_active) && kdb_trap(type, 0, frame))
989		return;
990#endif
991	printf("trap number		= %d\n", type);
992	if (type <= MAX_TRAP_MSG)
993		panic(trap_msg[type]);
994	else
995		panic("unknown/reserved trap");
996}
997
998/*
999 * Double fault handler. Called when a fault occurs while writing
1000 * a frame for a trap/exception onto the stack. This usually occurs
1001 * when the stack overflows (such is the case with infinite recursion,
1002 * for example).
1003 *
1004 * XXX Note that the current PTD gets replaced by IdlePTD when the
1005 * task switch occurs. This means that the stack that was active at
1006 * the time of the double fault is not available at <kstack> unless
1007 * the machine was idle when the double fault occurred. The downside
1008 * of this is that "trace <ebp>" in ddb won't work.
1009 */
1010void
1011dblfault_handler()
1012{
1013	printf("\nFatal double fault:\n");
1014	printf("eip = 0x%x\n", PCPU_GET(common_tss.tss_eip));
1015	printf("esp = 0x%x\n", PCPU_GET(common_tss.tss_esp));
1016	printf("ebp = 0x%x\n", PCPU_GET(common_tss.tss_ebp));
1017#ifdef SMP
1018	/* two separate prints in case of a trap on an unmapped page */
1019	printf("cpuid = %d; ", PCPU_GET(cpuid));
1020	printf("lapic.id = %08x\n", lapic.id);
1021#endif
1022	panic("double fault");
1023}
1024
1025/*
1026 * Compensate for 386 brain damage (missing URKR).
1027 * This is a little simpler than the pagefault handler in trap() because
1028 * it the page tables have already been faulted in and high addresses
1029 * are thrown out early for other reasons.
1030 */
1031int trapwrite(addr)
1032	unsigned addr;
1033{
1034	struct proc *p;
1035	vm_offset_t va;
1036	struct vmspace *vm;
1037	int rv;
1038
1039	va = trunc_page((vm_offset_t)addr);
1040	/*
1041	 * XXX - MAX is END.  Changed > to >= for temp. fix.
1042	 */
1043	if (va >= VM_MAXUSER_ADDRESS)
1044		return (1);
1045
1046	p = curproc;
1047	vm = p->p_vmspace;
1048
1049	PROC_LOCK(p);
1050	++p->p_lock;
1051	PROC_UNLOCK(p);
1052
1053	if (!grow_stack (p, va)) {
1054		PROC_LOCK(p);
1055		--p->p_lock;
1056		PROC_UNLOCK(p);
1057		return (1);
1058	}
1059
1060	/*
1061	 * fault the data page
1062	 */
1063	rv = vm_fault(&vm->vm_map, va, VM_PROT_WRITE, VM_FAULT_DIRTY);
1064
1065	PROC_LOCK(p);
1066	--p->p_lock;
1067	PROC_UNLOCK(p);
1068
1069	if (rv != KERN_SUCCESS)
1070		return 1;
1071
1072	return (0);
1073}
1074
1075/*
1076 *	syscall -	MP aware system call request C handler
1077 *
1078 *	A system call is essentially treated as a trap except that the
1079 *	MP lock is not held on entry or return.  We are responsible for
1080 *	obtaining the MP lock if necessary and for handling ASTs
1081 *	(e.g. a task switch) prior to return.
1082 *
1083 *	In general, only simple access and manipulation of curproc and
1084 *	the current stack is allowed without having to hold MP lock.
1085 */
1086void
1087syscall(frame)
1088	struct trapframe frame;
1089{
1090	caddr_t params;
1091	int i;
1092	struct sysent *callp;
1093	struct proc *p = curproc;
1094	u_quad_t sticks;
1095	int error;
1096	int narg;
1097	int args[8];
1098	u_int code;
1099
1100	atomic_add_int(&cnt.v_syscall, 1);
1101
1102#ifdef DIAGNOSTIC
1103	if (ISPL(frame.tf_cs) != SEL_UPL) {
1104		mtx_lock(&Giant);
1105		panic("syscall");
1106		/* NOT REACHED */
1107	}
1108#endif
1109
1110	mtx_lock_spin(&sched_lock);
1111	sticks = p->p_sticks;
1112	mtx_unlock_spin(&sched_lock);
1113
1114	p->p_md.md_regs = &frame;
1115	params = (caddr_t)frame.tf_esp + sizeof(int);
1116	code = frame.tf_eax;
1117
1118	if (p->p_sysent->sv_prepsyscall) {
1119		/*
1120		 * The prep code is not MP aware.
1121		 */
1122		mtx_lock(&Giant);
1123		(*p->p_sysent->sv_prepsyscall)(&frame, args, &code, &params);
1124		mtx_unlock(&Giant);
1125	} else {
1126		/*
1127		 * Need to check if this is a 32 bit or 64 bit syscall.
1128		 * fuword is MP aware.
1129		 */
1130		if (code == SYS_syscall) {
1131			/*
1132			 * Code is first argument, followed by actual args.
1133			 */
1134			code = fuword(params);
1135			params += sizeof(int);
1136		} else if (code == SYS___syscall) {
1137			/*
1138			 * Like syscall, but code is a quad, so as to maintain
1139			 * quad alignment for the rest of the arguments.
1140			 */
1141			code = fuword(params);
1142			params += sizeof(quad_t);
1143		}
1144	}
1145
1146 	if (p->p_sysent->sv_mask)
1147 		code &= p->p_sysent->sv_mask;
1148
1149 	if (code >= p->p_sysent->sv_size)
1150 		callp = &p->p_sysent->sv_table[0];
1151  	else
1152 		callp = &p->p_sysent->sv_table[code];
1153
1154	narg = callp->sy_narg & SYF_ARGMASK;
1155
1156	/*
1157	 * copyin is MP aware, but the tracing code is not
1158	 */
1159	if (params && (i = narg * sizeof(int)) &&
1160	    (error = copyin(params, (caddr_t)args, (u_int)i))) {
1161		mtx_lock(&Giant);
1162#ifdef KTRACE
1163		if (KTRPOINT(p, KTR_SYSCALL))
1164			ktrsyscall(p->p_tracep, code, narg, args);
1165#endif
1166		goto bad;
1167	}
1168
1169	/*
1170	 * Try to run the syscall without the MP lock if the syscall
1171	 * is MP safe.  We have to obtain the MP lock no matter what if
1172	 * we are ktracing
1173	 */
1174	if ((callp->sy_narg & SYF_MPSAFE) == 0) {
1175		mtx_lock(&Giant);
1176	}
1177
1178#ifdef KTRACE
1179	if (KTRPOINT(p, KTR_SYSCALL)) {
1180		if (!mtx_owned(&Giant))
1181			mtx_lock(&Giant);
1182		ktrsyscall(p->p_tracep, code, narg, args);
1183	}
1184#endif
1185	p->p_retval[0] = 0;
1186	p->p_retval[1] = frame.tf_edx;
1187
1188	STOPEVENT(p, S_SCE, narg);	/* MP aware */
1189
1190	error = (*callp->sy_call)(p, args);
1191
1192	/*
1193	 * MP SAFE (we may or may not have the MP lock at this point)
1194	 */
1195	switch (error) {
1196	case 0:
1197		frame.tf_eax = p->p_retval[0];
1198		frame.tf_edx = p->p_retval[1];
1199		frame.tf_eflags &= ~PSL_C;
1200		break;
1201
1202	case ERESTART:
1203		/*
1204		 * Reconstruct pc, assuming lcall $X,y is 7 bytes,
1205		 * int 0x80 is 2 bytes. We saved this in tf_err.
1206		 */
1207		frame.tf_eip -= frame.tf_err;
1208		break;
1209
1210	case EJUSTRETURN:
1211		break;
1212
1213	default:
1214bad:
1215 		if (p->p_sysent->sv_errsize) {
1216 			if (error >= p->p_sysent->sv_errsize)
1217  				error = -1;	/* XXX */
1218   			else
1219  				error = p->p_sysent->sv_errtbl[error];
1220		}
1221		frame.tf_eax = error;
1222		frame.tf_eflags |= PSL_C;
1223		break;
1224	}
1225
1226	/*
1227	 * Traced syscall.  trapsignal() is not MP aware.
1228	 */
1229	if ((frame.tf_eflags & PSL_T) && !(frame.tf_eflags & PSL_VM)) {
1230		if (!mtx_owned(&Giant))
1231			mtx_lock(&Giant);
1232		frame.tf_eflags &= ~PSL_T;
1233		trapsignal(p, SIGTRAP, 0);
1234	}
1235
1236	/*
1237	 * Handle reschedule and other end-of-syscall issues
1238	 */
1239	userret(p, &frame, sticks);
1240
1241#ifdef KTRACE
1242	if (KTRPOINT(p, KTR_SYSRET)) {
1243		if (!mtx_owned(&Giant))
1244			mtx_lock(&Giant);
1245		ktrsysret(p->p_tracep, code, error, p->p_retval[0]);
1246	}
1247#endif
1248
1249	/*
1250	 * This works because errno is findable through the
1251	 * register set.  If we ever support an emulation where this
1252	 * is not the case, this code will need to be revisited.
1253	 */
1254	STOPEVENT(p, S_SCX, code);
1255
1256	/*
1257	 * Release Giant if we had to get it
1258	 */
1259	if (mtx_owned(&Giant))
1260		mtx_unlock(&Giant);
1261
1262#ifdef WITNESS
1263	if (witness_list(p)) {
1264		panic("system call %s returning with mutex(s) held\n",
1265		    syscallnames[code]);
1266	}
1267#endif
1268	mtx_assert(&sched_lock, MA_NOTOWNED);
1269	mtx_assert(&Giant, MA_NOTOWNED);
1270}
1271
1272void
1273ast(framep)
1274	struct trapframe *framep;
1275{
1276	struct proc *p = CURPROC;
1277	u_quad_t sticks;
1278
1279	KASSERT(TRAPF_USERMODE(framep), ("ast in kernel mode"));
1280
1281	/*
1282	 * We check for a pending AST here rather than in the assembly as
1283	 * acquiring and releasing mutexes in assembly is not fun.
1284	 */
1285	mtx_lock_spin(&sched_lock);
1286	if (!(astpending(p) || resched_wanted())) {
1287		mtx_unlock_spin(&sched_lock);
1288		return;
1289	}
1290
1291	sticks = p->p_sticks;
1292
1293	astoff(p);
1294	cnt.v_soft++;
1295	mtx_intr_enable(&sched_lock);
1296	if (p->p_sflag & PS_OWEUPC) {
1297		p->p_sflag &= ~PS_OWEUPC;
1298		mtx_unlock_spin(&sched_lock);
1299		mtx_lock(&Giant);
1300		mtx_lock_spin(&sched_lock);
1301		addupc_task(p, p->p_stats->p_prof.pr_addr,
1302			    p->p_stats->p_prof.pr_ticks);
1303	}
1304	if (p->p_sflag & PS_ALRMPEND) {
1305		p->p_sflag &= ~PS_ALRMPEND;
1306		mtx_unlock_spin(&sched_lock);
1307		if (!mtx_owned(&Giant))
1308			mtx_lock(&Giant);
1309		psignal(p, SIGVTALRM);
1310		mtx_lock_spin(&sched_lock);
1311	}
1312	if (p->p_sflag & PS_PROFPEND) {
1313		p->p_sflag &= ~PS_PROFPEND;
1314		mtx_unlock_spin(&sched_lock);
1315		if (!mtx_owned(&Giant))
1316			mtx_lock(&Giant);
1317		psignal(p, SIGPROF);
1318	} else
1319		mtx_unlock_spin(&sched_lock);
1320
1321	userret(p, framep, sticks);
1322
1323	if (mtx_owned(&Giant))
1324		mtx_unlock(&Giant);
1325}
1326