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