Merge branch 'vendor/OPENPAM'
[dragonfly.git] / sys / platform / vkernel / i386 / npx.c
1 /*
2  * Copyright (c) 2006 The DragonFly Project.  All rights reserved.
3  * Copyright (c) 1990 William Jolitz.
4  * Copyright (c) 1991 The Regents of the University of California.
5  * All rights reserved.
6  * 
7  * This code is derived from software contributed to The DragonFly Project
8  * by Matthew Dillon <dillon@backplane.com>
9  * 
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  * 3. Neither the name of The DragonFly Project nor the names of its
21  *    contributors may be used to endorse or promote products derived
22  *    from this software without specific, prior written permission.
23  * 
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
28  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
30  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
32  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
33  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
34  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  * 
37  * from: @(#)npx.c      7.2 (Berkeley) 5/12/91
38  * $FreeBSD: src/sys/i386/isa/npx.c,v 1.80.2.3 2001/10/20 19:04:38 tegge Exp $
39  * $DragonFly: src/sys/platform/vkernel/i386/npx.c,v 1.8 2008/01/29 19:54:56 dillon Exp $
40  */
41
42 #include "opt_debug_npx.h"
43
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/bus.h>
47 #include <sys/kernel.h>
48 #include <sys/malloc.h>
49 #include <sys/module.h>
50 #include <sys/sysctl.h>
51 #include <sys/proc.h>
52 #include <sys/rman.h>
53 #ifdef NPX_DEBUG
54 #include <sys/syslog.h>
55 #endif
56 #include <sys/signalvar.h>
57
58 #include <sys/thread2.h>
59 #include <sys/mplock2.h>
60
61 #ifndef SMP
62 #include <machine/asmacros.h>
63 #endif
64 #include <machine/cputypes.h>
65 #include <machine/frame.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 #define fldcw(addr)             __asm("fldcw %0" : : "m" (*(addr)))
77 #define fnclex()                __asm("fnclex")
78 #define fninit()                __asm("fninit")
79 #define fnop()                  __asm("fnop")
80 #define fnsave(addr)            __asm __volatile("fnsave %0" : "=m" (*(addr)))
81 #define fnstcw(addr)            __asm __volatile("fnstcw %0" : "=m" (*(addr)))
82 #define fnstsw(addr)            __asm __volatile("fnstsw %0" : "=m" (*(addr)))
83 #define frstor(addr)            __asm("frstor %0" : : "m" (*(addr)))
84 #ifndef CPU_DISABLE_SSE
85 #define fxrstor(addr)           __asm("fxrstor %0" : : "m" (*(addr)))
86 #define fxsave(addr)            __asm __volatile("fxsave %0" : "=m" (*(addr)))
87 #endif
88
89 typedef u_char bool_t;
90 #ifndef CPU_DISABLE_SSE
91 static  void    fpu_clean_state(void);
92 #endif
93
94 int cpu_fxsr = 0;
95
96 static struct krate badfprate = { 1 };
97
98 /*static        int     npx_attach      (device_t dev);*/
99 static  void    fpusave         (union savefpu *);
100 static  void    fpurstor        (union savefpu *);
101
102 #if (defined(I586_CPU) || defined(I686_CPU)) && !defined(CPU_DISABLE_SSE)
103 int mmxopt = 1;
104 SYSCTL_INT(_kern, OID_AUTO, mmxopt, CTLFLAG_RD, &mmxopt, 0,
105         "MMX/XMM optimized bcopy/copyin/copyout support");
106 #endif
107
108 static int      hw_instruction_sse;
109 SYSCTL_INT(_hw, OID_AUTO, instruction_sse, CTLFLAG_RD,
110     &hw_instruction_sse, 0, "SIMD/MMX2 instructions available in CPU");
111
112 #if 0
113 /*
114  * Attach routine - announce which it is, and wire into system
115  */
116 int
117 npx_attach(device_t dev)
118 {
119         npxinit(__INITIAL_NPXCW__);
120         return (0);
121 }
122 #endif
123
124 void
125 init_fpu(int supports_sse)
126 {
127         cpu_fxsr = hw_instruction_sse = supports_sse;
128 }
129
130 /*
131  * Initialize the floating point unit.
132  */
133 void
134 npxinit(u_short control)
135 {
136         static union savefpu dummy __aligned(16);
137
138         /*
139          * fninit has the same h/w bugs as fnsave.  Use the detoxified
140          * fnsave to throw away any junk in the fpu.  npxsave() initializes
141          * the fpu and sets npxthread = NULL as important side effects.
142          */
143         npxsave(&dummy);
144         crit_enter();
145         /*stop_emulating();*/
146         fldcw(&control);
147         fpusave(curthread->td_savefpu);
148         mdcpu->gd_npxthread = NULL;
149         /*start_emulating();*/
150         crit_exit();
151 }
152
153 /*
154  * Free coprocessor (if we have it).
155  */
156 void
157 npxexit(void)
158 {
159         if (curthread == mdcpu->gd_npxthread)
160                 npxsave(curthread->td_savefpu);
161 }
162
163 #if 0
164 /* 
165  * The following mechanism is used to ensure that the FPE_... value
166  * that is passed as a trapcode to the signal handler of the user
167  * process does not have more than one bit set.
168  * 
169  * Multiple bits may be set if the user process modifies the control
170  * word while a status word bit is already set.  While this is a sign
171  * of bad coding, we have no choise than to narrow them down to one
172  * bit, since we must not send a trapcode that is not exactly one of
173  * the FPE_ macros.
174  *
175  * The mechanism has a static table with 127 entries.  Each combination
176  * of the 7 FPU status word exception bits directly translates to a
177  * position in this table, where a single FPE_... value is stored.
178  * This FPE_... value stored there is considered the "most important"
179  * of the exception bits and will be sent as the signal code.  The
180  * precedence of the bits is based upon Intel Document "Numerical
181  * Applications", Chapter "Special Computational Situations".
182  *
183  * The macro to choose one of these values does these steps: 1) Throw
184  * away status word bits that cannot be masked.  2) Throw away the bits
185  * currently masked in the control word, assuming the user isn't
186  * interested in them anymore.  3) Reinsert status word bit 7 (stack
187  * fault) if it is set, which cannot be masked but must be presered.
188  * 4) Use the remaining bits to point into the trapcode table.
189  *
190  * The 6 maskable bits in order of their preference, as stated in the
191  * above referenced Intel manual:
192  * 1  Invalid operation (FP_X_INV)
193  * 1a   Stack underflow
194  * 1b   Stack overflow
195  * 1c   Operand of unsupported format
196  * 1d   SNaN operand.
197  * 2  QNaN operand (not an exception, irrelavant here)
198  * 3  Any other invalid-operation not mentioned above or zero divide
199  *      (FP_X_INV, FP_X_DZ)
200  * 4  Denormal operand (FP_X_DNML)
201  * 5  Numeric over/underflow (FP_X_OFL, FP_X_UFL)
202  * 6  Inexact result (FP_X_IMP) 
203  */
204 static char fpetable[128] = {
205         0,
206         FPE_FLTINV,     /*  1 - INV */
207         FPE_FLTUND,     /*  2 - DNML */
208         FPE_FLTINV,     /*  3 - INV | DNML */
209         FPE_FLTDIV,     /*  4 - DZ */
210         FPE_FLTINV,     /*  5 - INV | DZ */
211         FPE_FLTDIV,     /*  6 - DNML | DZ */
212         FPE_FLTINV,     /*  7 - INV | DNML | DZ */
213         FPE_FLTOVF,     /*  8 - OFL */
214         FPE_FLTINV,     /*  9 - INV | OFL */
215         FPE_FLTUND,     /*  A - DNML | OFL */
216         FPE_FLTINV,     /*  B - INV | DNML | OFL */
217         FPE_FLTDIV,     /*  C - DZ | OFL */
218         FPE_FLTINV,     /*  D - INV | DZ | OFL */
219         FPE_FLTDIV,     /*  E - DNML | DZ | OFL */
220         FPE_FLTINV,     /*  F - INV | DNML | DZ | OFL */
221         FPE_FLTUND,     /* 10 - UFL */
222         FPE_FLTINV,     /* 11 - INV | UFL */
223         FPE_FLTUND,     /* 12 - DNML | UFL */
224         FPE_FLTINV,     /* 13 - INV | DNML | UFL */
225         FPE_FLTDIV,     /* 14 - DZ | UFL */
226         FPE_FLTINV,     /* 15 - INV | DZ | UFL */
227         FPE_FLTDIV,     /* 16 - DNML | DZ | UFL */
228         FPE_FLTINV,     /* 17 - INV | DNML | DZ | UFL */
229         FPE_FLTOVF,     /* 18 - OFL | UFL */
230         FPE_FLTINV,     /* 19 - INV | OFL | UFL */
231         FPE_FLTUND,     /* 1A - DNML | OFL | UFL */
232         FPE_FLTINV,     /* 1B - INV | DNML | OFL | UFL */
233         FPE_FLTDIV,     /* 1C - DZ | OFL | UFL */
234         FPE_FLTINV,     /* 1D - INV | DZ | OFL | UFL */
235         FPE_FLTDIV,     /* 1E - DNML | DZ | OFL | UFL */
236         FPE_FLTINV,     /* 1F - INV | DNML | DZ | OFL | UFL */
237         FPE_FLTRES,     /* 20 - IMP */
238         FPE_FLTINV,     /* 21 - INV | IMP */
239         FPE_FLTUND,     /* 22 - DNML | IMP */
240         FPE_FLTINV,     /* 23 - INV | DNML | IMP */
241         FPE_FLTDIV,     /* 24 - DZ | IMP */
242         FPE_FLTINV,     /* 25 - INV | DZ | IMP */
243         FPE_FLTDIV,     /* 26 - DNML | DZ | IMP */
244         FPE_FLTINV,     /* 27 - INV | DNML | DZ | IMP */
245         FPE_FLTOVF,     /* 28 - OFL | IMP */
246         FPE_FLTINV,     /* 29 - INV | OFL | IMP */
247         FPE_FLTUND,     /* 2A - DNML | OFL | IMP */
248         FPE_FLTINV,     /* 2B - INV | DNML | OFL | IMP */
249         FPE_FLTDIV,     /* 2C - DZ | OFL | IMP */
250         FPE_FLTINV,     /* 2D - INV | DZ | OFL | IMP */
251         FPE_FLTDIV,     /* 2E - DNML | DZ | OFL | IMP */
252         FPE_FLTINV,     /* 2F - INV | DNML | DZ | OFL | IMP */
253         FPE_FLTUND,     /* 30 - UFL | IMP */
254         FPE_FLTINV,     /* 31 - INV | UFL | IMP */
255         FPE_FLTUND,     /* 32 - DNML | UFL | IMP */
256         FPE_FLTINV,     /* 33 - INV | DNML | UFL | IMP */
257         FPE_FLTDIV,     /* 34 - DZ | UFL | IMP */
258         FPE_FLTINV,     /* 35 - INV | DZ | UFL | IMP */
259         FPE_FLTDIV,     /* 36 - DNML | DZ | UFL | IMP */
260         FPE_FLTINV,     /* 37 - INV | DNML | DZ | UFL | IMP */
261         FPE_FLTOVF,     /* 38 - OFL | UFL | IMP */
262         FPE_FLTINV,     /* 39 - INV | OFL | UFL | IMP */
263         FPE_FLTUND,     /* 3A - DNML | OFL | UFL | IMP */
264         FPE_FLTINV,     /* 3B - INV | DNML | OFL | UFL | IMP */
265         FPE_FLTDIV,     /* 3C - DZ | OFL | UFL | IMP */
266         FPE_FLTINV,     /* 3D - INV | DZ | OFL | UFL | IMP */
267         FPE_FLTDIV,     /* 3E - DNML | DZ | OFL | UFL | IMP */
268         FPE_FLTINV,     /* 3F - INV | DNML | DZ | OFL | UFL | IMP */
269         FPE_FLTSUB,     /* 40 - STK */
270         FPE_FLTSUB,     /* 41 - INV | STK */
271         FPE_FLTUND,     /* 42 - DNML | STK */
272         FPE_FLTSUB,     /* 43 - INV | DNML | STK */
273         FPE_FLTDIV,     /* 44 - DZ | STK */
274         FPE_FLTSUB,     /* 45 - INV | DZ | STK */
275         FPE_FLTDIV,     /* 46 - DNML | DZ | STK */
276         FPE_FLTSUB,     /* 47 - INV | DNML | DZ | STK */
277         FPE_FLTOVF,     /* 48 - OFL | STK */
278         FPE_FLTSUB,     /* 49 - INV | OFL | STK */
279         FPE_FLTUND,     /* 4A - DNML | OFL | STK */
280         FPE_FLTSUB,     /* 4B - INV | DNML | OFL | STK */
281         FPE_FLTDIV,     /* 4C - DZ | OFL | STK */
282         FPE_FLTSUB,     /* 4D - INV | DZ | OFL | STK */
283         FPE_FLTDIV,     /* 4E - DNML | DZ | OFL | STK */
284         FPE_FLTSUB,     /* 4F - INV | DNML | DZ | OFL | STK */
285         FPE_FLTUND,     /* 50 - UFL | STK */
286         FPE_FLTSUB,     /* 51 - INV | UFL | STK */
287         FPE_FLTUND,     /* 52 - DNML | UFL | STK */
288         FPE_FLTSUB,     /* 53 - INV | DNML | UFL | STK */
289         FPE_FLTDIV,     /* 54 - DZ | UFL | STK */
290         FPE_FLTSUB,     /* 55 - INV | DZ | UFL | STK */
291         FPE_FLTDIV,     /* 56 - DNML | DZ | UFL | STK */
292         FPE_FLTSUB,     /* 57 - INV | DNML | DZ | UFL | STK */
293         FPE_FLTOVF,     /* 58 - OFL | UFL | STK */
294         FPE_FLTSUB,     /* 59 - INV | OFL | UFL | STK */
295         FPE_FLTUND,     /* 5A - DNML | OFL | UFL | STK */
296         FPE_FLTSUB,     /* 5B - INV | DNML | OFL | UFL | STK */
297         FPE_FLTDIV,     /* 5C - DZ | OFL | UFL | STK */
298         FPE_FLTSUB,     /* 5D - INV | DZ | OFL | UFL | STK */
299         FPE_FLTDIV,     /* 5E - DNML | DZ | OFL | UFL | STK */
300         FPE_FLTSUB,     /* 5F - INV | DNML | DZ | OFL | UFL | STK */
301         FPE_FLTRES,     /* 60 - IMP | STK */
302         FPE_FLTSUB,     /* 61 - INV | IMP | STK */
303         FPE_FLTUND,     /* 62 - DNML | IMP | STK */
304         FPE_FLTSUB,     /* 63 - INV | DNML | IMP | STK */
305         FPE_FLTDIV,     /* 64 - DZ | IMP | STK */
306         FPE_FLTSUB,     /* 65 - INV | DZ | IMP | STK */
307         FPE_FLTDIV,     /* 66 - DNML | DZ | IMP | STK */
308         FPE_FLTSUB,     /* 67 - INV | DNML | DZ | IMP | STK */
309         FPE_FLTOVF,     /* 68 - OFL | IMP | STK */
310         FPE_FLTSUB,     /* 69 - INV | OFL | IMP | STK */
311         FPE_FLTUND,     /* 6A - DNML | OFL | IMP | STK */
312         FPE_FLTSUB,     /* 6B - INV | DNML | OFL | IMP | STK */
313         FPE_FLTDIV,     /* 6C - DZ | OFL | IMP | STK */
314         FPE_FLTSUB,     /* 6D - INV | DZ | OFL | IMP | STK */
315         FPE_FLTDIV,     /* 6E - DNML | DZ | OFL | IMP | STK */
316         FPE_FLTSUB,     /* 6F - INV | DNML | DZ | OFL | IMP | STK */
317         FPE_FLTUND,     /* 70 - UFL | IMP | STK */
318         FPE_FLTSUB,     /* 71 - INV | UFL | IMP | STK */
319         FPE_FLTUND,     /* 72 - DNML | UFL | IMP | STK */
320         FPE_FLTSUB,     /* 73 - INV | DNML | UFL | IMP | STK */
321         FPE_FLTDIV,     /* 74 - DZ | UFL | IMP | STK */
322         FPE_FLTSUB,     /* 75 - INV | DZ | UFL | IMP | STK */
323         FPE_FLTDIV,     /* 76 - DNML | DZ | UFL | IMP | STK */
324         FPE_FLTSUB,     /* 77 - INV | DNML | DZ | UFL | IMP | STK */
325         FPE_FLTOVF,     /* 78 - OFL | UFL | IMP | STK */
326         FPE_FLTSUB,     /* 79 - INV | OFL | UFL | IMP | STK */
327         FPE_FLTUND,     /* 7A - DNML | OFL | UFL | IMP | STK */
328         FPE_FLTSUB,     /* 7B - INV | DNML | OFL | UFL | IMP | STK */
329         FPE_FLTDIV,     /* 7C - DZ | OFL | UFL | IMP | STK */
330         FPE_FLTSUB,     /* 7D - INV | DZ | OFL | UFL | IMP | STK */
331         FPE_FLTDIV,     /* 7E - DNML | DZ | OFL | UFL | IMP | STK */
332         FPE_FLTSUB,     /* 7F - INV | DNML | DZ | OFL | UFL | IMP | STK */
333 };
334 #endif
335
336 #if 0
337
338 /*
339  * Preserve the FP status word, clear FP exceptions, then generate a SIGFPE.
340  *
341  * Clearing exceptions is necessary mainly to avoid IRQ13 bugs.  We now
342  * depend on longjmp() restoring a usable state.  Restoring the state
343  * or examining it might fail if we didn't clear exceptions.
344  *
345  * The error code chosen will be one of the FPE_... macros. It will be
346  * sent as the second argument to old BSD-style signal handlers and as
347  * "siginfo_t->si_code" (second argument) to SA_SIGINFO signal handlers.
348  *
349  * XXX the FP state is not preserved across signal handlers.  So signal
350  * handlers cannot afford to do FP unless they preserve the state or
351  * longjmp() out.  Both preserving the state and longjmp()ing may be
352  * destroyed by IRQ13 bugs.  Clearing FP exceptions is not an acceptable
353  * solution for signals other than SIGFPE.
354  *
355  * The MP lock is not held on entry (see i386/i386/exception.s) and
356  * should not be held on exit.  Interrupts are enabled.  We must enter
357  * a critical section to stabilize the FP system and prevent an interrupt
358  * or preemption from changing the FP state out from under us.
359  */
360 void
361 npx_intr(void *dummy)
362 {
363         int code;
364         u_short control;
365         u_short status;
366         struct intrframe *frame;
367
368         crit_enter();
369
370         /*
371          * This exception can only occur with CR0_TS clear, otherwise we
372          * would get a DNA exception.  However, since interrupts were
373          * enabled a preemption could have sneaked in and used the FP system
374          * before we entered our critical section.  If that occured, the
375          * TS bit will be set and npxthread will be NULL.
376          */
377         panic("npx_intr: not coded");
378         /* XXX FP STATE FLAG MUST BE PART OF CONTEXT SUPPLIED BY REAL KERNEL */
379 #if 0
380         if (rcr0() & CR0_TS) {
381                 KASSERT(mdcpu->gd_npxthread == NULL, ("gd_npxthread was %p with TS set!", mdcpu->gd_npxthread));
382                 npxdna();
383                 crit_exit();
384                 return;
385         }
386 #endif
387         if (mdcpu->gd_npxthread == NULL) {
388                 get_mplock();
389                 kprintf("npxintr: npxthread = %p, curthread = %p\n",
390                        mdcpu->gd_npxthread, curthread);
391                 panic("npxintr from nowhere");
392         }
393         if (mdcpu->gd_npxthread != curthread) {
394                 get_mplock();
395                 kprintf("npxintr: npxthread = %p, curthread = %p\n",
396                        mdcpu->gd_npxthread, curthread);
397                 panic("npxintr from non-current process");
398         }
399
400         outb(0xf0, 0);
401         fnstsw(&status);
402         fnstcw(&control);
403         fnclex();
404
405         get_mplock();
406
407         /*
408          * Pass exception to process.
409          */
410         frame = (struct intrframe *)&dummy;     /* XXX */
411         if ((ISPL(frame->if_cs) == SEL_UPL) /*||(frame->if_eflags&PSL_VM)*/) {
412                 /*
413                  * Interrupt is essentially a trap, so we can afford to call
414                  * the SIGFPE handler (if any) as soon as the interrupt
415                  * returns.
416                  *
417                  * XXX little or nothing is gained from this, and plenty is
418                  * lost - the interrupt frame has to contain the trap frame
419                  * (this is otherwise only necessary for the rescheduling trap
420                  * in doreti, and the frame for that could easily be set up
421                  * just before it is used).
422                  */
423                 curthread->td_lwp->lwp_md.md_regs = INTR_TO_TRAPFRAME(frame);
424                 /*
425                  * Encode the appropriate code for detailed information on
426                  * this exception.
427                  */
428                 code = 
429                     fpetable[(status & ~control & 0x3f) | (status & 0x40)];
430                 trapsignal(curthread->td_lwp, SIGFPE, code);
431         } else {
432                 /*
433                  * Nested interrupt.  These losers occur when:
434                  *      o an IRQ13 is bogusly generated at a bogus time, e.g.:
435                  *              o immediately after an fnsave or frstor of an
436                  *                error state.
437                  *              o a couple of 386 instructions after
438                  *                "fstpl _memvar" causes a stack overflow.
439                  *        These are especially nasty when combined with a
440                  *        trace trap.
441                  *      o an IRQ13 occurs at the same time as another higher-
442                  *        priority interrupt.
443                  *
444                  * Treat them like a true async interrupt.
445                  */
446                 lwpsignal(curproc, curthread->td_lwp, SIGFPE);
447         }
448         rel_mplock();
449         crit_exit();
450 }
451
452 #endif
453
454 /*
455  * Implement the device not available (DNA) exception.  gd_npxthread had 
456  * better be NULL.  Restore the current thread's FP state and set gd_npxthread
457  * to curthread.
458  *
459  * Interrupts are enabled and preemption can occur.  Enter a critical
460  * section to stabilize the FP state.
461  */
462 int
463 npxdna(struct trapframe *frame)
464 {
465         thread_t td = curthread;
466         int didinit = 0;
467
468         if (mdcpu->gd_npxthread != NULL) {
469                 kprintf("npxdna: npxthread = %p, curthread = %p\n",
470                        mdcpu->gd_npxthread, td);
471                 panic("npxdna");
472         }
473
474         /*
475          * Setup the initial saved state if the thread has never before
476          * used the FP unit.  This also occurs when a thread pushes a
477          * signal handler and uses FP in the handler.
478          */
479         if ((curthread->td_flags & TDF_USINGFP) == 0) {
480                 curthread->td_flags |= TDF_USINGFP;
481                 npxinit(__INITIAL_NPXCW__);
482                 didinit = 1;
483         }
484
485         /*
486          * The setting of gd_npxthread and the call to fpurstor() must not
487          * be preempted by an interrupt thread or we will take an npxdna
488          * trap and potentially save our current fpstate (which is garbage)
489          * and then restore the garbage rather then the originally saved
490          * fpstate.
491          */
492         crit_enter();
493         /*stop_emulating();*/
494         /*
495          * Record new context early in case frstor causes an IRQ13.
496          */
497         mdcpu->gd_npxthread = td;
498         /*
499          * The following frstor may cause an IRQ13 when the state being
500          * restored has a pending error.  The error will appear to have been
501          * triggered by the current (npx) user instruction even when that
502          * instruction is a no-wait instruction that should not trigger an
503          * error (e.g., fnclex).  On at least one 486 system all of the
504          * no-wait instructions are broken the same as frstor, so our
505          * treatment does not amplify the breakage.  On at least one
506          * 386/Cyrix 387 system, fnclex works correctly while frstor and
507          * fnsave are broken, so our treatment breaks fnclex if it is the
508          * first FPU instruction after a context switch.
509          */
510         if ((td->td_savefpu->sv_xmm.sv_env.en_mxcsr & ~0xFFBF) && cpu_fxsr) {
511                 krateprintf(&badfprate,
512                             "FXRSTR: illegal FP MXCSR %08x didinit = %d\n",
513                             td->td_savefpu->sv_xmm.sv_env.en_mxcsr, didinit);
514                 td->td_savefpu->sv_xmm.sv_env.en_mxcsr &= 0xFFBF;
515                 lwpsignal(curproc, curthread->td_lwp, SIGFPE);
516         }
517         fpurstor(curthread->td_savefpu);
518         crit_exit();
519
520         return (1);
521 }
522
523 /*
524  * Wrapper for the fnsave instruction to handle h/w bugs.  If there is an error
525  * pending, then fnsave generates a bogus IRQ13 on some systems.  Force
526  * any IRQ13 to be handled immediately, and then ignore it.  This routine is
527  * often called at splhigh so it must not use many system services.  In
528  * particular, it's much easier to install a special handler than to
529  * guarantee that it's safe to use npxintr() and its supporting code.
530  *
531  * WARNING!  This call is made during a switch and the MP lock will be
532  * setup for the new target thread rather then the current thread, so we
533  * cannot do anything here that depends on the *_mplock() functions as
534  * we may trip over their assertions.
535  *
536  * WARNING!  When using fxsave we MUST fninit after saving the FP state.  The
537  * kernel will always assume that the FP state is 'safe' (will not cause
538  * exceptions) for mmx/xmm use if npxthread is NULL.  The kernel must still
539  * setup a custom save area before actually using the FP unit, but it will
540  * not bother calling fninit.  This greatly improves kernel performance when
541  * it wishes to use the FP unit.
542  */
543 void
544 npxsave(union savefpu *addr)
545 {
546         crit_enter();
547         /*stop_emulating();*/
548         fpusave(addr);
549         mdcpu->gd_npxthread = NULL;
550         fninit();
551         /*start_emulating();*/
552         crit_exit();
553 }
554
555 static void
556 fpusave(union savefpu *addr)
557 {
558         if (cpu_fxsr)
559                 fxsave(addr);
560         else
561                 fnsave(addr);
562 }
563
564 /*
565  * Save the FP state to the mcontext structure.
566  *
567  * WARNING: If you want to try to npxsave() directly to mctx->mc_fpregs,
568  * then it MUST be 16-byte aligned.  Currently this is not guarenteed.
569  */
570 void
571 npxpush(mcontext_t *mctx)
572 {
573         thread_t td = curthread;
574
575         if (td->td_flags & TDF_USINGFP) {
576                 if (mdcpu->gd_npxthread == td) {
577                         /*
578                          * XXX Note: This is a bit inefficient if the signal
579                          * handler uses floating point, extra faults will
580                          * occur.
581                          */
582                         mctx->mc_ownedfp = _MC_FPOWNED_FPU;
583                         npxsave(td->td_savefpu);
584                 } else {
585                         mctx->mc_ownedfp = _MC_FPOWNED_PCB;
586                 }
587                 bcopy(td->td_savefpu, mctx->mc_fpregs, sizeof(mctx->mc_fpregs));
588                 td->td_flags &= ~TDF_USINGFP;
589                 mctx->mc_fpformat =
590 #ifndef CPU_DISABLE_SSE
591                         (cpu_fxsr) ? _MC_FPFMT_XMM :
592 #endif
593                         _MC_FPFMT_387;
594         } else {
595                 mctx->mc_ownedfp = _MC_FPOWNED_NONE;
596                 mctx->mc_fpformat = _MC_FPFMT_NODEV;
597         }
598 }
599
600 /*
601  * Restore the FP state from the mcontext structure.
602  */
603 void
604 npxpop(mcontext_t *mctx)
605 {
606         thread_t td = curthread;
607
608         switch(mctx->mc_ownedfp) {
609         case _MC_FPOWNED_NONE:
610                 /*
611                  * If the signal handler used the FP unit but the interrupted
612                  * code did not, release the FP unit.  Clear TDF_USINGFP will
613                  * force the FP unit to reinit so the interrupted code sees
614                  * a clean slate.
615                  */
616                 if (td->td_flags & TDF_USINGFP) {
617                         if (td == mdcpu->gd_npxthread)
618                                 npxsave(td->td_savefpu);
619                         td->td_flags &= ~TDF_USINGFP;
620                 }
621                 break;
622         case _MC_FPOWNED_FPU:
623         case _MC_FPOWNED_PCB:
624                 /*
625                  * Clear ownership of the FP unit and restore our saved state.
626                  *
627                  * NOTE: The signal handler may have set-up some FP state and
628                  * enabled the FP unit, so we have to restore no matter what.
629                  *
630                  * XXX: This is bit inefficient, if the code being returned
631                  * to is actively using the FP this results in multiple
632                  * kernel faults.
633                  *
634                  * WARNING: The saved state was exposed to userland and may
635                  * have to be sanitized to avoid a GP fault in the kernel.
636                  */
637                 if (td == mdcpu->gd_npxthread)
638                         npxsave(td->td_savefpu);
639                 bcopy(mctx->mc_fpregs, td->td_savefpu, sizeof(*td->td_savefpu));
640                 if ((td->td_savefpu->sv_xmm.sv_env.en_mxcsr & ~0xFFBF) &&
641                     cpu_fxsr) {
642                         krateprintf(&badfprate,
643                                     "pid %d (%s) signal return from user: "
644                                     "illegal FP MXCSR %08x\n",
645                                     td->td_proc->p_pid,
646                                     td->td_proc->p_comm,
647                                     td->td_savefpu->sv_xmm.sv_env.en_mxcsr);
648                         td->td_savefpu->sv_xmm.sv_env.en_mxcsr &= 0xFFBF;
649                 }
650                 td->td_flags |= TDF_USINGFP;
651                 break;
652         }
653 }
654
655
656 #ifndef CPU_DISABLE_SSE
657 /*
658  * On AuthenticAMD processors, the fxrstor instruction does not restore
659  * the x87's stored last instruction pointer, last data pointer, and last
660  * opcode values, except in the rare case in which the exception summary
661  * (ES) bit in the x87 status word is set to 1.
662  *
663  * In order to avoid leaking this information across processes, we clean
664  * these values by performing a dummy load before executing fxrstor().
665  */
666 static  double  dummy_variable = 0.0;
667 static void
668 fpu_clean_state(void)
669 {
670         u_short status;
671
672         /*
673          * Clear the ES bit in the x87 status word if it is currently
674          * set, in order to avoid causing a fault in the upcoming load.
675          */
676         fnstsw(&status);
677         if (status & 0x80)
678                 fnclex();
679
680         /*
681          * Load the dummy variable into the x87 stack.  This mangles
682          * the x87 stack, but we don't care since we're about to call
683          * fxrstor() anyway.
684          */
685         __asm __volatile("ffree %%st(7); fld %0" : : "m" (dummy_variable));
686 }
687 #endif /* CPU_DISABLE_SSE */
688
689 static void
690 fpurstor(union savefpu *addr)
691 {
692 #ifndef CPU_DISABLE_SSE
693         if (cpu_fxsr) {
694                 fpu_clean_state();
695                 fxrstor(addr);
696         } else {
697                 frstor(addr);
698         }
699 #else
700         frstor(addr);
701 #endif
702 }
703