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