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