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