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