xref: /dragonfly/sys/platform/pc64/x86_64/trap.c (revision 6c2b3e4e)
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 void
804 trap_handle_userenter(struct thread *td)
805 {
806 	userenter(td, td->td_proc);
807 }
808 
809 void
810 trap_handle_userexit(struct trapframe *frame, int sticks)
811 {
812 	struct lwp *lp = curthread->td_lwp;
813 
814 	if (lp) {
815 		userret(lp, frame, sticks);
816 		userexit(lp);
817 	}
818 }
819 
820 static int
821 trap_pfault(struct trapframe *frame, int usermode)
822 {
823 	vm_offset_t va;
824 	struct vmspace *vm = NULL;
825 	vm_map_t map;
826 	int rv = 0;
827 	int fault_flags;
828 	vm_prot_t ftype;
829 	thread_t td = curthread;
830 	struct lwp *lp = td->td_lwp;
831 	struct proc *p;
832 
833 	va = trunc_page(frame->tf_addr);
834 	if (va >= VM_MIN_KERNEL_ADDRESS) {
835 		/*
836 		 * Don't allow user-mode faults in kernel address space.
837 		 */
838 		if (usermode) {
839 			fault_flags = -1;
840 			ftype = -1;
841 			goto nogo;
842 		}
843 
844 		map = &kernel_map;
845 	} else {
846 		/*
847 		 * This is a fault on non-kernel virtual memory.
848 		 * vm is initialized above to NULL. If curproc is NULL
849 		 * or curproc->p_vmspace is NULL the fault is fatal.
850 		 */
851 		if (lp != NULL)
852 			vm = lp->lwp_vmspace;
853 
854 		if (vm == NULL) {
855 			fault_flags = -1;
856 			ftype = -1;
857 			goto nogo;
858 		}
859 
860 		/*
861 		 * Debugging, try to catch kernel faults on the user address
862 		 * space when not inside on onfault (e.g. copyin/copyout)
863 		 * routine.
864 		 */
865 		if (usermode == 0 && (td->td_pcb == NULL ||
866 		    td->td_pcb->pcb_onfault == NULL)) {
867 #ifdef DDB
868 			if (freeze_on_seg_fault) {
869 				kprintf("trap_pfault: user address fault from kernel mode "
870 					"%016lx\n", (long)frame->tf_addr);
871 				while (freeze_on_seg_fault)
872 					    tsleep(&freeze_on_seg_fault, 0, "frzseg", hz * 20);
873 			}
874 #endif
875 		}
876 		map = &vm->vm_map;
877 	}
878 
879 	/*
880 	 * PGEX_I is defined only if the execute disable bit capability is
881 	 * supported and enabled.
882 	 */
883 	if (frame->tf_err & PGEX_W)
884 		ftype = VM_PROT_WRITE;
885 #if JG
886 	else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
887 		ftype = VM_PROT_EXECUTE;
888 #endif
889 	else
890 		ftype = VM_PROT_READ;
891 
892 	if (map != &kernel_map) {
893 		/*
894 		 * Keep swapout from messing with us during this
895 		 *	critical time.
896 		 */
897 		PHOLD(lp->lwp_proc);
898 
899 		/*
900 		 * Issue fault
901 		 */
902 		fault_flags = 0;
903 		if (usermode)
904 			fault_flags |= VM_FAULT_BURST;
905 		if (ftype & VM_PROT_WRITE)
906 			fault_flags |= VM_FAULT_DIRTY;
907 		else
908 			fault_flags |= VM_FAULT_NORMAL;
909 		rv = vm_fault(map, va, ftype, fault_flags);
910 
911 		PRELE(lp->lwp_proc);
912 	} else {
913 		/*
914 		 * Don't have to worry about process locking or stacks in the
915 		 * kernel.
916 		 */
917 		fault_flags = VM_FAULT_NORMAL;
918 		rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
919 	}
920 	if (rv == KERN_SUCCESS)
921 		return (0);
922 nogo:
923 	if (!usermode) {
924 		/*
925 		 * NOTE: in 64-bit mode traps push rsp/ss
926 		 *	 even if no ring change occurs.
927 		 */
928 		if (td->td_pcb->pcb_onfault &&
929 		    td->td_pcb->pcb_onfault_sp == frame->tf_rsp &&
930 		    td->td_gd->gd_intr_nesting_level == 0) {
931 			frame->tf_rip = (register_t)td->td_pcb->pcb_onfault;
932 			return (0);
933 		}
934 		trap_fatal(frame, frame->tf_addr);
935 		return (-1);
936 	}
937 
938 	/*
939 	 * NOTE: on x86_64 we have a tf_addr field in the trapframe, no
940 	 * kludge is needed to pass the fault address to signal handlers.
941 	 */
942 	p = td->td_proc;
943 #ifdef DDB
944 	if (td->td_lwp->lwp_vkernel == NULL) {
945 		while (freeze_on_seg_fault) {
946 			tsleep(p, 0, "freeze", hz * 20);
947 		}
948 		if (ddb_on_seg_fault)
949 			Debugger("ddb_on_seg_fault");
950 	}
951 #endif
952 
953 	return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
954 }
955 
956 static void
957 trap_fatal(struct trapframe *frame, vm_offset_t eva)
958 {
959 	int code, ss;
960 	u_int type;
961 	long rsp;
962 	struct soft_segment_descriptor softseg;
963 	char *msg;
964 
965 	code = frame->tf_err;
966 	type = frame->tf_trapno;
967 	sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)], &softseg);
968 
969 	if (type <= MAX_TRAP_MSG)
970 		msg = trap_msg[type];
971 	else
972 		msg = "UNKNOWN";
973 	kprintf("\n\nFatal trap %d: %s while in %s mode\n", type, msg,
974 	    ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
975 	/* three separate prints in case of a trap on an unmapped page */
976 	kprintf("cpuid = %d; ", mycpu->gd_cpuid);
977 	kprintf("lapic->id = %08x\n", lapic->id);
978 	if (type == T_PAGEFLT) {
979 		kprintf("fault virtual address	= 0x%lx\n", eva);
980 		kprintf("fault code		= %s %s %s, %s\n",
981 			code & PGEX_U ? "user" : "supervisor",
982 			code & PGEX_W ? "write" : "read",
983 			code & PGEX_I ? "instruction" : "data",
984 			code & PGEX_P ? "protection violation" : "page not present");
985 	}
986 	kprintf("instruction pointer	= 0x%lx:0x%lx\n",
987 	       frame->tf_cs & 0xffff, frame->tf_rip);
988         if (ISPL(frame->tf_cs) == SEL_UPL) {
989 		ss = frame->tf_ss & 0xffff;
990 		rsp = frame->tf_rsp;
991 	} else {
992 		/*
993 		 * NOTE: in 64-bit mode traps push rsp/ss even if no ring
994 		 *	 change occurs.
995 		 */
996 		ss = GSEL(GDATA_SEL, SEL_KPL);
997 		rsp = frame->tf_rsp;
998 	}
999 	kprintf("stack pointer	        = 0x%x:0x%lx\n", ss, rsp);
1000 	kprintf("frame pointer	        = 0x%x:0x%lx\n", ss, frame->tf_rbp);
1001 	kprintf("code segment		= base 0x%lx, limit 0x%lx, type 0x%x\n",
1002 	       softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
1003 	kprintf("			= DPL %d, pres %d, long %d, def32 %d, gran %d\n",
1004 	       softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
1005 	       softseg.ssd_gran);
1006 	kprintf("processor eflags	= ");
1007 	if (frame->tf_rflags & PSL_T)
1008 		kprintf("trace trap, ");
1009 	if (frame->tf_rflags & PSL_I)
1010 		kprintf("interrupt enabled, ");
1011 	if (frame->tf_rflags & PSL_NT)
1012 		kprintf("nested task, ");
1013 	if (frame->tf_rflags & PSL_RF)
1014 		kprintf("resume, ");
1015 	kprintf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
1016 	kprintf("current process		= ");
1017 	if (curproc) {
1018 		kprintf("%lu\n",
1019 		    (u_long)curproc->p_pid);
1020 	} else {
1021 		kprintf("Idle\n");
1022 	}
1023 	kprintf("current thread          = pri %d ", curthread->td_pri);
1024 	if (curthread->td_critcount)
1025 		kprintf("(CRIT)");
1026 	kprintf("\n");
1027 
1028 #ifdef DDB
1029 	if ((debugger_on_panic || db_active) && kdb_trap(type, code, frame))
1030 		return;
1031 #endif
1032 	kprintf("trap number		= %d\n", type);
1033 	if (type <= MAX_TRAP_MSG)
1034 		panic("%s", trap_msg[type]);
1035 	else
1036 		panic("unknown/reserved trap");
1037 }
1038 
1039 /*
1040  * Double fault handler. Called when a fault occurs while writing
1041  * a frame for a trap/exception onto the stack. This usually occurs
1042  * when the stack overflows (such is the case with infinite recursion,
1043  * for example).
1044  */
1045 static __inline
1046 int
1047 in_kstack_guard(register_t rptr)
1048 {
1049 	thread_t td = curthread;
1050 
1051 	if ((char *)rptr >= td->td_kstack &&
1052 	    (char *)rptr < td->td_kstack + PAGE_SIZE) {
1053 		return 1;
1054 	}
1055 	return 0;
1056 }
1057 
1058 void
1059 dblfault_handler(struct trapframe *frame)
1060 {
1061 	thread_t td = curthread;
1062 
1063 	if (in_kstack_guard(frame->tf_rsp) || in_kstack_guard(frame->tf_rbp)) {
1064 		kprintf("DOUBLE FAULT - KERNEL STACK GUARD HIT!\n");
1065 		if (in_kstack_guard(frame->tf_rsp))
1066 			frame->tf_rsp = (register_t)(td->td_kstack + PAGE_SIZE);
1067 		if (in_kstack_guard(frame->tf_rbp))
1068 			frame->tf_rbp = (register_t)(td->td_kstack + PAGE_SIZE);
1069 	} else {
1070 		kprintf("DOUBLE FAULT\n");
1071 	}
1072 	kprintf("\nFatal double fault\n");
1073 	kprintf("rip = 0x%lx\n", frame->tf_rip);
1074 	kprintf("rsp = 0x%lx\n", frame->tf_rsp);
1075 	kprintf("rbp = 0x%lx\n", frame->tf_rbp);
1076 	/* three separate prints in case of a trap on an unmapped page */
1077 	kprintf("cpuid = %d; ", mycpu->gd_cpuid);
1078 	kprintf("lapic->id = %08x\n", lapic->id);
1079 	panic("double fault");
1080 }
1081 
1082 /*
1083  * syscall2 -	MP aware system call request C handler
1084  *
1085  * A system call is essentially treated as a trap except that the
1086  * MP lock is not held on entry or return.  We are responsible for
1087  * obtaining the MP lock if necessary and for handling ASTs
1088  * (e.g. a task switch) prior to return.
1089  *
1090  * MPSAFE
1091  */
1092 void
1093 syscall2(struct trapframe *frame)
1094 {
1095 	struct thread *td = curthread;
1096 	struct proc *p = td->td_proc;
1097 	struct lwp *lp = td->td_lwp;
1098 	caddr_t params;
1099 	struct sysent *callp;
1100 	register_t orig_tf_rflags;
1101 	int sticks;
1102 	int error;
1103 	int narg;
1104 #ifdef INVARIANTS
1105 	int crit_count = td->td_critcount;
1106 #endif
1107 	int have_mplock = 0;
1108 	register_t *argp;
1109 	u_int code;
1110 	int reg, regcnt;
1111 	union sysunion args;
1112 	register_t *argsdst;
1113 
1114 	mycpu->gd_cnt.v_syscall++;
1115 
1116 #ifdef DIAGNOSTIC
1117 	if (ISPL(frame->tf_cs) != SEL_UPL) {
1118 		get_mplock();
1119 		panic("syscall");
1120 		/* NOT REACHED */
1121 	}
1122 #endif
1123 
1124 	KTR_LOG(kernentry_syscall, p->p_pid, lp->lwp_tid,
1125 		frame->tf_rax);
1126 
1127 	userenter(td, p);	/* lazy raise our priority */
1128 
1129 	reg = 0;
1130 	regcnt = 6;
1131 	/*
1132 	 * Misc
1133 	 */
1134 	sticks = (int)td->td_sticks;
1135 	orig_tf_rflags = frame->tf_rflags;
1136 
1137 	/*
1138 	 * Virtual kernel intercept - if a VM context managed by a virtual
1139 	 * kernel issues a system call the virtual kernel handles it, not us.
1140 	 * Restore the virtual kernel context and return from its system
1141 	 * call.  The current frame is copied out to the virtual kernel.
1142 	 */
1143 	if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
1144 		vkernel_trap(lp, frame);
1145 		error = EJUSTRETURN;
1146 		goto out;
1147 	}
1148 
1149 	/*
1150 	 * Get the system call parameters and account for time
1151 	 */
1152 	KASSERT(lp->lwp_md.md_regs == frame,
1153 		("Frame mismatch %p %p", lp->lwp_md.md_regs, frame));
1154 	params = (caddr_t)frame->tf_rsp + sizeof(register_t);
1155 	code = frame->tf_rax;
1156 
1157 	if (p->p_sysent->sv_prepsyscall) {
1158 		(*p->p_sysent->sv_prepsyscall)(
1159 			frame, (int *)(&args.nosys.sysmsg + 1),
1160 			&code, &params);
1161 	} else {
1162 		if (code == SYS_syscall || code == SYS___syscall) {
1163 			code = frame->tf_rdi;
1164 			reg++;
1165 			regcnt--;
1166 		}
1167 	}
1168 
1169 	if (p->p_sysent->sv_mask)
1170 		code &= p->p_sysent->sv_mask;
1171 
1172 	if (code >= p->p_sysent->sv_size)
1173 		callp = &p->p_sysent->sv_table[0];
1174 	else
1175 		callp = &p->p_sysent->sv_table[code];
1176 
1177 	narg = callp->sy_narg & SYF_ARGMASK;
1178 
1179 	/*
1180 	 * On x86_64 we get up to six arguments in registers. The rest are
1181 	 * on the stack. The first six members of 'struct trapframe' happen
1182 	 * to be the registers used to pass arguments, in exactly the right
1183 	 * order.
1184 	 */
1185 	argp = &frame->tf_rdi;
1186 	argp += reg;
1187 	argsdst = (register_t *)(&args.nosys.sysmsg + 1);
1188 	/*
1189 	 * JG can we overflow the space pointed to by 'argsdst'
1190 	 * either with 'bcopy' or with 'copyin'?
1191 	 */
1192 	bcopy(argp, argsdst, sizeof(register_t) * regcnt);
1193 	/*
1194 	 * copyin is MP aware, but the tracing code is not
1195 	 */
1196 	if (narg > regcnt) {
1197 		KASSERT(params != NULL, ("copyin args with no params!"));
1198 		error = copyin(params, &argsdst[regcnt],
1199 			(narg - regcnt) * sizeof(register_t));
1200 		if (error) {
1201 #ifdef KTRACE
1202 			if (KTRPOINT(td, KTR_SYSCALL)) {
1203 				MAKEMPSAFE(have_mplock);
1204 
1205 				ktrsyscall(lp, code, narg,
1206 					(void *)(&args.nosys.sysmsg + 1));
1207 			}
1208 #endif
1209 			goto bad;
1210 		}
1211 	}
1212 
1213 #ifdef KTRACE
1214 	if (KTRPOINT(td, KTR_SYSCALL)) {
1215 		MAKEMPSAFE(have_mplock);
1216 		ktrsyscall(lp, code, narg, (void *)(&args.nosys.sysmsg + 1));
1217 	}
1218 #endif
1219 
1220 	/*
1221 	 * Default return value is 0 (will be copied to %rax).  Double-value
1222 	 * returns use %rax and %rdx.  %rdx is left unchanged for system
1223 	 * calls which return only one result.
1224 	 */
1225 	args.sysmsg_fds[0] = 0;
1226 	args.sysmsg_fds[1] = frame->tf_rdx;
1227 
1228 	/*
1229 	 * The syscall might manipulate the trap frame. If it does it
1230 	 * will probably return EJUSTRETURN.
1231 	 */
1232 	args.sysmsg_frame = frame;
1233 
1234 	STOPEVENT(p, S_SCE, narg);	/* MP aware */
1235 
1236 	/*
1237 	 * NOTE: All system calls run MPSAFE now.  The system call itself
1238 	 *	 is responsible for getting the MP lock.
1239 	 */
1240 #ifdef SYSCALL_DEBUG
1241 	uint64_t tscval = rdtsc();
1242 #endif
1243 	error = (*callp->sy_call)(&args);
1244 #ifdef SYSCALL_DEBUG
1245 	tscval = rdtsc() - tscval;
1246 	tscval = tscval * 1000000 / tsc_frequency;
1247 	if (SysCallsWorstCase[code] < tscval)
1248 		SysCallsWorstCase[code] = tscval;
1249 #endif
1250 
1251 out:
1252 	/*
1253 	 * MP SAFE (we may or may not have the MP lock at this point)
1254 	 */
1255 	//kprintf("SYSMSG %d ", error);
1256 	switch (error) {
1257 	case 0:
1258 		/*
1259 		 * Reinitialize proc pointer `p' as it may be different
1260 		 * if this is a child returning from fork syscall.
1261 		 */
1262 		p = curproc;
1263 		lp = curthread->td_lwp;
1264 		frame->tf_rax = args.sysmsg_fds[0];
1265 		frame->tf_rdx = args.sysmsg_fds[1];
1266 		frame->tf_rflags &= ~PSL_C;
1267 		break;
1268 	case ERESTART:
1269 		/*
1270 		 * Reconstruct pc, we know that 'syscall' is 2 bytes.
1271 		 * We have to do a full context restore so that %r10
1272 		 * (which was holding the value of %rcx) is restored for
1273 		 * the next iteration.
1274 		 */
1275 		if (frame->tf_err != 0 && frame->tf_err != 2)
1276 			kprintf("lp %s:%d frame->tf_err is weird %ld\n",
1277 				td->td_comm, lp->lwp_proc->p_pid, frame->tf_err);
1278 		frame->tf_rip -= frame->tf_err;
1279 		frame->tf_r10 = frame->tf_rcx;
1280 		break;
1281 	case EJUSTRETURN:
1282 		break;
1283 	case EASYNC:
1284 		panic("Unexpected EASYNC return value (for now)");
1285 	default:
1286 bad:
1287 		if (p->p_sysent->sv_errsize) {
1288 			if (error >= p->p_sysent->sv_errsize)
1289 				error = -1;	/* XXX */
1290 			else
1291 				error = p->p_sysent->sv_errtbl[error];
1292 		}
1293 		frame->tf_rax = error;
1294 		frame->tf_rflags |= PSL_C;
1295 		break;
1296 	}
1297 
1298 	/*
1299 	 * Traced syscall.  trapsignal() is not MP aware.
1300 	 */
1301 	if (orig_tf_rflags & PSL_T) {
1302 		MAKEMPSAFE(have_mplock);
1303 		frame->tf_rflags &= ~PSL_T;
1304 		trapsignal(lp, SIGTRAP, TRAP_TRACE);
1305 	}
1306 
1307 	/*
1308 	 * Handle reschedule and other end-of-syscall issues
1309 	 */
1310 	userret(lp, frame, sticks);
1311 
1312 #ifdef KTRACE
1313 	if (KTRPOINT(td, KTR_SYSRET)) {
1314 		MAKEMPSAFE(have_mplock);
1315 		ktrsysret(lp, code, error, args.sysmsg_result);
1316 	}
1317 #endif
1318 
1319 	/*
1320 	 * This works because errno is findable through the
1321 	 * register set.  If we ever support an emulation where this
1322 	 * is not the case, this code will need to be revisited.
1323 	 */
1324 	STOPEVENT(p, S_SCX, code);
1325 
1326 	userexit(lp);
1327 	/*
1328 	 * Release the MP lock if we had to get it
1329 	 */
1330 	if (have_mplock)
1331 		rel_mplock();
1332 	KTR_LOG(kernentry_syscall_ret, p->p_pid, lp->lwp_tid, error);
1333 #ifdef INVARIANTS
1334 	KASSERT(crit_count == td->td_critcount,
1335 		("syscall: critical section count mismatch! %d/%d",
1336 		crit_count, td->td_pri));
1337 	KASSERT(&td->td_toks_base == td->td_toks_stop,
1338 		("syscall: extra tokens held after trap! %ld",
1339 		td->td_toks_stop - &td->td_toks_base));
1340 #endif
1341 }
1342 
1343 /*
1344  * NOTE: mplock not held at any point
1345  */
1346 void
1347 fork_return(struct lwp *lp, struct trapframe *frame)
1348 {
1349 	frame->tf_rax = 0;		/* Child returns zero */
1350 	frame->tf_rflags &= ~PSL_C;	/* success */
1351 	frame->tf_rdx = 1;
1352 
1353 	generic_lwp_return(lp, frame);
1354 	KTR_LOG(kernentry_fork_ret, lp->lwp_proc->p_pid, lp->lwp_tid);
1355 }
1356 
1357 /*
1358  * Simplified back end of syscall(), used when returning from fork()
1359  * directly into user mode.
1360  *
1361  * This code will return back into the fork trampoline code which then
1362  * runs doreti.
1363  *
1364  * NOTE: The mplock is not held at any point.
1365  */
1366 void
1367 generic_lwp_return(struct lwp *lp, struct trapframe *frame)
1368 {
1369 	struct proc *p = lp->lwp_proc;
1370 
1371 	/*
1372 	 * Newly forked processes are given a kernel priority.  We have to
1373 	 * adjust the priority to a normal user priority and fake entry
1374 	 * into the kernel (call userenter()) to install a passive release
1375 	 * function just in case userret() decides to stop the process.  This
1376 	 * can occur when ^Z races a fork.  If we do not install the passive
1377 	 * release function the current process designation will not be
1378 	 * released when the thread goes to sleep.
1379 	 */
1380 	lwkt_setpri_self(TDPRI_USER_NORM);
1381 	userenter(lp->lwp_thread, p);
1382 	userret(lp, frame, 0);
1383 #ifdef KTRACE
1384 	if (KTRPOINT(lp->lwp_thread, KTR_SYSRET))
1385 		ktrsysret(lp, SYS_fork, 0, 0);
1386 #endif
1387 	lp->lwp_flags |= LWP_PASSIVE_ACQ;
1388 	userexit(lp);
1389 	lp->lwp_flags &= ~LWP_PASSIVE_ACQ;
1390 }
1391 
1392 /*
1393  * If PGEX_FPFAULT is set then set FP_VIRTFP in the PCB to force a T_DNA
1394  * fault (which is then passed back to the virtual kernel) if an attempt is
1395  * made to use the FP unit.
1396  *
1397  * XXX this is a fairly big hack.
1398  */
1399 void
1400 set_vkernel_fp(struct trapframe *frame)
1401 {
1402 	struct thread *td = curthread;
1403 
1404 	if (frame->tf_xflags & PGEX_FPFAULT) {
1405 		td->td_pcb->pcb_flags |= FP_VIRTFP;
1406 		if (mdcpu->gd_npxthread == td)
1407 			npxexit();
1408 	} else {
1409 		td->td_pcb->pcb_flags &= ~FP_VIRTFP;
1410 	}
1411 }
1412 
1413 /*
1414  * Called from vkernel_trap() to fixup the vkernel's syscall
1415  * frame for vmspace_ctl() return.
1416  */
1417 void
1418 cpu_vkernel_trap(struct trapframe *frame, int error)
1419 {
1420 	frame->tf_rax = error;
1421 	if (error)
1422 		frame->tf_rflags |= PSL_C;
1423 	else
1424 		frame->tf_rflags &= ~PSL_C;
1425 }
1426