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