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