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