Add an INVARIANTS test in both the trap code and system call code. The
[dragonfly.git] / sys / i386 / 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/i386/i386/Attic/trap.c,v 1.77 2006/06/05 20:59:19 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/sysproto.h>
73 #include <sys/sysunion.h>
74
75 #include <vm/vm.h>
76 #include <vm/vm_param.h>
77 #include <sys/lock.h>
78 #include <vm/pmap.h>
79 #include <vm/vm_kern.h>
80 #include <vm/vm_map.h>
81 #include <vm/vm_page.h>
82 #include <vm/vm_extern.h>
83
84 #include <machine/cpu.h>
85 #include <machine/ipl.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 <i386/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 extern void sendsys2 (struct trapframe frame);
125 extern void waitsys2 (struct trapframe frame);
126
127 static int trap_pfault (struct trapframe *, int, vm_offset_t);
128 static void trap_fatal (struct trapframe *, vm_offset_t);
129 void dblfault_handler (void);
130
131 extern inthand_t IDTVEC(syscall);
132
133 #define MAX_TRAP_MSG            28
134 static char *trap_msg[] = {
135         "",                                     /*  0 unused */
136         "privileged instruction fault",         /*  1 T_PRIVINFLT */
137         "",                                     /*  2 unused */
138         "breakpoint instruction fault",         /*  3 T_BPTFLT */
139         "",                                     /*  4 unused */
140         "",                                     /*  5 unused */
141         "arithmetic trap",                      /*  6 T_ARITHTRAP */
142         "system forced exception",              /*  7 T_ASTFLT */
143         "",                                     /*  8 unused */
144         "general protection fault",             /*  9 T_PROTFLT */
145         "trace trap",                           /* 10 T_TRCTRAP */
146         "",                                     /* 11 unused */
147         "page fault",                           /* 12 T_PAGEFLT */
148         "",                                     /* 13 unused */
149         "alignment fault",                      /* 14 T_ALIGNFLT */
150         "",                                     /* 15 unused */
151         "",                                     /* 16 unused */
152         "",                                     /* 17 unused */
153         "integer divide fault",                 /* 18 T_DIVIDE */
154         "non-maskable interrupt trap",          /* 19 T_NMI */
155         "overflow trap",                        /* 20 T_OFLOW */
156         "FPU bounds check fault",               /* 21 T_BOUND */
157         "FPU device not available",             /* 22 T_DNA */
158         "double fault",                         /* 23 T_DOUBLEFLT */
159         "FPU operand fetch fault",              /* 24 T_FPOPFLT */
160         "invalid TSS fault",                    /* 25 T_TSSFLT */
161         "segment not present fault",            /* 26 T_SEGNPFLT */
162         "stack fault",                          /* 27 T_STKFLT */
163         "machine check trap",                   /* 28 T_MCHK */
164 };
165
166 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
167 extern int has_f00f_bug;
168 #endif
169
170 #ifdef DDB
171 static int ddb_on_nmi = 1;
172 SYSCTL_INT(_machdep, OID_AUTO, ddb_on_nmi, CTLFLAG_RW,
173         &ddb_on_nmi, 0, "Go to DDB on NMI");
174 #endif
175 static int panic_on_nmi = 1;
176 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
177         &panic_on_nmi, 0, "Panic on NMI");
178 static int fast_release;
179 SYSCTL_INT(_machdep, OID_AUTO, fast_release, CTLFLAG_RW,
180         &fast_release, 0, "Passive Release was optimal");
181 static int slow_release;
182 SYSCTL_INT(_machdep, OID_AUTO, slow_release, CTLFLAG_RW,
183         &slow_release, 0, "Passive Release was nonoptimal");
184 #ifdef SMP
185 static int syscall_mpsafe = 0;
186 SYSCTL_INT(_kern, OID_AUTO, syscall_mpsafe, CTLFLAG_RW,
187         &syscall_mpsafe, 0, "Allow MPSAFE marked syscalls to run without BGL");
188 TUNABLE_INT("kern.syscall_mpsafe", &syscall_mpsafe);
189 static int trap_mpsafe = 0;
190 SYSCTL_INT(_kern, OID_AUTO, trap_mpsafe, CTLFLAG_RW,
191         &trap_mpsafe, 0, "Allow traps to mostly run without the BGL");
192 TUNABLE_INT("kern.trap_mpsafe", &trap_mpsafe);
193 #endif
194
195 MALLOC_DEFINE(M_SYSMSG, "sysmsg", "sysmsg structure");
196 extern int max_sysmsg;
197
198 /*
199  * Passive USER->KERNEL transition.  This only occurs if we block in the
200  * kernel while still holding our userland priority.  We have to fixup our
201  * priority in order to avoid potential deadlocks before we allow the system
202  * to switch us to another thread.
203  */
204 static void
205 passive_release(struct thread *td)
206 {
207         struct lwp *lp = td->td_lwp;
208
209         td->td_release = NULL;
210         lwkt_setpri_self(TDPRI_KERN_USER);
211         lp->lwp_proc->p_usched->release_curproc(lp);
212 }
213
214 /*
215  * userenter() passively intercepts the thread switch function to increase
216  * the thread priority from a user priority to a kernel priority, reducing
217  * syscall and trap overhead for the case where no switch occurs.
218  */
219
220 static __inline void
221 userenter(struct thread *curtd)
222 {
223         curtd->td_release = passive_release;
224 }
225
226 /*
227  * Handle signals, upcalls, profiling, and other AST's and/or tasks that
228  * must be completed before we can return to or try to return to userland.
229  *
230  * Note that td_sticks is a 64 bit quantity, but there's no point doing 64
231  * arithmatic on the delta calculation so the absolute tick values are
232  * truncated to an integer.
233  */
234 static void
235 userret(struct lwp *lp, struct trapframe *frame, int sticks)
236 {
237         struct proc *p = lp->lwp_proc;
238         int sig;
239
240         /*
241          * Charge system time if profiling.  Note: times are in microseconds.
242          * This may do a copyout and block, so do it first even though it
243          * means some system time will be charged as user time.
244          */
245         if (p->p_flag & P_PROFIL) {
246                 addupc_task(p, frame->tf_eip, 
247                         (u_int)((int)p->p_thread->td_sticks - sticks));
248         }
249
250 recheck:
251         /*
252          * Block here if we are in a stopped state.
253          */
254         if (p->p_flag & P_STOPPED) {
255                 get_mplock();
256                 tstop(p);
257                 rel_mplock();
258                 goto recheck;
259         }
260
261         /*
262          * Post any pending upcalls
263          */
264         if (p->p_flag & P_UPCALLPEND) {
265                 p->p_flag &= ~P_UPCALLPEND;
266                 get_mplock();
267                 postupcall(lp);
268                 rel_mplock();
269                 goto recheck;
270         }
271
272         /*
273          * Post any pending signals
274          */
275         if ((sig = CURSIG(p)) != 0) {
276                 get_mplock();
277                 postsig(sig);
278                 rel_mplock();
279                 goto recheck;
280         }
281
282         /*
283          * block here if we are swapped out, but still process signals
284          * (such as SIGKILL).  proc0 (the swapin scheduler) is already
285          * aware of our situation, we do not have to wake it up.
286          */
287         if (p->p_flag & P_SWAPPEDOUT) {
288                 get_mplock();
289                 p->p_flag |= P_SWAPWAIT;
290                 swapin_request();
291                 if (p->p_flag & P_SWAPWAIT)
292                         tsleep(p, PCATCH, "SWOUT", 0);
293                 p->p_flag &= ~P_SWAPWAIT;
294                 rel_mplock();
295                 goto recheck;
296         }
297 }
298
299 /*
300  * Cleanup from userenter and any passive release that might have occured.
301  * We must reclaim the current-process designation before we can return
302  * to usermode.  We also handle both LWKT and USER reschedule requests.
303  */
304 static __inline void
305 userexit(struct lwp *lp)
306 {
307         struct thread *td = lp->lwp_thread;
308         globaldata_t gd = td->td_gd;
309
310 #if 0
311         /*
312          * If a user reschedule is requested force a new process to be
313          * chosen by releasing the current process.  Our process will only
314          * be chosen again if it has a considerably better priority.
315          */
316         if (user_resched_wanted())
317                 lp->lwp_proc->p_usched->release_curproc(lp);
318 #endif
319
320         /*
321          * Handle a LWKT reschedule request first.  Since our passive release
322          * is still in place we do not have to do anything special.
323          */
324         if (lwkt_resched_wanted())
325                 lwkt_switch();
326
327         /*
328          * Acquire the current process designation for this user scheduler
329          * on this cpu.  This will also handle any user-reschedule requests.
330          */
331         lp->lwp_proc->p_usched->acquire_curproc(lp);
332         /* We may have switched cpus on acquisition */
333         gd = td->td_gd;
334
335         /*
336          * Reduce our priority in preparation for a return to userland.  If
337          * our passive release function was still in place, our priority was
338          * never raised and does not need to be reduced.
339          */
340         if (td->td_release == NULL)
341                 lwkt_setpri_self(TDPRI_USER_NORM);
342         td->td_release = NULL;
343
344         /*
345          * After reducing our priority there might be other kernel-level
346          * LWKTs that now have a greater priority.  Run them as necessary.
347          * We don't have to worry about losing cpu to userland because
348          * we still control the current-process designation and we no longer
349          * have a passive release function installed.
350          */
351         if (lwkt_checkpri_self())
352                 lwkt_switch();
353 }
354
355 /*
356  * Exception, fault, and trap interface to the kernel.
357  * This common code is called from assembly language IDT gate entry
358  * routines that prepare a suitable stack frame, and restore this
359  * frame after the exception has been processed.
360  *
361  * This function is also called from doreti in an interlock to handle ASTs.
362  * For example:  hardwareint->INTROUTINE->(set ast)->doreti->trap
363  *
364  * NOTE!  We have to retrieve the fault address prior to obtaining the
365  * MP lock because get_mplock() may switch out.  YYY cr2 really ought
366  * to be retrieved by the assembly code, not here.
367  *
368  * XXX gd_trap_nesting_level currently prevents lwkt_switch() from panicing
369  * if an attempt is made to switch from a fast interrupt or IPI.  This is
370  * necessary to properly take fatal kernel traps on SMP machines if 
371  * get_mplock() has to block.
372  */
373
374 void
375 trap(frame)
376         struct trapframe frame;
377 {
378         struct globaldata *gd = mycpu;
379         struct thread *td = gd->gd_curthread;
380         struct lwp *lp = td->td_lwp;
381         struct proc *p;
382         int sticks = 0;
383         int i = 0, ucode = 0, type, code;
384 #ifdef SMP
385         int have_mplock = 0;
386 #endif
387 #ifdef INVARIANTS
388         int crit_count = td->td_pri & ~TDPRI_MASK;
389 #endif
390         vm_offset_t eva;
391
392         p = td->td_proc;
393 #ifdef DDB
394         if (db_active) {
395                 eva = (frame.tf_trapno == T_PAGEFLT ? rcr2() : 0);
396                 ++gd->gd_trap_nesting_level;
397                 MAKEMPSAFE(have_mplock);
398                 trap_fatal(&frame, eva);
399                 --gd->gd_trap_nesting_level;
400                 goto out2;
401         }
402 #endif
403
404         eva = 0;
405         ++gd->gd_trap_nesting_level;
406         if (frame.tf_trapno == T_PAGEFLT) {
407                 /*
408                  * For some Cyrix CPUs, %cr2 is clobbered by interrupts.
409                  * This problem is worked around by using an interrupt
410                  * gate for the pagefault handler.  We are finally ready
411                  * to read %cr2 and then must reenable interrupts.
412                  *
413                  * XXX this should be in the switch statement, but the
414                  * NO_FOOF_HACK and VM86 goto and ifdefs obfuscate the
415                  * flow of control too much for this to be obviously
416                  * correct.
417                  */
418                 eva = rcr2();
419                 cpu_enable_intr();
420         }
421 #ifdef SMP
422         if (trap_mpsafe == 0)
423                 MAKEMPSAFE(have_mplock);
424 #endif
425
426         --gd->gd_trap_nesting_level;
427
428         if (!(frame.tf_eflags & PSL_I)) {
429                 /*
430                  * Buggy application or kernel code has disabled interrupts
431                  * and then trapped.  Enabling interrupts now is wrong, but
432                  * it is better than running with interrupts disabled until
433                  * they are accidentally enabled later.
434                  */
435                 type = frame.tf_trapno;
436                 if (ISPL(frame.tf_cs)==SEL_UPL || (frame.tf_eflags & PSL_VM)) {
437                         MAKEMPSAFE(have_mplock);
438                         printf(
439                             "pid %ld (%s): trap %d with interrupts disabled\n",
440                             (long)curproc->p_pid, curproc->p_comm, type);
441                 } else if (type != T_BPTFLT && type != T_TRCTRAP) {
442                         /*
443                          * XXX not quite right, since this may be for a
444                          * multiple fault in user mode.
445                          */
446                         MAKEMPSAFE(have_mplock);
447                         printf("kernel trap %d with interrupts disabled\n",
448                             type);
449                 }
450                 cpu_enable_intr();
451         }
452
453 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
454 restart:
455 #endif
456         type = frame.tf_trapno;
457         code = frame.tf_err;
458
459         if (in_vm86call) {
460                 ASSERT_MP_LOCK_HELD(curthread);
461                 if (frame.tf_eflags & PSL_VM &&
462                     (type == T_PROTFLT || type == T_STKFLT)) {
463 #ifdef SMP
464                         KKASSERT(td->td_mpcount > 0);
465 #endif
466                         i = vm86_emulate((struct vm86frame *)&frame);
467 #ifdef SMP
468                         KKASSERT(td->td_mpcount > 0);
469 #endif
470                         if (i != 0) {
471                                 /*
472                                  * returns to original process
473                                  */
474 #ifdef SMP
475                                 vm86_trap((struct vm86frame *)&frame,
476                                           have_mplock);
477 #else
478                                 vm86_trap((struct vm86frame *)&frame, 0);
479 #endif
480                                 KKASSERT(0); /* NOT REACHED */
481                         }
482                         goto out2;
483                 }
484                 switch (type) {
485                         /*
486                          * these traps want either a process context, or
487                          * assume a normal userspace trap.
488                          */
489                 case T_PROTFLT:
490                 case T_SEGNPFLT:
491                         trap_fatal(&frame, eva);
492                         goto out2;
493                 case T_TRCTRAP:
494                         type = T_BPTFLT;        /* kernel breakpoint */
495                         /* FALL THROUGH */
496                 }
497                 goto kernel_trap;       /* normal kernel trap handling */
498         }
499
500         if ((ISPL(frame.tf_cs) == SEL_UPL) || (frame.tf_eflags & PSL_VM)) {
501                 /* user trap */
502
503                 userenter(td);
504
505                 sticks = (int)td->td_sticks;
506                 lp->lwp_md.md_regs = &frame;
507
508                 switch (type) {
509                 case T_PRIVINFLT:       /* privileged instruction fault */
510                         ucode = type;
511                         i = SIGILL;
512                         break;
513
514                 case T_BPTFLT:          /* bpt instruction fault */
515                 case T_TRCTRAP:         /* trace trap */
516                         frame.tf_eflags &= ~PSL_T;
517                         i = SIGTRAP;
518                         break;
519
520                 case T_ARITHTRAP:       /* arithmetic trap */
521                         ucode = code;
522                         i = SIGFPE;
523                         break;
524
525                 case T_ASTFLT:          /* Allow process switch */
526                         mycpu->gd_cnt.v_soft++;
527                         if (mycpu->gd_reqflags & RQF_AST_OWEUPC) {
528                                 atomic_clear_int_nonlocked(&mycpu->gd_reqflags,
529                                             RQF_AST_OWEUPC);
530                                 addupc_task(p, p->p_prof.pr_addr,
531                                             p->p_prof.pr_ticks);
532                         }
533                         goto out;
534
535                         /*
536                          * The following two traps can happen in
537                          * vm86 mode, and, if so, we want to handle
538                          * them specially.
539                          */
540                 case T_PROTFLT:         /* general protection fault */
541                 case T_STKFLT:          /* stack fault */
542                         if (frame.tf_eflags & PSL_VM) {
543                                 i = vm86_emulate((struct vm86frame *)&frame);
544                                 if (i == 0)
545                                         goto out;
546                                 break;
547                         }
548                         /* FALL THROUGH */
549
550                 case T_SEGNPFLT:        /* segment not present fault */
551                 case T_TSSFLT:          /* invalid TSS fault */
552                 case T_DOUBLEFLT:       /* double fault */
553                 default:
554                         ucode = code + BUS_SEGM_FAULT ;
555                         i = SIGBUS;
556                         break;
557
558                 case T_PAGEFLT:         /* page fault */
559                         MAKEMPSAFE(have_mplock);
560                         i = trap_pfault(&frame, TRUE, eva);
561                         if (i == -1)
562                                 goto out;
563 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
564                         if (i == -2)
565                                 goto restart;
566 #endif
567                         if (i == 0)
568                                 goto out;
569
570                         ucode = T_PAGEFLT;
571                         break;
572
573                 case T_DIVIDE:          /* integer divide fault */
574                         ucode = FPE_INTDIV;
575                         i = SIGFPE;
576                         break;
577
578 #if NISA > 0
579                 case T_NMI:
580                         MAKEMPSAFE(have_mplock);
581 #ifdef POWERFAIL_NMI
582                         goto handle_powerfail;
583 #else /* !POWERFAIL_NMI */
584                         /* machine/parity/power fail/"kitchen sink" faults */
585                         if (isa_nmi(code) == 0) {
586 #ifdef DDB
587                                 /*
588                                  * NMI can be hooked up to a pushbutton
589                                  * for debugging.
590                                  */
591                                 if (ddb_on_nmi) {
592                                         printf ("NMI ... going to debugger\n");
593                                         kdb_trap (type, 0, &frame);
594                                 }
595 #endif /* DDB */
596                                 goto out2;
597                         } else if (panic_on_nmi)
598                                 panic("NMI indicates hardware failure");
599                         break;
600 #endif /* POWERFAIL_NMI */
601 #endif /* NISA > 0 */
602
603                 case T_OFLOW:           /* integer overflow fault */
604                         ucode = FPE_INTOVF;
605                         i = SIGFPE;
606                         break;
607
608                 case T_BOUND:           /* bounds check fault */
609                         ucode = FPE_FLTSUB;
610                         i = SIGFPE;
611                         break;
612
613                 case T_DNA:
614 #if NNPX > 0
615                         /* 
616                          * The kernel may have switched out the FP unit's
617                          * state, causing the user process to take a fault
618                          * when it tries to use the FP unit.  Restore the
619                          * state here
620                          */
621                         if (npxdna())
622                                 goto out;
623 #endif
624                         if (!pmath_emulate) {
625                                 i = SIGFPE;
626                                 ucode = FPE_FPU_NP_TRAP;
627                                 break;
628                         }
629                         i = (*pmath_emulate)(&frame);
630                         if (i == 0) {
631                                 if (!(frame.tf_eflags & PSL_T))
632                                         goto out2;
633                                 frame.tf_eflags &= ~PSL_T;
634                                 i = SIGTRAP;
635                         }
636                         /* else ucode = emulator_only_knows() XXX */
637                         break;
638
639                 case T_FPOPFLT:         /* FPU operand fetch fault */
640                         ucode = T_FPOPFLT;
641                         i = SIGILL;
642                         break;
643
644                 case T_XMMFLT:          /* SIMD floating-point exception */
645                         ucode = 0; /* XXX */
646                         i = SIGFPE;
647                         break;
648                 }
649         } else {
650 kernel_trap:
651                 /* kernel trap */
652
653                 switch (type) {
654                 case T_PAGEFLT:                 /* page fault */
655                         MAKEMPSAFE(have_mplock);
656                         trap_pfault(&frame, FALSE, eva);
657                         goto out2;
658
659                 case T_DNA:
660 #if NNPX > 0
661                         /*
662                          * The kernel may be using npx for copying or other
663                          * purposes.
664                          */
665                         if (npxdna())
666                                 goto out2;
667 #endif
668                         break;
669
670                 case T_PROTFLT:         /* general protection fault */
671                 case T_SEGNPFLT:        /* segment not present fault */
672                         /*
673                          * Invalid segment selectors and out of bounds
674                          * %eip's and %esp's can be set up in user mode.
675                          * This causes a fault in kernel mode when the
676                          * kernel tries to return to user mode.  We want
677                          * to get this fault so that we can fix the
678                          * problem here and not have to check all the
679                          * selectors and pointers when the user changes
680                          * them.
681                          */
682 #define MAYBE_DORETI_FAULT(where, whereto)                              \
683         do {                                                            \
684                 if (frame.tf_eip == (int)where) {                       \
685                         frame.tf_eip = (int)whereto;                    \
686                         goto out2;                                      \
687                 }                                                       \
688         } while (0)
689                         /*
690                          * Since we don't save %gs across an interrupt
691                          * frame this check must occur outside the intr
692                          * nesting level check.
693                          */
694                         if (frame.tf_eip == (int)cpu_switch_load_gs) {
695                                 td->td_pcb->pcb_gs = 0;
696                                 MAKEMPSAFE(have_mplock);
697                                 psignal(p, SIGBUS);
698                                 goto out2;
699                         }
700                         if (mycpu->gd_intr_nesting_level == 0) {
701                                 /*
702                                  * Invalid %fs's and %gs's can be created using
703                                  * procfs or PT_SETREGS or by invalidating the
704                                  * underlying LDT entry.  This causes a fault
705                                  * in kernel mode when the kernel attempts to
706                                  * switch contexts.  Lose the bad context
707                                  * (XXX) so that we can continue, and generate
708                                  * a signal.
709                                  */
710                                 MAYBE_DORETI_FAULT(doreti_iret,
711                                                    doreti_iret_fault);
712                                 MAYBE_DORETI_FAULT(doreti_popl_ds,
713                                                    doreti_popl_ds_fault);
714                                 MAYBE_DORETI_FAULT(doreti_popl_es,
715                                                    doreti_popl_es_fault);
716                                 MAYBE_DORETI_FAULT(doreti_popl_fs,
717                                                    doreti_popl_fs_fault);
718                                 if (td->td_pcb->pcb_onfault) {
719                                         frame.tf_eip = 
720                                             (register_t)td->td_pcb->pcb_onfault;
721                                         goto out2;
722                                 }
723                         }
724                         break;
725
726                 case T_TSSFLT:
727                         /*
728                          * PSL_NT can be set in user mode and isn't cleared
729                          * automatically when the kernel is entered.  This
730                          * causes a TSS fault when the kernel attempts to
731                          * `iret' because the TSS link is uninitialized.  We
732                          * want to get this fault so that we can fix the
733                          * problem here and not every time the kernel is
734                          * entered.
735                          */
736                         if (frame.tf_eflags & PSL_NT) {
737                                 frame.tf_eflags &= ~PSL_NT;
738                                 goto out2;
739                         }
740                         break;
741
742                 case T_TRCTRAP:  /* trace trap */
743                         if (frame.tf_eip == (int)IDTVEC(syscall)) {
744                                 /*
745                                  * We've just entered system mode via the
746                                  * syscall lcall.  Continue single stepping
747                                  * silently until the syscall handler has
748                                  * saved the flags.
749                                  */
750                                 goto out2;
751                         }
752                         if (frame.tf_eip == (int)IDTVEC(syscall) + 1) {
753                                 /*
754                                  * The syscall handler has now saved the
755                                  * flags.  Stop single stepping it.
756                                  */
757                                 frame.tf_eflags &= ~PSL_T;
758                                 goto out2;
759                         }
760                         /*
761                          * Ignore debug register trace traps due to
762                          * accesses in the user's address space, which
763                          * can happen under several conditions such as
764                          * if a user sets a watchpoint on a buffer and
765                          * then passes that buffer to a system call.
766                          * We still want to get TRCTRAPS for addresses
767                          * in kernel space because that is useful when
768                          * debugging the kernel.
769                          */
770                         if (user_dbreg_trap()) {
771                                 /*
772                                  * Reset breakpoint bits because the
773                                  * processor doesn't
774                                  */
775                                 load_dr6(rdr6() & 0xfffffff0);
776                                 goto out2;
777                         }
778                         /*
779                          * Fall through (TRCTRAP kernel mode, kernel address)
780                          */
781                 case T_BPTFLT:
782                         /*
783                          * If DDB is enabled, let it handle the debugger trap.
784                          * Otherwise, debugger traps "can't happen".
785                          */
786 #ifdef DDB
787                         MAKEMPSAFE(have_mplock);
788                         if (kdb_trap (type, 0, &frame))
789                                 goto out2;
790 #endif
791                         break;
792
793 #if NISA > 0
794                 case T_NMI:
795                         MAKEMPSAFE(have_mplock);
796 #ifdef POWERFAIL_NMI
797 #ifndef TIMER_FREQ
798 #  define TIMER_FREQ 1193182
799 #endif
800         handle_powerfail:
801                 {
802                   static unsigned lastalert = 0;
803
804                   if(time_second - lastalert > 10)
805                     {
806                       log(LOG_WARNING, "NMI: power fail\n");
807                       sysbeep(TIMER_FREQ/880, hz);
808                       lastalert = time_second;
809                     }
810                     /* YYY mp count */
811                   goto out2;
812                 }
813 #else /* !POWERFAIL_NMI */
814                         /* machine/parity/power fail/"kitchen sink" faults */
815                         if (isa_nmi(code) == 0) {
816 #ifdef DDB
817                                 /*
818                                  * NMI can be hooked up to a pushbutton
819                                  * for debugging.
820                                  */
821                                 if (ddb_on_nmi) {
822                                         printf ("NMI ... going to debugger\n");
823                                         kdb_trap (type, 0, &frame);
824                                 }
825 #endif /* DDB */
826                                 goto out2;
827                         } else if (panic_on_nmi == 0)
828                                 goto out2;
829                         /* FALL THROUGH */
830 #endif /* POWERFAIL_NMI */
831 #endif /* NISA > 0 */
832                 }
833
834                 MAKEMPSAFE(have_mplock);
835                 trap_fatal(&frame, eva);
836                 goto out2;
837         }
838
839         /* Translate fault for emulators (e.g. Linux) */
840         if (*p->p_sysent->sv_transtrap)
841                 i = (*p->p_sysent->sv_transtrap)(i, type);
842
843         MAKEMPSAFE(have_mplock);
844         trapsignal(p, i, ucode);
845
846 #ifdef DEBUG
847         if (type <= MAX_TRAP_MSG) {
848                 uprintf("fatal process exception: %s",
849                         trap_msg[type]);
850                 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
851                         uprintf(", fault VA = 0x%lx", (u_long)eva);
852                 uprintf("\n");
853         }
854 #endif
855
856 out:
857 #ifdef SMP
858         if (ISPL(frame.tf_cs) == SEL_UPL)
859                 KASSERT(td->td_mpcount == have_mplock, ("badmpcount trap/end from %p", (void *)frame.tf_eip));
860 #endif
861         userret(lp, &frame, sticks);
862         userexit(lp);
863 out2:   ;
864 #ifdef SMP
865         if (have_mplock)
866                 rel_mplock();
867 #endif
868 #ifdef INVARIANTS
869         KASSERT(crit_count == (td->td_pri & ~TDPRI_MASK),
870                 ("syscall: critical section count mismatch! %d/%d",
871                 crit_count / TDPRI_CRIT, td->td_pri / TDPRI_CRIT));
872 #endif
873 }
874
875 #ifdef notyet
876 /*
877  * This version doesn't allow a page fault to user space while
878  * in the kernel. The rest of the kernel needs to be made "safe"
879  * before this can be used. I think the only things remaining
880  * to be made safe is the process tracing/debugging code.
881  */
882 static int
883 trap_pfault(frame, usermode, eva)
884         struct trapframe *frame;
885         int usermode;
886         vm_offset_t eva;
887 {
888         vm_offset_t va;
889         struct vmspace *vm = NULL;
890         vm_map_t map = 0;
891         int rv = 0;
892         vm_prot_t ftype;
893         thread_t td = curthread;
894         struct proc *p = td->td_proc;   /* may be NULL */
895
896         if (frame->tf_err & PGEX_W)
897                 ftype = VM_PROT_WRITE;
898         else
899                 ftype = VM_PROT_READ;
900
901         va = trunc_page(eva);
902         if (va < VM_MIN_KERNEL_ADDRESS) {
903                 vm_offset_t v;
904                 vm_page_t mpte;
905
906                 if (p == NULL ||
907                     (!usermode && va < VM_MAXUSER_ADDRESS &&
908                      (td->td_gd->gd_intr_nesting_level != 0 || 
909                       td->td_pcb->pcb_onfault == NULL))) {
910                         trap_fatal(frame, eva);
911                         return (-1);
912                 }
913
914                 /*
915                  * This is a fault on non-kernel virtual memory.
916                  * vm is initialized above to NULL. If curproc is NULL
917                  * or curproc->p_vmspace is NULL the fault is fatal.
918                  */
919                 vm = p->p_vmspace;
920                 if (vm == NULL)
921                         goto nogo;
922
923                 map = &vm->vm_map;
924
925                 /*
926                  * Keep swapout from messing with us during this
927                  *      critical time.
928                  */
929                 ++p->p_lock;
930
931                 /*
932                  * Grow the stack if necessary
933                  */
934                 /* grow_stack returns false only if va falls into
935                  * a growable stack region and the stack growth
936                  * fails.  It returns true if va was not within
937                  * a growable stack region, or if the stack 
938                  * growth succeeded.
939                  */
940                 if (!grow_stack (p, va)) {
941                         rv = KERN_FAILURE;
942                         --p->p_lock;
943                         goto nogo;
944                 }
945                 
946                 /* Fault in the user page: */
947                 rv = vm_fault(map, va, ftype,
948                               (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
949                                                       : VM_FAULT_NORMAL);
950
951                 --p->p_lock;
952         } else {
953                 /*
954                  * Don't allow user-mode faults in kernel address space.
955                  */
956                 if (usermode)
957                         goto nogo;
958
959                 /*
960                  * Since we know that kernel virtual address addresses
961                  * always have pte pages mapped, we just have to fault
962                  * the page.
963                  */
964                 rv = vm_fault(kernel_map, va, ftype, VM_FAULT_NORMAL);
965         }
966
967         if (rv == KERN_SUCCESS)
968                 return (0);
969 nogo:
970         if (!usermode) {
971                 if (mtd->td_gd->gd_intr_nesting_level == 0 && 
972                     td->td_pcb->pcb_onfault) {
973                         frame->tf_eip = (register_t)td->td_pcb->pcb_onfault;
974                         return (0);
975                 }
976                 trap_fatal(frame, eva);
977                 return (-1);
978         }
979
980         /* kludge to pass faulting virtual address to sendsig */
981         frame->tf_err = eva;
982
983         return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
984 }
985 #endif
986
987 int
988 trap_pfault(frame, usermode, eva)
989         struct trapframe *frame;
990         int usermode;
991         vm_offset_t eva;
992 {
993         vm_offset_t va;
994         struct vmspace *vm = NULL;
995         vm_map_t map = 0;
996         int rv = 0;
997         vm_prot_t ftype;
998         thread_t td = curthread;
999         struct proc *p = td->td_proc;
1000
1001         va = trunc_page(eva);
1002         if (va >= KERNBASE) {
1003                 /*
1004                  * Don't allow user-mode faults in kernel address space.
1005                  * An exception:  if the faulting address is the invalid
1006                  * instruction entry in the IDT, then the Intel Pentium
1007                  * F00F bug workaround was triggered, and we need to
1008                  * treat it is as an illegal instruction, and not a page
1009                  * fault.
1010                  */
1011 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
1012                 if ((eva == (unsigned int)&idt[6]) && has_f00f_bug) {
1013                         frame->tf_trapno = T_PRIVINFLT;
1014                         return -2;
1015                 }
1016 #endif
1017                 if (usermode)
1018                         goto nogo;
1019
1020                 map = kernel_map;
1021         } else {
1022                 /*
1023                  * This is a fault on non-kernel virtual memory.
1024                  * vm is initialized above to NULL. If curproc is NULL
1025                  * or curproc->p_vmspace is NULL the fault is fatal.
1026                  */
1027                 if (p != NULL)
1028                         vm = p->p_vmspace;
1029
1030                 if (vm == NULL)
1031                         goto nogo;
1032
1033                 map = &vm->vm_map;
1034         }
1035
1036         if (frame->tf_err & PGEX_W)
1037                 ftype = VM_PROT_WRITE;
1038         else
1039                 ftype = VM_PROT_READ;
1040
1041         if (map != kernel_map) {
1042                 /*
1043                  * Keep swapout from messing with us during this
1044                  *      critical time.
1045                  */
1046                 ++p->p_lock;
1047
1048                 /*
1049                  * Grow the stack if necessary
1050                  */
1051                 /* grow_stack returns false only if va falls into
1052                  * a growable stack region and the stack growth
1053                  * fails.  It returns true if va was not within
1054                  * a growable stack region, or if the stack 
1055                  * growth succeeded.
1056                  */
1057                 if (!grow_stack (p, va)) {
1058                         rv = KERN_FAILURE;
1059                         --p->p_lock;
1060                         goto nogo;
1061                 }
1062
1063                 /* Fault in the user page: */
1064                 rv = vm_fault(map, va, ftype,
1065                               (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
1066                                                       : VM_FAULT_NORMAL);
1067
1068                 --p->p_lock;
1069         } else {
1070                 /*
1071                  * Don't have to worry about process locking or stacks in the kernel.
1072                  */
1073                 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
1074         }
1075
1076         if (rv == KERN_SUCCESS)
1077                 return (0);
1078 nogo:
1079         if (!usermode) {
1080                 if (td->td_gd->gd_intr_nesting_level == 0 &&
1081                     td->td_pcb->pcb_onfault) {
1082                         frame->tf_eip = (register_t)td->td_pcb->pcb_onfault;
1083                         return (0);
1084                 }
1085                 trap_fatal(frame, eva);
1086                 return (-1);
1087         }
1088
1089         /* kludge to pass faulting virtual address to sendsig */
1090         frame->tf_err = eva;
1091
1092         return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
1093 }
1094
1095 static void
1096 trap_fatal(frame, eva)
1097         struct trapframe *frame;
1098         vm_offset_t eva;
1099 {
1100         int code, type, ss, esp;
1101         struct soft_segment_descriptor softseg;
1102
1103         code = frame->tf_err;
1104         type = frame->tf_trapno;
1105         sdtossd(&gdt[mycpu->gd_cpuid * NGDT + IDXSEL(frame->tf_cs & 0xffff)].sd, &softseg);
1106
1107         if (type <= MAX_TRAP_MSG)
1108                 printf("\n\nFatal trap %d: %s while in %s mode\n",
1109                         type, trap_msg[type],
1110                         frame->tf_eflags & PSL_VM ? "vm86" :
1111                         ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
1112 #ifdef SMP
1113         /* three separate prints in case of a trap on an unmapped page */
1114         printf("mp_lock = %08x; ", mp_lock);
1115         printf("cpuid = %d; ", mycpu->gd_cpuid);
1116         printf("lapic.id = %08x\n", lapic.id);
1117 #endif
1118         if (type == T_PAGEFLT) {
1119                 printf("fault virtual address   = 0x%x\n", eva);
1120                 printf("fault code              = %s %s, %s\n",
1121                         code & PGEX_U ? "user" : "supervisor",
1122                         code & PGEX_W ? "write" : "read",
1123                         code & PGEX_P ? "protection violation" : "page not present");
1124         }
1125         printf("instruction pointer     = 0x%x:0x%x\n",
1126                frame->tf_cs & 0xffff, frame->tf_eip);
1127         if ((ISPL(frame->tf_cs) == SEL_UPL) || (frame->tf_eflags & PSL_VM)) {
1128                 ss = frame->tf_ss & 0xffff;
1129                 esp = frame->tf_esp;
1130         } else {
1131                 ss = GSEL(GDATA_SEL, SEL_KPL);
1132                 esp = (int)&frame->tf_esp;
1133         }
1134         printf("stack pointer           = 0x%x:0x%x\n", ss, esp);
1135         printf("frame pointer           = 0x%x:0x%x\n", ss, frame->tf_ebp);
1136         printf("code segment            = base 0x%x, limit 0x%x, type 0x%x\n",
1137                softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
1138         printf("                        = DPL %d, pres %d, def32 %d, gran %d\n",
1139                softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_def32,
1140                softseg.ssd_gran);
1141         printf("processor eflags        = ");
1142         if (frame->tf_eflags & PSL_T)
1143                 printf("trace trap, ");
1144         if (frame->tf_eflags & PSL_I)
1145                 printf("interrupt enabled, ");
1146         if (frame->tf_eflags & PSL_NT)
1147                 printf("nested task, ");
1148         if (frame->tf_eflags & PSL_RF)
1149                 printf("resume, ");
1150         if (frame->tf_eflags & PSL_VM)
1151                 printf("vm86, ");
1152         printf("IOPL = %d\n", (frame->tf_eflags & PSL_IOPL) >> 12);
1153         printf("current process         = ");
1154         if (curproc) {
1155                 printf("%lu (%s)\n",
1156                     (u_long)curproc->p_pid, curproc->p_comm ?
1157                     curproc->p_comm : "");
1158         } else {
1159                 printf("Idle\n");
1160         }
1161         printf("current thread          = pri %d ", curthread->td_pri);
1162         if (curthread->td_pri >= TDPRI_CRIT)
1163                 printf("(CRIT)");
1164         printf("\n");
1165 #ifdef SMP
1166 /**
1167  *  XXX FIXME:
1168  *      we probably SHOULD have stopped the other CPUs before now!
1169  *      another CPU COULD have been touching cpl at this moment...
1170  */
1171         printf(" <- SMP: XXX");
1172 #endif
1173         printf("\n");
1174
1175 #ifdef KDB
1176         if (kdb_trap(&psl))
1177                 return;
1178 #endif
1179 #ifdef DDB
1180         if ((debugger_on_panic || db_active) && kdb_trap(type, code, frame))
1181                 return;
1182 #endif
1183         printf("trap number             = %d\n", type);
1184         if (type <= MAX_TRAP_MSG)
1185                 panic("%s", trap_msg[type]);
1186         else
1187                 panic("unknown/reserved trap");
1188 }
1189
1190 /*
1191  * Double fault handler. Called when a fault occurs while writing
1192  * a frame for a trap/exception onto the stack. This usually occurs
1193  * when the stack overflows (such is the case with infinite recursion,
1194  * for example).
1195  *
1196  * XXX Note that the current PTD gets replaced by IdlePTD when the
1197  * task switch occurs. This means that the stack that was active at
1198  * the time of the double fault is not available at <kstack> unless
1199  * the machine was idle when the double fault occurred. The downside
1200  * of this is that "trace <ebp>" in ddb won't work.
1201  */
1202 void
1203 dblfault_handler()
1204 {
1205         struct mdglobaldata *gd = mdcpu;
1206
1207         printf("\nFatal double fault:\n");
1208         printf("eip = 0x%x\n", gd->gd_common_tss.tss_eip);
1209         printf("esp = 0x%x\n", gd->gd_common_tss.tss_esp);
1210         printf("ebp = 0x%x\n", gd->gd_common_tss.tss_ebp);
1211 #ifdef SMP
1212         /* three separate prints in case of a trap on an unmapped page */
1213         printf("mp_lock = %08x; ", mp_lock);
1214         printf("cpuid = %d; ", mycpu->gd_cpuid);
1215         printf("lapic.id = %08x\n", lapic.id);
1216 #endif
1217         panic("double fault");
1218 }
1219
1220 /*
1221  * Compensate for 386 brain damage (missing URKR).
1222  * This is a little simpler than the pagefault handler in trap() because
1223  * it the page tables have already been faulted in and high addresses
1224  * are thrown out early for other reasons.
1225  */
1226 int trapwrite(addr)
1227         unsigned addr;
1228 {
1229         struct proc *p;
1230         vm_offset_t va;
1231         struct vmspace *vm;
1232         int rv;
1233
1234         va = trunc_page((vm_offset_t)addr);
1235         /*
1236          * XXX - MAX is END.  Changed > to >= for temp. fix.
1237          */
1238         if (va >= VM_MAXUSER_ADDRESS)
1239                 return (1);
1240
1241         p = curproc;
1242         vm = p->p_vmspace;
1243
1244         ++p->p_lock;
1245
1246         if (!grow_stack (p, va)) {
1247                 --p->p_lock;
1248                 return (1);
1249         }
1250
1251         /*
1252          * fault the data page
1253          */
1254         rv = vm_fault(&vm->vm_map, va, VM_PROT_WRITE, VM_FAULT_DIRTY);
1255
1256         --p->p_lock;
1257
1258         if (rv != KERN_SUCCESS)
1259                 return 1;
1260
1261         return (0);
1262 }
1263
1264 /*
1265  *      syscall2 -      MP aware system call request C handler
1266  *
1267  *      A system call is essentially treated as a trap except that the
1268  *      MP lock is not held on entry or return.  We are responsible for
1269  *      obtaining the MP lock if necessary and for handling ASTs
1270  *      (e.g. a task switch) prior to return.
1271  *
1272  *      In general, only simple access and manipulation of curproc and
1273  *      the current stack is allowed without having to hold MP lock.
1274  *
1275  *      MPSAFE - note that large sections of this routine are run without
1276  *               the MP lock.
1277  */
1278
1279 void
1280 syscall2(struct trapframe frame)
1281 {
1282         struct thread *td = curthread;
1283         struct proc *p = td->td_proc;
1284         struct lwp *lp = td->td_lwp;
1285         caddr_t params;
1286         struct sysent *callp;
1287         register_t orig_tf_eflags;
1288         int sticks;
1289         int error;
1290         int narg;
1291 #ifdef INVARIANTS
1292         int crit_count = td->td_pri & ~TDPRI_MASK;
1293 #endif
1294 #ifdef SMP
1295         int have_mplock = 0;
1296 #endif
1297         u_int code;
1298         union sysunion args;
1299
1300 #ifdef DIAGNOSTIC
1301         if (ISPL(frame.tf_cs) != SEL_UPL) {
1302                 get_mplock();
1303                 panic("syscall");
1304                 /* NOT REACHED */
1305         }
1306 #endif
1307
1308 #ifdef SMP
1309         KASSERT(td->td_mpcount == 0, ("badmpcount syscall2 from %p", (void *)frame.tf_eip));
1310         if (syscall_mpsafe == 0)
1311                 MAKEMPSAFE(have_mplock);
1312 #endif
1313         userenter(td);          /* lazy raise our priority */
1314
1315         sticks = (int)td->td_sticks;
1316
1317         lp->lwp_md.md_regs = &frame;
1318         params = (caddr_t)frame.tf_esp + sizeof(int);
1319         code = frame.tf_eax;
1320         orig_tf_eflags = frame.tf_eflags;
1321
1322         if (p->p_sysent->sv_prepsyscall) {
1323                 (*p->p_sysent->sv_prepsyscall)(
1324                         &frame, (int *)(&args.nosys.usrmsg + 1),
1325                         &code, &params);
1326         } else {
1327                 /*
1328                  * Need to check if this is a 32 bit or 64 bit syscall.
1329                  * fuword is MP aware.
1330                  */
1331                 if (code == SYS_syscall) {
1332                         /*
1333                          * Code is first argument, followed by actual args.
1334                          */
1335                         code = fuword(params);
1336                         params += sizeof(int);
1337                 } else if (code == SYS___syscall) {
1338                         /*
1339                          * Like syscall, but code is a quad, so as to maintain
1340                          * quad alignment for the rest of the arguments.
1341                          */
1342                         code = fuword(params);
1343                         params += sizeof(quad_t);
1344                 }
1345         }
1346
1347         code &= p->p_sysent->sv_mask;
1348         if (code >= p->p_sysent->sv_size)
1349                 callp = &p->p_sysent->sv_table[0];
1350         else
1351                 callp = &p->p_sysent->sv_table[code];
1352
1353         narg = callp->sy_narg & SYF_ARGMASK;
1354
1355         /*
1356          * copyin is MP aware, but the tracing code is not
1357          */
1358         if (narg && params) {
1359                 error = copyin(params, (caddr_t)(&args.nosys.usrmsg + 1),
1360                                 narg * sizeof(register_t));
1361                 if (error) {
1362 #ifdef KTRACE
1363                         if (KTRPOINT(td, KTR_SYSCALL)) {
1364                                 MAKEMPSAFE(have_mplock);
1365                                 
1366                                 ktrsyscall(p, code, narg,
1367                                         (void *)(&args.nosys.usrmsg + 1));
1368                         }
1369 #endif
1370                         goto bad;
1371                 }
1372         }
1373
1374 #ifdef KTRACE
1375         if (KTRPOINT(td, KTR_SYSCALL)) {
1376                 MAKEMPSAFE(have_mplock);
1377                 ktrsyscall(p, code, narg, (void *)(&args.nosys.usrmsg + 1));
1378         }
1379 #endif
1380
1381         /*
1382          * For traditional syscall code edx is left untouched when 32 bit
1383          * results are returned.  Since edx is loaded from fds[1] when the 
1384          * system call returns we pre-set it here.
1385          */
1386         lwkt_initmsg(&args.lmsg, &td->td_msgport, 0,
1387                         lwkt_cmd_op(code), lwkt_cmd_op_none);
1388         args.sysmsg_copyout = NULL;
1389         args.sysmsg_fds[0] = 0;
1390         args.sysmsg_fds[1] = frame.tf_edx;
1391
1392         STOPEVENT(p, S_SCE, narg);      /* MP aware */
1393
1394 #ifdef SMP
1395         /*
1396          * Try to run the syscall without the MP lock if the syscall
1397          * is MP safe.  We have to obtain the MP lock no matter what if 
1398          * we are ktracing
1399          */
1400         if ((callp->sy_narg & SYF_MPSAFE) == 0)
1401                 MAKEMPSAFE(have_mplock);
1402 #endif
1403
1404         error = (*callp->sy_call)(&args);
1405
1406         /*
1407          * MP SAFE (we may or may not have the MP lock at this point)
1408          */
1409         switch (error) {
1410         case 0:
1411                 /*
1412                  * Reinitialize proc pointer `p' as it may be different
1413                  * if this is a child returning from fork syscall.
1414                  */
1415                 p = curproc;
1416                 lp = curthread->td_lwp;
1417                 frame.tf_eax = args.sysmsg_fds[0];
1418                 frame.tf_edx = args.sysmsg_fds[1];
1419                 frame.tf_eflags &= ~PSL_C;
1420                 break;
1421         case ERESTART:
1422                 /*
1423                  * Reconstruct pc, assuming lcall $X,y is 7 bytes,
1424                  * int 0x80 is 2 bytes. We saved this in tf_err.
1425                  */
1426                 frame.tf_eip -= frame.tf_err;
1427                 break;
1428         case EJUSTRETURN:
1429                 break;
1430         case EASYNC:
1431                 panic("Unexpected EASYNC return value (for now)");
1432         default:
1433 bad:
1434                 if (p->p_sysent->sv_errsize) {
1435                         if (error >= p->p_sysent->sv_errsize)
1436                                 error = -1;     /* XXX */
1437                         else
1438                                 error = p->p_sysent->sv_errtbl[error];
1439                 }
1440                 frame.tf_eax = error;
1441                 frame.tf_eflags |= PSL_C;
1442                 break;
1443         }
1444
1445         /*
1446          * Traced syscall.  trapsignal() is not MP aware.
1447          */
1448         if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1449                 MAKEMPSAFE(have_mplock);
1450                 frame.tf_eflags &= ~PSL_T;
1451                 trapsignal(p, SIGTRAP, 0);
1452         }
1453
1454         /*
1455          * Handle reschedule and other end-of-syscall issues
1456          */
1457         userret(lp, &frame, sticks);
1458
1459 #ifdef KTRACE
1460         if (KTRPOINT(td, KTR_SYSRET)) {
1461                 MAKEMPSAFE(have_mplock);
1462                 ktrsysret(p, code, error, args.sysmsg_result);
1463         }
1464 #endif
1465
1466         /*
1467          * This works because errno is findable through the
1468          * register set.  If we ever support an emulation where this
1469          * is not the case, this code will need to be revisited.
1470          */
1471         STOPEVENT(p, S_SCX, code);
1472
1473         userexit(lp);
1474 #ifdef SMP
1475         /*
1476          * Release the MP lock if we had to get it
1477          */
1478         KASSERT(td->td_mpcount == have_mplock, 
1479                 ("badmpcount syscall2/end from %p", (void *)frame.tf_eip));
1480         if (have_mplock)
1481                 rel_mplock();
1482 #endif
1483 #ifdef INVARIANTS
1484         KASSERT(crit_count == (td->td_pri & ~TDPRI_MASK), 
1485                 ("syscall: critical section count mismatch! %d/%d",
1486                 crit_count / TDPRI_CRIT, td->td_pri / TDPRI_CRIT));
1487 #endif
1488 }
1489
1490 /*
1491  *      free_sysun -    Put an unused sysun on the free list.
1492  */
1493 static __inline void
1494 free_sysun(struct thread *td, union sysunion *sysun)
1495 {
1496         struct globaldata *gd = td->td_gd;
1497
1498         crit_enter_quick(td);
1499         sysun->lmsg.opaque.ms_sysunnext = gd->gd_freesysun;
1500         gd->gd_freesysun = sysun;
1501         crit_exit_quick(td);
1502 }
1503
1504 /*
1505  *      sendsys2 -      MP aware system message request C handler
1506  */
1507 void
1508 sendsys2(struct trapframe frame)
1509 {
1510         struct globaldata *gd;
1511         struct thread *td = curthread;
1512         struct proc *p = td->td_proc;
1513         struct lwp *lp = td->td_lwp;
1514         register_t orig_tf_eflags;
1515         struct sysent *callp;
1516         union sysunion *sysun = NULL;
1517         lwkt_msg_t umsg;
1518 #ifdef SMP
1519         int have_mplock = 0;
1520 #endif
1521         int sticks;
1522         int error;
1523         int narg;
1524         u_int code = 0;
1525         int msgsize;
1526         int result;
1527
1528 #ifdef DIAGNOSTIC
1529         if (ISPL(frame.tf_cs) != SEL_UPL) {
1530                 get_mplock();
1531                 panic("sendsys");
1532                 /* NOT REACHED */
1533         }
1534 #endif
1535
1536 #ifdef SMP
1537         KASSERT(td->td_mpcount == 0,
1538                 ("badmpcount sendsys2 from %p", (void *)frame.tf_eip));
1539         if (syscall_mpsafe == 0)
1540                 MAKEMPSAFE(have_mplock);
1541 #endif
1542         /*
1543          * access non-atomic field from critical section.  p_sticks is
1544          * updated by the clock interrupt.  Also use this opportunity
1545          * to lazy-raise our LWKT priority.
1546          */
1547         userenter(td);
1548         sticks = td->td_sticks;
1549
1550         lp->lwp_md.md_regs = &frame;
1551         orig_tf_eflags = frame.tf_eflags;
1552         result = 0;
1553
1554         /*
1555          * Extract the system call message.  If msgsize is zero we are 
1556          * blocking on a message and/or message port.  If msgsize is -1 
1557          * we are testing a message for completion or a message port for
1558          * activity.
1559          *
1560          * The userland system call message size includes the size of the
1561          * userland lwkt_msg plus arguments.  We load it into the userland
1562          * portion of our sysunion structure then we initialize the kerneland
1563          * portion and go.
1564          */
1565
1566         /*
1567          * Bad message size
1568          */
1569         if ((msgsize = frame.tf_edx) < sizeof(struct lwkt_msg) ||
1570             msgsize > sizeof(union sysunion) - sizeof(struct sysmsg)) {
1571                 error = ENOSYS;
1572                 goto bad2;
1573         }
1574
1575         /*
1576          * Obtain a sysun from our per-cpu cache or allocate a new one.  Use
1577          * the opaque field to store the original (user) message pointer.
1578          * A critical section is necessary to interlock against interrupts
1579          * returning system messages to the thread cache.
1580          */
1581         gd = td->td_gd;
1582         crit_enter_quick(td);
1583         if ((sysun = gd->gd_freesysun) != NULL)
1584                 gd->gd_freesysun = sysun->lmsg.opaque.ms_sysunnext;
1585         else
1586                 sysun = malloc(sizeof(union sysunion), M_SYSMSG, M_WAITOK);
1587         crit_exit_quick(td);
1588
1589         /*
1590          * Copy the user request into the kernel copy of the user request.
1591          */
1592         umsg = (void *)frame.tf_ecx;
1593         error = copyin(umsg, &sysun->nosys.usrmsg, msgsize);
1594         if (error)
1595                 goto bad1;
1596         if ((sysun->nosys.usrmsg.umsg.ms_flags & MSGF_ASYNC)) {
1597                 error = suser(td);
1598                 if (error) {
1599                         goto bad1;
1600                 }
1601                 if (max_sysmsg > 0 && lp->lwp_nsysmsg >= max_sysmsg) {
1602                         error = E2BIG;
1603                         goto bad1;
1604                 }
1605         }
1606
1607         /*
1608          * Initialize the kernel message from the copied-in data and
1609          * pull in appropriate flags from the userland message.
1610          *
1611          * ms_abort_port is usually initialized in sendmsg/domsg, but since
1612          * we are not calling those functions (yet), we have to do it manually.
1613          */
1614         lwkt_initmsg(&sysun->lmsg, &td->td_msgport, 0,
1615                         sysun->nosys.usrmsg.umsg.ms_cmd,
1616                         lwkt_cmd_op_none);
1617         sysun->lmsg.ms_abort_port = sysun->lmsg.ms_reply_port;
1618         sysun->sysmsg_copyout = NULL;
1619         sysun->lmsg.opaque.ms_umsg = umsg;
1620         sysun->lmsg.ms_flags |= sysun->nosys.usrmsg.umsg.ms_flags & MSGF_ASYNC;
1621
1622         /*
1623          * Extract the system call number, lookup the system call, and
1624          * set the default return value.
1625          */
1626         code = (u_int)sysun->lmsg.ms_cmd.cm_op;
1627         /* We don't handle the syscall() syscall yet */
1628         if (code == 0) {
1629                 error = ENOTSUP;
1630                 free_sysun(td, sysun);
1631                 goto bad2;
1632         }
1633         if (code >= p->p_sysent->sv_size) {
1634                 error = ENOSYS;
1635                 free_sysun(td, sysun);
1636                 goto bad1;
1637         }
1638
1639         callp = &p->p_sysent->sv_table[code];
1640
1641         narg = (msgsize - sizeof(struct lwkt_msg)) / sizeof(register_t);
1642
1643 #ifdef KTRACE
1644         if (KTRPOINT(td, KTR_SYSCALL)) {
1645                 MAKEMPSAFE(have_mplock);
1646                 ktrsyscall(p, code, narg, (void *)(&sysun->nosys.usrmsg + 1));
1647         }
1648 #endif
1649         sysun->lmsg.u.ms_fds[0] = 0;
1650         sysun->lmsg.u.ms_fds[1] = 0;
1651
1652         STOPEVENT(p, S_SCE, narg);      /* MP aware */
1653
1654         /*
1655          * Make the system call.  An error code is always returned, results
1656          * are copied back via ms_result32 or ms_result64.  YYY temporary
1657          * stage copy p_retval[] into ms_result32/64
1658          *
1659          * NOTE!  XXX if this is a child returning from a fork curproc
1660          * might be different.  YYY huh? a child returning from a fork
1661          * should never 'return' from this call, it should go right to the
1662          * fork_trampoline function.
1663          *
1664          * Obtain the MP lock if necessary.
1665          */
1666 #ifdef SMP
1667         if ((callp->sy_narg & SYF_MPSAFE) == 0)
1668                 MAKEMPSAFE(have_mplock);
1669 #endif
1670         error = (*callp->sy_call)(sysun);
1671         gd = td->td_gd; /* RELOAD, might have switched cpus */
1672
1673 bad1:
1674         /*
1675          * If a synchronous return copy p_retval to ms_result64 and return
1676          * the sysmsg to the free pool.
1677          *
1678          * YYY Don't writeback message if execve() YYY
1679          */
1680         sysun->nosys.usrmsg.umsg.ms_error = error;
1681         sysun->nosys.usrmsg.umsg.u.ms_fds[0] = sysun->lmsg.u.ms_fds[0];
1682         sysun->nosys.usrmsg.umsg.u.ms_fds[1] = sysun->lmsg.u.ms_fds[1];
1683         result = sysun->nosys.usrmsg.umsg.u.ms_fds[0]; /* for ktrace */
1684         if (error != 0 || code != SYS_execve) {
1685                 int error2;
1686                 error2 = copyout(&sysun->nosys.usrmsg.umsg.ms_copyout_start,
1687                                 &umsg->ms_copyout_start,
1688                                 ms_copyout_size);
1689                 if (error2 != 0)
1690                         error = error2;
1691         }
1692         if (error == EASYNC) {
1693                 /*
1694                  * Since only the current process ever messes with msgq,
1695                  * we can safely manipulate it in parallel with the async
1696                  * operation.
1697                  */
1698                 TAILQ_INSERT_TAIL(&lp->lwp_sysmsgq, &sysun->sysmsg, msgq);
1699                 lp->lwp_nsysmsg++;
1700                 error = (int)&sysun->sysmsg;
1701         } else {
1702                 free_sysun(td, sysun);
1703         }
1704 bad2:
1705         frame.tf_eax = (register_t)error;
1706
1707         /*
1708          * Traced syscall.  trapsignal() is not MP aware.
1709          */
1710         if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1711                 MAKEMPSAFE(have_mplock);
1712                 frame.tf_eflags &= ~PSL_T;
1713                 trapsignal(p, SIGTRAP, 0);
1714         }
1715
1716         /*
1717          * Handle reschedule and other end-of-syscall issues
1718          */
1719         userret(lp, &frame, sticks);
1720
1721 #ifdef KTRACE
1722         if (KTRPOINT(td, KTR_SYSRET)) {
1723                 MAKEMPSAFE(have_mplock);
1724                 ktrsysret(p, code, error, result);
1725         }
1726 #endif
1727
1728         /*
1729          * This works because errno is findable through the
1730          * register set.  If we ever support an emulation where this
1731          * is not the case, this code will need to be revisited.
1732          */
1733         STOPEVENT(p, S_SCX, code);
1734
1735         userexit(lp);
1736 #ifdef SMP
1737         /*
1738          * Release the MP lock if we had to get it
1739          */
1740         KASSERT(td->td_mpcount == have_mplock,
1741                 ("badmpcount sendsys2/end from %p", (void *)frame.tf_eip));
1742         if (have_mplock)
1743                 rel_mplock();
1744 #endif
1745 }
1746
1747 /*
1748  *      waitsys2 -      MP aware system message wait C handler
1749  */
1750 void
1751 waitsys2(struct trapframe frame)
1752 {
1753         struct globaldata *gd;
1754         struct thread *td = curthread;
1755         struct proc *p = td->td_proc;
1756         struct lwp *lp = td->td_lwp;
1757         union sysunion *sysun = NULL;
1758         lwkt_msg_t umsg;
1759         register_t orig_tf_eflags;
1760         int error = 0, result, sticks;
1761 #ifdef SMP
1762         int have_mplock = 0;
1763 #endif
1764         u_int code = 0;
1765
1766 #ifdef DIAGNOSTIC
1767         if (ISPL(frame.tf_cs) != SEL_UPL) {
1768                 get_mplock();
1769                 panic("waitsys2");
1770                 /* NOT REACHED */
1771         }
1772 #endif
1773
1774 #ifdef SMP
1775         KASSERT(td->td_mpcount == 0, ("badmpcount waitsys from %p",
1776                 (void *)frame.tf_eip));
1777         if (syscall_mpsafe == 0)
1778                 MAKEMPSAFE(have_mplock);
1779 #endif
1780
1781         /*
1782          * access non-atomic field from critical section.  p_sticks is
1783          * updated by the clock interrupt.  Also use this opportunity
1784          * to lazy-raise our LWKT priority.
1785          */
1786         userenter(td);
1787         sticks = td->td_sticks;
1788
1789         lp->lwp_md.md_regs = &frame;
1790         orig_tf_eflags = frame.tf_eflags;
1791         result = 0;
1792
1793         if (frame.tf_ecx) {
1794                 struct sysmsg *ptr;
1795                 int found = 0;
1796                 TAILQ_FOREACH(ptr, &lp->lwp_sysmsgq, msgq) {
1797                         if ((void *)ptr == (void *)frame.tf_ecx) {
1798                                 sysun = (void *)sysmsg_wait(lp,
1799                                              (void *)frame.tf_ecx, 1);
1800                                 found = 1;
1801                                 break;
1802                         }
1803                 }
1804                 if (!found) {
1805                         error = ENOENT;
1806                         goto bad;
1807                 }
1808         }
1809         else if (frame.tf_eax) {
1810                 printf("waitport/checkport only the default port is supported at the moment\n");
1811                 error = ENOTSUP;
1812                 goto bad;
1813         }
1814         else {
1815                 switch(frame.tf_edx) {
1816                 case 0:
1817                         sysun = (void *)sysmsg_wait(lp, NULL, 0);
1818                         break;
1819                 case -1:
1820                         sysun = (void *)sysmsg_wait(lp, NULL, 1);
1821                         break;
1822                 default:
1823                         error = ENOSYS;
1824                         goto bad;
1825                 }
1826         }
1827         if (sysun) {
1828                 gd = td->td_gd;
1829                 umsg = sysun->lmsg.opaque.ms_umsg;
1830                 frame.tf_eax = (register_t)sysun;
1831                 sysun->nosys.usrmsg.umsg.u.ms_fds[0] = sysun->lmsg.u.ms_fds[0];
1832                 sysun->nosys.usrmsg.umsg.u.ms_fds[1] = sysun->lmsg.u.ms_fds[1];
1833                 sysun->nosys.usrmsg.umsg.ms_error = sysun->lmsg.ms_error;
1834                 error = sysun->lmsg.ms_error;
1835                 result = sysun->lmsg.u.ms_fds[0]; /* for ktrace */
1836                 error = copyout(&sysun->nosys.usrmsg.umsg.ms_copyout_start,
1837                                 &umsg->ms_copyout_start, ms_copyout_size);
1838                 free_sysun(td, sysun);
1839                 frame.tf_edx = 0;
1840                 code = (u_int)sysun->lmsg.ms_cmd.cm_op;
1841         }
1842 bad:
1843         if (error)
1844                 frame.tf_eax = error;
1845         /*
1846          * Traced syscall.  trapsignal() is not MP aware.
1847          */
1848         if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1849                 MAKEMPSAFE(have_mplock);
1850                 frame.tf_eflags &= ~PSL_T;
1851                 trapsignal(p, SIGTRAP, 0);
1852         }
1853
1854         /*
1855          * Handle reschedule and other end-of-syscall issues
1856          */
1857         userret(lp, &frame, sticks);
1858
1859 #ifdef KTRACE
1860         if (KTRPOINT(td, KTR_SYSRET)) {
1861                 MAKEMPSAFE(have_mplock);
1862                 ktrsysret(p, code, error, result);
1863         }
1864 #endif
1865
1866         /*
1867          * This works because errno is findable through the
1868          * register set.  If we ever support an emulation where this
1869          * is not the case, this code will need to be revisited.
1870          */
1871         STOPEVENT(p, S_SCX, code);
1872
1873         userexit(lp);
1874 #ifdef SMP
1875         KASSERT(td->td_mpcount == have_mplock, 
1876                 ("badmpcount waitsys/end from %p", (void *)frame.tf_eip));
1877         if (have_mplock)
1878                 rel_mplock();
1879 #endif
1880 }
1881
1882 /*
1883  * Simplified back end of syscall(), used when returning from fork()
1884  * directly into user mode.  MP lock is held on entry and should be
1885  * released on return.  This code will return back into the fork
1886  * trampoline code which then runs doreti.
1887  */
1888 void
1889 fork_return(p, frame)
1890         struct proc *p;
1891         struct trapframe frame;
1892 {
1893         struct lwp *lp;
1894
1895         KKASSERT(p->p_nthreads == 1);
1896
1897         lp = LIST_FIRST(&p->p_lwps);
1898
1899         frame.tf_eax = 0;               /* Child returns zero */
1900         frame.tf_eflags &= ~PSL_C;      /* success */
1901         frame.tf_edx = 1;
1902
1903         /*
1904          * Newly forked processes are given a kernel priority.  We have to
1905          * adjust the priority to a normal user priority and fake entry
1906          * into the kernel (call userenter()) to install a passive release
1907          * function just in case userret() decides to stop the process.  This
1908          * can occur when ^Z races a fork.  If we do not install the passive
1909          * release function the current process designation will not be
1910          * released when the thread goes to sleep.
1911          */
1912         lwkt_setpri_self(TDPRI_USER_NORM);
1913         userenter(lp->lwp_thread);
1914         userret(lp, &frame, 0);
1915 #ifdef KTRACE
1916         if (KTRPOINT(lp->lwp_thread, KTR_SYSRET))
1917                 ktrsysret(p, SYS_fork, 0, 0);
1918 #endif
1919         p->p_flag |= P_PASSIVE_ACQ;
1920         userexit(lp);
1921         p->p_flag &= ~P_PASSIVE_ACQ;
1922 #ifdef SMP
1923         KKASSERT(lp->lwp_thread->td_mpcount == 1);
1924         rel_mplock();
1925 #endif
1926 }