2 * Copyright (C) 1994, David Greenman
3 * Copyright (c) 1990, 1993
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
7 * the University of Utah, and William Jolitz.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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.
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
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 * $DragonFly: src/sys/platform/pc32/i386/trap.c,v 1.38 2003/10/25 17:36:22 dillon Exp $
43 * 386 Trap and System call handling
51 #include "opt_ktrace.h"
52 #include "opt_clock.h"
55 #include <sys/param.h>
56 #include <sys/systm.h>
58 #include <sys/pioctl.h>
59 #include <sys/kernel.h>
60 #include <sys/resourcevar.h>
61 #include <sys/signalvar.h>
62 #include <sys/syscall.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysent.h>
66 #include <sys/vmmeter.h>
67 #include <sys/malloc.h>
69 #include <sys/ktrace.h>
71 #include <sys/sysproto.h>
72 #include <sys/sysunion.h>
75 #include <vm/vm_param.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>
83 #include <machine/cpu.h>
84 #include <machine/ipl.h>
85 #include <machine/md_var.h>
86 #include <machine/pcb.h>
88 #include <machine/smp.h>
90 #include <machine/tss.h>
91 #include <machine/globaldata.h>
93 #include <i386/isa/intr_machdep.h>
96 #include <sys/syslog.h>
97 #include <machine/clock.h>
100 #include <machine/vm86.h>
103 #include <sys/msgport2.h>
104 #include <sys/thread2.h>
106 int (*pmath_emulate) (struct trapframe *);
108 extern void trap (struct trapframe frame);
109 extern int trapwrite (unsigned addr);
110 extern void syscall2 (struct trapframe frame);
111 extern void sendsys2 (struct trapframe frame);
113 static int trap_pfault (struct trapframe *, int, vm_offset_t);
114 static void trap_fatal (struct trapframe *, vm_offset_t);
115 void dblfault_handler (void);
117 extern inthand_t IDTVEC(syscall);
119 #define MAX_TRAP_MSG 28
120 static char *trap_msg[] = {
122 "privileged instruction fault", /* 1 T_PRIVINFLT */
124 "breakpoint instruction fault", /* 3 T_BPTFLT */
127 "arithmetic trap", /* 6 T_ARITHTRAP */
128 "system forced exception", /* 7 T_ASTFLT */
130 "general protection fault", /* 9 T_PROTFLT */
131 "trace trap", /* 10 T_TRCTRAP */
133 "page fault", /* 12 T_PAGEFLT */
135 "alignment fault", /* 14 T_ALIGNFLT */
139 "integer divide fault", /* 18 T_DIVIDE */
140 "non-maskable interrupt trap", /* 19 T_NMI */
141 "overflow trap", /* 20 T_OFLOW */
142 "FPU bounds check fault", /* 21 T_BOUND */
143 "FPU device not available", /* 22 T_DNA */
144 "double fault", /* 23 T_DOUBLEFLT */
145 "FPU operand fetch fault", /* 24 T_FPOPFLT */
146 "invalid TSS fault", /* 25 T_TSSFLT */
147 "segment not present fault", /* 26 T_SEGNPFLT */
148 "stack fault", /* 27 T_STKFLT */
149 "machine check trap", /* 28 T_MCHK */
152 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
153 extern int has_f00f_bug;
157 static int ddb_on_nmi = 1;
158 SYSCTL_INT(_machdep, OID_AUTO, ddb_on_nmi, CTLFLAG_RW,
159 &ddb_on_nmi, 0, "Go to DDB on NMI");
161 static int panic_on_nmi = 1;
162 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
163 &panic_on_nmi, 0, "Panic on NMI");
164 static int fast_release;
165 SYSCTL_INT(_machdep, OID_AUTO, fast_release, CTLFLAG_RW,
166 &fast_release, 0, "Passive Release was optimal");
167 static int slow_release;
168 SYSCTL_INT(_machdep, OID_AUTO, slow_release, CTLFLAG_RW,
169 &slow_release, 0, "Passive Release was nonoptimal");
170 static int pass_release;
171 SYSCTL_INT(_machdep, OID_AUTO, pass_release, CTLFLAG_RW,
172 &pass_release, 0, "Passive Release on switch");
173 static int pass_hold;
174 SYSCTL_INT(_machdep, OID_AUTO, pass_hold, CTLFLAG_RW,
175 &pass_hold, 0, "Passive Held on switch");
177 MALLOC_DEFINE(M_SYSMSG, "sysmsg", "sysmsg structure");
180 * USER->KERNEL transition. Do not transition us out of userland from the
181 * point of view of the userland scheduler unless we actually have to
184 * passive_release is called from within a critical section and the BGL will
185 * still be held. This function is NOT called for preemptions, only for
186 * switchouts. We only actually release our P_CURPROC designation when we
187 * are going to sleep, otherwise another process might be assigned P_CURPROC
191 passive_release(struct thread *td)
193 struct proc *p = td->td_proc;
195 if ((p->p_flag & P_CP_RELEASED) == 0) {
196 p->p_flag |= P_CP_RELEASED;
197 lwkt_setpri_self(TDPRI_KERN_USER);
199 if ((p->p_flag & P_CURPROC) && (td->td_flags & TDF_RUNQ) == 0) {
200 td->td_release = NULL;
203 } else if ((p->p_flag & (P_CURPROC|P_PASSIVE_ACQ)) == (P_CURPROC|P_PASSIVE_ACQ)) {
204 td->td_release = NULL;
212 * userenter() passively intercepts the thread switch function to increase
213 * the thread priority from a user priority to a kernel priority, reducing
214 * syscall and trap overhead for the case where no switch occurs.
218 userenter(struct thread *curtd)
220 curtd->td_release = passive_release;
224 userexit(struct proc *p)
226 struct thread *td = p->p_thread;
229 * Reacquire our P_CURPROC status and adjust the LWKT priority
230 * for our return to userland. We can fast path the case where
231 * td_release was not called by checking particular proc flags.
232 * Otherwise we do it the slow way.
234 * Lowering our priority may make other higher priority threads
235 * runnable. lwkt_setpri_self() does not switch away, so call
236 * lwkt_maybe_switch() to deal with it.
238 td->td_release = NULL;
239 if ((p->p_flag & (P_CP_RELEASED|P_CURPROC)) == P_CURPROC) {
245 switch(p->p_rtprio.type) {
247 lwkt_setpri_self(TDPRI_USER_IDLE);
249 case RTP_PRIO_REALTIME:
251 lwkt_setpri_self(TDPRI_USER_REAL);
254 lwkt_setpri_self(TDPRI_USER_NORM);
263 userret(struct proc *p, struct trapframe *frame, u_quad_t oticks)
268 * Post any pending signals
270 while ((sig = CURSIG(p)) != 0) {
275 * If a reschedule has been requested then we release the current
276 * process in order to shift our P_CURPROC designation to another
277 * user process. userexit() will reacquire P_CURPROC and block
280 if (resched_wanted()) {
281 p->p_thread->td_release = NULL;
282 if ((p->p_flag & P_CP_RELEASED) == 0) {
283 p->p_flag |= P_CP_RELEASED;
284 lwkt_setpri_self(TDPRI_KERN_USER);
286 if (p->p_flag & P_CURPROC) {
294 * Charge system time if profiling. Note: times are in microseconds.
296 if (p->p_flag & P_PROFIL) {
297 addupc_task(p, frame->tf_eip,
298 (u_int)(curthread->td_sticks - oticks));
302 * Post any pending signals XXX
304 while ((sig = CURSIG(p)) != 0)
308 #ifdef DEVICE_POLLING
309 extern u_int32_t poll_in_trap;
310 extern int ether_poll (int count);
311 #endif /* DEVICE_POLLING */
314 * Exception, fault, and trap interface to the FreeBSD kernel.
315 * This common code is called from assembly language IDT gate entry
316 * routines that prepare a suitable stack frame, and restore this
317 * frame after the exception has been processed.
319 * This function is also called from doreti in an interlock to handle ASTs.
320 * For example: hardwareint->INTROUTINE->(set ast)->doreti->trap
322 * NOTE! We have to retrieve the fault address prior to obtaining the
323 * MP lock because get_mplock() may switch out. YYY cr2 really ought
324 * to be retrieved by the assembly code, not here.
328 struct trapframe frame;
330 struct thread *td = curthread;
333 int i = 0, ucode = 0, type, code;
339 eva = (frame.tf_trapno == T_PAGEFLT ? rcr2() : 0);
341 trap_fatal(&frame, eva);
347 if (frame.tf_trapno == T_PAGEFLT) {
349 * For some Cyrix CPUs, %cr2 is clobbered by interrupts.
350 * This problem is worked around by using an interrupt
351 * gate for the pagefault handler. We are finally ready
352 * to read %cr2 and then must reenable interrupts.
354 * XXX this should be in the switch statement, but the
355 * NO_FOOF_HACK and VM86 goto and ifdefs obfuscate the
356 * flow of control too much for this to be obviously
366 * MP lock is held at this point
369 if (!(frame.tf_eflags & PSL_I)) {
371 * Buggy application or kernel code has disabled interrupts
372 * and then trapped. Enabling interrupts now is wrong, but
373 * it is better than running with interrupts disabled until
374 * they are accidentally enabled later.
376 type = frame.tf_trapno;
377 if (ISPL(frame.tf_cs)==SEL_UPL || (frame.tf_eflags & PSL_VM)) {
379 "pid %ld (%s): trap %d with interrupts disabled\n",
380 (long)curproc->p_pid, curproc->p_comm, type);
381 } else if (type != T_BPTFLT && type != T_TRCTRAP) {
383 * XXX not quite right, since this may be for a
384 * multiple fault in user mode.
386 printf("kernel trap %d with interrupts disabled\n",
393 #ifdef DEVICE_POLLING
395 ether_poll(poll_in_trap);
396 #endif /* DEVICE_POLLING */
398 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
401 type = frame.tf_trapno;
405 if (frame.tf_eflags & PSL_VM &&
406 (type == T_PROTFLT || type == T_STKFLT)) {
408 KKASSERT(curthread->td_mpcount > 0);
410 i = vm86_emulate((struct vm86frame *)&frame);
412 KKASSERT(curthread->td_mpcount > 0);
416 * returns to original process
418 vm86_trap((struct vm86frame *)&frame);
425 * these traps want either a process context, or
426 * assume a normal userspace trap.
430 trap_fatal(&frame, eva);
433 type = T_BPTFLT; /* kernel breakpoint */
436 goto kernel_trap; /* normal kernel trap handling */
439 if ((ISPL(frame.tf_cs) == SEL_UPL) || (frame.tf_eflags & PSL_VM)) {
444 sticks = curthread->td_sticks;
445 p->p_md.md_regs = &frame;
448 case T_PRIVINFLT: /* privileged instruction fault */
453 case T_BPTFLT: /* bpt instruction fault */
454 case T_TRCTRAP: /* trace trap */
455 frame.tf_eflags &= ~PSL_T;
459 case T_ARITHTRAP: /* arithmetic trap */
464 case T_ASTFLT: /* Allow process switch */
465 mycpu->gd_cnt.v_soft++;
466 if (mycpu->gd_reqflags & RQF_AST_OWEUPC) {
467 atomic_clear_int_nonlocked(&mycpu->gd_reqflags,
469 addupc_task(p, p->p_stats->p_prof.pr_addr,
470 p->p_stats->p_prof.pr_ticks);
475 * The following two traps can happen in
476 * vm86 mode, and, if so, we want to handle
479 case T_PROTFLT: /* general protection fault */
480 case T_STKFLT: /* stack fault */
481 if (frame.tf_eflags & PSL_VM) {
482 i = vm86_emulate((struct vm86frame *)&frame);
489 case T_SEGNPFLT: /* segment not present fault */
490 case T_TSSFLT: /* invalid TSS fault */
491 case T_DOUBLEFLT: /* double fault */
493 ucode = code + BUS_SEGM_FAULT ;
497 case T_PAGEFLT: /* page fault */
498 i = trap_pfault(&frame, TRUE, eva);
501 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
511 case T_DIVIDE: /* integer divide fault */
519 goto handle_powerfail;
520 #else /* !POWERFAIL_NMI */
521 /* machine/parity/power fail/"kitchen sink" faults */
522 if (isa_nmi(code) == 0) {
525 * NMI can be hooked up to a pushbutton
529 printf ("NMI ... going to debugger\n");
530 kdb_trap (type, 0, &frame);
534 } else if (panic_on_nmi)
535 panic("NMI indicates hardware failure");
537 #endif /* POWERFAIL_NMI */
538 #endif /* NISA > 0 */
540 case T_OFLOW: /* integer overflow fault */
545 case T_BOUND: /* bounds check fault */
552 /* if a transparent fault (due to context switch "late") */
556 if (!pmath_emulate) {
558 ucode = FPE_FPU_NP_TRAP;
561 i = (*pmath_emulate)(&frame);
563 if (!(frame.tf_eflags & PSL_T))
565 frame.tf_eflags &= ~PSL_T;
568 /* else ucode = emulator_only_knows() XXX */
571 case T_FPOPFLT: /* FPU operand fetch fault */
576 case T_XMMFLT: /* SIMD floating-point exception */
586 case T_PAGEFLT: /* page fault */
587 (void) trap_pfault(&frame, FALSE, eva);
593 * The kernel is apparently using npx for copying.
594 * XXX this should be fatal unless the kernel has
595 * registered such use.
602 case T_PROTFLT: /* general protection fault */
603 case T_SEGNPFLT: /* segment not present fault */
605 * Invalid segment selectors and out of bounds
606 * %eip's and %esp's can be set up in user mode.
607 * This causes a fault in kernel mode when the
608 * kernel tries to return to user mode. We want
609 * to get this fault so that we can fix the
610 * problem here and not have to check all the
611 * selectors and pointers when the user changes
614 #define MAYBE_DORETI_FAULT(where, whereto) \
616 if (frame.tf_eip == (int)where) { \
617 frame.tf_eip = (int)whereto; \
621 if (mycpu->gd_intr_nesting_level == 0) {
623 * Invalid %fs's and %gs's can be created using
624 * procfs or PT_SETREGS or by invalidating the
625 * underlying LDT entry. This causes a fault
626 * in kernel mode when the kernel attempts to
627 * switch contexts. Lose the bad context
628 * (XXX) so that we can continue, and generate
631 if (frame.tf_eip == (int)cpu_switch_load_gs) {
632 curthread->td_pcb->pcb_gs = 0;
636 MAYBE_DORETI_FAULT(doreti_iret,
638 MAYBE_DORETI_FAULT(doreti_popl_ds,
639 doreti_popl_ds_fault);
640 MAYBE_DORETI_FAULT(doreti_popl_es,
641 doreti_popl_es_fault);
642 MAYBE_DORETI_FAULT(doreti_popl_fs,
643 doreti_popl_fs_fault);
644 if (curthread->td_pcb->pcb_onfault) {
645 frame.tf_eip = (int)curthread->td_pcb->pcb_onfault;
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
661 if (frame.tf_eflags & PSL_NT) {
662 frame.tf_eflags &= ~PSL_NT;
667 case T_TRCTRAP: /* trace trap */
668 if (frame.tf_eip == (int)IDTVEC(syscall)) {
670 * We've just entered system mode via the
671 * syscall lcall. Continue single stepping
672 * silently until the syscall handler has
677 if (frame.tf_eip == (int)IDTVEC(syscall) + 1) {
679 * The syscall handler has now saved the
680 * flags. Stop single stepping it.
682 frame.tf_eflags &= ~PSL_T;
686 * Ignore debug register trace traps due to
687 * accesses in the user's address space, which
688 * can happen under several conditions such as
689 * if a user sets a watchpoint on a buffer and
690 * then passes that buffer to a system call.
691 * We still want to get TRCTRAPS for addresses
692 * in kernel space because that is useful when
693 * debugging the kernel.
695 if (user_dbreg_trap()) {
697 * Reset breakpoint bits because the
700 load_dr6(rdr6() & 0xfffffff0);
704 * Fall through (TRCTRAP kernel mode, kernel address)
708 * If DDB is enabled, let it handle the debugger trap.
709 * Otherwise, debugger traps "can't happen".
712 if (kdb_trap (type, 0, &frame))
721 # define TIMER_FREQ 1193182
725 static unsigned lastalert = 0;
727 if(time_second - lastalert > 10)
729 log(LOG_WARNING, "NMI: power fail\n");
730 sysbeep(TIMER_FREQ/880, hz);
731 lastalert = time_second;
736 #else /* !POWERFAIL_NMI */
737 /* machine/parity/power fail/"kitchen sink" faults */
738 if (isa_nmi(code) == 0) {
741 * NMI can be hooked up to a pushbutton
745 printf ("NMI ... going to debugger\n");
746 kdb_trap (type, 0, &frame);
750 } else if (panic_on_nmi == 0)
753 #endif /* POWERFAIL_NMI */
754 #endif /* NISA > 0 */
757 trap_fatal(&frame, eva);
761 /* Translate fault for emulators (e.g. Linux) */
762 if (*p->p_sysent->sv_transtrap)
763 i = (*p->p_sysent->sv_transtrap)(i, type);
765 trapsignal(p, i, ucode);
768 if (type <= MAX_TRAP_MSG) {
769 uprintf("fatal process exception: %s",
771 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
772 uprintf(", fault VA = 0x%lx", (u_long)eva);
779 if (ISPL(frame.tf_cs) == SEL_UPL)
780 KASSERT(curthread->td_mpcount == 1, ("badmpcount trap from %p", (void *)frame.tf_eip));
782 userret(p, &frame, sticks);
786 KKASSERT(curthread->td_mpcount > 0);
793 * This version doesn't allow a page fault to user space while
794 * in the kernel. The rest of the kernel needs to be made "safe"
795 * before this can be used. I think the only things remaining
796 * to be made safe are the iBCS2 code and the process tracing/
800 trap_pfault(frame, usermode, eva)
801 struct trapframe *frame;
806 struct vmspace *vm = NULL;
810 struct proc *p = curproc;
812 if (frame->tf_err & PGEX_W)
813 ftype = VM_PROT_WRITE;
815 ftype = VM_PROT_READ;
817 va = trunc_page(eva);
818 if (va < VM_MIN_KERNEL_ADDRESS) {
823 (!usermode && va < VM_MAXUSER_ADDRESS &&
824 (mycpu->gd_intr_nesting_level != 0 ||
825 curthread->td_pcb->pcb_onfault == NULL))) {
826 trap_fatal(frame, eva);
831 * This is a fault on non-kernel virtual memory.
832 * vm is initialized above to NULL. If curproc is NULL
833 * or curproc->p_vmspace is NULL the fault is fatal.
842 * Keep swapout from messing with us during this
848 * Grow the stack if necessary
850 /* grow_stack returns false only if va falls into
851 * a growable stack region and the stack growth
852 * fails. It returns true if va was not within
853 * a growable stack region, or if the stack
856 if (!grow_stack (p, va)) {
862 /* Fault in the user page: */
863 rv = vm_fault(map, va, ftype,
864 (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
870 * Don't allow user-mode faults in kernel address space.
876 * Since we know that kernel virtual address addresses
877 * always have pte pages mapped, we just have to fault
880 rv = vm_fault(kernel_map, va, ftype, VM_FAULT_NORMAL);
883 if (rv == KERN_SUCCESS)
887 if (mycpu->gd_intr_nesting_level == 0 && curthread->td_pcb->pcb_onfault) {
888 frame->tf_eip = (int)curthread->td_pcb->pcb_onfault;
891 trap_fatal(frame, eva);
895 /* kludge to pass faulting virtual address to sendsig */
898 return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
903 trap_pfault(frame, usermode, eva)
904 struct trapframe *frame;
909 struct vmspace *vm = NULL;
913 struct proc *p = curproc;
915 va = trunc_page(eva);
916 if (va >= KERNBASE) {
918 * Don't allow user-mode faults in kernel address space.
919 * An exception: if the faulting address is the invalid
920 * instruction entry in the IDT, then the Intel Pentium
921 * F00F bug workaround was triggered, and we need to
922 * treat it is as an illegal instruction, and not a page
925 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
926 if ((eva == (unsigned int)&idt[6]) && has_f00f_bug) {
927 frame->tf_trapno = T_PRIVINFLT;
937 * This is a fault on non-kernel virtual memory.
938 * vm is initialized above to NULL. If curproc is NULL
939 * or curproc->p_vmspace is NULL the fault is fatal.
950 if (frame->tf_err & PGEX_W)
951 ftype = VM_PROT_WRITE;
953 ftype = VM_PROT_READ;
955 if (map != kernel_map) {
957 * Keep swapout from messing with us during this
963 * Grow the stack if necessary
965 /* grow_stack returns false only if va falls into
966 * a growable stack region and the stack growth
967 * fails. It returns true if va was not within
968 * a growable stack region, or if the stack
971 if (!grow_stack (p, va)) {
977 /* Fault in the user page: */
978 rv = vm_fault(map, va, ftype,
979 (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
985 * Don't have to worry about process locking or stacks in the kernel.
987 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
990 if (rv == KERN_SUCCESS)
994 if (mycpu->gd_intr_nesting_level == 0 && curthread->td_pcb->pcb_onfault) {
995 frame->tf_eip = (int)curthread->td_pcb->pcb_onfault;
998 trap_fatal(frame, eva);
1002 /* kludge to pass faulting virtual address to sendsig */
1003 frame->tf_err = eva;
1005 return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
1009 trap_fatal(frame, eva)
1010 struct trapframe *frame;
1013 int code, type, ss, esp;
1014 struct soft_segment_descriptor softseg;
1016 code = frame->tf_err;
1017 type = frame->tf_trapno;
1018 sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)].sd, &softseg);
1020 if (type <= MAX_TRAP_MSG)
1021 printf("\n\nFatal trap %d: %s while in %s mode\n",
1022 type, trap_msg[type],
1023 frame->tf_eflags & PSL_VM ? "vm86" :
1024 ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
1026 /* three seperate prints in case of a trap on an unmapped page */
1027 printf("mp_lock = %08x; ", mp_lock);
1028 printf("cpuid = %d; ", mycpu->gd_cpuid);
1029 printf("lapic.id = %08x\n", lapic.id);
1031 if (type == T_PAGEFLT) {
1032 printf("fault virtual address = 0x%x\n", eva);
1033 printf("fault code = %s %s, %s\n",
1034 code & PGEX_U ? "user" : "supervisor",
1035 code & PGEX_W ? "write" : "read",
1036 code & PGEX_P ? "protection violation" : "page not present");
1038 printf("instruction pointer = 0x%x:0x%x\n",
1039 frame->tf_cs & 0xffff, frame->tf_eip);
1040 if ((ISPL(frame->tf_cs) == SEL_UPL) || (frame->tf_eflags & PSL_VM)) {
1041 ss = frame->tf_ss & 0xffff;
1042 esp = frame->tf_esp;
1044 ss = GSEL(GDATA_SEL, SEL_KPL);
1045 esp = (int)&frame->tf_esp;
1047 printf("stack pointer = 0x%x:0x%x\n", ss, esp);
1048 printf("frame pointer = 0x%x:0x%x\n", ss, frame->tf_ebp);
1049 printf("code segment = base 0x%x, limit 0x%x, type 0x%x\n",
1050 softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
1051 printf(" = DPL %d, pres %d, def32 %d, gran %d\n",
1052 softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_def32,
1054 printf("processor eflags = ");
1055 if (frame->tf_eflags & PSL_T)
1056 printf("trace trap, ");
1057 if (frame->tf_eflags & PSL_I)
1058 printf("interrupt enabled, ");
1059 if (frame->tf_eflags & PSL_NT)
1060 printf("nested task, ");
1061 if (frame->tf_eflags & PSL_RF)
1063 if (frame->tf_eflags & PSL_VM)
1065 printf("IOPL = %d\n", (frame->tf_eflags & PSL_IOPL) >> 12);
1066 printf("current process = ");
1068 printf("%lu (%s)\n",
1069 (u_long)curproc->p_pid, curproc->p_comm ?
1070 curproc->p_comm : "");
1074 printf("current thread = pri %d ", curthread->td_pri);
1075 if (curthread->td_pri >= TDPRI_CRIT)
1078 printf("interrupt mask = ");
1079 if ((curthread->td_cpl & net_imask) == net_imask)
1081 if ((curthread->td_cpl & tty_imask) == tty_imask)
1083 if ((curthread->td_cpl & bio_imask) == bio_imask)
1085 if ((curthread->td_cpl & cam_imask) == cam_imask)
1087 if (curthread->td_cpl == 0)
1092 * we probably SHOULD have stopped the other CPUs before now!
1093 * another CPU COULD have been touching cpl at this moment...
1095 printf(" <- SMP: XXX");
1104 if ((debugger_on_panic || db_active) && kdb_trap(type, code, frame))
1107 printf("trap number = %d\n", type);
1108 if (type <= MAX_TRAP_MSG)
1109 panic("%s", trap_msg[type]);
1111 panic("unknown/reserved trap");
1115 * Double fault handler. Called when a fault occurs while writing
1116 * a frame for a trap/exception onto the stack. This usually occurs
1117 * when the stack overflows (such is the case with infinite recursion,
1120 * XXX Note that the current PTD gets replaced by IdlePTD when the
1121 * task switch occurs. This means that the stack that was active at
1122 * the time of the double fault is not available at <kstack> unless
1123 * the machine was idle when the double fault occurred. The downside
1124 * of this is that "trace <ebp>" in ddb won't work.
1129 struct mdglobaldata *gd = mdcpu;
1131 printf("\nFatal double fault:\n");
1132 printf("eip = 0x%x\n", gd->gd_common_tss.tss_eip);
1133 printf("esp = 0x%x\n", gd->gd_common_tss.tss_esp);
1134 printf("ebp = 0x%x\n", gd->gd_common_tss.tss_ebp);
1136 /* three seperate prints in case of a trap on an unmapped page */
1137 printf("mp_lock = %08x; ", mp_lock);
1138 printf("cpuid = %d; ", mycpu->gd_cpuid);
1139 printf("lapic.id = %08x\n", lapic.id);
1141 panic("double fault");
1145 * Compensate for 386 brain damage (missing URKR).
1146 * This is a little simpler than the pagefault handler in trap() because
1147 * it the page tables have already been faulted in and high addresses
1148 * are thrown out early for other reasons.
1158 va = trunc_page((vm_offset_t)addr);
1160 * XXX - MAX is END. Changed > to >= for temp. fix.
1162 if (va >= VM_MAXUSER_ADDRESS)
1170 if (!grow_stack (p, va)) {
1176 * fault the data page
1178 rv = vm_fault(&vm->vm_map, va, VM_PROT_WRITE, VM_FAULT_DIRTY);
1182 if (rv != KERN_SUCCESS)
1189 * syscall2 - MP aware system call request C handler
1191 * A system call is essentially treated as a trap except that the
1192 * MP lock is not held on entry or return. We are responsible for
1193 * obtaining the MP lock if necessary and for handling ASTs
1194 * (e.g. a task switch) prior to return.
1196 * In general, only simple access and manipulation of curproc and
1197 * the current stack is allowed without having to hold MP lock.
1200 syscall2(struct trapframe frame)
1202 struct thread *td = curthread;
1203 struct proc *p = td->td_proc;
1206 struct sysent *callp;
1207 register_t orig_tf_eflags;
1212 union sysunion args;
1215 if (ISPL(frame.tf_cs) != SEL_UPL) {
1223 KASSERT(curthread->td_mpcount == 0, ("badmpcount syscall from %p", (void *)frame.tf_eip));
1227 * access non-atomic field from critical section. p_sticks is
1228 * updated by the clock interrupt. Also use this opportunity
1229 * to lazy-raise our LWKT priority.
1232 crit_enter_quick(td);
1233 sticks = curthread->td_sticks;
1234 crit_exit_quick(td);
1236 p->p_md.md_regs = &frame;
1237 params = (caddr_t)frame.tf_esp + sizeof(int);
1238 code = frame.tf_eax;
1239 orig_tf_eflags = frame.tf_eflags;
1241 if (p->p_sysent->sv_prepsyscall) {
1243 * The prep code is not MP aware.
1245 (*p->p_sysent->sv_prepsyscall)(&frame, (int *)(&args.nosys.usrmsg + 1), &code, ¶ms);
1248 * Need to check if this is a 32 bit or 64 bit syscall.
1249 * fuword is MP aware.
1251 if (code == SYS_syscall) {
1253 * Code is first argument, followed by actual args.
1255 code = fuword(params);
1256 params += sizeof(int);
1257 } else if (code == SYS___syscall) {
1259 * Like syscall, but code is a quad, so as to maintain
1260 * quad alignment for the rest of the arguments.
1262 code = fuword(params);
1263 params += sizeof(quad_t);
1267 if (p->p_sysent->sv_mask)
1268 code &= p->p_sysent->sv_mask;
1270 if (code >= p->p_sysent->sv_size)
1271 callp = &p->p_sysent->sv_table[0];
1273 callp = &p->p_sysent->sv_table[code];
1275 narg = callp->sy_narg & SYF_ARGMASK;
1278 * copyin is MP aware, but the tracing code is not
1280 if (params && (i = narg * sizeof(register_t)) &&
1281 (error = copyin(params, (caddr_t)(&args.nosys.usrmsg + 1), (u_int)i))) {
1283 if (KTRPOINT(td, KTR_SYSCALL))
1284 ktrsyscall(p->p_tracep, code, narg, (void *)(&args.nosys.usrmsg + 1));
1291 * Try to run the syscall without the MP lock if the syscall
1292 * is MP safe. We have to obtain the MP lock no matter what if
1295 if ((callp->sy_narg & SYF_MPSAFE) == 0) {
1302 if (KTRPOINT(td, KTR_SYSCALL)) {
1303 ktrsyscall(p->p_tracep, code, narg, (void *)(&args.nosys.usrmsg + 1));
1306 lwkt_initmsg(&args.lmsg, &td->td_msgport, code);
1307 args.sysmsg_fds[0] = 0;
1308 args.sysmsg_fds[1] = frame.tf_edx;
1310 STOPEVENT(p, S_SCE, narg); /* MP aware */
1312 error = (*callp->sy_call)(&args);
1315 * MP SAFE (we may or may not have the MP lock at this point)
1320 * Reinitialize proc pointer `p' as it may be different
1321 * if this is a child returning from fork syscall.
1324 frame.tf_eax = args.sysmsg_fds[0];
1325 frame.tf_edx = args.sysmsg_fds[1];
1326 frame.tf_eflags &= ~PSL_C;
1330 * Reconstruct pc, assuming lcall $X,y is 7 bytes,
1331 * int 0x80 is 2 bytes. We saved this in tf_err.
1333 frame.tf_eip -= frame.tf_err;
1338 panic("Unexpected EASYNC return value (for now)");
1341 if (p->p_sysent->sv_errsize) {
1342 if (error >= p->p_sysent->sv_errsize)
1343 error = -1; /* XXX */
1345 error = p->p_sysent->sv_errtbl[error];
1347 frame.tf_eax = error;
1348 frame.tf_eflags |= PSL_C;
1353 * Traced syscall. trapsignal() is not MP aware.
1355 if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1356 frame.tf_eflags &= ~PSL_T;
1357 trapsignal(p, SIGTRAP, 0);
1361 * Handle reschedule and other end-of-syscall issues
1363 userret(p, &frame, sticks);
1366 if (KTRPOINT(td, KTR_SYSRET)) {
1367 ktrsysret(p->p_tracep, code, error, args.sysmsg_result);
1372 * This works because errno is findable through the
1373 * register set. If we ever support an emulation where this
1374 * is not the case, this code will need to be revisited.
1376 STOPEVENT(p, S_SCX, code);
1381 * Release the MP lock if we had to get it
1383 KASSERT(curthread->td_mpcount == 1, ("badmpcount syscall from %p", (void *)frame.tf_eip));
1389 * sendsys2 - MP aware system message request C handler
1392 sendsys2(struct trapframe frame)
1394 struct globaldata *gd;
1395 struct thread *td = curthread;
1396 struct proc *p = td->td_proc;
1397 register_t orig_tf_eflags;
1398 struct sysent *callp;
1399 union sysunion *sysun;
1409 if (ISPL(frame.tf_cs) != SEL_UPL) {
1417 KASSERT(curthread->td_mpcount == 0, ("badmpcount syscall from %p", (void *)frame.tf_eip));
1421 * access non-atomic field from critical section. p_sticks is
1422 * updated by the clock interrupt. Also use this opportunity
1423 * to lazy-raise our LWKT priority.
1426 crit_enter_quick(td);
1427 sticks = curthread->td_sticks;
1428 crit_exit_quick(td);
1430 p->p_md.md_regs = &frame;
1431 orig_tf_eflags = frame.tf_eflags;
1435 * Handle the waitport/waitmsg/checkport/checkmsg case
1437 * YYY MOVE THIS TO INT 0x82! We don't really need to combine it
1440 if ((msgsize = frame.tf_edx) <= 0) {
1442 printf("waitmsg/checkmsg not yet supported: %08x\n",
1448 printf("waitport/checkport only the default port is supported at the moment\n");
1455 * Wait on port for message
1457 sysun = lwkt_getport(&td->td_msgport);
1462 * Test port for message
1464 sysun = lwkt_getport(&td->td_msgport);
1472 umsg = sysun->lmsg.opaque.ms_umsg;
1473 frame.tf_eax = (register_t)umsg;
1474 if (sysun->lmsg.ms_cleanupmsg)
1475 sysun->lmsg.ms_cleanupmsg(&td->td_msgport, &sysun->lmsg);
1476 atomic_add_int_nonlocked(&td->td_msgport.mp_refs, -1);
1477 sysun->nosys.usrmsg.umsg.u.ms_fds[0] = sysun->lmsg.u.ms_fds[0];
1478 sysun->nosys.usrmsg.umsg.u.ms_fds[1] = sysun->lmsg.u.ms_fds[1];
1479 sysun->nosys.usrmsg.umsg.ms_error = sysun->lmsg.ms_error;
1480 error = sysun->lmsg.ms_error;
1481 result = sysun->lmsg.u.ms_fds[0]; /* for ktrace */
1482 if (error != 0 || code != SYS_execve) {
1484 &sysun->nosys.usrmsg.umsg.ms_copyout_start,
1485 &umsg->ms_copyout_start,
1488 crit_enter_quick(td);
1489 sysun->lmsg.opaque.ms_sysunnext = gd->gd_freesysun;
1490 gd->gd_freesysun = sysun;
1491 crit_exit_quick(td);
1502 * Extract the system call message. If msgsize is zero we are
1503 * blocking on a message and/or message port. If msgsize is -1
1504 * we are testing a message for completion or a message port for
1507 * The userland system call message size includes the size of the
1508 * userland lwkt_msg plus arguments. We load it into the userland
1509 * portion of our sysunion structure then we initialize the kerneland
1516 if (msgsize < sizeof(struct lwkt_msg) ||
1517 msgsize > sizeof(union sysunion) - sizeof(union sysmsg)
1524 * Obtain a sysun from our per-cpu cache or allocate a new one. Use
1525 * the opaque field to store the original (user) message pointer.
1526 * A critical section is necessary to interlock against interrupts
1527 * returning system messages to the thread cache.
1530 crit_enter_quick(td);
1531 if ((sysun = gd->gd_freesysun) != NULL) {
1532 gd->gd_freesysun = sysun->lmsg.opaque.ms_sysunnext;
1533 crit_exit_quick(td);
1535 crit_exit_quick(td);
1536 sysun = malloc(sizeof(union sysunion), M_SYSMSG, M_WAITOK);
1538 atomic_add_int_nonlocked(&td->td_msgport.mp_refs, 1);
1541 * Copy the user request into the kernel copy of the user request.
1543 umsg = (void *)frame.tf_ecx;
1544 error = copyin(umsg, &sysun->nosys.usrmsg, msgsize);
1547 if ((sysun->nosys.usrmsg.umsg.ms_flags & MSGF_ASYNC) &&
1548 (error = suser(td)) != 0
1554 * Initialize the kernel message from the copied-in data and
1555 * pull in appropriate flags from the userland message.
1557 lwkt_initmsg(&sysun->lmsg, &td->td_msgport,
1558 sysun->nosys.usrmsg.umsg.ms_cmd);
1559 sysun->lmsg.opaque.ms_umsg = umsg;
1560 sysun->lmsg.ms_flags |= sysun->nosys.usrmsg.umsg.ms_flags & MSGF_ASYNC;
1563 * Extract the system call number, lookup the system call, and
1564 * set the default return value.
1566 code = (u_int)sysun->lmsg.ms_cmd;
1567 if (code >= p->p_sysent->sv_size) {
1572 callp = &p->p_sysent->sv_table[code];
1574 narg = (msgsize - sizeof(struct lwkt_msg)) / sizeof(register_t);
1577 if (KTRPOINT(td, KTR_SYSCALL)) {
1578 ktrsyscall(p->p_tracep, code, narg, (void *)(&sysun->nosys.usrmsg + 1));
1581 sysun->lmsg.u.ms_fds[0] = 0;
1582 sysun->lmsg.u.ms_fds[1] = 0;
1584 STOPEVENT(p, S_SCE, narg); /* MP aware */
1587 * Make the system call. An error code is always returned, results
1588 * are copied back via ms_result32 or ms_result64. YYY temporary
1589 * stage copy p_retval[] into ms_result32/64
1591 * NOTE! XXX if this is a child returning from a fork curproc
1592 * might be different. YYY huh? a child returning from a fork
1593 * should never 'return' from this call, it should go right to the
1594 * fork_trampoline function.
1596 error = (*callp->sy_call)(sysun);
1597 gd = td->td_gd; /* RELOAD, might have switched cpus */
1601 * If a synchronous return copy p_retval to ms_result64 and return
1602 * the sysmsg to the free pool.
1604 * YYY Don't writeback message if execve() YYY
1606 if (error != EASYNC) {
1607 atomic_add_int_nonlocked(&td->td_msgport.mp_refs, -1);
1608 sysun->nosys.usrmsg.umsg.u.ms_fds[0] = sysun->lmsg.u.ms_fds[0];
1609 sysun->nosys.usrmsg.umsg.u.ms_fds[1] = sysun->lmsg.u.ms_fds[1];
1610 result = sysun->nosys.usrmsg.umsg.u.ms_fds[0]; /* for ktrace */
1611 if (error != 0 || code != SYS_execve) {
1613 error2 = copyout(&sysun->nosys.usrmsg.umsg.ms_copyout_start,
1614 &umsg->ms_copyout_start,
1619 crit_enter_quick(td);
1620 sysun->lmsg.opaque.ms_sysunnext = gd->gd_freesysun;
1621 gd->gd_freesysun = sysun;
1622 crit_exit_quick(td);
1625 frame.tf_eax = error;
1629 * Traced syscall. trapsignal() is not MP aware.
1631 if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1632 frame.tf_eflags &= ~PSL_T;
1633 trapsignal(p, SIGTRAP, 0);
1637 * Handle reschedule and other end-of-syscall issues
1639 userret(p, &frame, sticks);
1642 if (KTRPOINT(td, KTR_SYSRET)) {
1643 ktrsysret(p->p_tracep, code, error, result);
1648 * This works because errno is findable through the
1649 * register set. If we ever support an emulation where this
1650 * is not the case, this code will need to be revisited.
1652 STOPEVENT(p, S_SCX, code);
1657 * Release the MP lock if we had to get it
1659 KASSERT(curthread->td_mpcount == 1, ("badmpcount syscall from %p", (void *)frame.tf_eip));
1665 * Simplified back end of syscall(), used when returning from fork()
1666 * directly into user mode. MP lock is held on entry and should be
1667 * released on return. This code will return back into the fork
1668 * trampoline code which then runs doreti.
1671 fork_return(p, frame)
1673 struct trapframe frame;
1675 frame.tf_eax = 0; /* Child returns zero */
1676 frame.tf_eflags &= ~PSL_C; /* success */
1679 userret(p, &frame, 0);
1681 if (KTRPOINT(p->p_thread, KTR_SYSRET))
1682 ktrsysret(p->p_tracep, SYS_fork, 0, 0);
1684 p->p_flag |= P_PASSIVE_ACQ;
1686 p->p_flag &= ~P_PASSIVE_ACQ;
1688 KKASSERT(curthread->td_mpcount == 1);