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