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