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