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