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