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