]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/fpu.c
IFC @ r242684
[FreeBSD/FreeBSD.git] / sys / amd64 / amd64 / fpu.c
1 /*-
2  * Copyright (c) 1990 William Jolitz.
3  * Copyright (c) 1991 The Regents of the University of California.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 4. Neither the name of the University nor the names of its contributors
15  *    may be used to endorse or promote products derived from this software
16  *    without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  *      from: @(#)npx.c 7.2 (Berkeley) 5/12/91
31  */
32
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/bus.h>
39 #include <sys/kernel.h>
40 #include <sys/lock.h>
41 #include <sys/malloc.h>
42 #include <sys/module.h>
43 #include <sys/mutex.h>
44 #include <sys/mutex.h>
45 #include <sys/proc.h>
46 #include <sys/sysctl.h>
47 #include <machine/bus.h>
48 #include <sys/rman.h>
49 #include <sys/signalvar.h>
50 #include <vm/uma.h>
51
52 #include <machine/cputypes.h>
53 #include <machine/frame.h>
54 #include <machine/intr_machdep.h>
55 #include <machine/md_var.h>
56 #include <machine/pcb.h>
57 #include <machine/psl.h>
58 #include <machine/resource.h>
59 #include <machine/specialreg.h>
60 #include <machine/segments.h>
61 #include <machine/ucontext.h>
62
63 /*
64  * Floating point support.
65  */
66
67 #if defined(__GNUCLIKE_ASM) && !defined(lint)
68
69 #define fldcw(cw)               __asm __volatile("fldcw %0" : : "m" (cw))
70 #define fnclex()                __asm __volatile("fnclex")
71 #define fninit()                __asm __volatile("fninit")
72 #define fnstcw(addr)            __asm __volatile("fnstcw %0" : "=m" (*(addr)))
73 #define fnstsw(addr)            __asm __volatile("fnstsw %0" : "=am" (*(addr)))
74 #define fxrstor(addr)           __asm __volatile("fxrstor %0" : : "m" (*(addr)))
75 #define fxsave(addr)            __asm __volatile("fxsave %0" : "=m" (*(addr)))
76 #define ldmxcsr(csr)            __asm __volatile("ldmxcsr %0" : : "m" (csr))
77 #define stmxcsr(addr)           __asm __volatile("stmxcsr %0" : : "m" (*(addr)))
78
79 static __inline void
80 xrstor(char *addr, uint64_t mask)
81 {
82         uint32_t low, hi;
83
84         low = mask;
85         hi = mask >> 32;
86         __asm __volatile("xrstor %0" : : "m" (*addr), "a" (low), "d" (hi));
87 }
88
89 static __inline void
90 xsave(char *addr, uint64_t mask)
91 {
92         uint32_t low, hi;
93
94         low = mask;
95         hi = mask >> 32;
96         __asm __volatile("xsave %0" : "=m" (*addr) : "a" (low), "d" (hi) :
97             "memory");
98 }
99
100 #else   /* !(__GNUCLIKE_ASM && !lint) */
101
102 void    fldcw(u_short cw);
103 void    fnclex(void);
104 void    fninit(void);
105 void    fnstcw(caddr_t addr);
106 void    fnstsw(caddr_t addr);
107 void    fxsave(caddr_t addr);
108 void    fxrstor(caddr_t addr);
109 void    ldmxcsr(u_int csr);
110 void    stmxcsr(u_int *csr);
111 void    xrstor(char *addr, uint64_t mask);
112 void    xsave(char *addr, uint64_t mask);
113
114 #endif  /* __GNUCLIKE_ASM && !lint */
115
116 #define start_emulating()       load_cr0(rcr0() | CR0_TS)
117 #define stop_emulating()        clts()
118
119 CTASSERT(sizeof(struct savefpu) == 512);
120 CTASSERT(sizeof(struct xstate_hdr) == 64);
121 CTASSERT(sizeof(struct savefpu_ymm) == 832);
122
123 /*
124  * This requirement is to make it easier for asm code to calculate
125  * offset of the fpu save area from the pcb address. FPU save area
126  * must be 64-byte aligned.
127  */
128 CTASSERT(sizeof(struct pcb) % XSAVE_AREA_ALIGN == 0);
129
130 static  void    fpu_clean_state(void);
131
132 SYSCTL_INT(_hw, HW_FLOATINGPT, floatingpoint, CTLFLAG_RD,
133     NULL, 1, "Floating point instructions executed in hardware");
134
135 static int use_xsaveopt;
136 int use_xsave;                  /* non-static for cpu_switch.S */
137 uint64_t xsave_mask;            /* the same */
138 static  struct savefpu *fpu_initialstate;
139
140 struct xsave_area_elm_descr {
141         u_int   offset;
142         u_int   size;
143 } *xsave_area_desc;
144
145 void
146 fpusave(void *addr)
147 {
148
149         if (use_xsave)
150                 xsave((char *)addr, xsave_mask);
151         else
152                 fxsave((char *)addr);
153 }
154
155 void
156 fpurestore(void *addr)
157 {
158
159         if (use_xsave)
160                 xrstor((char *)addr, xsave_mask);
161         else
162                 fxrstor((char *)addr);
163 }
164
165 /*
166  * Enable XSAVE if supported and allowed by user.
167  * Calculate the xsave_mask.
168  */
169 static void
170 fpuinit_bsp1(void)
171 {
172         u_int cp[4];
173         uint64_t xsave_mask_user;
174
175         if ((cpu_feature2 & CPUID2_XSAVE) != 0) {
176                 use_xsave = 1;
177                 TUNABLE_INT_FETCH("hw.use_xsave", &use_xsave);
178         }
179         if (!use_xsave)
180                 return;
181
182         cpuid_count(0xd, 0x0, cp);
183         xsave_mask = XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE;
184         if ((cp[0] & xsave_mask) != xsave_mask)
185                 panic("CPU0 does not support X87 or SSE: %x", cp[0]);
186         xsave_mask = ((uint64_t)cp[3] << 32) | cp[0];
187         xsave_mask_user = xsave_mask;
188         TUNABLE_ULONG_FETCH("hw.xsave_mask", &xsave_mask_user);
189         xsave_mask_user |= XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE;
190         xsave_mask &= xsave_mask_user;
191
192         cpuid_count(0xd, 0x1, cp);
193         if ((cp[0] & CPUID_EXTSTATE_XSAVEOPT) != 0) {
194                 /*
195                  * Patch the XSAVE instruction in the cpu_switch code
196                  * to XSAVEOPT.  We assume that XSAVE encoding used
197                  * REX byte, and set the bit 4 of the r/m byte.
198                  */
199                 ctx_switch_xsave[3] |= 0x10;
200                 use_xsaveopt = 1;
201         }
202 }
203
204 /*
205  * Calculate the fpu save area size.
206  */
207 static void
208 fpuinit_bsp2(void)
209 {
210         u_int cp[4];
211
212         if (use_xsave) {
213                 cpuid_count(0xd, 0x0, cp);
214                 cpu_max_ext_state_size = cp[1];
215
216                 /*
217                  * Reload the cpu_feature2, since we enabled OSXSAVE.
218                  */
219                 do_cpuid(1, cp);
220                 cpu_feature2 = cp[2];
221         } else
222                 cpu_max_ext_state_size = sizeof(struct savefpu);
223 }
224
225 /*
226  * Initialize the floating point unit.
227  */
228 void
229 fpuinit(void)
230 {
231         register_t saveintr;
232         u_int mxcsr;
233         u_short control;
234
235         if (IS_BSP())
236                 fpuinit_bsp1();
237
238         if (use_xsave) {
239                 load_cr4(rcr4() | CR4_XSAVE);
240                 load_xcr(XCR0, xsave_mask);
241         }
242
243         /*
244          * XCR0 shall be set up before CPU can report the save area size.
245          */
246         if (IS_BSP())
247                 fpuinit_bsp2();
248
249         /*
250          * It is too early for critical_enter() to work on AP.
251          */
252         saveintr = intr_disable();
253         stop_emulating();
254         fninit();
255         control = __INITIAL_FPUCW__;
256         fldcw(control);
257         mxcsr = __INITIAL_MXCSR__;
258         ldmxcsr(mxcsr);
259         start_emulating();
260         intr_restore(saveintr);
261 }
262
263 /*
264  * On the boot CPU we generate a clean state that is used to
265  * initialize the floating point unit when it is first used by a
266  * process.
267  */
268 static void
269 fpuinitstate(void *arg __unused)
270 {
271         register_t saveintr;
272         int cp[4], i, max_ext_n;
273
274         fpu_initialstate = malloc(cpu_max_ext_state_size, M_DEVBUF,
275             M_WAITOK | M_ZERO);
276         saveintr = intr_disable();
277         stop_emulating();
278
279         fpusave(fpu_initialstate);
280         if (fpu_initialstate->sv_env.en_mxcsr_mask)
281                 cpu_mxcsr_mask = fpu_initialstate->sv_env.en_mxcsr_mask;
282         else
283                 cpu_mxcsr_mask = 0xFFBF;
284
285         /*
286          * The fninit instruction does not modify XMM registers.  The
287          * fpusave call dumped the garbage contained in the registers
288          * after reset to the initial state saved.  Clear XMM
289          * registers file image to make the startup program state and
290          * signal handler XMM register content predictable.
291          */
292         bzero(&fpu_initialstate->sv_xmm[0], sizeof(struct xmmacc));
293
294         /*
295          * Create a table describing the layout of the CPU Extended
296          * Save Area.
297          */
298         if (use_xsaveopt) {
299                 max_ext_n = flsl(xsave_mask);
300                 xsave_area_desc = malloc(max_ext_n * sizeof(struct
301                     xsave_area_elm_descr), M_DEVBUF, M_WAITOK | M_ZERO);
302                 /* x87 state */
303                 xsave_area_desc[0].offset = 0;
304                 xsave_area_desc[0].size = 160;
305                 /* XMM */
306                 xsave_area_desc[1].offset = 160;
307                 xsave_area_desc[1].size = 288 - 160;
308
309                 for (i = 2; i < max_ext_n; i++) {
310                         cpuid_count(0xd, i, cp);
311                         xsave_area_desc[i].offset = cp[1];
312                         xsave_area_desc[i].size = cp[0];
313                 }
314         }
315
316         start_emulating();
317         intr_restore(saveintr);
318 }
319 SYSINIT(fpuinitstate, SI_SUB_DRIVERS, SI_ORDER_ANY, fpuinitstate, NULL);
320
321 /*
322  * Free coprocessor (if we have it).
323  */
324 void
325 fpuexit(struct thread *td)
326 {
327
328         critical_enter();
329         if (curthread == PCPU_GET(fpcurthread)) {
330                 stop_emulating();
331                 fpusave(curpcb->pcb_save);
332                 start_emulating();
333                 PCPU_SET(fpcurthread, 0);
334         }
335         critical_exit();
336 }
337
338 int
339 fpuformat()
340 {
341
342         return (_MC_FPFMT_XMM);
343 }
344
345 /* 
346  * The following mechanism is used to ensure that the FPE_... value
347  * that is passed as a trapcode to the signal handler of the user
348  * process does not have more than one bit set.
349  * 
350  * Multiple bits may be set if the user process modifies the control
351  * word while a status word bit is already set.  While this is a sign
352  * of bad coding, we have no choise than to narrow them down to one
353  * bit, since we must not send a trapcode that is not exactly one of
354  * the FPE_ macros.
355  *
356  * The mechanism has a static table with 127 entries.  Each combination
357  * of the 7 FPU status word exception bits directly translates to a
358  * position in this table, where a single FPE_... value is stored.
359  * This FPE_... value stored there is considered the "most important"
360  * of the exception bits and will be sent as the signal code.  The
361  * precedence of the bits is based upon Intel Document "Numerical
362  * Applications", Chapter "Special Computational Situations".
363  *
364  * The macro to choose one of these values does these steps: 1) Throw
365  * away status word bits that cannot be masked.  2) Throw away the bits
366  * currently masked in the control word, assuming the user isn't
367  * interested in them anymore.  3) Reinsert status word bit 7 (stack
368  * fault) if it is set, which cannot be masked but must be presered.
369  * 4) Use the remaining bits to point into the trapcode table.
370  *
371  * The 6 maskable bits in order of their preference, as stated in the
372  * above referenced Intel manual:
373  * 1  Invalid operation (FP_X_INV)
374  * 1a   Stack underflow
375  * 1b   Stack overflow
376  * 1c   Operand of unsupported format
377  * 1d   SNaN operand.
378  * 2  QNaN operand (not an exception, irrelavant here)
379  * 3  Any other invalid-operation not mentioned above or zero divide
380  *      (FP_X_INV, FP_X_DZ)
381  * 4  Denormal operand (FP_X_DNML)
382  * 5  Numeric over/underflow (FP_X_OFL, FP_X_UFL)
383  * 6  Inexact result (FP_X_IMP) 
384  */
385 static char fpetable[128] = {
386         0,
387         FPE_FLTINV,     /*  1 - INV */
388         FPE_FLTUND,     /*  2 - DNML */
389         FPE_FLTINV,     /*  3 - INV | DNML */
390         FPE_FLTDIV,     /*  4 - DZ */
391         FPE_FLTINV,     /*  5 - INV | DZ */
392         FPE_FLTDIV,     /*  6 - DNML | DZ */
393         FPE_FLTINV,     /*  7 - INV | DNML | DZ */
394         FPE_FLTOVF,     /*  8 - OFL */
395         FPE_FLTINV,     /*  9 - INV | OFL */
396         FPE_FLTUND,     /*  A - DNML | OFL */
397         FPE_FLTINV,     /*  B - INV | DNML | OFL */
398         FPE_FLTDIV,     /*  C - DZ | OFL */
399         FPE_FLTINV,     /*  D - INV | DZ | OFL */
400         FPE_FLTDIV,     /*  E - DNML | DZ | OFL */
401         FPE_FLTINV,     /*  F - INV | DNML | DZ | OFL */
402         FPE_FLTUND,     /* 10 - UFL */
403         FPE_FLTINV,     /* 11 - INV | UFL */
404         FPE_FLTUND,     /* 12 - DNML | UFL */
405         FPE_FLTINV,     /* 13 - INV | DNML | UFL */
406         FPE_FLTDIV,     /* 14 - DZ | UFL */
407         FPE_FLTINV,     /* 15 - INV | DZ | UFL */
408         FPE_FLTDIV,     /* 16 - DNML | DZ | UFL */
409         FPE_FLTINV,     /* 17 - INV | DNML | DZ | UFL */
410         FPE_FLTOVF,     /* 18 - OFL | UFL */
411         FPE_FLTINV,     /* 19 - INV | OFL | UFL */
412         FPE_FLTUND,     /* 1A - DNML | OFL | UFL */
413         FPE_FLTINV,     /* 1B - INV | DNML | OFL | UFL */
414         FPE_FLTDIV,     /* 1C - DZ | OFL | UFL */
415         FPE_FLTINV,     /* 1D - INV | DZ | OFL | UFL */
416         FPE_FLTDIV,     /* 1E - DNML | DZ | OFL | UFL */
417         FPE_FLTINV,     /* 1F - INV | DNML | DZ | OFL | UFL */
418         FPE_FLTRES,     /* 20 - IMP */
419         FPE_FLTINV,     /* 21 - INV | IMP */
420         FPE_FLTUND,     /* 22 - DNML | IMP */
421         FPE_FLTINV,     /* 23 - INV | DNML | IMP */
422         FPE_FLTDIV,     /* 24 - DZ | IMP */
423         FPE_FLTINV,     /* 25 - INV | DZ | IMP */
424         FPE_FLTDIV,     /* 26 - DNML | DZ | IMP */
425         FPE_FLTINV,     /* 27 - INV | DNML | DZ | IMP */
426         FPE_FLTOVF,     /* 28 - OFL | IMP */
427         FPE_FLTINV,     /* 29 - INV | OFL | IMP */
428         FPE_FLTUND,     /* 2A - DNML | OFL | IMP */
429         FPE_FLTINV,     /* 2B - INV | DNML | OFL | IMP */
430         FPE_FLTDIV,     /* 2C - DZ | OFL | IMP */
431         FPE_FLTINV,     /* 2D - INV | DZ | OFL | IMP */
432         FPE_FLTDIV,     /* 2E - DNML | DZ | OFL | IMP */
433         FPE_FLTINV,     /* 2F - INV | DNML | DZ | OFL | IMP */
434         FPE_FLTUND,     /* 30 - UFL | IMP */
435         FPE_FLTINV,     /* 31 - INV | UFL | IMP */
436         FPE_FLTUND,     /* 32 - DNML | UFL | IMP */
437         FPE_FLTINV,     /* 33 - INV | DNML | UFL | IMP */
438         FPE_FLTDIV,     /* 34 - DZ | UFL | IMP */
439         FPE_FLTINV,     /* 35 - INV | DZ | UFL | IMP */
440         FPE_FLTDIV,     /* 36 - DNML | DZ | UFL | IMP */
441         FPE_FLTINV,     /* 37 - INV | DNML | DZ | UFL | IMP */
442         FPE_FLTOVF,     /* 38 - OFL | UFL | IMP */
443         FPE_FLTINV,     /* 39 - INV | OFL | UFL | IMP */
444         FPE_FLTUND,     /* 3A - DNML | OFL | UFL | IMP */
445         FPE_FLTINV,     /* 3B - INV | DNML | OFL | UFL | IMP */
446         FPE_FLTDIV,     /* 3C - DZ | OFL | UFL | IMP */
447         FPE_FLTINV,     /* 3D - INV | DZ | OFL | UFL | IMP */
448         FPE_FLTDIV,     /* 3E - DNML | DZ | OFL | UFL | IMP */
449         FPE_FLTINV,     /* 3F - INV | DNML | DZ | OFL | UFL | IMP */
450         FPE_FLTSUB,     /* 40 - STK */
451         FPE_FLTSUB,     /* 41 - INV | STK */
452         FPE_FLTUND,     /* 42 - DNML | STK */
453         FPE_FLTSUB,     /* 43 - INV | DNML | STK */
454         FPE_FLTDIV,     /* 44 - DZ | STK */
455         FPE_FLTSUB,     /* 45 - INV | DZ | STK */
456         FPE_FLTDIV,     /* 46 - DNML | DZ | STK */
457         FPE_FLTSUB,     /* 47 - INV | DNML | DZ | STK */
458         FPE_FLTOVF,     /* 48 - OFL | STK */
459         FPE_FLTSUB,     /* 49 - INV | OFL | STK */
460         FPE_FLTUND,     /* 4A - DNML | OFL | STK */
461         FPE_FLTSUB,     /* 4B - INV | DNML | OFL | STK */
462         FPE_FLTDIV,     /* 4C - DZ | OFL | STK */
463         FPE_FLTSUB,     /* 4D - INV | DZ | OFL | STK */
464         FPE_FLTDIV,     /* 4E - DNML | DZ | OFL | STK */
465         FPE_FLTSUB,     /* 4F - INV | DNML | DZ | OFL | STK */
466         FPE_FLTUND,     /* 50 - UFL | STK */
467         FPE_FLTSUB,     /* 51 - INV | UFL | STK */
468         FPE_FLTUND,     /* 52 - DNML | UFL | STK */
469         FPE_FLTSUB,     /* 53 - INV | DNML | UFL | STK */
470         FPE_FLTDIV,     /* 54 - DZ | UFL | STK */
471         FPE_FLTSUB,     /* 55 - INV | DZ | UFL | STK */
472         FPE_FLTDIV,     /* 56 - DNML | DZ | UFL | STK */
473         FPE_FLTSUB,     /* 57 - INV | DNML | DZ | UFL | STK */
474         FPE_FLTOVF,     /* 58 - OFL | UFL | STK */
475         FPE_FLTSUB,     /* 59 - INV | OFL | UFL | STK */
476         FPE_FLTUND,     /* 5A - DNML | OFL | UFL | STK */
477         FPE_FLTSUB,     /* 5B - INV | DNML | OFL | UFL | STK */
478         FPE_FLTDIV,     /* 5C - DZ | OFL | UFL | STK */
479         FPE_FLTSUB,     /* 5D - INV | DZ | OFL | UFL | STK */
480         FPE_FLTDIV,     /* 5E - DNML | DZ | OFL | UFL | STK */
481         FPE_FLTSUB,     /* 5F - INV | DNML | DZ | OFL | UFL | STK */
482         FPE_FLTRES,     /* 60 - IMP | STK */
483         FPE_FLTSUB,     /* 61 - INV | IMP | STK */
484         FPE_FLTUND,     /* 62 - DNML | IMP | STK */
485         FPE_FLTSUB,     /* 63 - INV | DNML | IMP | STK */
486         FPE_FLTDIV,     /* 64 - DZ | IMP | STK */
487         FPE_FLTSUB,     /* 65 - INV | DZ | IMP | STK */
488         FPE_FLTDIV,     /* 66 - DNML | DZ | IMP | STK */
489         FPE_FLTSUB,     /* 67 - INV | DNML | DZ | IMP | STK */
490         FPE_FLTOVF,     /* 68 - OFL | IMP | STK */
491         FPE_FLTSUB,     /* 69 - INV | OFL | IMP | STK */
492         FPE_FLTUND,     /* 6A - DNML | OFL | IMP | STK */
493         FPE_FLTSUB,     /* 6B - INV | DNML | OFL | IMP | STK */
494         FPE_FLTDIV,     /* 6C - DZ | OFL | IMP | STK */
495         FPE_FLTSUB,     /* 6D - INV | DZ | OFL | IMP | STK */
496         FPE_FLTDIV,     /* 6E - DNML | DZ | OFL | IMP | STK */
497         FPE_FLTSUB,     /* 6F - INV | DNML | DZ | OFL | IMP | STK */
498         FPE_FLTUND,     /* 70 - UFL | IMP | STK */
499         FPE_FLTSUB,     /* 71 - INV | UFL | IMP | STK */
500         FPE_FLTUND,     /* 72 - DNML | UFL | IMP | STK */
501         FPE_FLTSUB,     /* 73 - INV | DNML | UFL | IMP | STK */
502         FPE_FLTDIV,     /* 74 - DZ | UFL | IMP | STK */
503         FPE_FLTSUB,     /* 75 - INV | DZ | UFL | IMP | STK */
504         FPE_FLTDIV,     /* 76 - DNML | DZ | UFL | IMP | STK */
505         FPE_FLTSUB,     /* 77 - INV | DNML | DZ | UFL | IMP | STK */
506         FPE_FLTOVF,     /* 78 - OFL | UFL | IMP | STK */
507         FPE_FLTSUB,     /* 79 - INV | OFL | UFL | IMP | STK */
508         FPE_FLTUND,     /* 7A - DNML | OFL | UFL | IMP | STK */
509         FPE_FLTSUB,     /* 7B - INV | DNML | OFL | UFL | IMP | STK */
510         FPE_FLTDIV,     /* 7C - DZ | OFL | UFL | IMP | STK */
511         FPE_FLTSUB,     /* 7D - INV | DZ | OFL | UFL | IMP | STK */
512         FPE_FLTDIV,     /* 7E - DNML | DZ | OFL | UFL | IMP | STK */
513         FPE_FLTSUB,     /* 7F - INV | DNML | DZ | OFL | UFL | IMP | STK */
514 };
515
516 /*
517  * Read the FP status and control words, then generate si_code value
518  * for SIGFPE.  The error code chosen will be one of the
519  * FPE_... macros.  It will be sent as the second argument to old
520  * BSD-style signal handlers and as "siginfo_t->si_code" (second
521  * argument) to SA_SIGINFO signal handlers.
522  *
523  * Some time ago, we cleared the x87 exceptions with FNCLEX there.
524  * Clearing exceptions was necessary mainly to avoid IRQ13 bugs.  The
525  * usermode code which understands the FPU hardware enough to enable
526  * the exceptions, can also handle clearing the exception state in the
527  * handler.  The only consequence of not clearing the exception is the
528  * rethrow of the SIGFPE on return from the signal handler and
529  * reexecution of the corresponding instruction.
530  *
531  * For XMM traps, the exceptions were never cleared.
532  */
533 int
534 fputrap_x87(void)
535 {
536         struct savefpu *pcb_save;
537         u_short control, status;
538
539         critical_enter();
540
541         /*
542          * Interrupt handling (for another interrupt) may have pushed the
543          * state to memory.  Fetch the relevant parts of the state from
544          * wherever they are.
545          */
546         if (PCPU_GET(fpcurthread) != curthread) {
547                 pcb_save = curpcb->pcb_save;
548                 control = pcb_save->sv_env.en_cw;
549                 status = pcb_save->sv_env.en_sw;
550         } else {
551                 fnstcw(&control);
552                 fnstsw(&status);
553         }
554
555         critical_exit();
556         return (fpetable[status & ((~control & 0x3f) | 0x40)]);
557 }
558
559 int
560 fputrap_sse(void)
561 {
562         u_int mxcsr;
563
564         critical_enter();
565         if (PCPU_GET(fpcurthread) != curthread)
566                 mxcsr = curpcb->pcb_save->sv_env.en_mxcsr;
567         else
568                 stmxcsr(&mxcsr);
569         critical_exit();
570         return (fpetable[(mxcsr & (~mxcsr >> 7)) & 0x3f]);
571 }
572
573 /*
574  * Implement device not available (DNA) exception
575  *
576  * It would be better to switch FP context here (if curthread != fpcurthread)
577  * and not necessarily for every context switch, but it is too hard to
578  * access foreign pcb's.
579  */
580
581 static int err_count = 0;
582
583 void
584 fpudna(void)
585 {
586
587         critical_enter();
588         if (PCPU_GET(fpcurthread) == curthread) {
589                 printf("fpudna: fpcurthread == curthread %d times\n",
590                     ++err_count);
591                 stop_emulating();
592                 critical_exit();
593                 return;
594         }
595         if (PCPU_GET(fpcurthread) != NULL) {
596                 printf("fpudna: fpcurthread = %p (%d), curthread = %p (%d)\n",
597                        PCPU_GET(fpcurthread),
598                        PCPU_GET(fpcurthread)->td_proc->p_pid,
599                        curthread, curthread->td_proc->p_pid);
600                 panic("fpudna");
601         }
602         stop_emulating();
603         /*
604          * Record new context early in case frstor causes a trap.
605          */
606         PCPU_SET(fpcurthread, curthread);
607
608         fpu_clean_state();
609
610         if ((curpcb->pcb_flags & PCB_FPUINITDONE) == 0) {
611                 /*
612                  * This is the first time this thread has used the FPU or
613                  * the PCB doesn't contain a clean FPU state.  Explicitly
614                  * load an initial state.
615                  *
616                  * We prefer to restore the state from the actual save
617                  * area in PCB instead of directly loading from
618                  * fpu_initialstate, to ignite the XSAVEOPT
619                  * tracking engine.
620                  */
621                 bcopy(fpu_initialstate, curpcb->pcb_save, cpu_max_ext_state_size);
622                 fpurestore(curpcb->pcb_save);
623                 if (curpcb->pcb_initial_fpucw != __INITIAL_FPUCW__)
624                         fldcw(curpcb->pcb_initial_fpucw);
625                 if (PCB_USER_FPU(curpcb))
626                         set_pcb_flags(curpcb,
627                             PCB_FPUINITDONE | PCB_USERFPUINITDONE);
628                 else
629                         set_pcb_flags(curpcb, PCB_FPUINITDONE);
630         } else
631                 fpurestore(curpcb->pcb_save);
632         critical_exit();
633 }
634
635 void
636 fpudrop()
637 {
638         struct thread *td;
639
640         td = PCPU_GET(fpcurthread);
641         KASSERT(td == curthread, ("fpudrop: fpcurthread != curthread"));
642         CRITICAL_ASSERT(td);
643         PCPU_SET(fpcurthread, NULL);
644         clear_pcb_flags(td->td_pcb, PCB_FPUINITDONE);
645         start_emulating();
646 }
647
648 /*
649  * Get the user state of the FPU into pcb->pcb_user_save without
650  * dropping ownership (if possible).  It returns the FPU ownership
651  * status.
652  */
653 int
654 fpugetregs(struct thread *td)
655 {
656         struct pcb *pcb;
657         uint64_t *xstate_bv, bit;
658         char *sa;
659         int max_ext_n, i;
660
661         pcb = td->td_pcb;
662         if ((pcb->pcb_flags & PCB_USERFPUINITDONE) == 0) {
663                 bcopy(fpu_initialstate, get_pcb_user_save_pcb(pcb),
664                     cpu_max_ext_state_size);
665                 get_pcb_user_save_pcb(pcb)->sv_env.en_cw =
666                     pcb->pcb_initial_fpucw;
667                 fpuuserinited(td);
668                 return (_MC_FPOWNED_PCB);
669         }
670         critical_enter();
671         if (td == PCPU_GET(fpcurthread) && PCB_USER_FPU(pcb)) {
672                 fpusave(get_pcb_user_save_pcb(pcb));
673                 critical_exit();
674                 return (_MC_FPOWNED_FPU);
675         } else {
676                 critical_exit();
677                 if (use_xsaveopt) {
678                         /*
679                          * Handle partially saved state.
680                          */
681                         sa = (char *)get_pcb_user_save_pcb(pcb);
682                         xstate_bv = (uint64_t *)(sa + sizeof(struct savefpu) +
683                             offsetof(struct xstate_hdr, xstate_bv));
684                         max_ext_n = flsl(xsave_mask);
685                         for (i = 0; i < max_ext_n; i++) {
686                                 bit = 1 << i;
687                                 if ((*xstate_bv & bit) != 0)
688                                         continue;
689                                 bcopy((char *)fpu_initialstate +
690                                     xsave_area_desc[i].offset,
691                                     sa + xsave_area_desc[i].offset,
692                                     xsave_area_desc[i].size);
693                                 *xstate_bv |= bit;
694                         }
695                 }
696                 return (_MC_FPOWNED_PCB);
697         }
698 }
699
700 void
701 fpuuserinited(struct thread *td)
702 {
703         struct pcb *pcb;
704
705         pcb = td->td_pcb;
706         if (PCB_USER_FPU(pcb))
707                 set_pcb_flags(pcb,
708                     PCB_FPUINITDONE | PCB_USERFPUINITDONE);
709         else
710                 set_pcb_flags(pcb, PCB_FPUINITDONE);
711 }
712
713 int
714 fpusetxstate(struct thread *td, char *xfpustate, size_t xfpustate_size)
715 {
716         struct xstate_hdr *hdr, *ehdr;
717         size_t len, max_len;
718         uint64_t bv;
719
720         /* XXXKIB should we clear all extended state in xstate_bv instead ? */
721         if (xfpustate == NULL)
722                 return (0);
723         if (!use_xsave)
724                 return (EOPNOTSUPP);
725
726         len = xfpustate_size;
727         if (len < sizeof(struct xstate_hdr))
728                 return (EINVAL);
729         max_len = cpu_max_ext_state_size - sizeof(struct savefpu);
730         if (len > max_len)
731                 return (EINVAL);
732
733         ehdr = (struct xstate_hdr *)xfpustate;
734         bv = ehdr->xstate_bv;
735
736         /*
737          * Avoid #gp.
738          */
739         if (bv & ~xsave_mask)
740                 return (EINVAL);
741         if ((bv & (XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE)) !=
742             (XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE))
743                 return (EINVAL);
744
745         hdr = (struct xstate_hdr *)(get_pcb_user_save_td(td) + 1);
746
747         hdr->xstate_bv = bv;
748         bcopy(xfpustate + sizeof(struct xstate_hdr),
749             (char *)(hdr + 1), len - sizeof(struct xstate_hdr));
750
751         return (0);
752 }
753
754 /*
755  * Set the state of the FPU.
756  */
757 int
758 fpusetregs(struct thread *td, struct savefpu *addr, char *xfpustate,
759     size_t xfpustate_size)
760 {
761         struct pcb *pcb;
762         int error;
763
764         pcb = td->td_pcb;
765         critical_enter();
766         if (td == PCPU_GET(fpcurthread) && PCB_USER_FPU(pcb)) {
767                 error = fpusetxstate(td, xfpustate, xfpustate_size);
768                 if (error != 0) {
769                         critical_exit();
770                         return (error);
771                 }
772                 bcopy(addr, get_pcb_user_save_td(td), sizeof(*addr));
773                 fpurestore(get_pcb_user_save_td(td));
774                 critical_exit();
775                 set_pcb_flags(pcb, PCB_FPUINITDONE | PCB_USERFPUINITDONE);
776         } else {
777                 critical_exit();
778                 error = fpusetxstate(td, xfpustate, xfpustate_size);
779                 if (error != 0)
780                         return (error);
781                 bcopy(addr, get_pcb_user_save_td(td), sizeof(*addr));
782                 fpuuserinited(td);
783         }
784         return (0);
785 }
786
787 /*
788  * On AuthenticAMD processors, the fxrstor instruction does not restore
789  * the x87's stored last instruction pointer, last data pointer, and last
790  * opcode values, except in the rare case in which the exception summary
791  * (ES) bit in the x87 status word is set to 1.
792  *
793  * In order to avoid leaking this information across processes, we clean
794  * these values by performing a dummy load before executing fxrstor().
795  */
796 static void
797 fpu_clean_state(void)
798 {
799         static float dummy_variable = 0.0;
800         u_short status;
801
802         /*
803          * Clear the ES bit in the x87 status word if it is currently
804          * set, in order to avoid causing a fault in the upcoming load.
805          */
806         fnstsw(&status);
807         if (status & 0x80)
808                 fnclex();
809
810         /*
811          * Load the dummy variable into the x87 stack.  This mangles
812          * the x87 stack, but we don't care since we're about to call
813          * fxrstor() anyway.
814          */
815         __asm __volatile("ffree %%st(7); flds %0" : : "m" (dummy_variable));
816 }
817
818 /*
819  * This really sucks.  We want the acpi version only, but it requires
820  * the isa_if.h file in order to get the definitions.
821  */
822 #include "opt_isa.h"
823 #ifdef DEV_ISA
824 #include <isa/isavar.h>
825 /*
826  * This sucks up the legacy ISA support assignments from PNPBIOS/ACPI.
827  */
828 static struct isa_pnp_id fpupnp_ids[] = {
829         { 0x040cd041, "Legacy ISA coprocessor support" }, /* PNP0C04 */
830         { 0 }
831 };
832
833 static int
834 fpupnp_probe(device_t dev)
835 {
836         int result;
837
838         result = ISA_PNP_PROBE(device_get_parent(dev), dev, fpupnp_ids);
839         if (result <= 0)
840                 device_quiet(dev);
841         return (result);
842 }
843
844 static int
845 fpupnp_attach(device_t dev)
846 {
847
848         return (0);
849 }
850
851 static device_method_t fpupnp_methods[] = {
852         /* Device interface */
853         DEVMETHOD(device_probe,         fpupnp_probe),
854         DEVMETHOD(device_attach,        fpupnp_attach),
855         DEVMETHOD(device_detach,        bus_generic_detach),
856         DEVMETHOD(device_shutdown,      bus_generic_shutdown),
857         DEVMETHOD(device_suspend,       bus_generic_suspend),
858         DEVMETHOD(device_resume,        bus_generic_resume),
859         
860         { 0, 0 }
861 };
862
863 static driver_t fpupnp_driver = {
864         "fpupnp",
865         fpupnp_methods,
866         1,                      /* no softc */
867 };
868
869 static devclass_t fpupnp_devclass;
870
871 DRIVER_MODULE(fpupnp, acpi, fpupnp_driver, fpupnp_devclass, 0, 0);
872 #endif  /* DEV_ISA */
873
874 static MALLOC_DEFINE(M_FPUKERN_CTX, "fpukern_ctx",
875     "Kernel contexts for FPU state");
876
877 #define FPU_KERN_CTX_FPUINITDONE 0x01
878
879 struct fpu_kern_ctx {
880         struct savefpu *prev;
881         uint32_t flags;
882         char hwstate1[];
883 };
884
885 struct fpu_kern_ctx *
886 fpu_kern_alloc_ctx(u_int flags)
887 {
888         struct fpu_kern_ctx *res;
889         size_t sz;
890
891         sz = sizeof(struct fpu_kern_ctx) + XSAVE_AREA_ALIGN +
892             cpu_max_ext_state_size;
893         res = malloc(sz, M_FPUKERN_CTX, ((flags & FPU_KERN_NOWAIT) ?
894             M_NOWAIT : M_WAITOK) | M_ZERO);
895         return (res);
896 }
897
898 void
899 fpu_kern_free_ctx(struct fpu_kern_ctx *ctx)
900 {
901
902         /* XXXKIB clear the memory ? */
903         free(ctx, M_FPUKERN_CTX);
904 }
905
906 static struct savefpu *
907 fpu_kern_ctx_savefpu(struct fpu_kern_ctx *ctx)
908 {
909         vm_offset_t p;
910
911         p = (vm_offset_t)&ctx->hwstate1;
912         p = roundup2(p, XSAVE_AREA_ALIGN);
913         return ((struct savefpu *)p);
914 }
915
916 int
917 fpu_kern_enter(struct thread *td, struct fpu_kern_ctx *ctx, u_int flags)
918 {
919         struct pcb *pcb;
920
921         pcb = td->td_pcb;
922         KASSERT(!PCB_USER_FPU(pcb) || pcb->pcb_save ==
923             get_pcb_user_save_pcb(pcb), ("mangled pcb_save"));
924         ctx->flags = 0;
925         if ((pcb->pcb_flags & PCB_FPUINITDONE) != 0)
926                 ctx->flags |= FPU_KERN_CTX_FPUINITDONE;
927         fpuexit(td);
928         ctx->prev = pcb->pcb_save;
929         pcb->pcb_save = fpu_kern_ctx_savefpu(ctx);
930         set_pcb_flags(pcb, PCB_KERNFPU);
931         clear_pcb_flags(pcb, PCB_FPUINITDONE);
932         return (0);
933 }
934
935 int
936 fpu_kern_leave(struct thread *td, struct fpu_kern_ctx *ctx)
937 {
938         struct pcb *pcb;
939
940         pcb = td->td_pcb;
941         critical_enter();
942         if (curthread == PCPU_GET(fpcurthread))
943                 fpudrop();
944         critical_exit();
945         pcb->pcb_save = ctx->prev;
946         if (pcb->pcb_save == get_pcb_user_save_pcb(pcb)) {
947                 if ((pcb->pcb_flags & PCB_USERFPUINITDONE) != 0) {
948                         set_pcb_flags(pcb, PCB_FPUINITDONE);
949                         clear_pcb_flags(pcb, PCB_KERNFPU);
950                 } else
951                         clear_pcb_flags(pcb, PCB_FPUINITDONE | PCB_KERNFPU);
952         } else {
953                 if ((ctx->flags & FPU_KERN_CTX_FPUINITDONE) != 0)
954                         set_pcb_flags(pcb, PCB_FPUINITDONE);
955                 else
956                         clear_pcb_flags(pcb, PCB_FPUINITDONE);
957                 KASSERT(!PCB_USER_FPU(pcb), ("unpaired fpu_kern_leave"));
958         }
959         return (0);
960 }
961
962 int
963 fpu_kern_thread(u_int flags)
964 {
965
966         KASSERT((curthread->td_pflags & TDP_KTHREAD) != 0,
967             ("Only kthread may use fpu_kern_thread"));
968         KASSERT(curpcb->pcb_save == get_pcb_user_save_pcb(curpcb),
969             ("mangled pcb_save"));
970         KASSERT(PCB_USER_FPU(curpcb), ("recursive call"));
971
972         set_pcb_flags(curpcb, PCB_KERNFPU);
973         return (0);
974 }
975
976 int
977 is_fpu_kern_thread(u_int flags)
978 {
979
980         if ((curthread->td_pflags & TDP_KTHREAD) == 0)
981                 return (0);
982         return ((curpcb->pcb_flags & PCB_KERNFPU) != 0);
983 }
984
985 /*
986  * FPU save area alloc/free/init utility routines
987  */
988 static uma_zone_t fpu_save_area_zone;
989
990 struct savefpu *
991 fpu_save_area_alloc(void)
992 {
993
994         if (fpu_save_area_zone == NULL) {
995                 fpu_save_area_zone = uma_zcreate("FPU_save_area",
996                                          cpu_max_ext_state_size,
997                                          NULL, NULL, NULL, NULL,
998                                          XSAVE_AREA_ALIGN - 1, 0);
999         }
1000
1001         return (uma_zalloc(fpu_save_area_zone, 0));
1002 }
1003
1004 void
1005 fpu_save_area_free(struct savefpu *fsa)
1006 {
1007
1008         uma_zfree(fpu_save_area_zone, fsa);
1009 }
1010
1011 void
1012 fpu_save_area_reset(struct savefpu *fsa)
1013 {
1014
1015         bcopy(fpu_initialstate, fsa, cpu_max_ext_state_size);
1016 }