kernel - More many-cores SMP work
[dragonfly.git] / sys / platform / pc64 / x86_64 / trap.c
1 /*-
2  * Copyright (c) 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (C) 1994, David Greenman
5  * Copyright (c) 2008 The DragonFly Project.
6  * Copyright (c) 2008 Jordan Gordeev.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * the University of Utah, and William Jolitz.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *      This product includes software developed by the University of
22  *      California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  *
39  * from: @(#)trap.c     7.4 (Berkeley) 5/13/91
40  * $FreeBSD: src/sys/i386/i386/trap.c,v 1.147.2.11 2003/02/27 19:09:59 luoqi Exp $
41  */
42
43 /*
44  * x86_64 Trap and System call handling
45  */
46
47 #include "use_isa.h"
48
49 #include "opt_ddb.h"
50 #include "opt_ktrace.h"
51
52 #include <machine/frame.h>
53 #include <sys/param.h>
54 #include <sys/systm.h>
55 #include <sys/kernel.h>
56 #include <sys/kerneldump.h>
57 #include <sys/proc.h>
58 #include <sys/pioctl.h>
59 #include <sys/types.h>
60 #include <sys/signal2.h>
61 #include <sys/syscall.h>
62 #include <sys/sysctl.h>
63 #include <sys/sysent.h>
64 #include <sys/systm.h>
65 #ifdef KTRACE
66 #include <sys/ktrace.h>
67 #endif
68 #include <sys/ktr.h>
69 #include <sys/sysmsg.h>
70 #include <sys/sysproto.h>
71 #include <sys/sysunion.h>
72
73 #include <vm/pmap.h>
74 #include <vm/vm.h>
75 #include <vm/vm_extern.h>
76 #include <vm/vm_kern.h>
77 #include <vm/vm_param.h>
78 #include <machine/cpu.h>
79 #include <machine/pcb.h>
80 #include <machine/smp.h>
81 #include <machine/thread.h>
82 #include <machine/clock.h>
83 #include <machine/vmparam.h>
84 #include <machine/md_var.h>
85 #include <machine_base/isa/isa_intr.h>
86 #include <machine_base/apic/lapic.h>
87
88 #include <ddb/ddb.h>
89
90 #include <sys/thread2.h>
91 #include <sys/mplock2.h>
92
93 #ifdef SMP
94
95 #define MAKEMPSAFE(have_mplock)                 \
96         if (have_mplock == 0) {                 \
97                 get_mplock();                   \
98                 have_mplock = 1;                \
99         }
100
101 #else
102
103 #define MAKEMPSAFE(have_mplock)
104
105 #endif
106
107 extern void trap(struct trapframe *frame);
108
109 static int trap_pfault(struct trapframe *, int);
110 static void trap_fatal(struct trapframe *, vm_offset_t);
111 void dblfault_handler(struct trapframe *frame);
112
113 #define MAX_TRAP_MSG            30
114 static char *trap_msg[] = {
115         "",                                     /*  0 unused */
116         "privileged instruction fault",         /*  1 T_PRIVINFLT */
117         "",                                     /*  2 unused */
118         "breakpoint instruction fault",         /*  3 T_BPTFLT */
119         "",                                     /*  4 unused */
120         "",                                     /*  5 unused */
121         "arithmetic trap",                      /*  6 T_ARITHTRAP */
122         "system forced exception",              /*  7 T_ASTFLT */
123         "",                                     /*  8 unused */
124         "general protection fault",             /*  9 T_PROTFLT */
125         "trace trap",                           /* 10 T_TRCTRAP */
126         "",                                     /* 11 unused */
127         "page fault",                           /* 12 T_PAGEFLT */
128         "",                                     /* 13 unused */
129         "alignment fault",                      /* 14 T_ALIGNFLT */
130         "",                                     /* 15 unused */
131         "",                                     /* 16 unused */
132         "",                                     /* 17 unused */
133         "integer divide fault",                 /* 18 T_DIVIDE */
134         "non-maskable interrupt trap",          /* 19 T_NMI */
135         "overflow trap",                        /* 20 T_OFLOW */
136         "FPU bounds check fault",               /* 21 T_BOUND */
137         "FPU device not available",             /* 22 T_DNA */
138         "double fault",                         /* 23 T_DOUBLEFLT */
139         "FPU operand fetch fault",              /* 24 T_FPOPFLT */
140         "invalid TSS fault",                    /* 25 T_TSSFLT */
141         "segment not present fault",            /* 26 T_SEGNPFLT */
142         "stack fault",                          /* 27 T_STKFLT */
143         "machine check trap",                   /* 28 T_MCHK */
144         "SIMD floating-point exception",        /* 29 T_XMMFLT */
145         "reserved (unknown) fault",             /* 30 T_RESERVED */
146 };
147
148 #ifdef DDB
149 static int ddb_on_nmi = 1;
150 SYSCTL_INT(_machdep, OID_AUTO, ddb_on_nmi, CTLFLAG_RW,
151         &ddb_on_nmi, 0, "Go to DDB on NMI");
152 static int ddb_on_seg_fault = 0;
153 SYSCTL_INT(_machdep, OID_AUTO, ddb_on_seg_fault, CTLFLAG_RW,
154         &ddb_on_seg_fault, 0, "Go to DDB on user seg-fault");
155 static int freeze_on_seg_fault = 0;
156 SYSCTL_INT(_machdep, OID_AUTO, freeze_on_seg_fault, CTLFLAG_RW,
157         &freeze_on_seg_fault, 0, "Go to DDB on user seg-fault");
158 #endif
159 static int panic_on_nmi = 1;
160 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
161         &panic_on_nmi, 0, "Panic on NMI");
162 static int fast_release;
163 SYSCTL_INT(_machdep, OID_AUTO, fast_release, CTLFLAG_RW,
164         &fast_release, 0, "Passive Release was optimal");
165 static int slow_release;
166 SYSCTL_INT(_machdep, OID_AUTO, slow_release, CTLFLAG_RW,
167         &slow_release, 0, "Passive Release was nonoptimal");
168
169 /*
170  * System call debugging records the worst-case system call
171  * overhead (inclusive of blocking), but may be inaccurate.
172  */
173 /*#define SYSCALL_DEBUG*/
174 #ifdef SYSCALL_DEBUG
175 uint64_t SysCallsWorstCase[SYS_MAXSYSCALL];
176 #endif
177
178 /*
179  * Passively intercepts the thread switch function to increase
180  * the thread priority from a user priority to a kernel priority, reducing
181  * syscall and trap overhead for the case where no switch occurs.
182  *
183  * Synchronizes td_ucred with p_ucred.  This is used by system calls,
184  * signal handling, faults, AST traps, and anything else that enters the
185  * kernel from userland and provides the kernel with a stable read-only
186  * copy of the process ucred.
187  */
188 static __inline void
189 userenter(struct thread *curtd, struct proc *curp)
190 {
191         struct ucred *ocred;
192         struct ucred *ncred;
193
194         curtd->td_release = lwkt_passive_release;
195
196         if (curtd->td_ucred != curp->p_ucred) {
197                 ncred = crhold(curp->p_ucred);
198                 ocred = curtd->td_ucred;
199                 curtd->td_ucred = ncred;
200                 if (ocred)
201                         crfree(ocred);
202         }
203 }
204
205 /*
206  * Handle signals, upcalls, profiling, and other AST's and/or tasks that
207  * must be completed before we can return to or try to return to userland.
208  *
209  * Note that td_sticks is a 64 bit quantity, but there's no point doing 64
210  * arithmatic on the delta calculation so the absolute tick values are
211  * truncated to an integer.
212  */
213 static void
214 userret(struct lwp *lp, struct trapframe *frame, int sticks)
215 {
216         struct proc *p = lp->lwp_proc;
217         int sig;
218
219         /*
220          * Charge system time if profiling.  Note: times are in microseconds.
221          * This may do a copyout and block, so do it first even though it
222          * means some system time will be charged as user time.
223          */
224         if (p->p_flag & P_PROFIL) {
225                 addupc_task(p, frame->tf_rip, 
226                         (u_int)((int)lp->lwp_thread->td_sticks - sticks));
227         }
228
229 recheck:
230         /*
231          * If the jungle wants us dead, so be it.
232          */
233         if (lp->lwp_flag & LWP_WEXIT) {
234                 lwkt_gettoken(&p->p_token);
235                 lwp_exit(0);
236                 lwkt_reltoken(&p->p_token);     /* NOT REACHED */
237         }
238
239         /*
240          * Block here if we are in a stopped state.
241          */
242         if (p->p_stat == SSTOP || dump_stop_usertds) {
243                 get_mplock();
244                 tstop();
245                 rel_mplock();
246                 goto recheck;
247         }
248
249         /*
250          * Post any pending upcalls.  If running a virtual kernel be sure
251          * to restore the virtual kernel's vmspace before posting the upcall.
252          */
253         if (p->p_flag & P_UPCALLPEND) {
254                 lwkt_gettoken(&p->p_token);
255                 p->p_flag &= ~P_UPCALLPEND;
256                 postupcall(lp);
257                 lwkt_reltoken(&p->p_token);
258                 goto recheck;
259         }
260
261         /*
262          * Post any pending signals.  If running a virtual kernel be sure
263          * to restore the virtual kernel's vmspace before posting the signal.
264          *
265          * WARNING!  postsig() can exit and not return.
266          */
267         if ((sig = CURSIG_TRACE(lp)) != 0) {
268                 lwkt_gettoken(&p->p_token);
269                 postsig(sig);
270                 lwkt_reltoken(&p->p_token);
271                 goto recheck;
272         }
273
274         /*
275          * block here if we are swapped out, but still process signals
276          * (such as SIGKILL).  proc0 (the swapin scheduler) is already
277          * aware of our situation, we do not have to wake it up.
278          */
279         if (p->p_flag & P_SWAPPEDOUT) {
280                 get_mplock();
281                 p->p_flag |= P_SWAPWAIT;
282                 swapin_request();
283                 if (p->p_flag & P_SWAPWAIT)
284                         tsleep(p, PCATCH, "SWOUT", 0);
285                 p->p_flag &= ~P_SWAPWAIT;
286                 rel_mplock();
287                 goto recheck;
288         }
289
290         /*
291          * Make sure postsig() handled request to restore old signal mask after
292          * running signal handler.
293          */
294         KKASSERT((lp->lwp_flag & LWP_OLDMASK) == 0);
295 }
296
297 /*
298  * Cleanup from userenter and any passive release that might have occured.
299  * We must reclaim the current-process designation before we can return
300  * to usermode.  We also handle both LWKT and USER reschedule requests.
301  */
302 static __inline void
303 userexit(struct lwp *lp)
304 {
305         struct thread *td = lp->lwp_thread;
306 /*      globaldata_t gd = td->td_gd;*/
307
308         /*
309          * Handle stop requests at kernel priority.  Any requests queued
310          * after this loop will generate another AST.
311          */
312         while (lp->lwp_proc->p_stat == SSTOP) {
313                 get_mplock();
314                 tstop();
315                 rel_mplock();
316         }
317
318         /*
319          * Reduce our priority in preparation for a return to userland.  If
320          * our passive release function was still in place, our priority was
321          * never raised and does not need to be reduced.
322          */
323         lwkt_passive_recover(td);
324
325         /*
326          * Become the current user scheduled process if we aren't already,
327          * and deal with reschedule requests and other factors.
328          */
329         lp->lwp_proc->p_usched->acquire_curproc(lp);
330         /* WARNING: we may have migrated cpu's */
331         /* gd = td->td_gd; */
332 }
333
334 #if !defined(KTR_KERNENTRY)
335 #define KTR_KERNENTRY   KTR_ALL
336 #endif
337 KTR_INFO_MASTER(kernentry);
338 KTR_INFO(KTR_KERNENTRY, kernentry, trap, 0, "STR",
339          sizeof(long) + sizeof(long) + sizeof(long) + sizeof(vm_offset_t));
340 KTR_INFO(KTR_KERNENTRY, kernentry, trap_ret, 0, "STR",
341          sizeof(long) + sizeof(long));
342 KTR_INFO(KTR_KERNENTRY, kernentry, syscall, 0, "STR",
343          sizeof(long) + sizeof(long) + sizeof(long));
344 KTR_INFO(KTR_KERNENTRY, kernentry, syscall_ret, 0, "STR",
345          sizeof(long) + sizeof(long) + sizeof(long));
346 KTR_INFO(KTR_KERNENTRY, kernentry, fork_ret, 0, "STR",
347          sizeof(long) + sizeof(long));
348
349 /*
350  * Exception, fault, and trap interface to the kernel.
351  * This common code is called from assembly language IDT gate entry
352  * routines that prepare a suitable stack frame, and restore this
353  * frame after the exception has been processed.
354  *
355  * This function is also called from doreti in an interlock to handle ASTs.
356  * For example:  hardwareint->INTROUTINE->(set ast)->doreti->trap
357  *
358  * NOTE!  We have to retrieve the fault address prior to obtaining the
359  * MP lock because get_mplock() may switch out.  YYY cr2 really ought
360  * to be retrieved by the assembly code, not here.
361  *
362  * XXX gd_trap_nesting_level currently prevents lwkt_switch() from panicing
363  * if an attempt is made to switch from a fast interrupt or IPI.  This is
364  * necessary to properly take fatal kernel traps on SMP machines if 
365  * get_mplock() has to block.
366  */
367
368 void
369 trap(struct trapframe *frame)
370 {
371         struct globaldata *gd = mycpu;
372         struct thread *td = gd->gd_curthread;
373         struct lwp *lp = td->td_lwp;
374         struct proc *p;
375         int sticks = 0;
376         int i = 0, ucode = 0, type, code;
377 #ifdef SMP
378         int have_mplock = 0;
379 #endif
380 #ifdef INVARIANTS
381         int crit_count = td->td_critcount;
382         lwkt_tokref_t curstop = td->td_toks_stop;
383 #endif
384         vm_offset_t eva;
385
386         p = td->td_proc;
387
388 #ifdef DDB
389         /*
390          * We need to allow T_DNA faults when the debugger is active since
391          * some dumping paths do large bcopy() which use the floating
392          * point registers for faster copying.
393          */
394         if (db_active && frame->tf_trapno != T_DNA) {
395                 eva = (frame->tf_trapno == T_PAGEFLT ? frame->tf_addr : 0);
396                 ++gd->gd_trap_nesting_level;
397                 MAKEMPSAFE(have_mplock);
398                 trap_fatal(frame, eva);
399                 --gd->gd_trap_nesting_level;
400                 goto out2;
401         }
402 #endif
403
404         eva = 0;
405
406         if ((frame->tf_rflags & PSL_I) == 0) {
407                 /*
408                  * Buggy application or kernel code has disabled interrupts
409                  * and then trapped.  Enabling interrupts now is wrong, but
410                  * it is better than running with interrupts disabled until
411                  * they are accidentally enabled later.
412                  */
413                 type = frame->tf_trapno;
414                 if (ISPL(frame->tf_cs) == SEL_UPL) {
415                         MAKEMPSAFE(have_mplock);
416                         /* JG curproc can be NULL */
417                         kprintf(
418                             "pid %ld (%s): trap %d with interrupts disabled\n",
419                             (long)curproc->p_pid, curproc->p_comm, type);
420                 } else if (type != T_NMI && type != T_BPTFLT &&
421                     type != T_TRCTRAP) {
422                         /*
423                          * XXX not quite right, since this may be for a
424                          * multiple fault in user mode.
425                          */
426                         MAKEMPSAFE(have_mplock);
427                         kprintf("kernel trap %d with interrupts disabled\n",
428                             type);
429                 }
430                 cpu_enable_intr();
431         }
432
433         type = frame->tf_trapno;
434         code = frame->tf_err;
435
436         if (ISPL(frame->tf_cs) == SEL_UPL) {
437                 /* user trap */
438
439                 KTR_LOG(kernentry_trap, p->p_pid, lp->lwp_tid,
440                         frame->tf_trapno, eva);
441
442                 userenter(td, p);
443
444                 sticks = (int)td->td_sticks;
445                 KASSERT(lp->lwp_md.md_regs == frame,
446                         ("Frame mismatch %p %p", lp->lwp_md.md_regs, frame));
447
448                 switch (type) {
449                 case T_PRIVINFLT:       /* privileged instruction fault */
450                         ucode = ILL_PRVOPC;
451                         i = SIGILL;
452                         break;
453
454                 case T_BPTFLT:          /* bpt instruction fault */
455                 case T_TRCTRAP:         /* trace trap */
456                         frame->tf_rflags &= ~PSL_T;
457                         ucode = TRAP_TRACE;
458                         i = SIGTRAP;
459                         break;
460
461                 case T_ARITHTRAP:       /* arithmetic trap */
462                         ucode = code;
463                         i = SIGFPE;
464 #if 0
465 #if JG
466                         ucode = fputrap();
467 #else
468                         ucode = code;
469 #endif
470                         i = SIGFPE;
471 #endif
472                         break;
473
474                 case T_ASTFLT:          /* Allow process switch */
475                         mycpu->gd_cnt.v_soft++;
476                         if (mycpu->gd_reqflags & RQF_AST_OWEUPC) {
477                                 atomic_clear_int(&mycpu->gd_reqflags,
478                                                  RQF_AST_OWEUPC);
479                                 addupc_task(p, p->p_prof.pr_addr,
480                                             p->p_prof.pr_ticks);
481                         }
482                         goto out;
483
484                 case T_PROTFLT:         /* general protection fault */
485                         i = SIGBUS;
486                         ucode = BUS_OBJERR;
487                         break;
488                 case T_SEGNPFLT:        /* segment not present fault */
489                         i = SIGBUS;
490                         ucode = BUS_ADRERR;
491                         break;
492                 case T_TSSFLT:          /* invalid TSS fault */
493                 case T_DOUBLEFLT:       /* double fault */
494                         i = SIGBUS;
495                         ucode = BUS_OBJERR;
496                 default:
497 #if 0
498                         ucode = code + BUS_SEGM_FAULT ; /* XXX: ???*/
499 #endif
500                         ucode = BUS_OBJERR;
501                         i = SIGBUS;
502                         break;
503
504                 case T_PAGEFLT:         /* page fault */
505                         i = trap_pfault(frame, TRUE);
506                         if (frame->tf_rip == 0) {
507                                 kprintf("T_PAGEFLT: Warning %%rip == 0!\n");
508                                 while (freeze_on_seg_fault) {
509                                         tsleep(p, 0, "freeze", hz * 20);
510                                 }
511                         }
512                         if (i == -1)
513                                 goto out;
514                         if (i == 0)
515                                 goto out;
516
517 #if 0
518                         ucode = T_PAGEFLT;
519 #endif
520                         if (i == SIGSEGV)
521                                 ucode = SEGV_MAPERR;
522                         else
523                                 ucode = BUS_ADRERR;
524                         break;
525
526                 case T_DIVIDE:          /* integer divide fault */
527                         ucode = FPE_INTDIV;
528                         i = SIGFPE;
529                         break;
530
531 #if NISA > 0
532                 case T_NMI:
533                         MAKEMPSAFE(have_mplock);
534                         /* machine/parity/power fail/"kitchen sink" faults */
535                         if (isa_nmi(code) == 0) {
536 #ifdef DDB
537                                 /*
538                                  * NMI can be hooked up to a pushbutton
539                                  * for debugging.
540                                  */
541                                 if (ddb_on_nmi) {
542                                         kprintf ("NMI ... going to debugger\n");
543                                         kdb_trap(type, 0, frame);
544                                 }
545 #endif /* DDB */
546                                 goto out2;
547                         } else if (panic_on_nmi)
548                                 panic("NMI indicates hardware failure");
549                         break;
550 #endif /* NISA > 0 */
551
552                 case T_OFLOW:           /* integer overflow fault */
553                         ucode = FPE_INTOVF;
554                         i = SIGFPE;
555                         break;
556
557                 case T_BOUND:           /* bounds check fault */
558                         ucode = FPE_FLTSUB;
559                         i = SIGFPE;
560                         break;
561
562                 case T_DNA:
563                         /*
564                          * Virtual kernel intercept - pass the DNA exception
565                          * to the virtual kernel if it asked to handle it.
566                          * This occurs when the virtual kernel is holding
567                          * onto the FP context for a different emulated
568                          * process then the one currently running.
569                          *
570                          * We must still call npxdna() since we may have
571                          * saved FP state that the virtual kernel needs
572                          * to hand over to a different emulated process.
573                          */
574                         if (lp->lwp_vkernel && lp->lwp_vkernel->ve &&
575                             (td->td_pcb->pcb_flags & FP_VIRTFP)
576                         ) {
577                                 npxdna();
578                                 break;
579                         }
580
581                         /*
582                          * The kernel may have switched out the FP unit's
583                          * state, causing the user process to take a fault
584                          * when it tries to use the FP unit.  Restore the
585                          * state here
586                          */
587                         if (npxdna())
588                                 goto out;
589                         i = SIGFPE;
590                         ucode = FPE_FPU_NP_TRAP;
591                         break;
592
593                 case T_FPOPFLT:         /* FPU operand fetch fault */
594                         ucode = ILL_COPROC;
595                         i = SIGILL;
596                         break;
597
598                 case T_XMMFLT:          /* SIMD floating-point exception */
599                         ucode = 0; /* XXX */
600                         i = SIGFPE;
601                         break;
602                 }
603         } else {
604                 /* kernel trap */
605
606                 switch (type) {
607                 case T_PAGEFLT:                 /* page fault */
608                         trap_pfault(frame, FALSE);
609                         goto out2;
610
611                 case T_DNA:
612                         /*
613                          * The kernel is apparently using fpu for copying.
614                          * XXX this should be fatal unless the kernel has
615                          * registered such use.
616                          */
617                         if (npxdna())
618                                 goto out2;
619                         break;
620
621                 case T_STKFLT:          /* stack fault */
622                         break;
623
624                 case T_PROTFLT:         /* general protection fault */
625                 case T_SEGNPFLT:        /* segment not present fault */
626                         /*
627                          * Invalid segment selectors and out of bounds
628                          * %rip's and %rsp's can be set up in user mode.
629                          * This causes a fault in kernel mode when the
630                          * kernel tries to return to user mode.  We want
631                          * to get this fault so that we can fix the
632                          * problem here and not have to check all the
633                          * selectors and pointers when the user changes
634                          * them.
635                          */
636                         if (mycpu->gd_intr_nesting_level == 0) {
637                                 if (td->td_pcb->pcb_onfault) {
638                                         frame->tf_rip = (register_t)
639                                                 td->td_pcb->pcb_onfault;
640                                         goto out2;
641                                 }
642                                 if (frame->tf_rip == (long)doreti_iret) {
643                                         frame->tf_rip = (long)doreti_iret_fault;
644                                         goto out2;
645                                 }
646                         }
647                         break;
648
649                 case T_TSSFLT:
650                         /*
651                          * PSL_NT can be set in user mode and isn't cleared
652                          * automatically when the kernel is entered.  This
653                          * causes a TSS fault when the kernel attempts to
654                          * `iret' because the TSS link is uninitialized.  We
655                          * want to get this fault so that we can fix the
656                          * problem here and not every time the kernel is
657                          * entered.
658                          */
659                         if (frame->tf_rflags & PSL_NT) {
660                                 frame->tf_rflags &= ~PSL_NT;
661                                 goto out2;
662                         }
663                         break;
664
665                 case T_TRCTRAP:  /* trace trap */
666 #if 0
667                         if (frame->tf_rip == (int)IDTVEC(syscall)) {
668                                 /*
669                                  * We've just entered system mode via the
670                                  * syscall lcall.  Continue single stepping
671                                  * silently until the syscall handler has
672                                  * saved the flags.
673                                  */
674                                 goto out2;
675                         }
676                         if (frame->tf_rip == (int)IDTVEC(syscall) + 1) {
677                                 /*
678                                  * The syscall handler has now saved the
679                                  * flags.  Stop single stepping it.
680                                  */
681                                 frame->tf_rflags &= ~PSL_T;
682                                 goto out2;
683                         }
684 #endif
685
686                         /*
687                          * Ignore debug register trace traps due to
688                          * accesses in the user's address space, which
689                          * can happen under several conditions such as
690                          * if a user sets a watchpoint on a buffer and
691                          * then passes that buffer to a system call.
692                          * We still want to get TRCTRAPS for addresses
693                          * in kernel space because that is useful when
694                          * debugging the kernel.
695                          */
696 #if JG
697                         if (user_dbreg_trap()) {
698                                 /*
699                                  * Reset breakpoint bits because the
700                                  * processor doesn't
701                                  */
702                                 /* XXX check upper bits here */
703                                 load_dr6(rdr6() & 0xfffffff0);
704                                 goto out2;
705                         }
706 #endif
707                         /*
708                          * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
709                          */
710                 case T_BPTFLT:
711                         /*
712                          * If DDB is enabled, let it handle the debugger trap.
713                          * Otherwise, debugger traps "can't happen".
714                          */
715                         ucode = TRAP_BRKPT;
716 #ifdef DDB
717                         MAKEMPSAFE(have_mplock);
718                         if (kdb_trap(type, 0, frame))
719                                 goto out2;
720 #endif
721                         break;
722
723 #if NISA > 0
724                 case T_NMI:
725                         MAKEMPSAFE(have_mplock);
726                         /* machine/parity/power fail/"kitchen sink" faults */
727                         if (isa_nmi(code) == 0) {
728 #ifdef DDB
729                                 /*
730                                  * NMI can be hooked up to a pushbutton
731                                  * for debugging.
732                                  */
733                                 if (ddb_on_nmi) {
734                                         kprintf ("NMI ... going to debugger\n");
735                                         kdb_trap(type, 0, frame);
736                                 }
737 #endif /* DDB */
738                                 goto out2;
739                         } else if (panic_on_nmi == 0)
740                                 goto out2;
741                         /* FALL THROUGH */
742 #endif /* NISA > 0 */
743                 }
744                 MAKEMPSAFE(have_mplock);
745                 trap_fatal(frame, 0);
746                 goto out2;
747         }
748
749         /*
750          * Virtual kernel intercept - if the fault is directly related to a
751          * VM context managed by a virtual kernel then let the virtual kernel
752          * handle it.
753          */
754         if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
755                 vkernel_trap(lp, frame);
756                 goto out;
757         }
758
759         /*
760          * Translate fault for emulators (e.g. Linux) 
761          */
762         if (*p->p_sysent->sv_transtrap)
763                 i = (*p->p_sysent->sv_transtrap)(i, type);
764
765         MAKEMPSAFE(have_mplock);
766         trapsignal(lp, i, ucode);
767
768 #ifdef DEBUG
769         if (type <= MAX_TRAP_MSG) {
770                 uprintf("fatal process exception: %s",
771                         trap_msg[type]);
772                 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
773                         uprintf(", fault VA = 0x%lx", frame->tf_addr);
774                 uprintf("\n");
775         }
776 #endif
777
778 out:
779         userret(lp, frame, sticks);
780         userexit(lp);
781 out2:   ;
782 #ifdef SMP
783         if (have_mplock)
784                 rel_mplock();
785 #endif
786         if (p != NULL && lp != NULL)
787                 KTR_LOG(kernentry_trap_ret, p->p_pid, lp->lwp_tid);
788 #ifdef INVARIANTS
789         KASSERT(crit_count == td->td_critcount,
790                 ("trap: critical section count mismatch! %d/%d",
791                 crit_count, td->td_pri));
792         KASSERT(curstop == td->td_toks_stop,
793                 ("trap: extra tokens held after trap! %ld/%ld",
794                 curstop - &td->td_toks_base,
795                 td->td_toks_stop - &td->td_toks_base));
796 #endif
797 }
798
799 static int
800 trap_pfault(struct trapframe *frame, int usermode)
801 {
802         vm_offset_t va;
803         struct vmspace *vm = NULL;
804         vm_map_t map;
805         int rv = 0;
806         int fault_flags;
807         vm_prot_t ftype;
808         thread_t td = curthread;
809         struct lwp *lp = td->td_lwp;
810         struct proc *p;
811
812         va = trunc_page(frame->tf_addr);
813         if (va >= VM_MIN_KERNEL_ADDRESS) {
814                 /*
815                  * Don't allow user-mode faults in kernel address space.
816                  */
817                 if (usermode) {
818                         fault_flags = -1;
819                         ftype = -1;
820                         goto nogo;
821                 }
822
823                 map = &kernel_map;
824         } else {
825                 /*
826                  * This is a fault on non-kernel virtual memory.
827                  * vm is initialized above to NULL. If curproc is NULL
828                  * or curproc->p_vmspace is NULL the fault is fatal.
829                  */
830                 if (lp != NULL)
831                         vm = lp->lwp_vmspace;
832
833                 if (vm == NULL) {
834                         fault_flags = -1;
835                         ftype = -1;
836                         goto nogo;
837                 }
838
839                 map = &vm->vm_map;
840         }
841
842         /*
843          * PGEX_I is defined only if the execute disable bit capability is
844          * supported and enabled.
845          */
846         if (frame->tf_err & PGEX_W)
847                 ftype = VM_PROT_WRITE;
848 #if JG
849         else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
850                 ftype = VM_PROT_EXECUTE;
851 #endif
852         else
853                 ftype = VM_PROT_READ;
854
855         if (map != &kernel_map) {
856                 /*
857                  * Keep swapout from messing with us during this
858                  *      critical time.
859                  */
860                 PHOLD(lp->lwp_proc);
861
862                 /*
863                  * Issue fault
864                  */
865                 fault_flags = 0;
866                 if (usermode)
867                         fault_flags |= VM_FAULT_BURST;
868                 if (ftype & VM_PROT_WRITE)
869                         fault_flags |= VM_FAULT_DIRTY;
870                 else
871                         fault_flags |= VM_FAULT_NORMAL;
872                 rv = vm_fault(map, va, ftype, fault_flags);
873
874                 PRELE(lp->lwp_proc);
875         } else {
876                 /*
877                  * Don't have to worry about process locking or stacks
878                  * in the kernel.
879                  */
880                 fault_flags = VM_FAULT_NORMAL;
881                 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
882         }
883
884         if (rv == KERN_SUCCESS)
885                 return (0);
886 nogo:
887         if (!usermode) {
888                 if (td->td_gd->gd_intr_nesting_level == 0 &&
889                     td->td_pcb->pcb_onfault) {
890                         frame->tf_rip = (register_t)td->td_pcb->pcb_onfault;
891                         return (0);
892                 }
893                 trap_fatal(frame, frame->tf_addr);
894                 return (-1);
895         }
896
897         /*
898          * NOTE: on x86_64 we have a tf_addr field in the trapframe, no
899          * kludge is needed to pass the fault address to signal handlers.
900          */
901         p = td->td_proc;
902         if (td->td_lwp->lwp_vkernel == NULL) {
903                 if (bootverbose || freeze_on_seg_fault || ddb_on_seg_fault) {
904                         kprintf("seg-fault ft=%04x ff=%04x addr=%p rip=%p "
905                             "pid=%d p_comm=%s\n",
906                             ftype, fault_flags,
907                             (void *)frame->tf_addr,
908                             (void *)frame->tf_rip,
909                             p->p_pid, p->p_comm);
910                 }
911 #ifdef DDB
912                 while (freeze_on_seg_fault) {
913                         tsleep(p, 0, "freeze", hz * 20);
914                 }
915                 if (ddb_on_seg_fault)
916                         Debugger("ddb_on_seg_fault");
917 #endif
918         }
919
920         return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
921 }
922
923 static void
924 trap_fatal(struct trapframe *frame, vm_offset_t eva)
925 {
926         int code, ss;
927         u_int type;
928         long rsp;
929         struct soft_segment_descriptor softseg;
930         char *msg;
931
932         code = frame->tf_err;
933         type = frame->tf_trapno;
934         sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)], &softseg);
935
936         if (type <= MAX_TRAP_MSG)
937                 msg = trap_msg[type];
938         else
939                 msg = "UNKNOWN";
940         kprintf("\n\nFatal trap %d: %s while in %s mode\n", type, msg,
941             ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
942 #ifdef SMP
943         /* three separate prints in case of a trap on an unmapped page */
944         kprintf("cpuid = %d; ", mycpu->gd_cpuid);
945         kprintf("lapic->id = %08x\n", lapic->id);
946 #endif
947         if (type == T_PAGEFLT) {
948                 kprintf("fault virtual address  = 0x%lx\n", eva);
949                 kprintf("fault code             = %s %s %s, %s\n",
950                         code & PGEX_U ? "user" : "supervisor",
951                         code & PGEX_W ? "write" : "read",
952                         code & PGEX_I ? "instruction" : "data",
953                         code & PGEX_P ? "protection violation" : "page not present");
954         }
955         kprintf("instruction pointer    = 0x%lx:0x%lx\n",
956                frame->tf_cs & 0xffff, frame->tf_rip);
957         if (ISPL(frame->tf_cs) == SEL_UPL) {
958                 ss = frame->tf_ss & 0xffff;
959                 rsp = frame->tf_rsp;
960         } else {
961                 ss = GSEL(GDATA_SEL, SEL_KPL);
962                 rsp = (long)&frame->tf_rsp;
963         }
964         kprintf("stack pointer          = 0x%x:0x%lx\n", ss, rsp);
965         kprintf("frame pointer          = 0x%x:0x%lx\n", ss, frame->tf_rbp);
966         kprintf("code segment           = base 0x%lx, limit 0x%lx, type 0x%x\n",
967                softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
968         kprintf("                       = DPL %d, pres %d, long %d, def32 %d, gran %d\n",
969                softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
970                softseg.ssd_gran);
971         kprintf("processor eflags       = ");
972         if (frame->tf_rflags & PSL_T)
973                 kprintf("trace trap, ");
974         if (frame->tf_rflags & PSL_I)
975                 kprintf("interrupt enabled, ");
976         if (frame->tf_rflags & PSL_NT)
977                 kprintf("nested task, ");
978         if (frame->tf_rflags & PSL_RF)
979                 kprintf("resume, ");
980         kprintf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
981         kprintf("current process                = ");
982         if (curproc) {
983                 kprintf("%lu\n",
984                     (u_long)curproc->p_pid);
985         } else {
986                 kprintf("Idle\n");
987         }
988         kprintf("current thread          = pri %d ", curthread->td_pri);
989         if (curthread->td_critcount)
990                 kprintf("(CRIT)");
991         kprintf("\n");
992
993 #ifdef DDB
994         if ((debugger_on_panic || db_active) && kdb_trap(type, code, frame))
995                 return;
996 #endif
997         kprintf("trap number            = %d\n", type);
998         if (type <= MAX_TRAP_MSG)
999                 panic("%s", trap_msg[type]);
1000         else
1001                 panic("unknown/reserved trap");
1002 }
1003
1004 /*
1005  * Double fault handler. Called when a fault occurs while writing
1006  * a frame for a trap/exception onto the stack. This usually occurs
1007  * when the stack overflows (such is the case with infinite recursion,
1008  * for example).
1009  */
1010 static __inline
1011 int
1012 in_kstack_guard(register_t rptr)
1013 {
1014         thread_t td = curthread;
1015
1016         if ((char *)rptr >= td->td_kstack &&
1017             (char *)rptr < td->td_kstack + PAGE_SIZE) {
1018                 return 1;
1019         }
1020         return 0;
1021 }
1022
1023 void
1024 dblfault_handler(struct trapframe *frame)
1025 {
1026         thread_t td = curthread;
1027
1028         if (in_kstack_guard(frame->tf_rsp) || in_kstack_guard(frame->tf_rbp)) {
1029                 kprintf("DOUBLE FAULT - KERNEL STACK GUARD HIT!\n");
1030                 if (in_kstack_guard(frame->tf_rsp))
1031                         frame->tf_rsp = (register_t)(td->td_kstack + PAGE_SIZE);
1032                 if (in_kstack_guard(frame->tf_rbp))
1033                         frame->tf_rbp = (register_t)(td->td_kstack + PAGE_SIZE);
1034         } else {
1035                 kprintf("DOUBLE FAULT\n");
1036         }
1037         kprintf("\nFatal double fault\n");
1038         kprintf("rip = 0x%lx\n", frame->tf_rip);
1039         kprintf("rsp = 0x%lx\n", frame->tf_rsp);
1040         kprintf("rbp = 0x%lx\n", frame->tf_rbp);
1041 #ifdef SMP
1042         /* three separate prints in case of a trap on an unmapped page */
1043         kprintf("cpuid = %d; ", mycpu->gd_cpuid);
1044         kprintf("lapic->id = %08x\n", lapic->id);
1045 #endif
1046         panic("double fault");
1047 }
1048
1049 /*
1050  * syscall2 -   MP aware system call request C handler
1051  *
1052  * A system call is essentially treated as a trap except that the
1053  * MP lock is not held on entry or return.  We are responsible for
1054  * obtaining the MP lock if necessary and for handling ASTs
1055  * (e.g. a task switch) prior to return.
1056  *
1057  * MPSAFE
1058  */
1059 void
1060 syscall2(struct trapframe *frame)
1061 {
1062         struct thread *td = curthread;
1063         struct proc *p = td->td_proc;
1064         struct lwp *lp = td->td_lwp;
1065         caddr_t params;
1066         struct sysent *callp;
1067         register_t orig_tf_rflags;
1068         int sticks;
1069         int error;
1070         int narg;
1071 #ifdef INVARIANTS
1072         int crit_count = td->td_critcount;
1073 #endif
1074 #ifdef SMP
1075         int have_mplock = 0;
1076 #endif
1077         register_t *argp;
1078         u_int code;
1079         int reg, regcnt;
1080         union sysunion args;
1081         register_t *argsdst;
1082
1083         mycpu->gd_cnt.v_syscall++;
1084
1085 #ifdef DIAGNOSTIC
1086         if (ISPL(frame->tf_cs) != SEL_UPL) {
1087                 get_mplock();
1088                 panic("syscall");
1089                 /* NOT REACHED */
1090         }
1091 #endif
1092
1093         KTR_LOG(kernentry_syscall, p->p_pid, lp->lwp_tid,
1094                 frame->tf_rax);
1095
1096         userenter(td, p);       /* lazy raise our priority */
1097
1098         reg = 0;
1099         regcnt = 6;
1100         /*
1101          * Misc
1102          */
1103         sticks = (int)td->td_sticks;
1104         orig_tf_rflags = frame->tf_rflags;
1105
1106         /*
1107          * Virtual kernel intercept - if a VM context managed by a virtual
1108          * kernel issues a system call the virtual kernel handles it, not us.
1109          * Restore the virtual kernel context and return from its system
1110          * call.  The current frame is copied out to the virtual kernel.
1111          */
1112         if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
1113                 vkernel_trap(lp, frame);
1114                 error = EJUSTRETURN;
1115                 goto out;
1116         }
1117
1118         /*
1119          * Get the system call parameters and account for time
1120          */
1121         KASSERT(lp->lwp_md.md_regs == frame,
1122                 ("Frame mismatch %p %p", lp->lwp_md.md_regs, frame));
1123         params = (caddr_t)frame->tf_rsp + sizeof(register_t);
1124         code = frame->tf_rax;
1125
1126         if (p->p_sysent->sv_prepsyscall) {
1127                 (*p->p_sysent->sv_prepsyscall)(
1128                         frame, (int *)(&args.nosys.sysmsg + 1),
1129                         &code, &params);
1130         } else {
1131                 if (code == SYS_syscall || code == SYS___syscall) {
1132                         code = frame->tf_rdi;
1133                         reg++;
1134                         regcnt--;
1135                 }
1136         }
1137
1138         if (p->p_sysent->sv_mask)
1139                 code &= p->p_sysent->sv_mask;
1140
1141         if (code >= p->p_sysent->sv_size)
1142                 callp = &p->p_sysent->sv_table[0];
1143         else
1144                 callp = &p->p_sysent->sv_table[code];
1145
1146         narg = callp->sy_narg & SYF_ARGMASK;
1147
1148         /*
1149          * On x86_64 we get up to six arguments in registers. The rest are
1150          * on the stack. The first six members of 'struct trapframe' happen
1151          * to be the registers used to pass arguments, in exactly the right
1152          * order.
1153          */
1154         argp = &frame->tf_rdi;
1155         argp += reg;
1156         argsdst = (register_t *)(&args.nosys.sysmsg + 1);
1157         /*
1158          * JG can we overflow the space pointed to by 'argsdst'
1159          * either with 'bcopy' or with 'copyin'?
1160          */
1161         bcopy(argp, argsdst, sizeof(register_t) * regcnt);
1162         /*
1163          * copyin is MP aware, but the tracing code is not
1164          */
1165         if (narg > regcnt) {
1166                 KASSERT(params != NULL, ("copyin args with no params!"));
1167                 error = copyin(params, &argsdst[regcnt],
1168                         (narg - regcnt) * sizeof(register_t));
1169                 if (error) {
1170 #ifdef KTRACE
1171                         if (KTRPOINT(td, KTR_SYSCALL)) {
1172                                 MAKEMPSAFE(have_mplock);
1173                                 
1174                                 ktrsyscall(lp, code, narg,
1175                                         (void *)(&args.nosys.sysmsg + 1));
1176                         }
1177 #endif
1178                         goto bad;
1179                 }
1180         }
1181
1182 #ifdef KTRACE
1183         if (KTRPOINT(td, KTR_SYSCALL)) {
1184                 MAKEMPSAFE(have_mplock);
1185                 ktrsyscall(lp, code, narg, (void *)(&args.nosys.sysmsg + 1));
1186         }
1187 #endif
1188
1189         /*
1190          * Default return value is 0 (will be copied to %rax).  Double-value
1191          * returns use %rax and %rdx.  %rdx is left unchanged for system
1192          * calls which return only one result.
1193          */
1194         args.sysmsg_fds[0] = 0;
1195         args.sysmsg_fds[1] = frame->tf_rdx;
1196
1197         /*
1198          * The syscall might manipulate the trap frame. If it does it
1199          * will probably return EJUSTRETURN.
1200          */
1201         args.sysmsg_frame = frame;
1202
1203         STOPEVENT(p, S_SCE, narg);      /* MP aware */
1204
1205         /*
1206          * NOTE: All system calls run MPSAFE now.  The system call itself
1207          *       is responsible for getting the MP lock.
1208          */
1209 #ifdef SYSCALL_DEBUG
1210         uint64_t tscval = rdtsc();
1211 #endif
1212         error = (*callp->sy_call)(&args);
1213 #ifdef SYSCALL_DEBUG
1214         tscval = rdtsc() - tscval;
1215         tscval = tscval * 1000000 / tsc_frequency;
1216         if (SysCallsWorstCase[code] < tscval)
1217                 SysCallsWorstCase[code] = tscval;
1218 #endif
1219
1220 out:
1221         /*
1222          * MP SAFE (we may or may not have the MP lock at this point)
1223          */
1224         //kprintf("SYSMSG %d ", error);
1225         switch (error) {
1226         case 0:
1227                 /*
1228                  * Reinitialize proc pointer `p' as it may be different
1229                  * if this is a child returning from fork syscall.
1230                  */
1231                 p = curproc;
1232                 lp = curthread->td_lwp;
1233                 frame->tf_rax = args.sysmsg_fds[0];
1234                 frame->tf_rdx = args.sysmsg_fds[1];
1235                 frame->tf_rflags &= ~PSL_C;
1236                 break;
1237         case ERESTART:
1238                 /*
1239                  * Reconstruct pc, we know that 'syscall' is 2 bytes.
1240                  * We have to do a full context restore so that %r10
1241                  * (which was holding the value of %rcx) is restored for
1242                  * the next iteration.
1243                  */
1244                 frame->tf_rip -= frame->tf_err;
1245                 frame->tf_r10 = frame->tf_rcx;
1246                 break;
1247         case EJUSTRETURN:
1248                 break;
1249         case EASYNC:
1250                 panic("Unexpected EASYNC return value (for now)");
1251         default:
1252 bad:
1253                 if (p->p_sysent->sv_errsize) {
1254                         if (error >= p->p_sysent->sv_errsize)
1255                                 error = -1;     /* XXX */
1256                         else
1257                                 error = p->p_sysent->sv_errtbl[error];
1258                 }
1259                 frame->tf_rax = error;
1260                 frame->tf_rflags |= PSL_C;
1261                 break;
1262         }
1263
1264         /*
1265          * Traced syscall.  trapsignal() is not MP aware.
1266          */
1267         if (orig_tf_rflags & PSL_T) {
1268                 MAKEMPSAFE(have_mplock);
1269                 frame->tf_rflags &= ~PSL_T;
1270                 trapsignal(lp, SIGTRAP, TRAP_TRACE);
1271         }
1272
1273         /*
1274          * Handle reschedule and other end-of-syscall issues
1275          */
1276         userret(lp, frame, sticks);
1277
1278 #ifdef KTRACE
1279         if (KTRPOINT(td, KTR_SYSRET)) {
1280                 MAKEMPSAFE(have_mplock);
1281                 ktrsysret(lp, code, error, args.sysmsg_result);
1282         }
1283 #endif
1284
1285         /*
1286          * This works because errno is findable through the
1287          * register set.  If we ever support an emulation where this
1288          * is not the case, this code will need to be revisited.
1289          */
1290         STOPEVENT(p, S_SCX, code);
1291
1292         userexit(lp);
1293 #ifdef SMP
1294         /*
1295          * Release the MP lock if we had to get it
1296          */
1297         if (have_mplock)
1298                 rel_mplock();
1299 #endif
1300         KTR_LOG(kernentry_syscall_ret, p->p_pid, lp->lwp_tid, error);
1301 #ifdef INVARIANTS
1302         KASSERT(crit_count == td->td_critcount,
1303                 ("syscall: critical section count mismatch! %d/%d",
1304                 crit_count, td->td_pri));
1305         KASSERT(&td->td_toks_base == td->td_toks_stop,
1306                 ("syscall: extra tokens held after trap! %ld",
1307                 td->td_toks_stop - &td->td_toks_base));
1308 #endif
1309 }
1310
1311 /*
1312  * NOTE: mplock not held at any point
1313  */
1314 void
1315 fork_return(struct lwp *lp, struct trapframe *frame)
1316 {
1317         frame->tf_rax = 0;              /* Child returns zero */
1318         frame->tf_rflags &= ~PSL_C;     /* success */
1319         frame->tf_rdx = 1;
1320
1321         generic_lwp_return(lp, frame);
1322         KTR_LOG(kernentry_fork_ret, lp->lwp_proc->p_pid, lp->lwp_tid);
1323 }
1324
1325 /*
1326  * Simplified back end of syscall(), used when returning from fork()
1327  * directly into user mode.
1328  *
1329  * This code will return back into the fork trampoline code which then
1330  * runs doreti.
1331  *
1332  * NOTE: The mplock is not held at any point.
1333  */
1334 void
1335 generic_lwp_return(struct lwp *lp, struct trapframe *frame)
1336 {
1337         struct proc *p = lp->lwp_proc;
1338
1339         /*
1340          * Newly forked processes are given a kernel priority.  We have to
1341          * adjust the priority to a normal user priority and fake entry
1342          * into the kernel (call userenter()) to install a passive release
1343          * function just in case userret() decides to stop the process.  This
1344          * can occur when ^Z races a fork.  If we do not install the passive
1345          * release function the current process designation will not be
1346          * released when the thread goes to sleep.
1347          */
1348         lwkt_setpri_self(TDPRI_USER_NORM);
1349         userenter(lp->lwp_thread, p);
1350         userret(lp, frame, 0);
1351 #ifdef KTRACE
1352         if (KTRPOINT(lp->lwp_thread, KTR_SYSRET))
1353                 ktrsysret(lp, SYS_fork, 0, 0);
1354 #endif
1355         p->p_flag |= P_PASSIVE_ACQ;
1356         userexit(lp);
1357         p->p_flag &= ~P_PASSIVE_ACQ;
1358 }
1359
1360 /*
1361  * If PGEX_FPFAULT is set then set FP_VIRTFP in the PCB to force a T_DNA
1362  * fault (which is then passed back to the virtual kernel) if an attempt is
1363  * made to use the FP unit.
1364  *
1365  * XXX this is a fairly big hack.
1366  */
1367 void
1368 set_vkernel_fp(struct trapframe *frame)
1369 {
1370         struct thread *td = curthread;
1371
1372         if (frame->tf_xflags & PGEX_FPFAULT) {
1373                 td->td_pcb->pcb_flags |= FP_VIRTFP;
1374                 if (mdcpu->gd_npxthread == td)
1375                         npxexit();
1376         } else {
1377                 td->td_pcb->pcb_flags &= ~FP_VIRTFP;
1378         }
1379 }
1380
1381 /*
1382  * Called from vkernel_trap() to fixup the vkernel's syscall
1383  * frame for vmspace_ctl() return.
1384  */
1385 void
1386 cpu_vkernel_trap(struct trapframe *frame, int error)
1387 {
1388         frame->tf_rax = error;
1389         if (error)
1390                 frame->tf_rflags |= PSL_C;
1391         else
1392                 frame->tf_rflags &= ~PSL_C;
1393 }