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