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