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