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