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