thread stage 3: create independant thread structure, unembed from proc.
[dragonfly.git] / sys / i386 / isa / npx.c
1 /*-
2  * Copyright (c) 1990 William Jolitz.
3  * Copyright (c) 1991 The Regents of the University of California.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *      This product includes software developed by the University of
17  *      California, Berkeley and its contributors.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      from: @(#)npx.c 7.2 (Berkeley) 5/12/91
35  * $FreeBSD: src/sys/i386/isa/npx.c,v 1.80.2.3 2001/10/20 19:04:38 tegge Exp $
36  * $DragonFly: src/sys/i386/isa/Attic/npx.c,v 1.4 2003/06/18 16:30:11 dillon Exp $
37  */
38
39 #include "opt_cpu.h"
40 #include "opt_debug_npx.h"
41 #include "opt_math_emulate.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/bus.h>
46 #include <sys/kernel.h>
47 #include <sys/malloc.h>
48 #include <sys/module.h>
49 #include <sys/sysctl.h>
50 #include <sys/proc.h>
51 #include <machine/bus.h>
52 #include <sys/rman.h>
53 #ifdef NPX_DEBUG
54 #include <sys/syslog.h>
55 #endif
56 #include <sys/signalvar.h>
57
58 #ifndef SMP
59 #include <machine/asmacros.h>
60 #endif
61 #include <machine/cputypes.h>
62 #include <machine/frame.h>
63 #include <machine/ipl.h>
64 #include <machine/md_var.h>
65 #include <machine/pcb.h>
66 #include <machine/psl.h>
67 #ifndef SMP
68 #include <machine/clock.h>
69 #endif
70 #include <machine/resource.h>
71 #include <machine/specialreg.h>
72 #include <machine/segments.h>
73
74 #ifndef SMP
75 #include <i386/isa/icu.h>
76 #include <i386/isa/intr_machdep.h>
77 #include <i386/isa/isa.h>
78 #endif
79
80 /*
81  * 387 and 287 Numeric Coprocessor Extension (NPX) Driver.
82  */
83
84 /* Configuration flags. */
85 #define NPX_DISABLE_I586_OPTIMIZED_BCOPY        (1 << 0)
86 #define NPX_DISABLE_I586_OPTIMIZED_BZERO        (1 << 1)
87 #define NPX_DISABLE_I586_OPTIMIZED_COPYIO       (1 << 2)
88 #define NPX_PREFER_EMULATOR                     (1 << 3)
89
90 #ifdef  __GNUC__
91
92 #define fldcw(addr)             __asm("fldcw %0" : : "m" (*(addr)))
93 #define fnclex()                __asm("fnclex")
94 #define fninit()                __asm("fninit")
95 #define fnop()                  __asm("fnop")
96 #define fnsave(addr)            __asm __volatile("fnsave %0" : "=m" (*(addr)))
97 #define fnstcw(addr)            __asm __volatile("fnstcw %0" : "=m" (*(addr)))
98 #define fnstsw(addr)            __asm __volatile("fnstsw %0" : "=m" (*(addr)))
99 #define fp_divide_by_0()        __asm("fldz; fld1; fdiv %st,%st(1); fnop")
100 #define frstor(addr)            __asm("frstor %0" : : "m" (*(addr)))
101 #ifdef CPU_ENABLE_SSE
102 #define fxrstor(addr)           __asm("fxrstor %0" : : "m" (*(addr)))
103 #define fxsave(addr)            __asm __volatile("fxsave %0" : "=m" (*(addr)))
104 #endif
105 #define start_emulating()       __asm("smsw %%ax; orb %0,%%al; lmsw %%ax" \
106                                       : : "n" (CR0_TS) : "ax")
107 #define stop_emulating()        __asm("clts")
108
109 #else   /* not __GNUC__ */
110
111 void    fldcw           __P((caddr_t addr));
112 void    fnclex          __P((void));
113 void    fninit          __P((void));
114 void    fnop            __P((void));
115 void    fnsave          __P((caddr_t addr));
116 void    fnstcw          __P((caddr_t addr));
117 void    fnstsw          __P((caddr_t addr));
118 void    fp_divide_by_0  __P((void));
119 void    frstor          __P((caddr_t addr));
120 #ifdef CPU_ENABLE_SSE
121 void    fxsave          __P((caddr_t addr));
122 void    fxrstor         __P((caddr_t addr));
123 #endif
124 void    start_emulating __P((void));
125 void    stop_emulating  __P((void));
126
127 #endif  /* __GNUC__ */
128
129 #ifdef CPU_ENABLE_SSE
130 #define GET_FPU_EXSW_PTR(pcb) \
131         (cpu_fxsr ? \
132                 &(pcb)->pcb_save.sv_xmm.sv_ex_sw : \
133                 &(pcb)->pcb_save.sv_87.sv_ex_sw)
134 #else /* CPU_ENABLE_SSE */
135 #define GET_FPU_EXSW_PTR(pcb) \
136         (&(pcb)->pcb_save.sv_87.sv_ex_sw)
137 #endif /* CPU_ENABLE_SSE */
138
139 typedef u_char bool_t;
140
141 static  int     npx_attach      __P((device_t dev));
142         void    npx_intr        __P((void *));
143 static  void    npx_identify    __P((driver_t *driver, device_t parent));
144 static  int     npx_probe       __P((device_t dev));
145 static  int     npx_probe1      __P((device_t dev));
146 static  void    fpusave         __P((union savefpu *));
147 static  void    fpurstor        __P((union savefpu *));
148 #ifdef I586_CPU
149 static  long    timezero        __P((const char *funcname,
150                                      void (*func)(void *buf, size_t len)));
151 #endif /* I586_CPU */
152
153 int     hw_float;               /* XXX currently just alias for npx_exists */
154
155 SYSCTL_INT(_hw,HW_FLOATINGPT, floatingpoint,
156         CTLFLAG_RD, &hw_float, 0, 
157         "Floatingpoint instructions executed in hardware");
158
159 #ifndef SMP
160 static  u_int                   npx0_imask = SWI_CLOCK_MASK;
161 static  struct gate_descriptor  npx_idt_probeintr;
162 static  int                     npx_intrno;
163 static  volatile u_int          npx_intrs_while_probing;
164 static  volatile u_int          npx_traps_while_probing;
165 #endif
166
167 static  bool_t                  npx_ex16;
168 static  bool_t                  npx_exists;
169 static  bool_t                  npx_irq13;
170 static  int                     npx_irq;        /* irq number */
171
172 #ifndef SMP
173 /*
174  * Special interrupt handlers.  Someday intr0-intr15 will be used to count
175  * interrupts.  We'll still need a special exception 16 handler.  The busy
176  * latch stuff in probeintr() can be moved to npxprobe().
177  */
178 inthand_t probeintr;
179 __asm("                                                         \n\
180         .text                                                   \n\
181         .p2align 2,0x90                                         \n\
182         .type   " __XSTRING(CNAME(probeintr)) ",@function       \n\
183 " __XSTRING(CNAME(probeintr)) ":                                \n\
184         ss                                                      \n\
185         incl    " __XSTRING(CNAME(npx_intrs_while_probing)) "   \n\
186         pushl   %eax                                            \n\
187         movb    $0x20,%al       # EOI (asm in strings loses cpp features) \n\
188         outb    %al,$0xa0       # IO_ICU2                       \n\
189         outb    %al,$0x20       # IO_ICU1                       \n\
190         movb    $0,%al                                          \n\
191         outb    %al,$0xf0       # clear BUSY# latch             \n\
192         popl    %eax                                            \n\
193         iret                                                    \n\
194 ");
195
196 inthand_t probetrap;
197 __asm("                                                         \n\
198         .text                                                   \n\
199         .p2align 2,0x90                                         \n\
200         .type   " __XSTRING(CNAME(probetrap)) ",@function       \n\
201 " __XSTRING(CNAME(probetrap)) ":                                \n\
202         ss                                                      \n\
203         incl    " __XSTRING(CNAME(npx_traps_while_probing)) "   \n\
204         fnclex                                                  \n\
205         iret                                                    \n\
206 ");
207 #endif /* SMP */
208
209 /*
210  * Identify routine.  Create a connection point on our parent for probing.
211  */
212 static void
213 npx_identify(driver, parent)
214         driver_t *driver;
215         device_t parent;
216 {
217         device_t child;
218
219         child = BUS_ADD_CHILD(parent, 0, "npx", 0);
220         if (child == NULL)
221                 panic("npx_identify");
222 }
223
224 /*
225  * Probe routine.  Initialize cr0 to give correct behaviour for [f]wait
226  * whether the device exists or not (XXX should be elsewhere).  Set flags
227  * to tell npxattach() what to do.  Modify device struct if npx doesn't
228  * need to use interrupts.  Return 1 if device exists.
229  */
230 static int
231 npx_probe(dev)
232         device_t dev;
233 {
234 #ifdef SMP
235
236         if (resource_int_value("npx", 0, "irq", &npx_irq) != 0)
237                 npx_irq = 13;
238         return npx_probe1(dev);
239
240 #else /* SMP */
241
242         int     result;
243         u_long  save_eflags;
244         u_char  save_icu1_mask;
245         u_char  save_icu2_mask;
246         struct  gate_descriptor save_idt_npxintr;
247         struct  gate_descriptor save_idt_npxtrap;
248         /*
249          * This routine is now just a wrapper for npxprobe1(), to install
250          * special npx interrupt and trap handlers, to enable npx interrupts
251          * and to disable other interrupts.  Someday isa_configure() will
252          * install suitable handlers and run with interrupts enabled so we
253          * won't need to do so much here.
254          */
255         if (resource_int_value("npx", 0, "irq", &npx_irq) != 0)
256                 npx_irq = 13;
257         npx_intrno = NRSVIDT + npx_irq;
258         save_eflags = read_eflags();
259         disable_intr();
260         save_icu1_mask = inb(IO_ICU1 + 1);
261         save_icu2_mask = inb(IO_ICU2 + 1);
262         save_idt_npxintr = idt[npx_intrno];
263         save_idt_npxtrap = idt[16];
264         outb(IO_ICU1 + 1, ~IRQ_SLAVE);
265         outb(IO_ICU2 + 1, ~(1 << (npx_irq - 8)));
266         setidt(16, probetrap, SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
267         setidt(npx_intrno, probeintr, SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
268         npx_idt_probeintr = idt[npx_intrno];
269         enable_intr();
270         result = npx_probe1(dev);
271         disable_intr();
272         outb(IO_ICU1 + 1, save_icu1_mask);
273         outb(IO_ICU2 + 1, save_icu2_mask);
274         idt[npx_intrno] = save_idt_npxintr;
275         idt[16] = save_idt_npxtrap;
276         write_eflags(save_eflags);
277         return (result);
278
279 #endif /* SMP */
280 }
281
282 static int
283 npx_probe1(dev)
284         device_t dev;
285 {
286 #ifndef SMP
287         u_short control;
288         u_short status;
289 #endif
290
291         /*
292          * Partially reset the coprocessor, if any.  Some BIOS's don't reset
293          * it after a warm boot.
294          */
295         outb(0xf1, 0);          /* full reset on some systems, NOP on others */
296         outb(0xf0, 0);          /* clear BUSY# latch */
297         /*
298          * Prepare to trap all ESC (i.e., NPX) instructions and all WAIT
299          * instructions.  We must set the CR0_MP bit and use the CR0_TS
300          * bit to control the trap, because setting the CR0_EM bit does
301          * not cause WAIT instructions to trap.  It's important to trap
302          * WAIT instructions - otherwise the "wait" variants of no-wait
303          * control instructions would degenerate to the "no-wait" variants
304          * after FP context switches but work correctly otherwise.  It's
305          * particularly important to trap WAITs when there is no NPX -
306          * otherwise the "wait" variants would always degenerate.
307          *
308          * Try setting CR0_NE to get correct error reporting on 486DX's.
309          * Setting it should fail or do nothing on lesser processors.
310          */
311         load_cr0(rcr0() | CR0_MP | CR0_NE);
312         /*
313          * But don't trap while we're probing.
314          */
315         stop_emulating();
316         /*
317          * Finish resetting the coprocessor, if any.  If there is an error
318          * pending, then we may get a bogus IRQ13, but probeintr() will handle
319          * it OK.  Bogus halts have never been observed, but we enabled
320          * IRQ13 and cleared the BUSY# latch early to handle them anyway.
321          */
322         fninit();
323
324 #ifdef SMP
325         /*
326          * Exception 16 MUST work for SMP.
327          */
328         npx_irq13 = 0;
329         npx_ex16 = hw_float = npx_exists = 1;
330         device_set_desc(dev, "math processor");
331         return (0);
332
333 #else /* !SMP */
334         device_set_desc(dev, "math processor");
335
336         /*
337          * Don't use fwait here because it might hang.
338          * Don't use fnop here because it usually hangs if there is no FPU.
339          */
340         DELAY(1000);            /* wait for any IRQ13 */
341 #ifdef DIAGNOSTIC
342         if (npx_intrs_while_probing != 0)
343                 printf("fninit caused %u bogus npx interrupt(s)\n",
344                        npx_intrs_while_probing);
345         if (npx_traps_while_probing != 0)
346                 printf("fninit caused %u bogus npx trap(s)\n",
347                        npx_traps_while_probing);
348 #endif
349         /*
350          * Check for a status of mostly zero.
351          */
352         status = 0x5a5a;
353         fnstsw(&status);
354         if ((status & 0xb8ff) == 0) {
355                 /*
356                  * Good, now check for a proper control word.
357                  */
358                 control = 0x5a5a;
359                 fnstcw(&control);
360                 if ((control & 0x1f3f) == 0x033f) {
361                         hw_float = npx_exists = 1;
362                         /*
363                          * We have an npx, now divide by 0 to see if exception
364                          * 16 works.
365                          */
366                         control &= ~(1 << 2);   /* enable divide by 0 trap */
367                         fldcw(&control);
368                         npx_traps_while_probing = npx_intrs_while_probing = 0;
369                         fp_divide_by_0();
370                         if (npx_traps_while_probing != 0) {
371                                 /*
372                                  * Good, exception 16 works.
373                                  */
374                                 npx_ex16 = 1;
375                                 return (0);
376                         }
377                         if (npx_intrs_while_probing != 0) {
378                                 int     rid;
379                                 struct  resource *r;
380                                 void    *intr;
381                                 /*
382                                  * Bad, we are stuck with IRQ13.
383                                  */
384                                 npx_irq13 = 1;
385                                 /*
386                                  * npxattach would be too late to set npx0_imask
387                                  */
388                                 npx0_imask |= (1 << npx_irq);
389
390                                 /*
391                                  * We allocate these resources permanently,
392                                  * so there is no need to keep track of them.
393                                  */
394                                 rid = 0;
395                                 r = bus_alloc_resource(dev, SYS_RES_IOPORT,
396                                                        &rid, IO_NPX, IO_NPX,
397                                                        IO_NPXSIZE, RF_ACTIVE);
398                                 if (r == 0)
399                                         panic("npx: can't get ports");
400                                 rid = 0;
401                                 r = bus_alloc_resource(dev, SYS_RES_IRQ,
402                                                        &rid, npx_irq, npx_irq,
403                                                        1, RF_ACTIVE);
404                                 if (r == 0)
405                                         panic("npx: can't get IRQ");
406                                 BUS_SETUP_INTR(device_get_parent(dev),
407                                                dev, r, INTR_TYPE_MISC,
408                                                npx_intr, 0, &intr);
409                                 if (intr == 0)
410                                         panic("npx: can't create intr");
411
412                                 return (0);
413                         }
414                         /*
415                          * Worse, even IRQ13 is broken.  Use emulator.
416                          */
417                 }
418         }
419         /*
420          * Probe failed, but we want to get to npxattach to initialize the
421          * emulator and say that it has been installed.  XXX handle devices
422          * that aren't really devices better.
423          */
424         return (0);
425 #endif /* SMP */
426 }
427
428 /*
429  * Attach routine - announce which it is, and wire into system
430  */
431 int
432 npx_attach(dev)
433         device_t dev;
434 {
435         int flags;
436
437         if (resource_int_value("npx", 0, "flags", &flags) != 0)
438                 flags = 0;
439
440         if (flags)
441                 device_printf(dev, "flags 0x%x ", flags);
442         if (npx_irq13) {
443                 device_printf(dev, "using IRQ 13 interface\n");
444         } else {
445 #if defined(MATH_EMULATE) || defined(GPL_MATH_EMULATE)
446                 if (npx_ex16) {
447                         if (!(flags & NPX_PREFER_EMULATOR))
448                                 device_printf(dev, "INT 16 interface\n");
449                         else {
450                                 device_printf(dev, "FPU exists, but flags request "
451                                     "emulator\n");
452                                 hw_float = npx_exists = 0;
453                         }
454                 } else if (npx_exists) {
455                         device_printf(dev, "error reporting broken; using 387 emulator\n");
456                         hw_float = npx_exists = 0;
457                 } else
458                         device_printf(dev, "387 emulator\n");
459 #else
460                 if (npx_ex16) {
461                         device_printf(dev, "INT 16 interface\n");
462                         if (flags & NPX_PREFER_EMULATOR) {
463                                 device_printf(dev, "emulator requested, but none compiled "
464                                     "into kernel, using FPU\n");
465                         }
466                 } else
467                         device_printf(dev, "no 387 emulator in kernel and no FPU!\n");
468 #endif
469         }
470         npxinit(__INITIAL_NPXCW__);
471
472 #ifdef I586_CPU
473         if (cpu_class == CPUCLASS_586 && npx_ex16 && npx_exists &&
474             timezero("i586_bzero()", i586_bzero) <
475             timezero("bzero()", bzero) * 4 / 5) {
476                 if (!(flags & NPX_DISABLE_I586_OPTIMIZED_BCOPY)) {
477                         bcopy_vector = i586_bcopy;
478                         ovbcopy_vector = i586_bcopy;
479                 }
480                 if (!(flags & NPX_DISABLE_I586_OPTIMIZED_BZERO))
481                         bzero = i586_bzero;
482                 if (!(flags & NPX_DISABLE_I586_OPTIMIZED_COPYIO)) {
483                         copyin_vector = i586_copyin;
484                         copyout_vector = i586_copyout;
485                 }
486         }
487 #endif
488
489         return (0);             /* XXX unused */
490 }
491
492 /*
493  * Initialize floating point unit.
494  */
495 void
496 npxinit(control)
497         u_short control;
498 {
499         static union savefpu dummy;
500
501         if (!npx_exists)
502                 return;
503         /*
504          * fninit has the same h/w bugs as fnsave.  Use the detoxified
505          * fnsave to throw away any junk in the fpu.  npxsave() initializes
506          * the fpu and sets npxthread = NULL as important side effects.
507          */
508         npxsave(&dummy);
509         stop_emulating();
510 #ifdef CPU_ENABLE_SSE
511         /* XXX npxsave() doesn't actually initialize the fpu in the SSE case. */
512         if (cpu_fxsr)
513                 fninit();
514 #endif
515         fldcw(&control);
516         if (curpcb != NULL)
517                 fpusave(&curpcb->pcb_save);
518         start_emulating();
519 }
520
521 /*
522  * Free coprocessor (if we have it).
523  */
524 void
525 npxexit(p)
526         struct proc *p;
527 {
528
529         if (p->p_thread == npxthread)
530                 npxsave(&curpcb->pcb_save);
531 #ifdef NPX_DEBUG
532         if (npx_exists) {
533                 u_int   masked_exceptions;
534
535                 masked_exceptions = curpcb->pcb_save.sv_87.sv_env.en_cw
536                                     & curpcb->pcb_save.sv_87.sv_env.en_sw & 0x7f;
537                 /*
538                  * Log exceptions that would have trapped with the old
539                  * control word (overflow, divide by 0, and invalid operand).
540                  */
541                 if (masked_exceptions & 0x0d)
542                         log(LOG_ERR,
543         "pid %d (%s) exited with masked floating point exceptions 0x%02x\n",
544                             p->p_pid, p->p_comm, masked_exceptions);
545         }
546 #endif
547 }
548
549 /* 
550  * The following mechanism is used to ensure that the FPE_... value
551  * that is passed as a trapcode to the signal handler of the user
552  * process does not have more than one bit set.
553  * 
554  * Multiple bits may be set if the user process modifies the control
555  * word while a status word bit is already set.  While this is a sign
556  * of bad coding, we have no choise than to narrow them down to one
557  * bit, since we must not send a trapcode that is not exactly one of
558  * the FPE_ macros.
559  *
560  * The mechanism has a static table with 127 entries.  Each combination
561  * of the 7 FPU status word exception bits directly translates to a
562  * position in this table, where a single FPE_... value is stored.
563  * This FPE_... value stored there is considered the "most important"
564  * of the exception bits and will be sent as the signal code.  The
565  * precedence of the bits is based upon Intel Document "Numerical
566  * Applications", Chapter "Special Computational Situations".
567  *
568  * The macro to choose one of these values does these steps: 1) Throw
569  * away status word bits that cannot be masked.  2) Throw away the bits
570  * currently masked in the control word, assuming the user isn't
571  * interested in them anymore.  3) Reinsert status word bit 7 (stack
572  * fault) if it is set, which cannot be masked but must be presered.
573  * 4) Use the remaining bits to point into the trapcode table.
574  *
575  * The 6 maskable bits in order of their preference, as stated in the
576  * above referenced Intel manual:
577  * 1  Invalid operation (FP_X_INV)
578  * 1a   Stack underflow
579  * 1b   Stack overflow
580  * 1c   Operand of unsupported format
581  * 1d   SNaN operand.
582  * 2  QNaN operand (not an exception, irrelavant here)
583  * 3  Any other invalid-operation not mentioned above or zero divide
584  *      (FP_X_INV, FP_X_DZ)
585  * 4  Denormal operand (FP_X_DNML)
586  * 5  Numeric over/underflow (FP_X_OFL, FP_X_UFL)
587  * 6  Inexact result (FP_X_IMP) 
588  */
589 static char fpetable[128] = {
590         0,
591         FPE_FLTINV,     /*  1 - INV */
592         FPE_FLTUND,     /*  2 - DNML */
593         FPE_FLTINV,     /*  3 - INV | DNML */
594         FPE_FLTDIV,     /*  4 - DZ */
595         FPE_FLTINV,     /*  5 - INV | DZ */
596         FPE_FLTDIV,     /*  6 - DNML | DZ */
597         FPE_FLTINV,     /*  7 - INV | DNML | DZ */
598         FPE_FLTOVF,     /*  8 - OFL */
599         FPE_FLTINV,     /*  9 - INV | OFL */
600         FPE_FLTUND,     /*  A - DNML | OFL */
601         FPE_FLTINV,     /*  B - INV | DNML | OFL */
602         FPE_FLTDIV,     /*  C - DZ | OFL */
603         FPE_FLTINV,     /*  D - INV | DZ | OFL */
604         FPE_FLTDIV,     /*  E - DNML | DZ | OFL */
605         FPE_FLTINV,     /*  F - INV | DNML | DZ | OFL */
606         FPE_FLTUND,     /* 10 - UFL */
607         FPE_FLTINV,     /* 11 - INV | UFL */
608         FPE_FLTUND,     /* 12 - DNML | UFL */
609         FPE_FLTINV,     /* 13 - INV | DNML | UFL */
610         FPE_FLTDIV,     /* 14 - DZ | UFL */
611         FPE_FLTINV,     /* 15 - INV | DZ | UFL */
612         FPE_FLTDIV,     /* 16 - DNML | DZ | UFL */
613         FPE_FLTINV,     /* 17 - INV | DNML | DZ | UFL */
614         FPE_FLTOVF,     /* 18 - OFL | UFL */
615         FPE_FLTINV,     /* 19 - INV | OFL | UFL */
616         FPE_FLTUND,     /* 1A - DNML | OFL | UFL */
617         FPE_FLTINV,     /* 1B - INV | DNML | OFL | UFL */
618         FPE_FLTDIV,     /* 1C - DZ | OFL | UFL */
619         FPE_FLTINV,     /* 1D - INV | DZ | OFL | UFL */
620         FPE_FLTDIV,     /* 1E - DNML | DZ | OFL | UFL */
621         FPE_FLTINV,     /* 1F - INV | DNML | DZ | OFL | UFL */
622         FPE_FLTRES,     /* 20 - IMP */
623         FPE_FLTINV,     /* 21 - INV | IMP */
624         FPE_FLTUND,     /* 22 - DNML | IMP */
625         FPE_FLTINV,     /* 23 - INV | DNML | IMP */
626         FPE_FLTDIV,     /* 24 - DZ | IMP */
627         FPE_FLTINV,     /* 25 - INV | DZ | IMP */
628         FPE_FLTDIV,     /* 26 - DNML | DZ | IMP */
629         FPE_FLTINV,     /* 27 - INV | DNML | DZ | IMP */
630         FPE_FLTOVF,     /* 28 - OFL | IMP */
631         FPE_FLTINV,     /* 29 - INV | OFL | IMP */
632         FPE_FLTUND,     /* 2A - DNML | OFL | IMP */
633         FPE_FLTINV,     /* 2B - INV | DNML | OFL | IMP */
634         FPE_FLTDIV,     /* 2C - DZ | OFL | IMP */
635         FPE_FLTINV,     /* 2D - INV | DZ | OFL | IMP */
636         FPE_FLTDIV,     /* 2E - DNML | DZ | OFL | IMP */
637         FPE_FLTINV,     /* 2F - INV | DNML | DZ | OFL | IMP */
638         FPE_FLTUND,     /* 30 - UFL | IMP */
639         FPE_FLTINV,     /* 31 - INV | UFL | IMP */
640         FPE_FLTUND,     /* 32 - DNML | UFL | IMP */
641         FPE_FLTINV,     /* 33 - INV | DNML | UFL | IMP */
642         FPE_FLTDIV,     /* 34 - DZ | UFL | IMP */
643         FPE_FLTINV,     /* 35 - INV | DZ | UFL | IMP */
644         FPE_FLTDIV,     /* 36 - DNML | DZ | UFL | IMP */
645         FPE_FLTINV,     /* 37 - INV | DNML | DZ | UFL | IMP */
646         FPE_FLTOVF,     /* 38 - OFL | UFL | IMP */
647         FPE_FLTINV,     /* 39 - INV | OFL | UFL | IMP */
648         FPE_FLTUND,     /* 3A - DNML | OFL | UFL | IMP */
649         FPE_FLTINV,     /* 3B - INV | DNML | OFL | UFL | IMP */
650         FPE_FLTDIV,     /* 3C - DZ | OFL | UFL | IMP */
651         FPE_FLTINV,     /* 3D - INV | DZ | OFL | UFL | IMP */
652         FPE_FLTDIV,     /* 3E - DNML | DZ | OFL | UFL | IMP */
653         FPE_FLTINV,     /* 3F - INV | DNML | DZ | OFL | UFL | IMP */
654         FPE_FLTSUB,     /* 40 - STK */
655         FPE_FLTSUB,     /* 41 - INV | STK */
656         FPE_FLTUND,     /* 42 - DNML | STK */
657         FPE_FLTSUB,     /* 43 - INV | DNML | STK */
658         FPE_FLTDIV,     /* 44 - DZ | STK */
659         FPE_FLTSUB,     /* 45 - INV | DZ | STK */
660         FPE_FLTDIV,     /* 46 - DNML | DZ | STK */
661         FPE_FLTSUB,     /* 47 - INV | DNML | DZ | STK */
662         FPE_FLTOVF,     /* 48 - OFL | STK */
663         FPE_FLTSUB,     /* 49 - INV | OFL | STK */
664         FPE_FLTUND,     /* 4A - DNML | OFL | STK */
665         FPE_FLTSUB,     /* 4B - INV | DNML | OFL | STK */
666         FPE_FLTDIV,     /* 4C - DZ | OFL | STK */
667         FPE_FLTSUB,     /* 4D - INV | DZ | OFL | STK */
668         FPE_FLTDIV,     /* 4E - DNML | DZ | OFL | STK */
669         FPE_FLTSUB,     /* 4F - INV | DNML | DZ | OFL | STK */
670         FPE_FLTUND,     /* 50 - UFL | STK */
671         FPE_FLTSUB,     /* 51 - INV | UFL | STK */
672         FPE_FLTUND,     /* 52 - DNML | UFL | STK */
673         FPE_FLTSUB,     /* 53 - INV | DNML | UFL | STK */
674         FPE_FLTDIV,     /* 54 - DZ | UFL | STK */
675         FPE_FLTSUB,     /* 55 - INV | DZ | UFL | STK */
676         FPE_FLTDIV,     /* 56 - DNML | DZ | UFL | STK */
677         FPE_FLTSUB,     /* 57 - INV | DNML | DZ | UFL | STK */
678         FPE_FLTOVF,     /* 58 - OFL | UFL | STK */
679         FPE_FLTSUB,     /* 59 - INV | OFL | UFL | STK */
680         FPE_FLTUND,     /* 5A - DNML | OFL | UFL | STK */
681         FPE_FLTSUB,     /* 5B - INV | DNML | OFL | UFL | STK */
682         FPE_FLTDIV,     /* 5C - DZ | OFL | UFL | STK */
683         FPE_FLTSUB,     /* 5D - INV | DZ | OFL | UFL | STK */
684         FPE_FLTDIV,     /* 5E - DNML | DZ | OFL | UFL | STK */
685         FPE_FLTSUB,     /* 5F - INV | DNML | DZ | OFL | UFL | STK */
686         FPE_FLTRES,     /* 60 - IMP | STK */
687         FPE_FLTSUB,     /* 61 - INV | IMP | STK */
688         FPE_FLTUND,     /* 62 - DNML | IMP | STK */
689         FPE_FLTSUB,     /* 63 - INV | DNML | IMP | STK */
690         FPE_FLTDIV,     /* 64 - DZ | IMP | STK */
691         FPE_FLTSUB,     /* 65 - INV | DZ | IMP | STK */
692         FPE_FLTDIV,     /* 66 - DNML | DZ | IMP | STK */
693         FPE_FLTSUB,     /* 67 - INV | DNML | DZ | IMP | STK */
694         FPE_FLTOVF,     /* 68 - OFL | IMP | STK */
695         FPE_FLTSUB,     /* 69 - INV | OFL | IMP | STK */
696         FPE_FLTUND,     /* 6A - DNML | OFL | IMP | STK */
697         FPE_FLTSUB,     /* 6B - INV | DNML | OFL | IMP | STK */
698         FPE_FLTDIV,     /* 6C - DZ | OFL | IMP | STK */
699         FPE_FLTSUB,     /* 6D - INV | DZ | OFL | IMP | STK */
700         FPE_FLTDIV,     /* 6E - DNML | DZ | OFL | IMP | STK */
701         FPE_FLTSUB,     /* 6F - INV | DNML | DZ | OFL | IMP | STK */
702         FPE_FLTUND,     /* 70 - UFL | IMP | STK */
703         FPE_FLTSUB,     /* 71 - INV | UFL | IMP | STK */
704         FPE_FLTUND,     /* 72 - DNML | UFL | IMP | STK */
705         FPE_FLTSUB,     /* 73 - INV | DNML | UFL | IMP | STK */
706         FPE_FLTDIV,     /* 74 - DZ | UFL | IMP | STK */
707         FPE_FLTSUB,     /* 75 - INV | DZ | UFL | IMP | STK */
708         FPE_FLTDIV,     /* 76 - DNML | DZ | UFL | IMP | STK */
709         FPE_FLTSUB,     /* 77 - INV | DNML | DZ | UFL | IMP | STK */
710         FPE_FLTOVF,     /* 78 - OFL | UFL | IMP | STK */
711         FPE_FLTSUB,     /* 79 - INV | OFL | UFL | IMP | STK */
712         FPE_FLTUND,     /* 7A - DNML | OFL | UFL | IMP | STK */
713         FPE_FLTSUB,     /* 7B - INV | DNML | OFL | UFL | IMP | STK */
714         FPE_FLTDIV,     /* 7C - DZ | OFL | UFL | IMP | STK */
715         FPE_FLTSUB,     /* 7D - INV | DZ | OFL | UFL | IMP | STK */
716         FPE_FLTDIV,     /* 7E - DNML | DZ | OFL | UFL | IMP | STK */
717         FPE_FLTSUB,     /* 7F - INV | DNML | DZ | OFL | UFL | IMP | STK */
718 };
719
720 /*
721  * Preserve the FP status word, clear FP exceptions, then generate a SIGFPE.
722  *
723  * Clearing exceptions is necessary mainly to avoid IRQ13 bugs.  We now
724  * depend on longjmp() restoring a usable state.  Restoring the state
725  * or examining it might fail if we didn't clear exceptions.
726  *
727  * The error code chosen will be one of the FPE_... macros. It will be
728  * sent as the second argument to old BSD-style signal handlers and as
729  * "siginfo_t->si_code" (second argument) to SA_SIGINFO signal handlers.
730  *
731  * XXX the FP state is not preserved across signal handlers.  So signal
732  * handlers cannot afford to do FP unless they preserve the state or
733  * longjmp() out.  Both preserving the state and longjmp()ing may be
734  * destroyed by IRQ13 bugs.  Clearing FP exceptions is not an acceptable
735  * solution for signals other than SIGFPE.
736  */
737 void
738 npx_intr(dummy)
739         void *dummy;
740 {
741         int code;
742         u_short control;
743         struct intrframe *frame;
744         u_long *exstat;
745
746         if (npxthread == NULL || !npx_exists) {
747                 printf("npxintr: npxthread = %p, curthread = %p, npx_exists = %d\n",
748                        npxthread, curthread, npx_exists);
749                 panic("npxintr from nowhere");
750         }
751         if (npxthread != curthread) {
752                 printf("npxintr: npxthread = %p, curthread = %p, npx_exists = %d\n",
753                        npxthread, curthread, npx_exists);
754                 panic("npxintr from non-current process");
755         }
756
757         exstat = GET_FPU_EXSW_PTR(curpcb);
758         outb(0xf0, 0);
759         fnstsw(exstat);
760         fnstcw(&control);
761         fnclex();
762
763         /*
764          * Pass exception to process.
765          */
766         frame = (struct intrframe *)&dummy;     /* XXX */
767         if ((ISPL(frame->if_cs) == SEL_UPL) || (frame->if_eflags & PSL_VM)) {
768                 /*
769                  * Interrupt is essentially a trap, so we can afford to call
770                  * the SIGFPE handler (if any) as soon as the interrupt
771                  * returns.
772                  *
773                  * XXX little or nothing is gained from this, and plenty is
774                  * lost - the interrupt frame has to contain the trap frame
775                  * (this is otherwise only necessary for the rescheduling trap
776                  * in doreti, and the frame for that could easily be set up
777                  * just before it is used).
778                  */
779                 curproc->p_md.md_regs = INTR_TO_TRAPFRAME(frame);
780                 /*
781                  * Encode the appropriate code for detailed information on
782                  * this exception.
783                  */
784                 code = 
785                     fpetable[(*exstat & ~control & 0x3f) | (*exstat & 0x40)];
786                 trapsignal(curproc, SIGFPE, code);
787         } else {
788                 /*
789                  * Nested interrupt.  These losers occur when:
790                  *      o an IRQ13 is bogusly generated at a bogus time, e.g.:
791                  *              o immediately after an fnsave or frstor of an
792                  *                error state.
793                  *              o a couple of 386 instructions after
794                  *                "fstpl _memvar" causes a stack overflow.
795                  *        These are especially nasty when combined with a
796                  *        trace trap.
797                  *      o an IRQ13 occurs at the same time as another higher-
798                  *        priority interrupt.
799                  *
800                  * Treat them like a true async interrupt.
801                  */
802                 psignal(curproc, SIGFPE);
803         }
804 }
805
806 /*
807  * Implement device not available (DNA) exception
808  *
809  * It would be better to switch FP context here (if curthread != npxthread)
810  * and not necessarily for every context switch, but it is too hard to
811  * access foreign pcb's.
812  */
813 int
814 npxdna()
815 {
816         u_long *exstat;
817
818         if (!npx_exists)
819                 return (0);
820         if (npxthread != NULL) {
821                 printf("npxdna: npxthread = %p, curthread = %p\n",
822                        npxthread, curthread);
823                 panic("npxdna");
824         }
825         stop_emulating();
826         /*
827          * Record new context early in case frstor causes an IRQ13.
828          */
829         npxthread = curthread;
830         exstat = GET_FPU_EXSW_PTR(curpcb);
831         *exstat = 0;
832         /*
833          * The following frstor may cause an IRQ13 when the state being
834          * restored has a pending error.  The error will appear to have been
835          * triggered by the current (npx) user instruction even when that
836          * instruction is a no-wait instruction that should not trigger an
837          * error (e.g., fnclex).  On at least one 486 system all of the
838          * no-wait instructions are broken the same as frstor, so our
839          * treatment does not amplify the breakage.  On at least one
840          * 386/Cyrix 387 system, fnclex works correctly while frstor and
841          * fnsave are broken, so our treatment breaks fnclex if it is the
842          * first FPU instruction after a context switch.
843          */
844         fpurstor(&curpcb->pcb_save);
845
846         return (1);
847 }
848
849 /*
850  * Wrapper for fnsave instruction to handle h/w bugs.  If there is an error
851  * pending, then fnsave generates a bogus IRQ13 on some systems.  Force
852  * any IRQ13 to be handled immediately, and then ignore it.  This routine is
853  * often called at splhigh so it must not use many system services.  In
854  * particular, it's much easier to install a special handler than to
855  * guarantee that it's safe to use npxintr() and its supporting code.
856  */
857 void
858 npxsave(addr)
859         union savefpu *addr;
860 {
861 #if defined(SMP) || defined(CPU_ENABLE_SSE)
862
863         stop_emulating();
864         fpusave(addr);
865
866         /* fnop(); */
867         start_emulating();
868         npxthread = NULL;
869
870 #else /* SMP or CPU_ENABLE_SSE */
871
872         u_char  icu1_mask;
873         u_char  icu2_mask;
874         u_char  old_icu1_mask;
875         u_char  old_icu2_mask;
876         struct gate_descriptor  save_idt_npxintr;
877
878         disable_intr();
879         old_icu1_mask = inb(IO_ICU1 + 1);
880         old_icu2_mask = inb(IO_ICU2 + 1);
881         save_idt_npxintr = idt[npx_intrno];
882         outb(IO_ICU1 + 1, old_icu1_mask & ~(IRQ_SLAVE | npx0_imask));
883         outb(IO_ICU2 + 1, old_icu2_mask & ~(npx0_imask >> 8));
884         idt[npx_intrno] = npx_idt_probeintr;
885         enable_intr();
886         stop_emulating();
887         fnsave(addr);
888         fnop();
889         start_emulating();
890         npxthread = NULL;
891         disable_intr();
892         icu1_mask = inb(IO_ICU1 + 1);   /* masks may have changed */
893         icu2_mask = inb(IO_ICU2 + 1);
894         outb(IO_ICU1 + 1,
895              (icu1_mask & ~npx0_imask) | (old_icu1_mask & npx0_imask));
896         outb(IO_ICU2 + 1,
897              (icu2_mask & ~(npx0_imask >> 8))
898              | (old_icu2_mask & (npx0_imask >> 8)));
899         idt[npx_intrno] = save_idt_npxintr;
900         enable_intr();          /* back to usual state */
901
902 #endif /* SMP */
903 }
904
905 static void
906 fpusave(addr)
907       union savefpu *addr;
908 {
909
910 #ifdef CPU_ENABLE_SSE
911         if (cpu_fxsr)
912                 fxsave(addr);
913         else
914 #endif
915                 fnsave(addr);
916 }
917
918 static void
919 fpurstor(addr)
920       union savefpu *addr;
921 {
922
923 #ifdef CPU_ENABLE_SSE
924         if (cpu_fxsr)
925                 fxrstor(addr);
926         else
927 #endif
928                 frstor(addr);
929 }
930
931 #ifdef I586_CPU
932 static long
933 timezero(funcname, func)
934         const char *funcname;
935         void (*func) __P((void *buf, size_t len));
936
937 {
938         void *buf;
939 #define BUFSIZE         1000000
940         long usec;
941         struct timeval finish, start;
942
943         buf = malloc(BUFSIZE, M_TEMP, M_NOWAIT);
944         if (buf == NULL)
945                 return (BUFSIZE);
946         microtime(&start);
947         (*func)(buf, BUFSIZE);
948         microtime(&finish);
949         usec = 1000000 * (finish.tv_sec - start.tv_sec) +
950             finish.tv_usec - start.tv_usec;
951         if (usec <= 0)
952                 usec = 1;
953         if (bootverbose)
954                 printf("%s bandwidth = %ld bytes/sec\n",
955                     funcname, (long)(BUFSIZE * (int64_t)1000000 / usec));
956         free(buf, M_TEMP);
957         return (usec);
958 }
959 #endif /* I586_CPU */
960
961 static device_method_t npx_methods[] = {
962         /* Device interface */
963         DEVMETHOD(device_identify,      npx_identify),
964         DEVMETHOD(device_probe,         npx_probe),
965         DEVMETHOD(device_attach,        npx_attach),
966         DEVMETHOD(device_detach,        bus_generic_detach),
967         DEVMETHOD(device_shutdown,      bus_generic_shutdown),
968         DEVMETHOD(device_suspend,       bus_generic_suspend),
969         DEVMETHOD(device_resume,        bus_generic_resume),
970         
971         { 0, 0 }
972 };
973
974 static driver_t npx_driver = {
975         "npx",
976         npx_methods,
977         1,                      /* no softc */
978 };
979
980 static devclass_t npx_devclass;
981
982 /*
983  * We prefer to attach to the root nexus so that the usual case (exception 16)
984  * doesn't describe the processor as being `on isa'.
985  */
986 DRIVER_MODULE(npx, nexus, npx_driver, npx_devclass, 0, 0);