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