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