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