Operations on the user scheduler must be inside a critical section (fixes
[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.13 2003/07/01 04:37:44 dillon Exp $
40  */
41
42 /*
43  * 386 Trap and System call handling
44  */
45
46 #include "opt_cpu.h"
47 #include "opt_ddb.h"
48 #include "opt_ktrace.h"
49 #include "opt_clock.h"
50 #include "opt_trap.h"
51
52 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/proc.h>
55 #include <sys/pioctl.h>
56 #include <sys/kernel.h>
57 #include <sys/resourcevar.h>
58 #include <sys/signalvar.h>
59 #include <sys/syscall.h>
60 #include <sys/sysctl.h>
61 #include <sys/sysent.h>
62 #include <sys/uio.h>
63 #include <sys/vmmeter.h>
64 #ifdef KTRACE
65 #include <sys/ktrace.h>
66 #endif
67
68 #include <vm/vm.h>
69 #include <vm/vm_param.h>
70 #include <sys/lock.h>
71 #include <vm/pmap.h>
72 #include <vm/vm_kern.h>
73 #include <vm/vm_map.h>
74 #include <vm/vm_page.h>
75 #include <vm/vm_extern.h>
76
77 #include <machine/cpu.h>
78 #include <machine/ipl.h>
79 #include <machine/md_var.h>
80 #include <machine/pcb.h>
81 #ifdef SMP
82 #include <machine/smp.h>
83 #endif
84 #include <machine/tss.h>
85 #include <machine/globaldata.h>
86
87 #include <i386/isa/intr_machdep.h>
88
89 #ifdef POWERFAIL_NMI
90 #include <sys/syslog.h>
91 #include <machine/clock.h>
92 #endif
93
94 #include <machine/vm86.h>
95
96 #include <ddb/ddb.h>
97 #include <sys/thread2.h>
98
99 #include "isa.h"
100 #include "npx.h"
101
102 int (*pmath_emulate) __P((struct trapframe *));
103
104 extern void trap __P((struct trapframe frame));
105 extern int trapwrite __P((unsigned addr));
106 extern void syscall2 __P((struct trapframe frame));
107
108 static int trap_pfault __P((struct trapframe *, int, vm_offset_t));
109 static void trap_fatal __P((struct trapframe *, vm_offset_t));
110 void dblfault_handler __P((void));
111
112 extern inthand_t IDTVEC(syscall);
113
114 #define MAX_TRAP_MSG            28
115 static char *trap_msg[] = {
116         "",                                     /*  0 unused */
117         "privileged instruction fault",         /*  1 T_PRIVINFLT */
118         "",                                     /*  2 unused */
119         "breakpoint instruction fault",         /*  3 T_BPTFLT */
120         "",                                     /*  4 unused */
121         "",                                     /*  5 unused */
122         "arithmetic trap",                      /*  6 T_ARITHTRAP */
123         "system forced exception",              /*  7 T_ASTFLT */
124         "",                                     /*  8 unused */
125         "general protection fault",             /*  9 T_PROTFLT */
126         "trace trap",                           /* 10 T_TRCTRAP */
127         "",                                     /* 11 unused */
128         "page fault",                           /* 12 T_PAGEFLT */
129         "",                                     /* 13 unused */
130         "alignment fault",                      /* 14 T_ALIGNFLT */
131         "",                                     /* 15 unused */
132         "",                                     /* 16 unused */
133         "",                                     /* 17 unused */
134         "integer divide fault",                 /* 18 T_DIVIDE */
135         "non-maskable interrupt trap",          /* 19 T_NMI */
136         "overflow trap",                        /* 20 T_OFLOW */
137         "FPU bounds check fault",               /* 21 T_BOUND */
138         "FPU device not available",             /* 22 T_DNA */
139         "double fault",                         /* 23 T_DOUBLEFLT */
140         "FPU operand fetch fault",              /* 24 T_FPOPFLT */
141         "invalid TSS fault",                    /* 25 T_TSSFLT */
142         "segment not present fault",            /* 26 T_SEGNPFLT */
143         "stack fault",                          /* 27 T_STKFLT */
144         "machine check trap",                   /* 28 T_MCHK */
145 };
146
147 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
148 extern int has_f00f_bug;
149 #endif
150
151 #ifdef DDB
152 static int ddb_on_nmi = 1;
153 SYSCTL_INT(_machdep, OID_AUTO, ddb_on_nmi, CTLFLAG_RW,
154         &ddb_on_nmi, 0, "Go to DDB on NMI");
155 #endif
156 static int panic_on_nmi = 1;
157 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
158         &panic_on_nmi, 0, "Panic on NMI");
159
160 /*
161  * USER->KERNEL transition.  Do not transition us out of userland from the
162  * point of view of the userland scheduler unless we actually have to
163  * switch.
164  *
165  * usertdsw is called from within a critical section.
166  */
167 static void
168 usertdsw(struct thread *ntd)
169 {
170         struct thread *td = curthread;
171
172         td->td_switch = cpu_heavy_switch;
173         lwkt_setpri_self(TDPRI_KERN_USER);
174 #if 0
175         /* 
176          * This is where we might want to catch the P_CURPROC designation
177          * and fix it for *any* switchout rather then just an mi_switch()
178          * switchout (move from mi_switch()?) YYY
179          */
180         if (p->p_flag & P_CURPROC) {
181                 ...
182         }
183 #endif
184         td->td_switch(ntd);
185 }
186
187 /*
188  * Note that userenter() may be re-entered several times due to AST
189  * processing.
190  */
191 static __inline void
192 userenter(void)
193 {
194         struct thread *td = curthread;
195
196         KKASSERT(td->td_switch == cpu_heavy_switch ||
197                 td->td_switch == usertdsw);
198         td->td_switch = usertdsw;
199 }
200
201 static int
202 userret(struct proc *p, struct trapframe *frame,
203         u_quad_t oticks, int have_mplock)
204 {
205         int sig, s;
206         struct thread *td = curthread;
207
208         /*
209          * Post any pending signals
210          */
211         crit_enter();
212         while ((sig = CURSIG(p)) != 0) {
213                 if (have_mplock == 0) {
214                         get_mplock();
215                         have_mplock = 1;
216                 }
217                 crit_exit();
218                 postsig(sig);
219                 crit_enter();
220         }
221
222         /*
223          * Set our priority properly and restore our switch function
224          */
225         if (td->td_switch == cpu_heavy_switch) {
226                 switch(p->p_rtprio.type) {
227                 case RTP_PRIO_IDLE:
228                         lwkt_setpri_self(TDPRI_USER_IDLE);
229                         break;
230                 case RTP_PRIO_REALTIME:
231                 case RTP_PRIO_FIFO:
232                         lwkt_setpri_self(TDPRI_USER_REAL);
233                         break;
234                 default:
235                         lwkt_setpri_self(TDPRI_USER_NORM);
236                         break;
237                 }
238         } else {
239                 KKASSERT(td->td_switch == usertdsw);
240                 td->td_switch = cpu_heavy_switch;
241         }
242         crit_exit();
243
244         /*
245          * If a reschedule has been requested we call chooseproc() to locate
246          * the next runnable process.  When we wakeup from that we check
247          * for pending signals again.
248          */
249         if (resched_wanted()) {
250                 uio_yield();
251                 if (have_mplock == 0) {
252                         get_mplock();
253                         have_mplock = 1;
254                 }
255                 while ((sig = CURSIG(p)) != 0)
256                         postsig(sig);
257         }
258
259         /*
260          * Charge system time if profiling.
261          */
262         if (p->p_flag & P_PROFIL) {
263                 if (have_mplock == 0) {
264                         get_mplock();
265                         have_mplock = 1;
266                 }
267                 addupc_task(p, frame->tf_eip, 
268                     (u_int)(curthread->td_sticks - oticks) * psratio);
269         }
270
271         /*
272          * In order to return to userland we need to be the designated
273          * current (user) process on this cpu.  We have to wait for
274          * the userland scheduler to schedule as P_CURPROC.
275          */
276         s = splhigh();
277         while ((p->p_flag & P_CURPROC) == 0) {
278                 p->p_stats->p_ru.ru_nivcsw++;
279                 lwkt_deschedule_self();
280                 mi_switch();
281         }
282         splx(s);
283         KKASSERT(mycpu->gd_uprocscheduled == 1);
284
285         return(have_mplock);
286 }
287
288 #ifdef DEVICE_POLLING
289 extern u_int32_t poll_in_trap;
290 extern int ether_poll __P((int count));
291 #endif /* DEVICE_POLLING */
292
293 /*
294  * Exception, fault, and trap interface to the FreeBSD kernel.
295  * This common code is called from assembly language IDT gate entry
296  * routines that prepare a suitable stack frame, and restore this
297  * frame after the exception has been processed.
298  */
299
300 void
301 trap(frame)
302         struct trapframe frame;
303 {
304         struct proc *p = curproc;
305         u_quad_t sticks = 0;
306         int i = 0, ucode = 0, type, code;
307         vm_offset_t eva;
308
309 #ifdef DDB
310         if (db_active) {
311                 eva = (frame.tf_trapno == T_PAGEFLT ? rcr2() : 0);
312                 trap_fatal(&frame, eva);
313                 return;
314         }
315 #endif
316
317         if (!(frame.tf_eflags & PSL_I)) {
318                 /*
319                  * Buggy application or kernel code has disabled interrupts
320                  * and then trapped.  Enabling interrupts now is wrong, but
321                  * it is better than running with interrupts disabled until
322                  * they are accidentally enabled later.
323                  */
324                 type = frame.tf_trapno;
325                 if (ISPL(frame.tf_cs) == SEL_UPL || (frame.tf_eflags & PSL_VM))
326                         printf(
327                             "pid %ld (%s): trap %d with interrupts disabled\n",
328                             (long)curproc->p_pid, curproc->p_comm, type);
329                 else if (type != T_BPTFLT && type != T_TRCTRAP)
330                         /*
331                          * XXX not quite right, since this may be for a
332                          * multiple fault in user mode.
333                          */
334                         printf("kernel trap %d with interrupts disabled\n",
335                             type);
336                 enable_intr();
337         }
338
339         eva = 0;
340         if (frame.tf_trapno == T_PAGEFLT) {
341                 /*
342                  * For some Cyrix CPUs, %cr2 is clobbered by interrupts.
343                  * This problem is worked around by using an interrupt
344                  * gate for the pagefault handler.  We are finally ready
345                  * to read %cr2 and then must reenable interrupts.
346                  *
347                  * XXX this should be in the switch statement, but the
348                  * NO_FOOF_HACK and VM86 goto and ifdefs obfuscate the
349                  * flow of control too much for this to be obviously
350                  * correct.
351                  */
352                 eva = rcr2();
353                 enable_intr();
354         }
355
356 #ifdef DEVICE_POLLING
357         if (poll_in_trap)
358                 ether_poll(poll_in_trap);
359 #endif /* DEVICE_POLLING */
360
361 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
362 restart:
363 #endif
364         type = frame.tf_trapno;
365         code = frame.tf_err;
366
367         if (in_vm86call) {
368                 if (frame.tf_eflags & PSL_VM &&
369                     (type == T_PROTFLT || type == T_STKFLT)) {
370                         i = vm86_emulate((struct vm86frame *)&frame);
371                         if (i != 0)
372                                 /*
373                                  * returns to original process
374                                  */
375                                 vm86_trap((struct vm86frame *)&frame);
376                         return;
377                 }
378                 switch (type) {
379                         /*
380                          * these traps want either a process context, or
381                          * assume a normal userspace trap.
382                          */
383                 case T_PROTFLT:
384                 case T_SEGNPFLT:
385                         trap_fatal(&frame, eva);
386                         return;
387                 case T_TRCTRAP:
388                         type = T_BPTFLT;        /* kernel breakpoint */
389                         /* FALL THROUGH */
390                 }
391                 goto kernel_trap;       /* normal kernel trap handling */
392         }
393
394         if ((ISPL(frame.tf_cs) == SEL_UPL) || (frame.tf_eflags & PSL_VM)) {
395                 /* user trap */
396
397                 userenter();
398
399                 sticks = curthread->td_sticks;
400                 p->p_md.md_regs = &frame;
401
402                 switch (type) {
403                 case T_PRIVINFLT:       /* privileged instruction fault */
404                         ucode = type;
405                         i = SIGILL;
406                         break;
407
408                 case T_BPTFLT:          /* bpt instruction fault */
409                 case T_TRCTRAP:         /* trace trap */
410                         frame.tf_eflags &= ~PSL_T;
411                         i = SIGTRAP;
412                         break;
413
414                 case T_ARITHTRAP:       /* arithmetic trap */
415                         ucode = code;
416                         i = SIGFPE;
417                         break;
418
419                 case T_ASTFLT:          /* Allow process switch */
420                         astoff();
421                         cnt.v_soft++;
422                         if (p->p_flag & P_OWEUPC) {
423                                 p->p_flag &= ~P_OWEUPC;
424                                 addupc_task(p, p->p_stats->p_prof.pr_addr,
425                                             p->p_stats->p_prof.pr_ticks);
426                         }
427                         goto out;
428
429                         /*
430                          * The following two traps can happen in
431                          * vm86 mode, and, if so, we want to handle
432                          * them specially.
433                          */
434                 case T_PROTFLT:         /* general protection fault */
435                 case T_STKFLT:          /* stack fault */
436                         if (frame.tf_eflags & PSL_VM) {
437                                 i = vm86_emulate((struct vm86frame *)&frame);
438                                 if (i == 0)
439                                         goto out;
440                                 break;
441                         }
442                         /* FALL THROUGH */
443
444                 case T_SEGNPFLT:        /* segment not present fault */
445                 case T_TSSFLT:          /* invalid TSS fault */
446                 case T_DOUBLEFLT:       /* double fault */
447                 default:
448                         ucode = code + BUS_SEGM_FAULT ;
449                         i = SIGBUS;
450                         break;
451
452                 case T_PAGEFLT:         /* page fault */
453                         i = trap_pfault(&frame, TRUE, eva);
454                         if (i == -1)
455                                 return;
456 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
457                         if (i == -2)
458                                 goto restart;
459 #endif
460                         if (i == 0)
461                                 goto out;
462
463                         ucode = T_PAGEFLT;
464                         break;
465
466                 case T_DIVIDE:          /* integer divide fault */
467                         ucode = FPE_INTDIV;
468                         i = SIGFPE;
469                         break;
470
471 #if NISA > 0
472                 case T_NMI:
473 #ifdef POWERFAIL_NMI
474                         goto handle_powerfail;
475 #else /* !POWERFAIL_NMI */
476                         /* machine/parity/power fail/"kitchen sink" faults */
477                         if (isa_nmi(code) == 0) {
478 #ifdef DDB
479                                 /*
480                                  * NMI can be hooked up to a pushbutton
481                                  * for debugging.
482                                  */
483                                 if (ddb_on_nmi) {
484                                         printf ("NMI ... going to debugger\n");
485                                         kdb_trap (type, 0, &frame);
486                                 }
487 #endif /* DDB */
488                                 return;
489                         } else if (panic_on_nmi)
490                                 panic("NMI indicates hardware failure");
491                         break;
492 #endif /* POWERFAIL_NMI */
493 #endif /* NISA > 0 */
494
495                 case T_OFLOW:           /* integer overflow fault */
496                         ucode = FPE_INTOVF;
497                         i = SIGFPE;
498                         break;
499
500                 case T_BOUND:           /* bounds check fault */
501                         ucode = FPE_FLTSUB;
502                         i = SIGFPE;
503                         break;
504
505                 case T_DNA:
506 #if NNPX > 0
507                         /* if a transparent fault (due to context switch "late") */
508                         if (npxdna())
509                                 return;
510 #endif
511                         if (!pmath_emulate) {
512                                 i = SIGFPE;
513                                 ucode = FPE_FPU_NP_TRAP;
514                                 break;
515                         }
516                         i = (*pmath_emulate)(&frame);
517                         if (i == 0) {
518                                 if (!(frame.tf_eflags & PSL_T))
519                                         return;
520                                 frame.tf_eflags &= ~PSL_T;
521                                 i = SIGTRAP;
522                         }
523                         /* else ucode = emulator_only_knows() XXX */
524                         break;
525
526                 case T_FPOPFLT:         /* FPU operand fetch fault */
527                         ucode = T_FPOPFLT;
528                         i = SIGILL;
529                         break;
530
531                 case T_XMMFLT:          /* SIMD floating-point exception */
532                         ucode = 0; /* XXX */
533                         i = SIGFPE;
534                         break;
535                 }
536         } else {
537 kernel_trap:
538                 /* kernel trap */
539
540                 switch (type) {
541                 case T_PAGEFLT:                 /* page fault */
542                         (void) trap_pfault(&frame, FALSE, eva);
543                         return;
544
545                 case T_DNA:
546 #if NNPX > 0
547                         /*
548                          * The kernel is apparently using npx for copying.
549                          * XXX this should be fatal unless the kernel has
550                          * registered such use.
551                          */
552                         if (npxdna())
553                                 return;
554 #endif
555                         break;
556
557                 case T_PROTFLT:         /* general protection fault */
558                 case T_SEGNPFLT:        /* segment not present fault */
559                         /*
560                          * Invalid segment selectors and out of bounds
561                          * %eip's and %esp's can be set up in user mode.
562                          * This causes a fault in kernel mode when the
563                          * kernel tries to return to user mode.  We want
564                          * to get this fault so that we can fix the
565                          * problem here and not have to check all the
566                          * selectors and pointers when the user changes
567                          * them.
568                          */
569 #define MAYBE_DORETI_FAULT(where, whereto)                              \
570         do {                                                            \
571                 if (frame.tf_eip == (int)where) {                       \
572                         frame.tf_eip = (int)whereto;                    \
573                         return;                                         \
574                 }                                                       \
575         } while (0)
576
577                         if (mycpu->gd_intr_nesting_level == 0) {
578                                 /*
579                                  * Invalid %fs's and %gs's can be created using
580                                  * procfs or PT_SETREGS or by invalidating the
581                                  * underlying LDT entry.  This causes a fault
582                                  * in kernel mode when the kernel attempts to
583                                  * switch contexts.  Lose the bad context
584                                  * (XXX) so that we can continue, and generate
585                                  * a signal.
586                                  */
587                                 if (frame.tf_eip == (int)cpu_switch_load_gs) {
588                                         curthread->td_pcb->pcb_gs = 0;
589                                         psignal(p, SIGBUS);
590                                         return;
591                                 }
592                                 MAYBE_DORETI_FAULT(doreti_iret,
593                                                    doreti_iret_fault);
594                                 MAYBE_DORETI_FAULT(doreti_popl_ds,
595                                                    doreti_popl_ds_fault);
596                                 MAYBE_DORETI_FAULT(doreti_popl_es,
597                                                    doreti_popl_es_fault);
598                                 MAYBE_DORETI_FAULT(doreti_popl_fs,
599                                                    doreti_popl_fs_fault);
600                                 if (curthread->td_pcb->pcb_onfault) {
601                                         frame.tf_eip = (int)curthread->td_pcb->pcb_onfault;
602                                         return;
603                                 }
604                         }
605                         break;
606
607                 case T_TSSFLT:
608                         /*
609                          * PSL_NT can be set in user mode and isn't cleared
610                          * automatically when the kernel is entered.  This
611                          * causes a TSS fault when the kernel attempts to
612                          * `iret' because the TSS link is uninitialized.  We
613                          * want to get this fault so that we can fix the
614                          * problem here and not every time the kernel is
615                          * entered.
616                          */
617                         if (frame.tf_eflags & PSL_NT) {
618                                 frame.tf_eflags &= ~PSL_NT;
619                                 return;
620                         }
621                         break;
622
623                 case T_TRCTRAP:  /* trace trap */
624                         if (frame.tf_eip == (int)IDTVEC(syscall)) {
625                                 /*
626                                  * We've just entered system mode via the
627                                  * syscall lcall.  Continue single stepping
628                                  * silently until the syscall handler has
629                                  * saved the flags.
630                                  */
631                                 return;
632                         }
633                         if (frame.tf_eip == (int)IDTVEC(syscall) + 1) {
634                                 /*
635                                  * The syscall handler has now saved the
636                                  * flags.  Stop single stepping it.
637                                  */
638                                 frame.tf_eflags &= ~PSL_T;
639                                 return;
640                         }
641                         /*
642                          * Ignore debug register trace traps due to
643                          * accesses in the user's address space, which
644                          * can happen under several conditions such as
645                          * if a user sets a watchpoint on a buffer and
646                          * then passes that buffer to a system call.
647                          * We still want to get TRCTRAPS for addresses
648                          * in kernel space because that is useful when
649                          * debugging the kernel.
650                          */
651                         if (user_dbreg_trap()) {
652                                 /*
653                                  * Reset breakpoint bits because the
654                                  * processor doesn't
655                                  */
656                                 load_dr6(rdr6() & 0xfffffff0);
657                                 return;
658                         }
659                         /*
660                          * Fall through (TRCTRAP kernel mode, kernel address)
661                          */
662                 case T_BPTFLT:
663                         /*
664                          * If DDB is enabled, let it handle the debugger trap.
665                          * Otherwise, debugger traps "can't happen".
666                          */
667 #ifdef DDB
668                         if (kdb_trap (type, 0, &frame))
669                                 return;
670 #endif
671                         break;
672
673 #if NISA > 0
674                 case T_NMI:
675 #ifdef POWERFAIL_NMI
676 #ifndef TIMER_FREQ
677 #  define TIMER_FREQ 1193182
678 #endif
679         handle_powerfail:
680                 {
681                   static unsigned lastalert = 0;
682
683                   if(time_second - lastalert > 10)
684                     {
685                       log(LOG_WARNING, "NMI: power fail\n");
686                       sysbeep(TIMER_FREQ/880, hz);
687                       lastalert = time_second;
688                     }
689                   return;
690                 }
691 #else /* !POWERFAIL_NMI */
692                         /* machine/parity/power fail/"kitchen sink" faults */
693                         if (isa_nmi(code) == 0) {
694 #ifdef DDB
695                                 /*
696                                  * NMI can be hooked up to a pushbutton
697                                  * for debugging.
698                                  */
699                                 if (ddb_on_nmi) {
700                                         printf ("NMI ... going to debugger\n");
701                                         kdb_trap (type, 0, &frame);
702                                 }
703 #endif /* DDB */
704                                 return;
705                         } else if (panic_on_nmi == 0)
706                                 return;
707                         /* FALL THROUGH */
708 #endif /* POWERFAIL_NMI */
709 #endif /* NISA > 0 */
710                 }
711
712                 trap_fatal(&frame, eva);
713                 return;
714         }
715
716         /* Translate fault for emulators (e.g. Linux) */
717         if (*p->p_sysent->sv_transtrap)
718                 i = (*p->p_sysent->sv_transtrap)(i, type);
719
720         trapsignal(p, i, ucode);
721
722 #ifdef DEBUG
723         if (type <= MAX_TRAP_MSG) {
724                 uprintf("fatal process exception: %s",
725                         trap_msg[type]);
726                 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
727                         uprintf(", fault VA = 0x%lx", (u_long)eva);
728                 uprintf("\n");
729         }
730 #endif
731
732 out:
733         userret(p, &frame, sticks, 1);
734 }
735
736 #ifdef notyet
737 /*
738  * This version doesn't allow a page fault to user space while
739  * in the kernel. The rest of the kernel needs to be made "safe"
740  * before this can be used. I think the only things remaining
741  * to be made safe are the iBCS2 code and the process tracing/
742  * debugging code.
743  */
744 static int
745 trap_pfault(frame, usermode, eva)
746         struct trapframe *frame;
747         int usermode;
748         vm_offset_t eva;
749 {
750         vm_offset_t va;
751         struct vmspace *vm = NULL;
752         vm_map_t map = 0;
753         int rv = 0;
754         vm_prot_t ftype;
755         struct proc *p = curproc;
756
757         if (frame->tf_err & PGEX_W)
758                 ftype = VM_PROT_WRITE;
759         else
760                 ftype = VM_PROT_READ;
761
762         va = trunc_page(eva);
763         if (va < VM_MIN_KERNEL_ADDRESS) {
764                 vm_offset_t v;
765                 vm_page_t mpte;
766
767                 if (p == NULL ||
768                     (!usermode && va < VM_MAXUSER_ADDRESS &&
769                      (mycpu->gd_intr_nesting_level != 0 || 
770                       curthread->td_pcb->pcb_onfault == NULL))) {
771                         trap_fatal(frame, eva);
772                         return (-1);
773                 }
774
775                 /*
776                  * This is a fault on non-kernel virtual memory.
777                  * vm is initialized above to NULL. If curproc is NULL
778                  * or curproc->p_vmspace is NULL the fault is fatal.
779                  */
780                 vm = p->p_vmspace;
781                 if (vm == NULL)
782                         goto nogo;
783
784                 map = &vm->vm_map;
785
786                 /*
787                  * Keep swapout from messing with us during this
788                  *      critical time.
789                  */
790                 ++p->p_lock;
791
792                 /*
793                  * Grow the stack if necessary
794                  */
795                 /* grow_stack returns false only if va falls into
796                  * a growable stack region and the stack growth
797                  * fails.  It returns true if va was not within
798                  * a growable stack region, or if the stack 
799                  * growth succeeded.
800                  */
801                 if (!grow_stack (p, va)) {
802                         rv = KERN_FAILURE;
803                         --p->p_lock;
804                         goto nogo;
805                 }
806                 
807                 /* Fault in the user page: */
808                 rv = vm_fault(map, va, ftype,
809                               (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
810                                                       : VM_FAULT_NORMAL);
811
812                 --p->p_lock;
813         } else {
814                 /*
815                  * Don't allow user-mode faults in kernel address space.
816                  */
817                 if (usermode)
818                         goto nogo;
819
820                 /*
821                  * Since we know that kernel virtual address addresses
822                  * always have pte pages mapped, we just have to fault
823                  * the page.
824                  */
825                 rv = vm_fault(kernel_map, va, ftype, VM_FAULT_NORMAL);
826         }
827
828         if (rv == KERN_SUCCESS)
829                 return (0);
830 nogo:
831         if (!usermode) {
832                 if (mycpu->gd_intr_nesting_level == 0 && curthread->td_pcb->pcb_onfault) {
833                         frame->tf_eip = (int)curthread->td_pcb->pcb_onfault;
834                         return (0);
835                 }
836                 trap_fatal(frame, eva);
837                 return (-1);
838         }
839
840         /* kludge to pass faulting virtual address to sendsig */
841         frame->tf_err = eva;
842
843         return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
844 }
845 #endif
846
847 int
848 trap_pfault(frame, usermode, eva)
849         struct trapframe *frame;
850         int usermode;
851         vm_offset_t eva;
852 {
853         vm_offset_t va;
854         struct vmspace *vm = NULL;
855         vm_map_t map = 0;
856         int rv = 0;
857         vm_prot_t ftype;
858         struct proc *p = curproc;
859
860         va = trunc_page(eva);
861         if (va >= KERNBASE) {
862                 /*
863                  * Don't allow user-mode faults in kernel address space.
864                  * An exception:  if the faulting address is the invalid
865                  * instruction entry in the IDT, then the Intel Pentium
866                  * F00F bug workaround was triggered, and we need to
867                  * treat it is as an illegal instruction, and not a page
868                  * fault.
869                  */
870 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
871                 if ((eva == (unsigned int)&idt[6]) && has_f00f_bug) {
872                         frame->tf_trapno = T_PRIVINFLT;
873                         return -2;
874                 }
875 #endif
876                 if (usermode)
877                         goto nogo;
878
879                 map = kernel_map;
880         } else {
881                 /*
882                  * This is a fault on non-kernel virtual memory.
883                  * vm is initialized above to NULL. If curproc is NULL
884                  * or curproc->p_vmspace is NULL the fault is fatal.
885                  */
886                 if (p != NULL)
887                         vm = p->p_vmspace;
888
889                 if (vm == NULL)
890                         goto nogo;
891
892                 map = &vm->vm_map;
893         }
894
895         if (frame->tf_err & PGEX_W)
896                 ftype = VM_PROT_WRITE;
897         else
898                 ftype = VM_PROT_READ;
899
900         if (map != kernel_map) {
901                 /*
902                  * Keep swapout from messing with us during this
903                  *      critical time.
904                  */
905                 ++p->p_lock;
906
907                 /*
908                  * Grow the stack if necessary
909                  */
910                 /* grow_stack returns false only if va falls into
911                  * a growable stack region and the stack growth
912                  * fails.  It returns true if va was not within
913                  * a growable stack region, or if the stack 
914                  * growth succeeded.
915                  */
916                 if (!grow_stack (p, va)) {
917                         rv = KERN_FAILURE;
918                         --p->p_lock;
919                         goto nogo;
920                 }
921
922                 /* Fault in the user page: */
923                 rv = vm_fault(map, va, ftype,
924                               (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
925                                                       : VM_FAULT_NORMAL);
926
927                 --p->p_lock;
928         } else {
929                 /*
930                  * Don't have to worry about process locking or stacks in the kernel.
931                  */
932                 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
933         }
934
935         if (rv == KERN_SUCCESS)
936                 return (0);
937 nogo:
938         if (!usermode) {
939                 if (mycpu->gd_intr_nesting_level == 0 && curthread->td_pcb->pcb_onfault) {
940                         frame->tf_eip = (int)curthread->td_pcb->pcb_onfault;
941                         return (0);
942                 }
943                 trap_fatal(frame, eva);
944                 return (-1);
945         }
946
947         /* kludge to pass faulting virtual address to sendsig */
948         frame->tf_err = eva;
949
950         return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
951 }
952
953 static void
954 trap_fatal(frame, eva)
955         struct trapframe *frame;
956         vm_offset_t eva;
957 {
958         int code, type, ss, esp;
959         struct soft_segment_descriptor softseg;
960
961         code = frame->tf_err;
962         type = frame->tf_trapno;
963         sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)].sd, &softseg);
964
965         if (type <= MAX_TRAP_MSG)
966                 printf("\n\nFatal trap %d: %s while in %s mode\n",
967                         type, trap_msg[type],
968                         frame->tf_eflags & PSL_VM ? "vm86" :
969                         ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
970 #ifdef SMP
971         /* three seperate prints in case of a trap on an unmapped page */
972         printf("mp_lock = %08x; ", mp_lock);
973         printf("cpuid = %d; ", cpuid);
974         printf("lapic.id = %08x\n", lapic.id);
975 #endif
976         if (type == T_PAGEFLT) {
977                 printf("fault virtual address   = 0x%x\n", eva);
978                 printf("fault code              = %s %s, %s\n",
979                         code & PGEX_U ? "user" : "supervisor",
980                         code & PGEX_W ? "write" : "read",
981                         code & PGEX_P ? "protection violation" : "page not present");
982         }
983         printf("instruction pointer     = 0x%x:0x%x\n",
984                frame->tf_cs & 0xffff, frame->tf_eip);
985         if ((ISPL(frame->tf_cs) == SEL_UPL) || (frame->tf_eflags & PSL_VM)) {
986                 ss = frame->tf_ss & 0xffff;
987                 esp = frame->tf_esp;
988         } else {
989                 ss = GSEL(GDATA_SEL, SEL_KPL);
990                 esp = (int)&frame->tf_esp;
991         }
992         printf("stack pointer           = 0x%x:0x%x\n", ss, esp);
993         printf("frame pointer           = 0x%x:0x%x\n", ss, frame->tf_ebp);
994         printf("code segment            = base 0x%x, limit 0x%x, type 0x%x\n",
995                softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
996         printf("                        = DPL %d, pres %d, def32 %d, gran %d\n",
997                softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_def32,
998                softseg.ssd_gran);
999         printf("processor eflags        = ");
1000         if (frame->tf_eflags & PSL_T)
1001                 printf("trace trap, ");
1002         if (frame->tf_eflags & PSL_I)
1003                 printf("interrupt enabled, ");
1004         if (frame->tf_eflags & PSL_NT)
1005                 printf("nested task, ");
1006         if (frame->tf_eflags & PSL_RF)
1007                 printf("resume, ");
1008         if (frame->tf_eflags & PSL_VM)
1009                 printf("vm86, ");
1010         printf("IOPL = %d\n", (frame->tf_eflags & PSL_IOPL) >> 12);
1011         printf("current process         = ");
1012         if (curproc) {
1013                 printf("%lu (%s)\n",
1014                     (u_long)curproc->p_pid, curproc->p_comm ?
1015                     curproc->p_comm : "");
1016         } else {
1017                 printf("Idle\n");
1018         }
1019         printf("current thread          = pri %d ", curthread->td_pri);
1020         if (curthread->td_pri >= TDPRI_CRIT)
1021                 printf("(CRIT)");
1022         printf("\n");
1023         printf("interrupt mask          = ");
1024         if ((curthread->td_cpl & net_imask) == net_imask)
1025                 printf("net ");
1026         if ((curthread->td_cpl & tty_imask) == tty_imask)
1027                 printf("tty ");
1028         if ((curthread->td_cpl & bio_imask) == bio_imask)
1029                 printf("bio ");
1030         if ((curthread->td_cpl & cam_imask) == cam_imask)
1031                 printf("cam ");
1032         if (curthread->td_cpl == 0)
1033                 printf("none");
1034 #ifdef SMP
1035 /**
1036  *  XXX FIXME:
1037  *      we probably SHOULD have stopped the other CPUs before now!
1038  *      another CPU COULD have been touching cpl at this moment...
1039  */
1040         printf(" <- SMP: XXX");
1041 #endif
1042         printf("\n");
1043
1044 #ifdef KDB
1045         if (kdb_trap(&psl))
1046                 return;
1047 #endif
1048 #ifdef DDB
1049         if ((debugger_on_panic || db_active) && kdb_trap(type, 0, frame))
1050                 return;
1051 #endif
1052         printf("trap number             = %d\n", type);
1053         if (type <= MAX_TRAP_MSG)
1054                 panic("%s", trap_msg[type]);
1055         else
1056                 panic("unknown/reserved trap");
1057 }
1058
1059 /*
1060  * Double fault handler. Called when a fault occurs while writing
1061  * a frame for a trap/exception onto the stack. This usually occurs
1062  * when the stack overflows (such is the case with infinite recursion,
1063  * for example).
1064  *
1065  * XXX Note that the current PTD gets replaced by IdlePTD when the
1066  * task switch occurs. This means that the stack that was active at
1067  * the time of the double fault is not available at <kstack> unless
1068  * the machine was idle when the double fault occurred. The downside
1069  * of this is that "trace <ebp>" in ddb won't work.
1070  */
1071 void
1072 dblfault_handler()
1073 {
1074         struct mdglobaldata *gd = mdcpu;
1075
1076         printf("\nFatal double fault:\n");
1077         printf("eip = 0x%x\n", gd->gd_common_tss.tss_eip);
1078         printf("esp = 0x%x\n", gd->gd_common_tss.tss_esp);
1079         printf("ebp = 0x%x\n", gd->gd_common_tss.tss_ebp);
1080 #ifdef SMP
1081         /* three seperate prints in case of a trap on an unmapped page */
1082         printf("mp_lock = %08x; ", mp_lock);
1083         printf("cpuid = %d; ", cpuid);
1084         printf("lapic.id = %08x\n", lapic.id);
1085 #endif
1086         panic("double fault");
1087 }
1088
1089 /*
1090  * Compensate for 386 brain damage (missing URKR).
1091  * This is a little simpler than the pagefault handler in trap() because
1092  * it the page tables have already been faulted in and high addresses
1093  * are thrown out early for other reasons.
1094  */
1095 int trapwrite(addr)
1096         unsigned addr;
1097 {
1098         struct proc *p;
1099         vm_offset_t va;
1100         struct vmspace *vm;
1101         int rv;
1102
1103         va = trunc_page((vm_offset_t)addr);
1104         /*
1105          * XXX - MAX is END.  Changed > to >= for temp. fix.
1106          */
1107         if (va >= VM_MAXUSER_ADDRESS)
1108                 return (1);
1109
1110         p = curproc;
1111         vm = p->p_vmspace;
1112
1113         ++p->p_lock;
1114
1115         if (!grow_stack (p, va)) {
1116                 --p->p_lock;
1117                 return (1);
1118         }
1119
1120         /*
1121          * fault the data page
1122          */
1123         rv = vm_fault(&vm->vm_map, va, VM_PROT_WRITE, VM_FAULT_DIRTY);
1124
1125         --p->p_lock;
1126
1127         if (rv != KERN_SUCCESS)
1128                 return 1;
1129
1130         return (0);
1131 }
1132
1133 /*
1134  *      syscall2 -      MP aware system call request C handler
1135  *
1136  *      A system call is essentially treated as a trap except that the
1137  *      MP lock is not held on entry or return.  We are responsible for
1138  *      obtaining the MP lock if necessary and for handling ASTs
1139  *      (e.g. a task switch) prior to return.
1140  *
1141  *      In general, only simple access and manipulation of curproc and
1142  *      the current stack is allowed without having to hold MP lock.
1143  */
1144 void
1145 syscall2(frame)
1146         struct trapframe frame;
1147 {
1148         struct thread *td = curthread;
1149         struct proc *p = td->td_proc;
1150         caddr_t params;
1151         int i;
1152         struct sysent *callp;
1153         register_t orig_tf_eflags;
1154         u_quad_t sticks;
1155         int error;
1156         int narg;
1157         int args[8];
1158         int have_mplock = 0;
1159         u_int code;
1160
1161 #ifdef DIAGNOSTIC
1162         if (ISPL(frame.tf_cs) != SEL_UPL) {
1163                 get_mplock();
1164                 panic("syscall");
1165                 /* NOT REACHED */
1166         }
1167 #endif
1168
1169         /*
1170          * access non-atomic field from critical section.  p_sticks is
1171          * updated by the clock interrupt.  Also use this opportunity
1172          * to raise our LWKT priority.
1173          */
1174         crit_enter();
1175         userenter();
1176         sticks = curthread->td_sticks;
1177         crit_exit();
1178
1179         p->p_md.md_regs = &frame;
1180         params = (caddr_t)frame.tf_esp + sizeof(int);
1181         code = frame.tf_eax;
1182         orig_tf_eflags = frame.tf_eflags;
1183
1184         if (p->p_sysent->sv_prepsyscall) {
1185                 /*
1186                  * The prep code is not MP aware.
1187                  */
1188                 get_mplock();
1189                 (*p->p_sysent->sv_prepsyscall)(&frame, args, &code, &params);
1190                 rel_mplock();
1191         } else {
1192                 /*
1193                  * Need to check if this is a 32 bit or 64 bit syscall.
1194                  * fuword is MP aware.
1195                  */
1196                 if (code == SYS_syscall) {
1197                         /*
1198                          * Code is first argument, followed by actual args.
1199                          */
1200                         code = fuword(params);
1201                         params += sizeof(int);
1202                 } else if (code == SYS___syscall) {
1203                         /*
1204                          * Like syscall, but code is a quad, so as to maintain
1205                          * quad alignment for the rest of the arguments.
1206                          */
1207                         code = fuword(params);
1208                         params += sizeof(quad_t);
1209                 }
1210         }
1211
1212         if (p->p_sysent->sv_mask)
1213                 code &= p->p_sysent->sv_mask;
1214
1215         if (code >= p->p_sysent->sv_size)
1216                 callp = &p->p_sysent->sv_table[0];
1217         else
1218                 callp = &p->p_sysent->sv_table[code];
1219
1220         narg = callp->sy_narg & SYF_ARGMASK;
1221
1222         /*
1223          * copyin is MP aware, but the tracing code is not
1224          */
1225         if (params && (i = narg * sizeof(int)) &&
1226             (error = copyin(params, (caddr_t)args, (u_int)i))) {
1227                 get_mplock();
1228                 have_mplock = 1;
1229 #ifdef KTRACE
1230                 if (KTRPOINT(td, KTR_SYSCALL))
1231                         ktrsyscall(p->p_tracep, code, narg, args);
1232 #endif
1233                 goto bad;
1234         }
1235
1236         /*
1237          * Try to run the syscall without the MP lock if the syscall
1238          * is MP safe.  We have to obtain the MP lock no matter what if 
1239          * we are ktracing
1240          */
1241         if ((callp->sy_narg & SYF_MPSAFE) == 0) {
1242                 get_mplock();
1243                 have_mplock = 1;
1244         }
1245
1246 #ifdef KTRACE
1247         if (KTRPOINT(td, KTR_SYSCALL)) {
1248                 if (have_mplock == 0) {
1249                         get_mplock();
1250                         have_mplock = 1;
1251                 }
1252                 ktrsyscall(p->p_tracep, code, narg, args);
1253         }
1254 #endif
1255         p->p_retval[0] = 0;
1256         p->p_retval[1] = frame.tf_edx;
1257
1258         STOPEVENT(p, S_SCE, narg);      /* MP aware */
1259
1260         error = (*callp->sy_call)(args);
1261
1262         /*
1263          * MP SAFE (we may or may not have the MP lock at this point)
1264          */
1265         switch (error) {
1266         case 0:
1267                 /*
1268                  * Reinitialize proc pointer `p' as it may be different
1269                  * if this is a child returning from fork syscall.
1270                  */
1271                 p = curproc;
1272                 frame.tf_eax = p->p_retval[0];
1273                 frame.tf_edx = p->p_retval[1];
1274                 frame.tf_eflags &= ~PSL_C;
1275                 break;
1276
1277         case ERESTART:
1278                 /*
1279                  * Reconstruct pc, assuming lcall $X,y is 7 bytes,
1280                  * int 0x80 is 2 bytes. We saved this in tf_err.
1281                  */
1282                 frame.tf_eip -= frame.tf_err;
1283                 break;
1284
1285         case EJUSTRETURN:
1286                 break;
1287
1288         default:
1289 bad:
1290                 if (p->p_sysent->sv_errsize) {
1291                         if (error >= p->p_sysent->sv_errsize)
1292                                 error = -1;     /* XXX */
1293                         else
1294                                 error = p->p_sysent->sv_errtbl[error];
1295                 }
1296                 frame.tf_eax = error;
1297                 frame.tf_eflags |= PSL_C;
1298                 break;
1299         }
1300
1301         /*
1302          * Traced syscall.  trapsignal() is not MP aware.
1303          */
1304         if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1305                 if (have_mplock == 0) {
1306                         get_mplock();
1307                         have_mplock = 1;
1308                 }
1309                 frame.tf_eflags &= ~PSL_T;
1310                 trapsignal(p, SIGTRAP, 0);
1311         }
1312
1313         /*
1314          * Handle reschedule and other end-of-syscall issues
1315          */
1316         have_mplock = userret(p, &frame, sticks, have_mplock);
1317
1318 #ifdef KTRACE
1319         if (KTRPOINT(td, KTR_SYSRET)) {
1320                 if (have_mplock == 0) {
1321                         get_mplock();
1322                         have_mplock = 1;
1323                 }
1324                 ktrsysret(p->p_tracep, code, error, p->p_retval[0]);
1325         }
1326 #endif
1327
1328         /*
1329          * This works because errno is findable through the
1330          * register set.  If we ever support an emulation where this
1331          * is not the case, this code will need to be revisited.
1332          */
1333         STOPEVENT(p, S_SCX, code);
1334
1335         /*
1336          * Release the MP lock if we had to get it
1337          */
1338         if (have_mplock)
1339                 rel_mplock();
1340 }
1341
1342 /*
1343  * Simplified back end of syscall(), used when returning from fork()
1344  * directly into user mode.  MP lock is held on entry and should be 
1345  * held on return.
1346  */
1347 void
1348 fork_return(p, frame)
1349         struct proc *p;
1350         struct trapframe frame;
1351 {
1352         frame.tf_eax = 0;               /* Child returns zero */
1353         frame.tf_eflags &= ~PSL_C;      /* success */
1354         frame.tf_edx = 1;
1355
1356         userret(p, &frame, 0, 1);
1357 #ifdef KTRACE
1358         if (KTRPOINT(p->p_thread, KTR_SYSRET))
1359                 ktrsysret(p->p_tracep, SYS_fork, 0, 0);
1360 #endif
1361 }