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