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