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