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