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