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