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