Get most of the VKERNEL pmap handling code in.
[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.1 2007/01/02 04:24:25 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 #include <sys/thread2.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/md_var.h>
65 #include <machine/pcb.h>
66 #include <machine/psl.h>
67 #ifndef SMP
68 #include <machine/clock.h>
69 #endif
70 #include <machine/specialreg.h>
71 #include <machine/segments.h>
72 #include <machine/globaldata.h>
73
74 #define fldcw(addr)             __asm("fldcw %0" : : "m" (*(addr)))
75 #define fnclex()                __asm("fnclex")
76 #define fninit()                __asm("fninit")
77 #define fnop()                  __asm("fnop")
78 #define fnsave(addr)            __asm __volatile("fnsave %0" : "=m" (*(addr)))
79 #define fnstcw(addr)            __asm __volatile("fnstcw %0" : "=m" (*(addr)))
80 #define fnstsw(addr)            __asm __volatile("fnstsw %0" : "=m" (*(addr)))
81 #define frstor(addr)            __asm("frstor %0" : : "m" (*(addr)))
82 #ifndef CPU_DISABLE_SSE
83 #define fxrstor(addr)           __asm("fxrstor %0" : : "m" (*(addr)))
84 #define fxsave(addr)            __asm __volatile("fxsave %0" : "=m" (*(addr)))
85 #endif
86
87 #ifndef CPU_DISABLE_SSE
88 #define GET_FPU_EXSW_PTR(td) \
89         (cpu_fxsr ? \
90                 &(td)->td_savefpu->sv_xmm.sv_ex_sw : \
91                 &(td)->td_savefpu->sv_87.sv_ex_sw)
92 #else /* CPU_DISABLE_SSE */
93 #define GET_FPU_EXSW_PTR(td) \
94         (&(td)->td_savefpu->sv_87.sv_ex_sw)
95 #endif /* CPU_DISABLE_SSE */
96
97 typedef u_char bool_t;
98 #ifndef CPU_DISABLE_SSE
99 static  void    fpu_clean_state(void);
100 #endif
101
102 int cpu_fxsr = 0;
103
104 static  int     npx_attach      (device_t dev);
105         void    npx_intr        (void *);
106 static  void    fpusave         (union savefpu *);
107 static  void    fpurstor        (union savefpu *);
108
109 #if (defined(I586_CPU) || defined(I686_CPU)) && !defined(CPU_DISABLE_SSE)
110 int mmxopt = 1;
111 SYSCTL_INT(_kern, OID_AUTO, mmxopt, CTLFLAG_RD, &mmxopt, 0,
112         "MMX/XMM optimized bcopy/copyin/copyout support");
113 #endif
114
115 /*
116  * Attach routine - announce which it is, and wire into system
117  */
118 int
119 npx_attach(device_t dev)
120 {
121         npxinit(__INITIAL_NPXCW__);
122         return (0);
123 }
124
125 /*
126  * Initialize the floating point unit.
127  */
128 void
129 npxinit(u_short control)
130 {
131         static union savefpu dummy;
132
133         /*
134          * fninit has the same h/w bugs as fnsave.  Use the detoxified
135          * fnsave to throw away any junk in the fpu.  npxsave() initializes
136          * the fpu and sets npxthread = NULL as important side effects.
137          */
138         npxsave(&dummy);
139         crit_enter();
140         /*stop_emulating();*/
141         fldcw(&control);
142         fpusave(curthread->td_savefpu);
143         mdcpu->gd_npxthread = NULL;
144         /*start_emulating();*/
145         crit_exit();
146 }
147
148 /*
149  * Free coprocessor (if we have it).
150  */
151 void
152 npxexit(void)
153 {
154         if (curthread == mdcpu->gd_npxthread)
155                 npxsave(curthread->td_savefpu);
156 }
157
158 /* 
159  * The following mechanism is used to ensure that the FPE_... value
160  * that is passed as a trapcode to the signal handler of the user
161  * process does not have more than one bit set.
162  * 
163  * Multiple bits may be set if the user process modifies the control
164  * word while a status word bit is already set.  While this is a sign
165  * of bad coding, we have no choise than to narrow them down to one
166  * bit, since we must not send a trapcode that is not exactly one of
167  * the FPE_ macros.
168  *
169  * The mechanism has a static table with 127 entries.  Each combination
170  * of the 7 FPU status word exception bits directly translates to a
171  * position in this table, where a single FPE_... value is stored.
172  * This FPE_... value stored there is considered the "most important"
173  * of the exception bits and will be sent as the signal code.  The
174  * precedence of the bits is based upon Intel Document "Numerical
175  * Applications", Chapter "Special Computational Situations".
176  *
177  * The macro to choose one of these values does these steps: 1) Throw
178  * away status word bits that cannot be masked.  2) Throw away the bits
179  * currently masked in the control word, assuming the user isn't
180  * interested in them anymore.  3) Reinsert status word bit 7 (stack
181  * fault) if it is set, which cannot be masked but must be presered.
182  * 4) Use the remaining bits to point into the trapcode table.
183  *
184  * The 6 maskable bits in order of their preference, as stated in the
185  * above referenced Intel manual:
186  * 1  Invalid operation (FP_X_INV)
187  * 1a   Stack underflow
188  * 1b   Stack overflow
189  * 1c   Operand of unsupported format
190  * 1d   SNaN operand.
191  * 2  QNaN operand (not an exception, irrelavant here)
192  * 3  Any other invalid-operation not mentioned above or zero divide
193  *      (FP_X_INV, FP_X_DZ)
194  * 4  Denormal operand (FP_X_DNML)
195  * 5  Numeric over/underflow (FP_X_OFL, FP_X_UFL)
196  * 6  Inexact result (FP_X_IMP) 
197  */
198 static char fpetable[128] = {
199         0,
200         FPE_FLTINV,     /*  1 - INV */
201         FPE_FLTUND,     /*  2 - DNML */
202         FPE_FLTINV,     /*  3 - INV | DNML */
203         FPE_FLTDIV,     /*  4 - DZ */
204         FPE_FLTINV,     /*  5 - INV | DZ */
205         FPE_FLTDIV,     /*  6 - DNML | DZ */
206         FPE_FLTINV,     /*  7 - INV | DNML | DZ */
207         FPE_FLTOVF,     /*  8 - OFL */
208         FPE_FLTINV,     /*  9 - INV | OFL */
209         FPE_FLTUND,     /*  A - DNML | OFL */
210         FPE_FLTINV,     /*  B - INV | DNML | OFL */
211         FPE_FLTDIV,     /*  C - DZ | OFL */
212         FPE_FLTINV,     /*  D - INV | DZ | OFL */
213         FPE_FLTDIV,     /*  E - DNML | DZ | OFL */
214         FPE_FLTINV,     /*  F - INV | DNML | DZ | OFL */
215         FPE_FLTUND,     /* 10 - UFL */
216         FPE_FLTINV,     /* 11 - INV | UFL */
217         FPE_FLTUND,     /* 12 - DNML | UFL */
218         FPE_FLTINV,     /* 13 - INV | DNML | UFL */
219         FPE_FLTDIV,     /* 14 - DZ | UFL */
220         FPE_FLTINV,     /* 15 - INV | DZ | UFL */
221         FPE_FLTDIV,     /* 16 - DNML | DZ | UFL */
222         FPE_FLTINV,     /* 17 - INV | DNML | DZ | UFL */
223         FPE_FLTOVF,     /* 18 - OFL | UFL */
224         FPE_FLTINV,     /* 19 - INV | OFL | UFL */
225         FPE_FLTUND,     /* 1A - DNML | OFL | UFL */
226         FPE_FLTINV,     /* 1B - INV | DNML | OFL | UFL */
227         FPE_FLTDIV,     /* 1C - DZ | OFL | UFL */
228         FPE_FLTINV,     /* 1D - INV | DZ | OFL | UFL */
229         FPE_FLTDIV,     /* 1E - DNML | DZ | OFL | UFL */
230         FPE_FLTINV,     /* 1F - INV | DNML | DZ | OFL | UFL */
231         FPE_FLTRES,     /* 20 - IMP */
232         FPE_FLTINV,     /* 21 - INV | IMP */
233         FPE_FLTUND,     /* 22 - DNML | IMP */
234         FPE_FLTINV,     /* 23 - INV | DNML | IMP */
235         FPE_FLTDIV,     /* 24 - DZ | IMP */
236         FPE_FLTINV,     /* 25 - INV | DZ | IMP */
237         FPE_FLTDIV,     /* 26 - DNML | DZ | IMP */
238         FPE_FLTINV,     /* 27 - INV | DNML | DZ | IMP */
239         FPE_FLTOVF,     /* 28 - OFL | IMP */
240         FPE_FLTINV,     /* 29 - INV | OFL | IMP */
241         FPE_FLTUND,     /* 2A - DNML | OFL | IMP */
242         FPE_FLTINV,     /* 2B - INV | DNML | OFL | IMP */
243         FPE_FLTDIV,     /* 2C - DZ | OFL | IMP */
244         FPE_FLTINV,     /* 2D - INV | DZ | OFL | IMP */
245         FPE_FLTDIV,     /* 2E - DNML | DZ | OFL | IMP */
246         FPE_FLTINV,     /* 2F - INV | DNML | DZ | OFL | IMP */
247         FPE_FLTUND,     /* 30 - UFL | IMP */
248         FPE_FLTINV,     /* 31 - INV | UFL | IMP */
249         FPE_FLTUND,     /* 32 - DNML | UFL | IMP */
250         FPE_FLTINV,     /* 33 - INV | DNML | UFL | IMP */
251         FPE_FLTDIV,     /* 34 - DZ | UFL | IMP */
252         FPE_FLTINV,     /* 35 - INV | DZ | UFL | IMP */
253         FPE_FLTDIV,     /* 36 - DNML | DZ | UFL | IMP */
254         FPE_FLTINV,     /* 37 - INV | DNML | DZ | UFL | IMP */
255         FPE_FLTOVF,     /* 38 - OFL | UFL | IMP */
256         FPE_FLTINV,     /* 39 - INV | OFL | UFL | IMP */
257         FPE_FLTUND,     /* 3A - DNML | OFL | UFL | IMP */
258         FPE_FLTINV,     /* 3B - INV | DNML | OFL | UFL | IMP */
259         FPE_FLTDIV,     /* 3C - DZ | OFL | UFL | IMP */
260         FPE_FLTINV,     /* 3D - INV | DZ | OFL | UFL | IMP */
261         FPE_FLTDIV,     /* 3E - DNML | DZ | OFL | UFL | IMP */
262         FPE_FLTINV,     /* 3F - INV | DNML | DZ | OFL | UFL | IMP */
263         FPE_FLTSUB,     /* 40 - STK */
264         FPE_FLTSUB,     /* 41 - INV | STK */
265         FPE_FLTUND,     /* 42 - DNML | STK */
266         FPE_FLTSUB,     /* 43 - INV | DNML | STK */
267         FPE_FLTDIV,     /* 44 - DZ | STK */
268         FPE_FLTSUB,     /* 45 - INV | DZ | STK */
269         FPE_FLTDIV,     /* 46 - DNML | DZ | STK */
270         FPE_FLTSUB,     /* 47 - INV | DNML | DZ | STK */
271         FPE_FLTOVF,     /* 48 - OFL | STK */
272         FPE_FLTSUB,     /* 49 - INV | OFL | STK */
273         FPE_FLTUND,     /* 4A - DNML | OFL | STK */
274         FPE_FLTSUB,     /* 4B - INV | DNML | OFL | STK */
275         FPE_FLTDIV,     /* 4C - DZ | OFL | STK */
276         FPE_FLTSUB,     /* 4D - INV | DZ | OFL | STK */
277         FPE_FLTDIV,     /* 4E - DNML | DZ | OFL | STK */
278         FPE_FLTSUB,     /* 4F - INV | DNML | DZ | OFL | STK */
279         FPE_FLTUND,     /* 50 - UFL | STK */
280         FPE_FLTSUB,     /* 51 - INV | UFL | STK */
281         FPE_FLTUND,     /* 52 - DNML | UFL | STK */
282         FPE_FLTSUB,     /* 53 - INV | DNML | UFL | STK */
283         FPE_FLTDIV,     /* 54 - DZ | UFL | STK */
284         FPE_FLTSUB,     /* 55 - INV | DZ | UFL | STK */
285         FPE_FLTDIV,     /* 56 - DNML | DZ | UFL | STK */
286         FPE_FLTSUB,     /* 57 - INV | DNML | DZ | UFL | STK */
287         FPE_FLTOVF,     /* 58 - OFL | UFL | STK */
288         FPE_FLTSUB,     /* 59 - INV | OFL | UFL | STK */
289         FPE_FLTUND,     /* 5A - DNML | OFL | UFL | STK */
290         FPE_FLTSUB,     /* 5B - INV | DNML | OFL | UFL | STK */
291         FPE_FLTDIV,     /* 5C - DZ | OFL | UFL | STK */
292         FPE_FLTSUB,     /* 5D - INV | DZ | OFL | UFL | STK */
293         FPE_FLTDIV,     /* 5E - DNML | DZ | OFL | UFL | STK */
294         FPE_FLTSUB,     /* 5F - INV | DNML | DZ | OFL | UFL | STK */
295         FPE_FLTRES,     /* 60 - IMP | STK */
296         FPE_FLTSUB,     /* 61 - INV | IMP | STK */
297         FPE_FLTUND,     /* 62 - DNML | IMP | STK */
298         FPE_FLTSUB,     /* 63 - INV | DNML | IMP | STK */
299         FPE_FLTDIV,     /* 64 - DZ | IMP | STK */
300         FPE_FLTSUB,     /* 65 - INV | DZ | IMP | STK */
301         FPE_FLTDIV,     /* 66 - DNML | DZ | IMP | STK */
302         FPE_FLTSUB,     /* 67 - INV | DNML | DZ | IMP | STK */
303         FPE_FLTOVF,     /* 68 - OFL | IMP | STK */
304         FPE_FLTSUB,     /* 69 - INV | OFL | IMP | STK */
305         FPE_FLTUND,     /* 6A - DNML | OFL | IMP | STK */
306         FPE_FLTSUB,     /* 6B - INV | DNML | OFL | IMP | STK */
307         FPE_FLTDIV,     /* 6C - DZ | OFL | IMP | STK */
308         FPE_FLTSUB,     /* 6D - INV | DZ | OFL | IMP | STK */
309         FPE_FLTDIV,     /* 6E - DNML | DZ | OFL | IMP | STK */
310         FPE_FLTSUB,     /* 6F - INV | DNML | DZ | OFL | IMP | STK */
311         FPE_FLTUND,     /* 70 - UFL | IMP | STK */
312         FPE_FLTSUB,     /* 71 - INV | UFL | IMP | STK */
313         FPE_FLTUND,     /* 72 - DNML | UFL | IMP | STK */
314         FPE_FLTSUB,     /* 73 - INV | DNML | UFL | IMP | STK */
315         FPE_FLTDIV,     /* 74 - DZ | UFL | IMP | STK */
316         FPE_FLTSUB,     /* 75 - INV | DZ | UFL | IMP | STK */
317         FPE_FLTDIV,     /* 76 - DNML | DZ | UFL | IMP | STK */
318         FPE_FLTSUB,     /* 77 - INV | DNML | DZ | UFL | IMP | STK */
319         FPE_FLTOVF,     /* 78 - OFL | UFL | IMP | STK */
320         FPE_FLTSUB,     /* 79 - INV | OFL | UFL | IMP | STK */
321         FPE_FLTUND,     /* 7A - DNML | OFL | UFL | IMP | STK */
322         FPE_FLTSUB,     /* 7B - INV | DNML | OFL | UFL | IMP | STK */
323         FPE_FLTDIV,     /* 7C - DZ | OFL | UFL | IMP | STK */
324         FPE_FLTSUB,     /* 7D - INV | DZ | OFL | UFL | IMP | STK */
325         FPE_FLTDIV,     /* 7E - DNML | DZ | OFL | UFL | IMP | STK */
326         FPE_FLTSUB,     /* 7F - INV | DNML | DZ | OFL | UFL | IMP | STK */
327 };
328
329 /*
330  * Preserve the FP status word, clear FP exceptions, then generate a SIGFPE.
331  *
332  * Clearing exceptions is necessary mainly to avoid IRQ13 bugs.  We now
333  * depend on longjmp() restoring a usable state.  Restoring the state
334  * or examining it might fail if we didn't clear exceptions.
335  *
336  * The error code chosen will be one of the FPE_... macros. It will be
337  * sent as the second argument to old BSD-style signal handlers and as
338  * "siginfo_t->si_code" (second argument) to SA_SIGINFO signal handlers.
339  *
340  * XXX the FP state is not preserved across signal handlers.  So signal
341  * handlers cannot afford to do FP unless they preserve the state or
342  * longjmp() out.  Both preserving the state and longjmp()ing may be
343  * destroyed by IRQ13 bugs.  Clearing FP exceptions is not an acceptable
344  * solution for signals other than SIGFPE.
345  *
346  * The MP lock is not held on entry (see i386/i386/exception.s) and
347  * should not be held on exit.  Interrupts are enabled.  We must enter
348  * a critical section to stabilize the FP system and prevent an interrupt
349  * or preemption from changing the FP state out from under us.
350  */
351 void
352 npx_intr(void *dummy)
353 {
354         int code;
355         u_short control;
356         struct intrframe *frame;
357         u_long *exstat;
358
359         crit_enter();
360
361         /*
362          * This exception can only occur with CR0_TS clear, otherwise we
363          * would get a DNA exception.  However, since interrupts were
364          * enabled a preemption could have sneaked in and used the FP system
365          * before we entered our critical section.  If that occured, the
366          * TS bit will be set and npxthread will be NULL.
367          */
368         if (rcr0() & CR0_TS) {
369                 KASSERT(mdcpu->gd_npxthread == NULL, ("gd_npxthread was %p with TS set!", mdcpu->gd_npxthread));
370                 npxdna();
371                 crit_exit();
372                 return;
373         }
374         if (mdcpu->gd_npxthread == NULL) {
375                 get_mplock();
376                 kprintf("npxintr: npxthread = %p, curthread = %p\n",
377                        mdcpu->gd_npxthread, curthread);
378                 panic("npxintr from nowhere");
379         }
380         if (mdcpu->gd_npxthread != curthread) {
381                 get_mplock();
382                 kprintf("npxintr: npxthread = %p, curthread = %p\n",
383                        mdcpu->gd_npxthread, curthread);
384                 panic("npxintr from non-current process");
385         }
386
387         exstat = GET_FPU_EXSW_PTR(curthread);
388         outb(0xf0, 0);
389         fnstsw(exstat);
390         fnstcw(&control);
391         fnclex();
392
393         get_mplock();
394
395         /*
396          * Pass exception to process.
397          */
398         frame = (struct intrframe *)&dummy;     /* XXX */
399         if ((ISPL(frame->if_cs) == SEL_UPL) || (frame->if_eflags & PSL_VM)) {
400                 /*
401                  * Interrupt is essentially a trap, so we can afford to call
402                  * the SIGFPE handler (if any) as soon as the interrupt
403                  * returns.
404                  *
405                  * XXX little or nothing is gained from this, and plenty is
406                  * lost - the interrupt frame has to contain the trap frame
407                  * (this is otherwise only necessary for the rescheduling trap
408                  * in doreti, and the frame for that could easily be set up
409                  * just before it is used).
410                  */
411                 curproc->p_md.md_regs = INTR_TO_TRAPFRAME(frame);
412                 /*
413                  * Encode the appropriate code for detailed information on
414                  * this exception.
415                  */
416                 code = 
417                     fpetable[(*exstat & ~control & 0x3f) | (*exstat & 0x40)];
418                 trapsignal(curproc, SIGFPE, code);
419         } else {
420                 /*
421                  * Nested interrupt.  These losers occur when:
422                  *      o an IRQ13 is bogusly generated at a bogus time, e.g.:
423                  *              o immediately after an fnsave or frstor of an
424                  *                error state.
425                  *              o a couple of 386 instructions after
426                  *                "fstpl _memvar" causes a stack overflow.
427                  *        These are especially nasty when combined with a
428                  *        trace trap.
429                  *      o an IRQ13 occurs at the same time as another higher-
430                  *        priority interrupt.
431                  *
432                  * Treat them like a true async interrupt.
433                  */
434                 ksignal(curproc, SIGFPE);
435         }
436         rel_mplock();
437         crit_exit();
438 }
439
440 /*
441  * Implement the device not available (DNA) exception.  gd_npxthread had 
442  * better be NULL.  Restore the current thread's FP state and set gd_npxthread
443  * to curthread.
444  *
445  * Interrupts are enabled and preemption can occur.  Enter a critical
446  * section to stabilize the FP state.
447  */
448 int
449 npxdna(void)
450 {
451         u_long *exstat;
452
453         if (mdcpu->gd_npxthread != NULL) {
454                 kprintf("npxdna: npxthread = %p, curthread = %p\n",
455                        mdcpu->gd_npxthread, curthread);
456                 panic("npxdna");
457         }
458         /*
459          * The setting of gd_npxthread and the call to fpurstor() must not
460          * be preempted by an interrupt thread or we will take an npxdna
461          * trap and potentially save our current fpstate (which is garbage)
462          * and then restore the garbage rather then the originally saved
463          * fpstate.
464          */
465         crit_enter();
466         /*stop_emulating();*/
467         /*
468          * Record new context early in case frstor causes an IRQ13.
469          */
470         mdcpu->gd_npxthread = curthread;
471         exstat = GET_FPU_EXSW_PTR(curthread);
472         *exstat = 0;
473         /*
474          * The following frstor may cause an IRQ13 when the state being
475          * restored has a pending error.  The error will appear to have been
476          * triggered by the current (npx) user instruction even when that
477          * instruction is a no-wait instruction that should not trigger an
478          * error (e.g., fnclex).  On at least one 486 system all of the
479          * no-wait instructions are broken the same as frstor, so our
480          * treatment does not amplify the breakage.  On at least one
481          * 386/Cyrix 387 system, fnclex works correctly while frstor and
482          * fnsave are broken, so our treatment breaks fnclex if it is the
483          * first FPU instruction after a context switch.
484          */
485         fpurstor(curthread->td_savefpu);
486         crit_exit();
487
488         return (1);
489 }
490
491 /*
492  * Wrapper for the fnsave instruction to handle h/w bugs.  If there is an error
493  * pending, then fnsave generates a bogus IRQ13 on some systems.  Force
494  * any IRQ13 to be handled immediately, and then ignore it.  This routine is
495  * often called at splhigh so it must not use many system services.  In
496  * particular, it's much easier to install a special handler than to
497  * guarantee that it's safe to use npxintr() and its supporting code.
498  *
499  * WARNING!  This call is made during a switch and the MP lock will be
500  * setup for the new target thread rather then the current thread, so we
501  * cannot do anything here that depends on the *_mplock() functions as
502  * we may trip over their assertions.
503  *
504  * WARNING!  When using fxsave we MUST fninit after saving the FP state.  The
505  * kernel will always assume that the FP state is 'safe' (will not cause
506  * exceptions) for mmx/xmm use if npxthread is NULL.  The kernel must still
507  * setup a custom save area before actually using the FP unit, but it will
508  * not bother calling fninit.  This greatly improves kernel performance when
509  * it wishes to use the FP unit.
510  */
511 void
512 npxsave(union savefpu *addr)
513 {
514         crit_enter();
515         /*stop_emulating();*/
516         fpusave(addr);
517         mdcpu->gd_npxthread = NULL;
518         fninit();
519         /*start_emulating();*/
520         crit_exit();
521 }
522
523 static void
524 fpusave(union savefpu *addr)
525 {
526         if (cpu_fxsr)
527                 fxsave(addr);
528         else
529                 fnsave(addr);
530 }
531
532 #ifndef CPU_DISABLE_SSE
533 /*
534  * On AuthenticAMD processors, the fxrstor instruction does not restore
535  * the x87's stored last instruction pointer, last data pointer, and last
536  * opcode values, except in the rare case in which the exception summary
537  * (ES) bit in the x87 status word is set to 1.
538  *
539  * In order to avoid leaking this information across processes, we clean
540  * these values by performing a dummy load before executing fxrstor().
541  */
542 static  double  dummy_variable = 0.0;
543 static void
544 fpu_clean_state(void)
545 {
546         u_short status;
547
548         /*
549          * Clear the ES bit in the x87 status word if it is currently
550          * set, in order to avoid causing a fault in the upcoming load.
551          */
552         fnstsw(&status);
553         if (status & 0x80)
554                 fnclex();
555
556         /*
557          * Load the dummy variable into the x87 stack.  This mangles
558          * the x87 stack, but we don't care since we're about to call
559          * fxrstor() anyway.
560          */
561         __asm __volatile("ffree %%st(7); fld %0" : : "m" (dummy_variable));
562 }
563 #endif /* CPU_DISABLE_SSE */
564
565 static void
566 fpurstor(union savefpu *addr)
567 {
568 #ifndef CPU_DISABLE_SSE
569         if (cpu_fxsr) {
570                 fpu_clean_state();
571                 fxrstor(addr);
572         } else {
573                 frstor(addr);
574         }
575 #else
576         frstor(addr);
577 #endif
578 }
579