Add a ton of infrastructure for VKERNEL support. Add code for intercepting
[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.82 2006/10/20 17:02:19 dillon Exp $
40  */
41
42 /*
43  * 386 Trap and System call handling
44  */
45
46 #include "use_isa.h"
47 #include "use_npx.h"
48
49 #include "opt_cpu.h"
50 #include "opt_ddb.h"
51 #include "opt_ktrace.h"
52 #include "opt_clock.h"
53 #include "opt_trap.h"
54
55 #include <sys/param.h>
56 #include <sys/systm.h>
57 #include <sys/proc.h>
58 #include <sys/pioctl.h>
59 #include <sys/kernel.h>
60 #include <sys/resourcevar.h>
61 #include <sys/signalvar.h>
62 #include <sys/syscall.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysent.h>
65 #include <sys/uio.h>
66 #include <sys/vmmeter.h>
67 #include <sys/malloc.h>
68 #ifdef KTRACE
69 #include <sys/ktrace.h>
70 #endif
71 #include <sys/upcall.h>
72 #include <sys/vkernel.h>
73 #include <sys/sysproto.h>
74 #include <sys/sysunion.h>
75
76 #include <vm/vm.h>
77 #include <vm/vm_param.h>
78 #include <sys/lock.h>
79 #include <vm/pmap.h>
80 #include <vm/vm_kern.h>
81 #include <vm/vm_map.h>
82 #include <vm/vm_page.h>
83 #include <vm/vm_extern.h>
84
85 #include <machine/cpu.h>
86 #include <machine/ipl.h>
87 #include <machine/md_var.h>
88 #include <machine/pcb.h>
89 #include <machine/smp.h>
90 #include <machine/tss.h>
91 #include <machine/globaldata.h>
92
93 #include <i386/isa/intr_machdep.h>
94
95 #ifdef POWERFAIL_NMI
96 #include <sys/syslog.h>
97 #include <machine/clock.h>
98 #endif
99
100 #include <machine/vm86.h>
101
102 #include <ddb/ddb.h>
103 #include <sys/msgport2.h>
104 #include <sys/thread2.h>
105
106 #ifdef SMP
107
108 #define MAKEMPSAFE(have_mplock)                 \
109         if (have_mplock == 0) {                 \
110                 get_mplock();                   \
111                 have_mplock = 1;                \
112         }
113
114 #else
115
116 #define MAKEMPSAFE(have_mplock)
117
118 #endif
119
120 int (*pmath_emulate) (struct trapframe *);
121
122 extern void trap (struct trapframe frame);
123 extern int trapwrite (unsigned addr);
124 extern void syscall2 (struct trapframe frame);
125
126 static int trap_pfault (struct trapframe *, int, vm_offset_t);
127 static void trap_fatal (struct trapframe *, vm_offset_t);
128 void dblfault_handler (void);
129
130 extern inthand_t IDTVEC(syscall);
131
132 #define MAX_TRAP_MSG            28
133 static char *trap_msg[] = {
134         "",                                     /*  0 unused */
135         "privileged instruction fault",         /*  1 T_PRIVINFLT */
136         "",                                     /*  2 unused */
137         "breakpoint instruction fault",         /*  3 T_BPTFLT */
138         "",                                     /*  4 unused */
139         "",                                     /*  5 unused */
140         "arithmetic trap",                      /*  6 T_ARITHTRAP */
141         "system forced exception",              /*  7 T_ASTFLT */
142         "",                                     /*  8 unused */
143         "general protection fault",             /*  9 T_PROTFLT */
144         "trace trap",                           /* 10 T_TRCTRAP */
145         "",                                     /* 11 unused */
146         "page fault",                           /* 12 T_PAGEFLT */
147         "",                                     /* 13 unused */
148         "alignment fault",                      /* 14 T_ALIGNFLT */
149         "",                                     /* 15 unused */
150         "",                                     /* 16 unused */
151         "",                                     /* 17 unused */
152         "integer divide fault",                 /* 18 T_DIVIDE */
153         "non-maskable interrupt trap",          /* 19 T_NMI */
154         "overflow trap",                        /* 20 T_OFLOW */
155         "FPU bounds check fault",               /* 21 T_BOUND */
156         "FPU device not available",             /* 22 T_DNA */
157         "double fault",                         /* 23 T_DOUBLEFLT */
158         "FPU operand fetch fault",              /* 24 T_FPOPFLT */
159         "invalid TSS fault",                    /* 25 T_TSSFLT */
160         "segment not present fault",            /* 26 T_SEGNPFLT */
161         "stack fault",                          /* 27 T_STKFLT */
162         "machine check trap",                   /* 28 T_MCHK */
163 };
164
165 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
166 extern int has_f00f_bug;
167 #endif
168
169 #ifdef DDB
170 static int ddb_on_nmi = 1;
171 SYSCTL_INT(_machdep, OID_AUTO, ddb_on_nmi, CTLFLAG_RW,
172         &ddb_on_nmi, 0, "Go to DDB on NMI");
173 #endif
174 static int panic_on_nmi = 1;
175 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
176         &panic_on_nmi, 0, "Panic on NMI");
177 static int fast_release;
178 SYSCTL_INT(_machdep, OID_AUTO, fast_release, CTLFLAG_RW,
179         &fast_release, 0, "Passive Release was optimal");
180 static int slow_release;
181 SYSCTL_INT(_machdep, OID_AUTO, slow_release, CTLFLAG_RW,
182         &slow_release, 0, "Passive Release was nonoptimal");
183 #ifdef SMP
184 static int syscall_mpsafe = 0;
185 SYSCTL_INT(_kern, OID_AUTO, syscall_mpsafe, CTLFLAG_RW,
186         &syscall_mpsafe, 0, "Allow MPSAFE marked syscalls to run without BGL");
187 TUNABLE_INT("kern.syscall_mpsafe", &syscall_mpsafe);
188 static int trap_mpsafe = 0;
189 SYSCTL_INT(_kern, OID_AUTO, trap_mpsafe, CTLFLAG_RW,
190         &trap_mpsafe, 0, "Allow traps to mostly run without the BGL");
191 TUNABLE_INT("kern.trap_mpsafe", &trap_mpsafe);
192 #endif
193
194 MALLOC_DEFINE(M_SYSMSG, "sysmsg", "sysmsg structure");
195 extern int max_sysmsg;
196
197 /*
198  * Passive USER->KERNEL transition.  This only occurs if we block in the
199  * kernel while still holding our userland priority.  We have to fixup our
200  * priority in order to avoid potential deadlocks before we allow the system
201  * to switch us to another thread.
202  */
203 static void
204 passive_release(struct thread *td)
205 {
206         struct lwp *lp = td->td_lwp;
207
208         td->td_release = NULL;
209         lwkt_setpri_self(TDPRI_KERN_USER);
210         lp->lwp_proc->p_usched->release_curproc(lp);
211 }
212
213 /*
214  * userenter() passively intercepts the thread switch function to increase
215  * the thread priority from a user priority to a kernel priority, reducing
216  * syscall and trap overhead for the case where no switch occurs.
217  */
218
219 static __inline void
220 userenter(struct thread *curtd)
221 {
222         curtd->td_release = passive_release;
223 }
224
225 /*
226  * Handle signals, upcalls, profiling, and other AST's and/or tasks that
227  * must be completed before we can return to or try to return to userland.
228  *
229  * Note that td_sticks is a 64 bit quantity, but there's no point doing 64
230  * arithmatic on the delta calculation so the absolute tick values are
231  * truncated to an integer.
232  */
233 static void
234 userret(struct lwp *lp, struct trapframe *frame, int sticks)
235 {
236         struct proc *p = lp->lwp_proc;
237         int sig;
238
239         /*
240          * Charge system time if profiling.  Note: times are in microseconds.
241          * This may do a copyout and block, so do it first even though it
242          * means some system time will be charged as user time.
243          */
244         if (p->p_flag & P_PROFIL) {
245                 addupc_task(p, frame->tf_eip, 
246                         (u_int)((int)lp->lwp_thread->td_sticks - sticks));
247         }
248
249 recheck:
250         /*
251          * Block here if we are in a stopped state.
252          */
253         if (p->p_flag & P_STOPPED) {
254                 get_mplock();
255                 tstop(p);
256                 rel_mplock();
257                 goto recheck;
258         }
259
260         /*
261          * Post any pending upcalls
262          */
263         if (p->p_flag & P_UPCALLPEND) {
264                 p->p_flag &= ~P_UPCALLPEND;
265                 get_mplock();
266                 postupcall(lp);
267                 rel_mplock();
268                 goto recheck;
269         }
270
271         /*
272          * Post any pending signals
273          */
274         if ((sig = CURSIG(p)) != 0) {
275                 get_mplock();
276                 postsig(sig);
277                 rel_mplock();
278                 goto recheck;
279         }
280
281         /*
282          * block here if we are swapped out, but still process signals
283          * (such as SIGKILL).  proc0 (the swapin scheduler) is already
284          * aware of our situation, we do not have to wake it up.
285          */
286         if (p->p_flag & P_SWAPPEDOUT) {
287                 get_mplock();
288                 p->p_flag |= P_SWAPWAIT;
289                 swapin_request();
290                 if (p->p_flag & P_SWAPWAIT)
291                         tsleep(p, PCATCH, "SWOUT", 0);
292                 p->p_flag &= ~P_SWAPWAIT;
293                 rel_mplock();
294                 goto recheck;
295         }
296 }
297
298 /*
299  * Cleanup from userenter and any passive release that might have occured.
300  * We must reclaim the current-process designation before we can return
301  * to usermode.  We also handle both LWKT and USER reschedule requests.
302  */
303 static __inline void
304 userexit(struct lwp *lp)
305 {
306         struct thread *td = lp->lwp_thread;
307         globaldata_t gd = td->td_gd;
308
309 #if 0
310         /*
311          * If a user reschedule is requested force a new process to be
312          * chosen by releasing the current process.  Our process will only
313          * be chosen again if it has a considerably better priority.
314          */
315         if (user_resched_wanted())
316                 lp->lwp_proc->p_usched->release_curproc(lp);
317 #endif
318
319         /*
320          * Handle a LWKT reschedule request first.  Since our passive release
321          * is still in place we do not have to do anything special.
322          */
323         if (lwkt_resched_wanted())
324                 lwkt_switch();
325
326         /*
327          * Acquire the current process designation for this user scheduler
328          * on this cpu.  This will also handle any user-reschedule requests.
329          */
330         lp->lwp_proc->p_usched->acquire_curproc(lp);
331         /* We may have switched cpus on acquisition */
332         gd = td->td_gd;
333
334         /*
335          * Reduce our priority in preparation for a return to userland.  If
336          * our passive release function was still in place, our priority was
337          * never raised and does not need to be reduced.
338          */
339         if (td->td_release == NULL)
340                 lwkt_setpri_self(TDPRI_USER_NORM);
341         td->td_release = NULL;
342
343         /*
344          * After reducing our priority there might be other kernel-level
345          * LWKTs that now have a greater priority.  Run them as necessary.
346          * We don't have to worry about losing cpu to userland because
347          * we still control the current-process designation and we no longer
348          * have a passive release function installed.
349          */
350         if (lwkt_checkpri_self())
351                 lwkt_switch();
352 }
353
354 /*
355  * Exception, fault, and trap interface to the kernel.
356  * This common code is called from assembly language IDT gate entry
357  * routines that prepare a suitable stack frame, and restore this
358  * frame after the exception has been processed.
359  *
360  * This function is also called from doreti in an interlock to handle ASTs.
361  * For example:  hardwareint->INTROUTINE->(set ast)->doreti->trap
362  *
363  * NOTE!  We have to retrieve the fault address prior to obtaining the
364  * MP lock because get_mplock() may switch out.  YYY cr2 really ought
365  * to be retrieved by the assembly code, not here.
366  *
367  * XXX gd_trap_nesting_level currently prevents lwkt_switch() from panicing
368  * if an attempt is made to switch from a fast interrupt or IPI.  This is
369  * necessary to properly take fatal kernel traps on SMP machines if 
370  * get_mplock() has to block.
371  */
372
373 void
374 trap(struct trapframe frame)
375 {
376         struct globaldata *gd = mycpu;
377         struct thread *td = gd->gd_curthread;
378         struct lwp *lp = td->td_lwp;
379         struct proc *p;
380         int sticks = 0;
381         int i = 0, ucode = 0, type, code;
382 #ifdef SMP
383         int have_mplock = 0;
384 #endif
385 #ifdef INVARIANTS
386         int crit_count = td->td_pri & ~TDPRI_MASK;
387 #endif
388         vm_offset_t eva;
389
390         p = td->td_proc;
391 #ifdef DDB
392         if (db_active) {
393                 eva = (frame.tf_trapno == T_PAGEFLT ? rcr2() : 0);
394                 ++gd->gd_trap_nesting_level;
395                 MAKEMPSAFE(have_mplock);
396                 trap_fatal(&frame, eva);
397                 --gd->gd_trap_nesting_level;
398                 goto out2;
399         }
400 #endif
401
402         eva = 0;
403         ++gd->gd_trap_nesting_level;
404         if (frame.tf_trapno == T_PAGEFLT) {
405                 /*
406                  * For some Cyrix CPUs, %cr2 is clobbered by interrupts.
407                  * This problem is worked around by using an interrupt
408                  * gate for the pagefault handler.  We are finally ready
409                  * to read %cr2 and then must reenable interrupts.
410                  *
411                  * XXX this should be in the switch statement, but the
412                  * NO_FOOF_HACK and VM86 goto and ifdefs obfuscate the
413                  * flow of control too much for this to be obviously
414                  * correct.
415                  */
416                 eva = rcr2();
417                 cpu_enable_intr();
418         }
419 #ifdef SMP
420         if (trap_mpsafe == 0)
421                 MAKEMPSAFE(have_mplock);
422 #endif
423
424         --gd->gd_trap_nesting_level;
425
426         if (!(frame.tf_eflags & PSL_I)) {
427                 /*
428                  * Buggy application or kernel code has disabled interrupts
429                  * and then trapped.  Enabling interrupts now is wrong, but
430                  * it is better than running with interrupts disabled until
431                  * they are accidentally enabled later.
432                  */
433                 type = frame.tf_trapno;
434                 if (ISPL(frame.tf_cs)==SEL_UPL || (frame.tf_eflags & PSL_VM)) {
435                         MAKEMPSAFE(have_mplock);
436                         printf(
437                             "pid %ld (%s): trap %d with interrupts disabled\n",
438                             (long)curproc->p_pid, curproc->p_comm, type);
439                 } else if (type != T_BPTFLT && type != T_TRCTRAP) {
440                         /*
441                          * XXX not quite right, since this may be for a
442                          * multiple fault in user mode.
443                          */
444                         MAKEMPSAFE(have_mplock);
445                         printf("kernel trap %d with interrupts disabled\n",
446                             type);
447                 }
448                 cpu_enable_intr();
449         }
450
451 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
452 restart:
453 #endif
454         type = frame.tf_trapno;
455         code = frame.tf_err;
456
457         if (in_vm86call) {
458                 ASSERT_MP_LOCK_HELD(curthread);
459                 if (frame.tf_eflags & PSL_VM &&
460                     (type == T_PROTFLT || type == T_STKFLT)) {
461 #ifdef SMP
462                         KKASSERT(td->td_mpcount > 0);
463 #endif
464                         i = vm86_emulate((struct vm86frame *)&frame);
465 #ifdef SMP
466                         KKASSERT(td->td_mpcount > 0);
467 #endif
468                         if (i != 0) {
469                                 /*
470                                  * returns to original process
471                                  */
472 #ifdef SMP
473                                 vm86_trap((struct vm86frame *)&frame,
474                                           have_mplock);
475 #else
476                                 vm86_trap((struct vm86frame *)&frame, 0);
477 #endif
478                                 KKASSERT(0); /* NOT REACHED */
479                         }
480                         goto out2;
481                 }
482                 switch (type) {
483                         /*
484                          * these traps want either a process context, or
485                          * assume a normal userspace trap.
486                          */
487                 case T_PROTFLT:
488                 case T_SEGNPFLT:
489                         trap_fatal(&frame, eva);
490                         goto out2;
491                 case T_TRCTRAP:
492                         type = T_BPTFLT;        /* kernel breakpoint */
493                         /* FALL THROUGH */
494                 }
495                 goto kernel_trap;       /* normal kernel trap handling */
496         }
497
498         if ((ISPL(frame.tf_cs) == SEL_UPL) || (frame.tf_eflags & PSL_VM)) {
499                 /* user trap */
500
501                 userenter(td);
502
503                 sticks = (int)td->td_sticks;
504                 lp->lwp_md.md_regs = &frame;
505
506                 switch (type) {
507                 case T_PRIVINFLT:       /* privileged instruction fault */
508                         ucode = type;
509                         i = SIGILL;
510                         break;
511
512                 case T_BPTFLT:          /* bpt instruction fault */
513                 case T_TRCTRAP:         /* trace trap */
514                         frame.tf_eflags &= ~PSL_T;
515                         i = SIGTRAP;
516                         break;
517
518                 case T_ARITHTRAP:       /* arithmetic trap */
519                         ucode = code;
520                         i = SIGFPE;
521                         break;
522
523                 case T_ASTFLT:          /* Allow process switch */
524                         mycpu->gd_cnt.v_soft++;
525                         if (mycpu->gd_reqflags & RQF_AST_OWEUPC) {
526                                 atomic_clear_int_nonlocked(&mycpu->gd_reqflags,
527                                             RQF_AST_OWEUPC);
528                                 addupc_task(p, p->p_prof.pr_addr,
529                                             p->p_prof.pr_ticks);
530                         }
531                         goto out;
532
533                         /*
534                          * The following two traps can happen in
535                          * vm86 mode, and, if so, we want to handle
536                          * them specially.
537                          */
538                 case T_PROTFLT:         /* general protection fault */
539                 case T_STKFLT:          /* stack fault */
540                         if (frame.tf_eflags & PSL_VM) {
541                                 i = vm86_emulate((struct vm86frame *)&frame);
542                                 if (i == 0)
543                                         goto out;
544                                 break;
545                         }
546                         /* FALL THROUGH */
547
548                 case T_SEGNPFLT:        /* segment not present fault */
549                 case T_TSSFLT:          /* invalid TSS fault */
550                 case T_DOUBLEFLT:       /* double fault */
551                 default:
552                         ucode = code + BUS_SEGM_FAULT ;
553                         i = SIGBUS;
554                         break;
555
556                 case T_PAGEFLT:         /* page fault */
557                         MAKEMPSAFE(have_mplock);
558                         i = trap_pfault(&frame, TRUE, eva);
559                         if (i == -1)
560                                 goto out;
561 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
562                         if (i == -2)
563                                 goto restart;
564 #endif
565                         if (i == 0)
566                                 goto out;
567
568                         ucode = T_PAGEFLT;
569
570                         /*
571                          * The code is lost because tf_err is overwritten
572                          * with the fault address.  Store it in the upper
573                          * 16 bits of tf_trapno for vkernel consumption.
574                          */
575                         if (p->p_vkernel && p->p_vkernel->vk_current) {
576                                 frame.tf_trapno |= (code << 16);
577                         }
578                         break;
579
580                 case T_DIVIDE:          /* integer divide fault */
581                         ucode = FPE_INTDIV;
582                         i = SIGFPE;
583                         break;
584
585 #if NISA > 0
586                 case T_NMI:
587                         MAKEMPSAFE(have_mplock);
588 #ifdef POWERFAIL_NMI
589                         goto handle_powerfail;
590 #else /* !POWERFAIL_NMI */
591                         /* machine/parity/power fail/"kitchen sink" faults */
592                         if (isa_nmi(code) == 0) {
593 #ifdef DDB
594                                 /*
595                                  * NMI can be hooked up to a pushbutton
596                                  * for debugging.
597                                  */
598                                 if (ddb_on_nmi) {
599                                         printf ("NMI ... going to debugger\n");
600                                         kdb_trap (type, 0, &frame);
601                                 }
602 #endif /* DDB */
603                                 goto out2;
604                         } else if (panic_on_nmi)
605                                 panic("NMI indicates hardware failure");
606                         break;
607 #endif /* POWERFAIL_NMI */
608 #endif /* NISA > 0 */
609
610                 case T_OFLOW:           /* integer overflow fault */
611                         ucode = FPE_INTOVF;
612                         i = SIGFPE;
613                         break;
614
615                 case T_BOUND:           /* bounds check fault */
616                         ucode = FPE_FLTSUB;
617                         i = SIGFPE;
618                         break;
619
620                 case T_DNA:
621 #if NNPX > 0
622                         /* 
623                          * The kernel may have switched out the FP unit's
624                          * state, causing the user process to take a fault
625                          * when it tries to use the FP unit.  Restore the
626                          * state here
627                          */
628                         if (npxdna())
629                                 goto out;
630 #endif
631                         if (!pmath_emulate) {
632                                 i = SIGFPE;
633                                 ucode = FPE_FPU_NP_TRAP;
634                                 break;
635                         }
636                         i = (*pmath_emulate)(&frame);
637                         if (i == 0) {
638                                 if (!(frame.tf_eflags & PSL_T))
639                                         goto out2;
640                                 frame.tf_eflags &= ~PSL_T;
641                                 i = SIGTRAP;
642                         }
643                         /* else ucode = emulator_only_knows() XXX */
644                         break;
645
646                 case T_FPOPFLT:         /* FPU operand fetch fault */
647                         ucode = T_FPOPFLT;
648                         i = SIGILL;
649                         break;
650
651                 case T_XMMFLT:          /* SIMD floating-point exception */
652                         ucode = 0; /* XXX */
653                         i = SIGFPE;
654                         break;
655                 }
656         } else {
657 kernel_trap:
658                 /* kernel trap */
659
660                 switch (type) {
661                 case T_PAGEFLT:                 /* page fault */
662                         MAKEMPSAFE(have_mplock);
663                         trap_pfault(&frame, FALSE, eva);
664                         goto out2;
665
666                 case T_DNA:
667 #if NNPX > 0
668                         /*
669                          * The kernel may be using npx for copying or other
670                          * purposes.
671                          */
672                         if (npxdna())
673                                 goto out2;
674 #endif
675                         break;
676
677                 case T_PROTFLT:         /* general protection fault */
678                 case T_SEGNPFLT:        /* segment not present fault */
679                         /*
680                          * Invalid segment selectors and out of bounds
681                          * %eip's and %esp's can be set up in user mode.
682                          * This causes a fault in kernel mode when the
683                          * kernel tries to return to user mode.  We want
684                          * to get this fault so that we can fix the
685                          * problem here and not have to check all the
686                          * selectors and pointers when the user changes
687                          * them.
688                          */
689 #define MAYBE_DORETI_FAULT(where, whereto)                              \
690         do {                                                            \
691                 if (frame.tf_eip == (int)where) {                       \
692                         frame.tf_eip = (int)whereto;                    \
693                         goto out2;                                      \
694                 }                                                       \
695         } while (0)
696                         /*
697                          * Since we don't save %gs across an interrupt
698                          * frame this check must occur outside the intr
699                          * nesting level check.
700                          */
701                         if (frame.tf_eip == (int)cpu_switch_load_gs) {
702                                 td->td_pcb->pcb_gs = 0;
703                                 MAKEMPSAFE(have_mplock);
704                                 ksignal(p, SIGBUS);
705                                 goto out2;
706                         }
707                         if (mycpu->gd_intr_nesting_level == 0) {
708                                 /*
709                                  * Invalid %fs's and %gs's can be created using
710                                  * procfs or PT_SETREGS or by invalidating the
711                                  * underlying LDT entry.  This causes a fault
712                                  * in kernel mode when the kernel attempts to
713                                  * switch contexts.  Lose the bad context
714                                  * (XXX) so that we can continue, and generate
715                                  * a signal.
716                                  */
717                                 MAYBE_DORETI_FAULT(doreti_iret,
718                                                    doreti_iret_fault);
719                                 MAYBE_DORETI_FAULT(doreti_popl_ds,
720                                                    doreti_popl_ds_fault);
721                                 MAYBE_DORETI_FAULT(doreti_popl_es,
722                                                    doreti_popl_es_fault);
723                                 MAYBE_DORETI_FAULT(doreti_popl_fs,
724                                                    doreti_popl_fs_fault);
725                                 if (td->td_pcb->pcb_onfault) {
726                                         frame.tf_eip = 
727                                             (register_t)td->td_pcb->pcb_onfault;
728                                         goto out2;
729                                 }
730                         }
731                         break;
732
733                 case T_TSSFLT:
734                         /*
735                          * PSL_NT can be set in user mode and isn't cleared
736                          * automatically when the kernel is entered.  This
737                          * causes a TSS fault when the kernel attempts to
738                          * `iret' because the TSS link is uninitialized.  We
739                          * want to get this fault so that we can fix the
740                          * problem here and not every time the kernel is
741                          * entered.
742                          */
743                         if (frame.tf_eflags & PSL_NT) {
744                                 frame.tf_eflags &= ~PSL_NT;
745                                 goto out2;
746                         }
747                         break;
748
749                 case T_TRCTRAP:  /* trace trap */
750                         if (frame.tf_eip == (int)IDTVEC(syscall)) {
751                                 /*
752                                  * We've just entered system mode via the
753                                  * syscall lcall.  Continue single stepping
754                                  * silently until the syscall handler has
755                                  * saved the flags.
756                                  */
757                                 goto out2;
758                         }
759                         if (frame.tf_eip == (int)IDTVEC(syscall) + 1) {
760                                 /*
761                                  * The syscall handler has now saved the
762                                  * flags.  Stop single stepping it.
763                                  */
764                                 frame.tf_eflags &= ~PSL_T;
765                                 goto out2;
766                         }
767                         /*
768                          * Ignore debug register trace traps due to
769                          * accesses in the user's address space, which
770                          * can happen under several conditions such as
771                          * if a user sets a watchpoint on a buffer and
772                          * then passes that buffer to a system call.
773                          * We still want to get TRCTRAPS for addresses
774                          * in kernel space because that is useful when
775                          * debugging the kernel.
776                          */
777                         if (user_dbreg_trap()) {
778                                 /*
779                                  * Reset breakpoint bits because the
780                                  * processor doesn't
781                                  */
782                                 load_dr6(rdr6() & 0xfffffff0);
783                                 goto out2;
784                         }
785                         /*
786                          * Fall through (TRCTRAP kernel mode, kernel address)
787                          */
788                 case T_BPTFLT:
789                         /*
790                          * If DDB is enabled, let it handle the debugger trap.
791                          * Otherwise, debugger traps "can't happen".
792                          */
793 #ifdef DDB
794                         MAKEMPSAFE(have_mplock);
795                         if (kdb_trap (type, 0, &frame))
796                                 goto out2;
797 #endif
798                         break;
799
800 #if NISA > 0
801                 case T_NMI:
802                         MAKEMPSAFE(have_mplock);
803 #ifdef POWERFAIL_NMI
804 #ifndef TIMER_FREQ
805 #  define TIMER_FREQ 1193182
806 #endif
807         handle_powerfail:
808                 {
809                   static unsigned lastalert = 0;
810
811                   if(time_second - lastalert > 10)
812                     {
813                       log(LOG_WARNING, "NMI: power fail\n");
814                       sysbeep(TIMER_FREQ/880, hz);
815                       lastalert = time_second;
816                     }
817                     /* YYY mp count */
818                   goto out2;
819                 }
820 #else /* !POWERFAIL_NMI */
821                         /* machine/parity/power fail/"kitchen sink" faults */
822                         if (isa_nmi(code) == 0) {
823 #ifdef DDB
824                                 /*
825                                  * NMI can be hooked up to a pushbutton
826                                  * for debugging.
827                                  */
828                                 if (ddb_on_nmi) {
829                                         printf ("NMI ... going to debugger\n");
830                                         kdb_trap (type, 0, &frame);
831                                 }
832 #endif /* DDB */
833                                 goto out2;
834                         } else if (panic_on_nmi == 0)
835                                 goto out2;
836                         /* FALL THROUGH */
837 #endif /* POWERFAIL_NMI */
838 #endif /* NISA > 0 */
839                 }
840
841                 MAKEMPSAFE(have_mplock);
842                 trap_fatal(&frame, eva);
843                 goto out2;
844         }
845
846         /*
847          * Virtual kernel intercept - if the fault is directly related to a
848          * VM context managed by a virtual kernel then let the virtual kernel
849          * handle it.
850          */
851         if (p->p_vkernel && p->p_vkernel->vk_current) {
852                 vkernel_trap(p, &frame);
853                 goto out;
854         }
855
856         /*
857          * Translate fault for emulators (e.g. Linux) 
858          */
859         if (*p->p_sysent->sv_transtrap)
860                 i = (*p->p_sysent->sv_transtrap)(i, type);
861
862         MAKEMPSAFE(have_mplock);
863         trapsignal(p, i, ucode);
864
865 #ifdef DEBUG
866         if (type <= MAX_TRAP_MSG) {
867                 uprintf("fatal process exception: %s",
868                         trap_msg[type]);
869                 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
870                         uprintf(", fault VA = 0x%lx", (u_long)eva);
871                 uprintf("\n");
872         }
873 #endif
874
875 out:
876 #ifdef SMP
877         if (ISPL(frame.tf_cs) == SEL_UPL)
878                 KASSERT(td->td_mpcount == have_mplock, ("badmpcount trap/end from %p", (void *)frame.tf_eip));
879 #endif
880         userret(lp, &frame, sticks);
881         userexit(lp);
882 out2:   ;
883 #ifdef SMP
884         if (have_mplock)
885                 rel_mplock();
886 #endif
887 #ifdef INVARIANTS
888         KASSERT(crit_count == (td->td_pri & ~TDPRI_MASK),
889                 ("syscall: critical section count mismatch! %d/%d",
890                 crit_count / TDPRI_CRIT, td->td_pri / TDPRI_CRIT));
891 #endif
892 }
893
894 #ifdef notyet
895 /*
896  * This version doesn't allow a page fault to user space while
897  * in the kernel. The rest of the kernel needs to be made "safe"
898  * before this can be used. I think the only things remaining
899  * to be made safe is the process tracing/debugging code.
900  */
901 static int
902 trap_pfault(struct trapframe *frame, int usermode, vm_offset_t eva)
903 {
904         vm_offset_t va;
905         struct vmspace *vm = NULL;
906         vm_map_t map = 0;
907         int rv = 0;
908         vm_prot_t ftype;
909         thread_t td = curthread;
910         struct proc *p = td->td_proc;   /* may be NULL */
911
912         if (frame->tf_err & PGEX_W)
913                 ftype = VM_PROT_WRITE;
914         else
915                 ftype = VM_PROT_READ;
916
917         va = trunc_page(eva);
918         if (va < VM_MIN_KERNEL_ADDRESS) {
919                 vm_offset_t v;
920                 vm_page_t mpte;
921
922                 if (p == NULL ||
923                     (!usermode && va < VM_MAXUSER_ADDRESS &&
924                      (td->td_gd->gd_intr_nesting_level != 0 || 
925                       td->td_pcb->pcb_onfault == NULL))) {
926                         trap_fatal(frame, eva);
927                         return (-1);
928                 }
929
930                 /*
931                  * This is a fault on non-kernel virtual memory.
932                  * vm is initialized above to NULL. If curproc is NULL
933                  * or curproc->p_vmspace is NULL the fault is fatal.
934                  */
935                 vm = p->p_vmspace;
936                 if (vm == NULL)
937                         goto nogo;
938
939                 map = &vm->vm_map;
940
941                 /*
942                  * Keep swapout from messing with us during this
943                  *      critical time.
944                  */
945                 ++p->p_lock;
946
947                 /*
948                  * Grow the stack if necessary
949                  */
950                 /* grow_stack returns false only if va falls into
951                  * a growable stack region and the stack growth
952                  * fails.  It returns true if va was not within
953                  * a growable stack region, or if the stack 
954                  * growth succeeded.
955                  */
956                 if (!grow_stack (p, va)) {
957                         rv = KERN_FAILURE;
958                         --p->p_lock;
959                         goto nogo;
960                 }
961                 
962                 /* Fault in the user page: */
963                 rv = vm_fault(map, va, ftype,
964                               (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
965                                                       : VM_FAULT_NORMAL);
966
967                 --p->p_lock;
968         } else {
969                 /*
970                  * Don't allow user-mode faults in kernel address space.
971                  */
972                 if (usermode)
973                         goto nogo;
974
975                 /*
976                  * Since we know that kernel virtual address addresses
977                  * always have pte pages mapped, we just have to fault
978                  * the page.
979                  */
980                 rv = vm_fault(kernel_map, va, ftype, VM_FAULT_NORMAL);
981         }
982
983         if (rv == KERN_SUCCESS)
984                 return (0);
985 nogo:
986         if (!usermode) {
987                 if (mtd->td_gd->gd_intr_nesting_level == 0 && 
988                     td->td_pcb->pcb_onfault) {
989                         frame->tf_eip = (register_t)td->td_pcb->pcb_onfault;
990                         return (0);
991                 }
992                 trap_fatal(frame, eva);
993                 return (-1);
994         }
995
996         /* kludge to pass faulting virtual address to sendsig */
997         frame->tf_err = eva;
998
999         return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
1000 }
1001 #endif
1002
1003 int
1004 trap_pfault(struct trapframe *frame, int usermode, vm_offset_t eva)
1005 {
1006         vm_offset_t va;
1007         struct vmspace *vm = NULL;
1008         vm_map_t map = 0;
1009         int rv = 0;
1010         vm_prot_t ftype;
1011         thread_t td = curthread;
1012         struct proc *p = td->td_proc;
1013
1014         va = trunc_page(eva);
1015         if (va >= KERNBASE) {
1016                 /*
1017                  * Don't allow user-mode faults in kernel address space.
1018                  * An exception:  if the faulting address is the invalid
1019                  * instruction entry in the IDT, then the Intel Pentium
1020                  * F00F bug workaround was triggered, and we need to
1021                  * treat it is as an illegal instruction, and not a page
1022                  * fault.
1023                  */
1024 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
1025                 if ((eva == (unsigned int)&idt[6]) && has_f00f_bug) {
1026                         frame->tf_trapno = T_PRIVINFLT;
1027                         return -2;
1028                 }
1029 #endif
1030                 if (usermode)
1031                         goto nogo;
1032
1033                 map = kernel_map;
1034         } else {
1035                 /*
1036                  * This is a fault on non-kernel virtual memory.
1037                  * vm is initialized above to NULL. If curproc is NULL
1038                  * or curproc->p_vmspace is NULL the fault is fatal.
1039                  */
1040                 if (p != NULL)
1041                         vm = p->p_vmspace;
1042
1043                 if (vm == NULL)
1044                         goto nogo;
1045
1046                 map = &vm->vm_map;
1047         }
1048
1049         if (frame->tf_err & PGEX_W)
1050                 ftype = VM_PROT_WRITE;
1051         else
1052                 ftype = VM_PROT_READ;
1053
1054         if (map != kernel_map) {
1055                 /*
1056                  * Keep swapout from messing with us during this
1057                  *      critical time.
1058                  */
1059                 ++p->p_lock;
1060
1061                 /*
1062                  * Grow the stack if necessary
1063                  */
1064                 /* grow_stack returns false only if va falls into
1065                  * a growable stack region and the stack growth
1066                  * fails.  It returns true if va was not within
1067                  * a growable stack region, or if the stack 
1068                  * growth succeeded.
1069                  */
1070                 if (!grow_stack (p, va)) {
1071                         rv = KERN_FAILURE;
1072                         --p->p_lock;
1073                         goto nogo;
1074                 }
1075
1076                 /* Fault in the user page: */
1077                 rv = vm_fault(map, va, ftype,
1078                               (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
1079                                                       : VM_FAULT_NORMAL);
1080
1081                 --p->p_lock;
1082         } else {
1083                 /*
1084                  * Don't have to worry about process locking or stacks in the kernel.
1085                  */
1086                 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
1087         }
1088
1089         if (rv == KERN_SUCCESS)
1090                 return (0);
1091 nogo:
1092         if (!usermode) {
1093                 if (td->td_gd->gd_intr_nesting_level == 0 &&
1094                     td->td_pcb->pcb_onfault) {
1095                         frame->tf_eip = (register_t)td->td_pcb->pcb_onfault;
1096                         return (0);
1097                 }
1098                 trap_fatal(frame, eva);
1099                 return (-1);
1100         }
1101
1102         /* kludge to pass faulting virtual address to sendsig */
1103         frame->tf_err = eva;
1104
1105         return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
1106 }
1107
1108 static void
1109 trap_fatal(struct trapframe *frame, vm_offset_t eva)
1110 {
1111         int code, type, ss, esp;
1112         struct soft_segment_descriptor softseg;
1113
1114         code = frame->tf_err;
1115         type = frame->tf_trapno;
1116         sdtossd(&gdt[mycpu->gd_cpuid * NGDT + IDXSEL(frame->tf_cs & 0xffff)].sd, &softseg);
1117
1118         if (type <= MAX_TRAP_MSG)
1119                 printf("\n\nFatal trap %d: %s while in %s mode\n",
1120                         type, trap_msg[type],
1121                         frame->tf_eflags & PSL_VM ? "vm86" :
1122                         ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
1123 #ifdef SMP
1124         /* three separate prints in case of a trap on an unmapped page */
1125         printf("mp_lock = %08x; ", mp_lock);
1126         printf("cpuid = %d; ", mycpu->gd_cpuid);
1127         printf("lapic.id = %08x\n", lapic.id);
1128 #endif
1129         if (type == T_PAGEFLT) {
1130                 printf("fault virtual address   = 0x%x\n", eva);
1131                 printf("fault code              = %s %s, %s\n",
1132                         code & PGEX_U ? "user" : "supervisor",
1133                         code & PGEX_W ? "write" : "read",
1134                         code & PGEX_P ? "protection violation" : "page not present");
1135         }
1136         printf("instruction pointer     = 0x%x:0x%x\n",
1137                frame->tf_cs & 0xffff, frame->tf_eip);
1138         if ((ISPL(frame->tf_cs) == SEL_UPL) || (frame->tf_eflags & PSL_VM)) {
1139                 ss = frame->tf_ss & 0xffff;
1140                 esp = frame->tf_esp;
1141         } else {
1142                 ss = GSEL(GDATA_SEL, SEL_KPL);
1143                 esp = (int)&frame->tf_esp;
1144         }
1145         printf("stack pointer           = 0x%x:0x%x\n", ss, esp);
1146         printf("frame pointer           = 0x%x:0x%x\n", ss, frame->tf_ebp);
1147         printf("code segment            = base 0x%x, limit 0x%x, type 0x%x\n",
1148                softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
1149         printf("                        = DPL %d, pres %d, def32 %d, gran %d\n",
1150                softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_def32,
1151                softseg.ssd_gran);
1152         printf("processor eflags        = ");
1153         if (frame->tf_eflags & PSL_T)
1154                 printf("trace trap, ");
1155         if (frame->tf_eflags & PSL_I)
1156                 printf("interrupt enabled, ");
1157         if (frame->tf_eflags & PSL_NT)
1158                 printf("nested task, ");
1159         if (frame->tf_eflags & PSL_RF)
1160                 printf("resume, ");
1161         if (frame->tf_eflags & PSL_VM)
1162                 printf("vm86, ");
1163         printf("IOPL = %d\n", (frame->tf_eflags & PSL_IOPL) >> 12);
1164         printf("current process         = ");
1165         if (curproc) {
1166                 printf("%lu (%s)\n",
1167                     (u_long)curproc->p_pid, curproc->p_comm ?
1168                     curproc->p_comm : "");
1169         } else {
1170                 printf("Idle\n");
1171         }
1172         printf("current thread          = pri %d ", curthread->td_pri);
1173         if (curthread->td_pri >= TDPRI_CRIT)
1174                 printf("(CRIT)");
1175         printf("\n");
1176 #ifdef SMP
1177 /**
1178  *  XXX FIXME:
1179  *      we probably SHOULD have stopped the other CPUs before now!
1180  *      another CPU COULD have been touching cpl at this moment...
1181  */
1182         printf(" <- SMP: XXX");
1183 #endif
1184         printf("\n");
1185
1186 #ifdef KDB
1187         if (kdb_trap(&psl))
1188                 return;
1189 #endif
1190 #ifdef DDB
1191         if ((debugger_on_panic || db_active) && kdb_trap(type, code, frame))
1192                 return;
1193 #endif
1194         printf("trap number             = %d\n", type);
1195         if (type <= MAX_TRAP_MSG)
1196                 panic("%s", trap_msg[type]);
1197         else
1198                 panic("unknown/reserved trap");
1199 }
1200
1201 /*
1202  * Double fault handler. Called when a fault occurs while writing
1203  * a frame for a trap/exception onto the stack. This usually occurs
1204  * when the stack overflows (such is the case with infinite recursion,
1205  * for example).
1206  *
1207  * XXX Note that the current PTD gets replaced by IdlePTD when the
1208  * task switch occurs. This means that the stack that was active at
1209  * the time of the double fault is not available at <kstack> unless
1210  * the machine was idle when the double fault occurred. The downside
1211  * of this is that "trace <ebp>" in ddb won't work.
1212  */
1213 void
1214 dblfault_handler(void)
1215 {
1216         struct mdglobaldata *gd = mdcpu;
1217
1218         printf("\nFatal double fault:\n");
1219         printf("eip = 0x%x\n", gd->gd_common_tss.tss_eip);
1220         printf("esp = 0x%x\n", gd->gd_common_tss.tss_esp);
1221         printf("ebp = 0x%x\n", gd->gd_common_tss.tss_ebp);
1222 #ifdef SMP
1223         /* three separate prints in case of a trap on an unmapped page */
1224         printf("mp_lock = %08x; ", mp_lock);
1225         printf("cpuid = %d; ", mycpu->gd_cpuid);
1226         printf("lapic.id = %08x\n", lapic.id);
1227 #endif
1228         panic("double fault");
1229 }
1230
1231 /*
1232  * Compensate for 386 brain damage (missing URKR).
1233  * This is a little simpler than the pagefault handler in trap() because
1234  * it the page tables have already been faulted in and high addresses
1235  * are thrown out early for other reasons.
1236  */
1237 int
1238 trapwrite(unsigned addr)
1239 {
1240         struct proc *p;
1241         vm_offset_t va;
1242         struct vmspace *vm;
1243         int rv;
1244
1245         va = trunc_page((vm_offset_t)addr);
1246         /*
1247          * XXX - MAX is END.  Changed > to >= for temp. fix.
1248          */
1249         if (va >= VM_MAXUSER_ADDRESS)
1250                 return (1);
1251
1252         p = curproc;
1253         vm = p->p_vmspace;
1254
1255         ++p->p_lock;
1256
1257         if (!grow_stack (p, va)) {
1258                 --p->p_lock;
1259                 return (1);
1260         }
1261
1262         /*
1263          * fault the data page
1264          */
1265         rv = vm_fault(&vm->vm_map, va, VM_PROT_WRITE, VM_FAULT_DIRTY);
1266
1267         --p->p_lock;
1268
1269         if (rv != KERN_SUCCESS)
1270                 return 1;
1271
1272         return (0);
1273 }
1274
1275 /*
1276  *      syscall2 -      MP aware system call request C handler
1277  *
1278  *      A system call is essentially treated as a trap except that the
1279  *      MP lock is not held on entry or return.  We are responsible for
1280  *      obtaining the MP lock if necessary and for handling ASTs
1281  *      (e.g. a task switch) prior to return.
1282  *
1283  *      In general, only simple access and manipulation of curproc and
1284  *      the current stack is allowed without having to hold MP lock.
1285  *
1286  *      MPSAFE - note that large sections of this routine are run without
1287  *               the MP lock.
1288  */
1289
1290 void
1291 syscall2(struct trapframe frame)
1292 {
1293         struct thread *td = curthread;
1294         struct proc *p = td->td_proc;
1295         struct lwp *lp = td->td_lwp;
1296         caddr_t params;
1297         struct sysent *callp;
1298         register_t orig_tf_eflags;
1299         int sticks;
1300         int error;
1301         int narg;
1302 #ifdef INVARIANTS
1303         int crit_count = td->td_pri & ~TDPRI_MASK;
1304 #endif
1305 #ifdef SMP
1306         int have_mplock = 0;
1307 #endif
1308         u_int code;
1309         union sysunion args;
1310
1311 #ifdef DIAGNOSTIC
1312         if (ISPL(frame.tf_cs) != SEL_UPL) {
1313                 get_mplock();
1314                 panic("syscall");
1315                 /* NOT REACHED */
1316         }
1317 #endif
1318
1319 #ifdef SMP
1320         KASSERT(td->td_mpcount == 0, ("badmpcount syscall2 from %p", (void *)frame.tf_eip));
1321         if (syscall_mpsafe == 0)
1322                 MAKEMPSAFE(have_mplock);
1323 #endif
1324         userenter(td);          /* lazy raise our priority */
1325
1326         /*
1327          * Misc
1328          */
1329         sticks = (int)td->td_sticks;
1330         orig_tf_eflags = frame.tf_eflags;
1331
1332         /*
1333          * Virtual kernel intercept - if a VM context managed by a virtual
1334          * kernel issues a system call the virtual kernel handles it, not us.
1335          * Restore the virtual kernel context and return from its system
1336          * call.  The current frame is copied out to the virtual kernel.
1337          */
1338         if (p->p_vkernel && p->p_vkernel->vk_current) {
1339                 error = vkernel_trap(p, &frame);
1340                 frame.tf_eax = error;
1341                 if (error)
1342                         frame.tf_eflags |= PSL_C;
1343                 error = EJUSTRETURN;
1344                 goto out;
1345         }
1346
1347         /*
1348          * Get the system call parameters and account for time
1349          */
1350         lp->lwp_md.md_regs = &frame;
1351         params = (caddr_t)frame.tf_esp + sizeof(int);
1352         code = frame.tf_eax;
1353
1354         if (p->p_sysent->sv_prepsyscall) {
1355                 (*p->p_sysent->sv_prepsyscall)(
1356                         &frame, (int *)(&args.nosys.sysmsg + 1),
1357                         &code, &params);
1358         } else {
1359                 /*
1360                  * Need to check if this is a 32 bit or 64 bit syscall.
1361                  * fuword is MP aware.
1362                  */
1363                 if (code == SYS_syscall) {
1364                         /*
1365                          * Code is first argument, followed by actual args.
1366                          */
1367                         code = fuword(params);
1368                         params += sizeof(int);
1369                 } else if (code == SYS___syscall) {
1370                         /*
1371                          * Like syscall, but code is a quad, so as to maintain
1372                          * quad alignment for the rest of the arguments.
1373                          */
1374                         code = fuword(params);
1375                         params += sizeof(quad_t);
1376                 }
1377         }
1378
1379         code &= p->p_sysent->sv_mask;
1380         if (code >= p->p_sysent->sv_size)
1381                 callp = &p->p_sysent->sv_table[0];
1382         else
1383                 callp = &p->p_sysent->sv_table[code];
1384
1385         narg = callp->sy_narg & SYF_ARGMASK;
1386
1387         /*
1388          * copyin is MP aware, but the tracing code is not
1389          */
1390         if (narg && params) {
1391                 error = copyin(params, (caddr_t)(&args.nosys.sysmsg + 1),
1392                                 narg * sizeof(register_t));
1393                 if (error) {
1394 #ifdef KTRACE
1395                         if (KTRPOINT(td, KTR_SYSCALL)) {
1396                                 MAKEMPSAFE(have_mplock);
1397                                 
1398                                 ktrsyscall(p, code, narg,
1399                                         (void *)(&args.nosys.sysmsg + 1));
1400                         }
1401 #endif
1402                         goto bad;
1403                 }
1404         }
1405
1406 #ifdef KTRACE
1407         if (KTRPOINT(td, KTR_SYSCALL)) {
1408                 MAKEMPSAFE(have_mplock);
1409                 ktrsyscall(p, code, narg, (void *)(&args.nosys.sysmsg + 1));
1410         }
1411 #endif
1412
1413         /*
1414          * For traditional syscall code edx is left untouched when 32 bit
1415          * results are returned.  Since edx is loaded from fds[1] when the 
1416          * system call returns we pre-set it here.
1417          */
1418         args.sysmsg_fds[0] = 0;
1419         args.sysmsg_fds[1] = frame.tf_edx;
1420
1421         /*
1422          * The syscall might manipulate the trap frame. If it does it
1423          * will probably return EJUSTRETURN.
1424          */
1425         args.sysmsg_frame = &frame;
1426
1427         STOPEVENT(p, S_SCE, narg);      /* MP aware */
1428
1429 #ifdef SMP
1430         /*
1431          * Try to run the syscall without the MP lock if the syscall
1432          * is MP safe.  We have to obtain the MP lock no matter what if 
1433          * we are ktracing
1434          */
1435         if ((callp->sy_narg & SYF_MPSAFE) == 0)
1436                 MAKEMPSAFE(have_mplock);
1437 #endif
1438
1439         error = (*callp->sy_call)(&args);
1440
1441 out:
1442         /*
1443          * MP SAFE (we may or may not have the MP lock at this point)
1444          */
1445         switch (error) {
1446         case 0:
1447                 /*
1448                  * Reinitialize proc pointer `p' as it may be different
1449                  * if this is a child returning from fork syscall.
1450                  */
1451                 p = curproc;
1452                 lp = curthread->td_lwp;
1453                 frame.tf_eax = args.sysmsg_fds[0];
1454                 frame.tf_edx = args.sysmsg_fds[1];
1455                 frame.tf_eflags &= ~PSL_C;
1456                 break;
1457         case ERESTART:
1458                 /*
1459                  * Reconstruct pc, assuming lcall $X,y is 7 bytes,
1460                  * int 0x80 is 2 bytes. We saved this in tf_err.
1461                  */
1462                 frame.tf_eip -= frame.tf_err;
1463                 break;
1464         case EJUSTRETURN:
1465                 break;
1466         case EASYNC:
1467                 panic("Unexpected EASYNC return value (for now)");
1468         default:
1469 bad:
1470                 if (p->p_sysent->sv_errsize) {
1471                         if (error >= p->p_sysent->sv_errsize)
1472                                 error = -1;     /* XXX */
1473                         else
1474                                 error = p->p_sysent->sv_errtbl[error];
1475                 }
1476                 frame.tf_eax = error;
1477                 frame.tf_eflags |= PSL_C;
1478                 break;
1479         }
1480
1481         /*
1482          * Traced syscall.  trapsignal() is not MP aware.
1483          */
1484         if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1485                 MAKEMPSAFE(have_mplock);
1486                 frame.tf_eflags &= ~PSL_T;
1487                 trapsignal(p, SIGTRAP, 0);
1488         }
1489
1490         /*
1491          * Handle reschedule and other end-of-syscall issues
1492          */
1493         userret(lp, &frame, sticks);
1494
1495 #ifdef KTRACE
1496         if (KTRPOINT(td, KTR_SYSRET)) {
1497                 MAKEMPSAFE(have_mplock);
1498                 ktrsysret(p, code, error, args.sysmsg_result);
1499         }
1500 #endif
1501
1502         /*
1503          * This works because errno is findable through the
1504          * register set.  If we ever support an emulation where this
1505          * is not the case, this code will need to be revisited.
1506          */
1507         STOPEVENT(p, S_SCX, code);
1508
1509         userexit(lp);
1510 #ifdef SMP
1511         /*
1512          * Release the MP lock if we had to get it
1513          */
1514         KASSERT(td->td_mpcount == have_mplock, 
1515                 ("badmpcount syscall2/end from %p", (void *)frame.tf_eip));
1516         if (have_mplock)
1517                 rel_mplock();
1518 #endif
1519 #ifdef INVARIANTS
1520         KASSERT(crit_count == (td->td_pri & ~TDPRI_MASK), 
1521                 ("syscall: critical section count mismatch! %d/%d",
1522                 crit_count / TDPRI_CRIT, td->td_pri / TDPRI_CRIT));
1523 #endif
1524 }
1525
1526 /*
1527  * Simplified back end of syscall(), used when returning from fork()
1528  * directly into user mode.  MP lock is held on entry and should be
1529  * released on return.  This code will return back into the fork
1530  * trampoline code which then runs doreti.
1531  */
1532 void
1533 fork_return(struct lwp *lp, struct trapframe frame)
1534 {
1535         struct proc *p = lp->lwp_proc;
1536
1537         frame.tf_eax = 0;               /* Child returns zero */
1538         frame.tf_eflags &= ~PSL_C;      /* success */
1539         frame.tf_edx = 1;
1540
1541         /*
1542          * Newly forked processes are given a kernel priority.  We have to
1543          * adjust the priority to a normal user priority and fake entry
1544          * into the kernel (call userenter()) to install a passive release
1545          * function just in case userret() decides to stop the process.  This
1546          * can occur when ^Z races a fork.  If we do not install the passive
1547          * release function the current process designation will not be
1548          * released when the thread goes to sleep.
1549          */
1550         lwkt_setpri_self(TDPRI_USER_NORM);
1551         userenter(lp->lwp_thread);
1552         userret(lp, &frame, 0);
1553 #ifdef KTRACE
1554         if (KTRPOINT(lp->lwp_thread, KTR_SYSRET))
1555                 ktrsysret(p, SYS_fork, 0, 0);
1556 #endif
1557         p->p_flag |= P_PASSIVE_ACQ;
1558         userexit(lp);
1559         p->p_flag &= ~P_PASSIVE_ACQ;
1560 #ifdef SMP
1561         KKASSERT(lp->lwp_thread->td_mpcount == 1);
1562         rel_mplock();
1563 #endif
1564 }