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