xref: /dragonfly/sys/platform/pc64/x86_64/npx.c (revision 1be00ff1850ebb705db236c08160ee8fea99b32a)
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  */
38 
39 #include "opt_cpu.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/bus.h>
44 #include <sys/kernel.h>
45 #include <sys/malloc.h>
46 #include <sys/module.h>
47 #include <sys/sysctl.h>
48 #include <sys/proc.h>
49 #include <sys/rman.h>
50 #include <sys/signalvar.h>
51 
52 #include <sys/thread2.h>
53 
54 #include <machine/cputypes.h>
55 #include <machine/frame.h>
56 #include <machine/md_var.h>
57 #include <machine/pcb.h>
58 #include <machine/psl.h>
59 #include <machine/specialreg.h>
60 #include <machine/segments.h>
61 #include <machine/globaldata.h>
62 
63 #define   fldcw(addr)                   __asm("fldcw %0" : : "m" (*(addr)))
64 #define   fnclex()            __asm("fnclex")
65 #define   fninit()            __asm("fninit")
66 #define   fnop()                        __asm("fnop")
67 #define   fnsave(addr)                  __asm __volatile("fnsave %0" : "=m" (*(addr)))
68 #define   fnstcw(addr)                  __asm __volatile("fnstcw %0" : "=m" (*(addr)))
69 #define   fnstsw(addr)                  __asm __volatile("fnstsw %0" : "=m" (*(addr)))
70 #define   frstor(addr)                  __asm("frstor %0" : : "m" (*(addr)))
71 #define   fxrstor(addr)                 __asm("fxrstor64 %0" : : "m" (*(addr)))
72 #define   fxsave(addr)                  __asm __volatile("fxsave64 %0" : "=m" (*(addr)))
73 #define   ldmxcsr(csr)                  __asm __volatile("ldmxcsr %0" : : "m" (csr))
74 #define   start_emulating()   __asm("smsw %%ax; orb %0,%%al; lmsw %%ax" \
75                                               : : "n" (CR0_TS) : "ax")
76 #define   stop_emulating()    __asm("clts")
77 
78 #ifndef CPU_DISABLE_AVX
79 static inline void
xrstor(const void * addr,uint64_t mask)80 xrstor(const void *addr, uint64_t mask)
81 {
82           const uint8_t *area = addr;
83           uint32_t low, high;
84 
85           low = mask;
86           high = mask >> 32;
87 
88           __asm __volatile("xrstor64 %[area]"
89                                :
90                                : [area] "m" (*area), "a" (low), "d" (high));
91 }
92 
93 static inline void
xsave(void * addr,uint64_t mask)94 xsave(void *addr, uint64_t mask)
95 {
96           uint8_t *area = addr;
97           uint32_t low, high;
98 
99           low = mask;
100           high = mask >> 32;
101 
102           __asm __volatile("xsave64 %[area]"
103                                : [area] "=m" (*area)
104                                : "a" (low), "d" (high)
105                                : "memory");
106 }
107 #endif /* !CPU_DISABLE_AVX */
108 
109 static    void      fpu_clean_state(void);
110 
111 static struct krate badfprate = { 1 };
112 
113 __read_mostly uint32_t npx_mxcsr_mask = 0xFFBF;   /* this is the default */
114 __read_mostly uint64_t npx_xcr0_mask = 0;
115 
116 /*
117  * Probe the npx_mxcsr_mask as described in the intel document
118  * "Intel processor identification and the CPUID instruction" Section 7
119  * "Denormals are Zero".
120  * Note that for fxsave to work reliably, the os support bit for
121  * FXSAVE/FXRESTORE operations in CR4 has to be set as per
122  * Intel 64 and IA-32 Architectures Developer's Manual: Vol. 1,
123  * 10.5.1.2.
124  */
npxprobemask(void)125 void npxprobemask(void)
126 {
127           static union savefpu dummy __aligned(64);
128 
129           crit_enter();
130           stop_emulating();
131           load_cr4(rcr4() | CR4_OSFXSR);
132           fxsave(&dummy);
133           npx_mxcsr_mask = ((uint32_t *)&dummy)[7];
134           start_emulating();
135           crit_exit();
136 }
137 
138 /*
139  * Initialize the floating point unit.
140  */
141 void
npxinit(void)142 npxinit(void)
143 {
144           static union savefpu dummy __aligned(64);
145           u_short control = __INITIAL_FPUCW__;
146           u_int mxcsr = __INITIAL_MXCSR__;
147 
148           /*
149            * fninit has the same h/w bugs as fnsave.  Use the detoxified
150            * fnsave to throw away any junk in the fpu.  npxsave() initializes
151            * the fpu and sets npxthread = NULL as important side effects.
152            */
153           npxsave(&dummy);
154           crit_enter();
155           stop_emulating();
156           fldcw(&control);
157           ldmxcsr(mxcsr);
158           fpusave(curthread->td_savefpu, npx_xcr0_mask);
159           mdcpu->gd_npxthread = NULL;
160           start_emulating();
161           crit_exit();
162 }
163 
164 /*
165  * Free coprocessor (if we have it).
166  */
167 void
npxexit(void)168 npxexit(void)
169 {
170           if (curthread == mdcpu->gd_npxthread)
171                     npxsave(curthread->td_savefpu);
172 }
173 
174 #if 0
175 /*
176  * The following mechanism is used to ensure that the FPE_... value
177  * that is passed as a trapcode to the signal handler of the user
178  * process does not have more than one bit set.
179  *
180  * Multiple bits may be set if the user process modifies the control
181  * word while a status word bit is already set.  While this is a sign
182  * of bad coding, we have no choise than to narrow them down to one
183  * bit, since we must not send a trapcode that is not exactly one of
184  * the FPE_ macros.
185  *
186  * The mechanism has a static table with 127 entries.  Each combination
187  * of the 7 FPU status word exception bits directly translates to a
188  * position in this table, where a single FPE_... value is stored.
189  * This FPE_... value stored there is considered the "most important"
190  * of the exception bits and will be sent as the signal code.  The
191  * precedence of the bits is based upon Intel Document "Numerical
192  * Applications", Chapter "Special Computational Situations".
193  *
194  * The macro to choose one of these values does these steps: 1) Throw
195  * away status word bits that cannot be masked.  2) Throw away the bits
196  * currently masked in the control word, assuming the user isn't
197  * interested in them anymore.  3) Reinsert status word bit 7 (stack
198  * fault) if it is set, which cannot be masked but must be presered.
199  * 4) Use the remaining bits to point into the trapcode table.
200  *
201  * The 6 maskable bits in order of their preference, as stated in the
202  * above referenced Intel manual:
203  * 1  Invalid operation (FP_X_INV)
204  * 1a   Stack underflow
205  * 1b   Stack overflow
206  * 1c   Operand of unsupported format
207  * 1d   SNaN operand.
208  * 2  QNaN operand (not an exception, irrelavant here)
209  * 3  Any other invalid-operation not mentioned above or zero divide
210  *      (FP_X_INV, FP_X_DZ)
211  * 4  Denormal operand (FP_X_DNML)
212  * 5  Numeric over/underflow (FP_X_OFL, FP_X_UFL)
213  * 6  Inexact result (FP_X_IMP)
214  */
215 static char fpetable[128] = {
216           0,
217           FPE_FLTINV,         /*  1 - INV */
218           FPE_FLTUND,         /*  2 - DNML */
219           FPE_FLTINV,         /*  3 - INV | DNML */
220           FPE_FLTDIV,         /*  4 - DZ */
221           FPE_FLTINV,         /*  5 - INV | DZ */
222           FPE_FLTDIV,         /*  6 - DNML | DZ */
223           FPE_FLTINV,         /*  7 - INV | DNML | DZ */
224           FPE_FLTOVF,         /*  8 - OFL */
225           FPE_FLTINV,         /*  9 - INV | OFL */
226           FPE_FLTUND,         /*  A - DNML | OFL */
227           FPE_FLTINV,         /*  B - INV | DNML | OFL */
228           FPE_FLTDIV,         /*  C - DZ | OFL */
229           FPE_FLTINV,         /*  D - INV | DZ | OFL */
230           FPE_FLTDIV,         /*  E - DNML | DZ | OFL */
231           FPE_FLTINV,         /*  F - INV | DNML | DZ | OFL */
232           FPE_FLTUND,         /* 10 - UFL */
233           FPE_FLTINV,         /* 11 - INV | UFL */
234           FPE_FLTUND,         /* 12 - DNML | UFL */
235           FPE_FLTINV,         /* 13 - INV | DNML | UFL */
236           FPE_FLTDIV,         /* 14 - DZ | UFL */
237           FPE_FLTINV,         /* 15 - INV | DZ | UFL */
238           FPE_FLTDIV,         /* 16 - DNML | DZ | UFL */
239           FPE_FLTINV,         /* 17 - INV | DNML | DZ | UFL */
240           FPE_FLTOVF,         /* 18 - OFL | UFL */
241           FPE_FLTINV,         /* 19 - INV | OFL | UFL */
242           FPE_FLTUND,         /* 1A - DNML | OFL | UFL */
243           FPE_FLTINV,         /* 1B - INV | DNML | OFL | UFL */
244           FPE_FLTDIV,         /* 1C - DZ | OFL | UFL */
245           FPE_FLTINV,         /* 1D - INV | DZ | OFL | UFL */
246           FPE_FLTDIV,         /* 1E - DNML | DZ | OFL | UFL */
247           FPE_FLTINV,         /* 1F - INV | DNML | DZ | OFL | UFL */
248           FPE_FLTRES,         /* 20 - IMP */
249           FPE_FLTINV,         /* 21 - INV | IMP */
250           FPE_FLTUND,         /* 22 - DNML | IMP */
251           FPE_FLTINV,         /* 23 - INV | DNML | IMP */
252           FPE_FLTDIV,         /* 24 - DZ | IMP */
253           FPE_FLTINV,         /* 25 - INV | DZ | IMP */
254           FPE_FLTDIV,         /* 26 - DNML | DZ | IMP */
255           FPE_FLTINV,         /* 27 - INV | DNML | DZ | IMP */
256           FPE_FLTOVF,         /* 28 - OFL | IMP */
257           FPE_FLTINV,         /* 29 - INV | OFL | IMP */
258           FPE_FLTUND,         /* 2A - DNML | OFL | IMP */
259           FPE_FLTINV,         /* 2B - INV | DNML | OFL | IMP */
260           FPE_FLTDIV,         /* 2C - DZ | OFL | IMP */
261           FPE_FLTINV,         /* 2D - INV | DZ | OFL | IMP */
262           FPE_FLTDIV,         /* 2E - DNML | DZ | OFL | IMP */
263           FPE_FLTINV,         /* 2F - INV | DNML | DZ | OFL | IMP */
264           FPE_FLTUND,         /* 30 - UFL | IMP */
265           FPE_FLTINV,         /* 31 - INV | UFL | IMP */
266           FPE_FLTUND,         /* 32 - DNML | UFL | IMP */
267           FPE_FLTINV,         /* 33 - INV | DNML | UFL | IMP */
268           FPE_FLTDIV,         /* 34 - DZ | UFL | IMP */
269           FPE_FLTINV,         /* 35 - INV | DZ | UFL | IMP */
270           FPE_FLTDIV,         /* 36 - DNML | DZ | UFL | IMP */
271           FPE_FLTINV,         /* 37 - INV | DNML | DZ | UFL | IMP */
272           FPE_FLTOVF,         /* 38 - OFL | UFL | IMP */
273           FPE_FLTINV,         /* 39 - INV | OFL | UFL | IMP */
274           FPE_FLTUND,         /* 3A - DNML | OFL | UFL | IMP */
275           FPE_FLTINV,         /* 3B - INV | DNML | OFL | UFL | IMP */
276           FPE_FLTDIV,         /* 3C - DZ | OFL | UFL | IMP */
277           FPE_FLTINV,         /* 3D - INV | DZ | OFL | UFL | IMP */
278           FPE_FLTDIV,         /* 3E - DNML | DZ | OFL | UFL | IMP */
279           FPE_FLTINV,         /* 3F - INV | DNML | DZ | OFL | UFL | IMP */
280           FPE_FLTSUB,         /* 40 - STK */
281           FPE_FLTSUB,         /* 41 - INV | STK */
282           FPE_FLTUND,         /* 42 - DNML | STK */
283           FPE_FLTSUB,         /* 43 - INV | DNML | STK */
284           FPE_FLTDIV,         /* 44 - DZ | STK */
285           FPE_FLTSUB,         /* 45 - INV | DZ | STK */
286           FPE_FLTDIV,         /* 46 - DNML | DZ | STK */
287           FPE_FLTSUB,         /* 47 - INV | DNML | DZ | STK */
288           FPE_FLTOVF,         /* 48 - OFL | STK */
289           FPE_FLTSUB,         /* 49 - INV | OFL | STK */
290           FPE_FLTUND,         /* 4A - DNML | OFL | STK */
291           FPE_FLTSUB,         /* 4B - INV | DNML | OFL | STK */
292           FPE_FLTDIV,         /* 4C - DZ | OFL | STK */
293           FPE_FLTSUB,         /* 4D - INV | DZ | OFL | STK */
294           FPE_FLTDIV,         /* 4E - DNML | DZ | OFL | STK */
295           FPE_FLTSUB,         /* 4F - INV | DNML | DZ | OFL | STK */
296           FPE_FLTUND,         /* 50 - UFL | STK */
297           FPE_FLTSUB,         /* 51 - INV | UFL | STK */
298           FPE_FLTUND,         /* 52 - DNML | UFL | STK */
299           FPE_FLTSUB,         /* 53 - INV | DNML | UFL | STK */
300           FPE_FLTDIV,         /* 54 - DZ | UFL | STK */
301           FPE_FLTSUB,         /* 55 - INV | DZ | UFL | STK */
302           FPE_FLTDIV,         /* 56 - DNML | DZ | UFL | STK */
303           FPE_FLTSUB,         /* 57 - INV | DNML | DZ | UFL | STK */
304           FPE_FLTOVF,         /* 58 - OFL | UFL | STK */
305           FPE_FLTSUB,         /* 59 - INV | OFL | UFL | STK */
306           FPE_FLTUND,         /* 5A - DNML | OFL | UFL | STK */
307           FPE_FLTSUB,         /* 5B - INV | DNML | OFL | UFL | STK */
308           FPE_FLTDIV,         /* 5C - DZ | OFL | UFL | STK */
309           FPE_FLTSUB,         /* 5D - INV | DZ | OFL | UFL | STK */
310           FPE_FLTDIV,         /* 5E - DNML | DZ | OFL | UFL | STK */
311           FPE_FLTSUB,         /* 5F - INV | DNML | DZ | OFL | UFL | STK */
312           FPE_FLTRES,         /* 60 - IMP | STK */
313           FPE_FLTSUB,         /* 61 - INV | IMP | STK */
314           FPE_FLTUND,         /* 62 - DNML | IMP | STK */
315           FPE_FLTSUB,         /* 63 - INV | DNML | IMP | STK */
316           FPE_FLTDIV,         /* 64 - DZ | IMP | STK */
317           FPE_FLTSUB,         /* 65 - INV | DZ | IMP | STK */
318           FPE_FLTDIV,         /* 66 - DNML | DZ | IMP | STK */
319           FPE_FLTSUB,         /* 67 - INV | DNML | DZ | IMP | STK */
320           FPE_FLTOVF,         /* 68 - OFL | IMP | STK */
321           FPE_FLTSUB,         /* 69 - INV | OFL | IMP | STK */
322           FPE_FLTUND,         /* 6A - DNML | OFL | IMP | STK */
323           FPE_FLTSUB,         /* 6B - INV | DNML | OFL | IMP | STK */
324           FPE_FLTDIV,         /* 6C - DZ | OFL | IMP | STK */
325           FPE_FLTSUB,         /* 6D - INV | DZ | OFL | IMP | STK */
326           FPE_FLTDIV,         /* 6E - DNML | DZ | OFL | IMP | STK */
327           FPE_FLTSUB,         /* 6F - INV | DNML | DZ | OFL | IMP | STK */
328           FPE_FLTUND,         /* 70 - UFL | IMP | STK */
329           FPE_FLTSUB,         /* 71 - INV | UFL | IMP | STK */
330           FPE_FLTUND,         /* 72 - DNML | UFL | IMP | STK */
331           FPE_FLTSUB,         /* 73 - INV | DNML | UFL | IMP | STK */
332           FPE_FLTDIV,         /* 74 - DZ | UFL | IMP | STK */
333           FPE_FLTSUB,         /* 75 - INV | DZ | UFL | IMP | STK */
334           FPE_FLTDIV,         /* 76 - DNML | DZ | UFL | IMP | STK */
335           FPE_FLTSUB,         /* 77 - INV | DNML | DZ | UFL | IMP | STK */
336           FPE_FLTOVF,         /* 78 - OFL | UFL | IMP | STK */
337           FPE_FLTSUB,         /* 79 - INV | OFL | UFL | IMP | STK */
338           FPE_FLTUND,         /* 7A - DNML | OFL | UFL | IMP | STK */
339           FPE_FLTSUB,         /* 7B - INV | DNML | OFL | UFL | IMP | STK */
340           FPE_FLTDIV,         /* 7C - DZ | OFL | UFL | IMP | STK */
341           FPE_FLTSUB,         /* 7D - INV | DZ | OFL | UFL | IMP | STK */
342           FPE_FLTDIV,         /* 7E - DNML | DZ | OFL | UFL | IMP | STK */
343           FPE_FLTSUB,         /* 7F - INV | DNML | DZ | OFL | UFL | IMP | STK */
344 };
345 
346 #endif
347 
348 /*
349  * Implement the device not available (DNA) exception.  gd_npxthread had
350  * better be NULL.  Restore the current thread's FP state and set gd_npxthread
351  * to curthread.
352  *
353  * Interrupts are enabled and preemption can occur.  Enter a critical
354  * section to stabilize the FP state.
355  */
356 int
npxdna(void)357 npxdna(void)
358 {
359           struct mdglobaldata *md = mdcpu;
360           thread_t td;
361           int didinit = 0;
362 
363           td = md->mi.gd_curthread;
364 
365           /*
366            * npxthread is almost always NULL.  When it isn't NULL it can
367            * only be exactly equal to 'td'.  This case occurs when the switch
368            * code pro-actively restores the FPU state due to the trap() code
369            * being interruptable (e.g. such as by an interrupt thread).
370            */
371           if (__predict_false(md->gd_npxthread != NULL)) {
372                     if (md->gd_npxthread == td) {
373                               return 1;
374                     }
375                     kprintf("npxdna: npxthread = %p, curthread = %p\n",
376                            md->gd_npxthread, td);
377                     panic("npxdna");
378           }
379 
380           /*
381            * Setup the initial saved state if the thread has never before
382            * used the FP unit.  This also occurs when a thread pushes a
383            * signal handler and uses FP in the handler.
384            */
385           crit_enter();
386           if ((td->td_flags & TDF_USINGFP) == 0) {
387                     td->td_flags |= TDF_USINGFP;
388                     npxinit();
389                     didinit = 1;
390           }
391 
392           /*
393            * The setting of gd_npxthread and the call to fpurstor() must not
394            * be preempted by an interrupt thread or we will take an npxdna
395            * trap and potentially save our current fpstate (which is garbage)
396            * and then restore the garbage rather then the originally saved
397            * fpstate.
398            */
399           stop_emulating();
400 
401           /*
402            * Record new context early in case frstor causes an IRQ13.
403            */
404           md->gd_npxthread = td;
405 
406           /*
407            * The following frstor may cause an IRQ13 when the state being
408            * restored has a pending error.  The error will appear to have been
409            * triggered by the current (npx) user instruction even when that
410            * instruction is a no-wait instruction that should not trigger an
411            * error (e.g., fnclex).  On at least one 486 system all of the
412            * no-wait instructions are broken the same as frstor, so our
413            * treatment does not amplify the breakage.  On at least one
414            * 386/Cyrix 387 system, fnclex works correctly while frstor and
415            * fnsave are broken, so our treatment breaks fnclex if it is the
416            * first FPU instruction after a context switch.
417            */
418           if ((td->td_savefpu->sv_xmm.sv_env.en_mxcsr & ~npx_mxcsr_mask) &&
419               cpu_fxsr) {
420                     krateprintf(&badfprate,
421                                   "%s: FXRSTOR: illegal FP MXCSR %08x didinit = %d\n",
422                                   td->td_comm, td->td_savefpu->sv_xmm.sv_env.en_mxcsr,
423                                   didinit);
424                     td->td_savefpu->sv_xmm.sv_env.en_mxcsr &= npx_mxcsr_mask;
425                     lwpsignal(td->td_proc, td->td_lwp, SIGFPE);
426           }
427           fpurstor(td->td_savefpu, npx_xcr0_mask);
428           crit_exit();
429 
430           return (1);
431 }
432 
433 /*
434  * From cpu heavy restore (already in critical section, gd_npxthread is NULL),
435  * and TDF_USINGFP is already set.  Actively restore the FPU state to avoid
436  * excessive npxdna traps.
437  */
438 void
npxdna_quick(thread_t newtd)439 npxdna_quick(thread_t newtd)
440 {
441           stop_emulating();
442           mdcpu->gd_npxthread = newtd;
443           if ((newtd->td_savefpu->sv_xmm.sv_env.en_mxcsr & ~npx_mxcsr_mask) &&
444               cpu_fxsr) {
445                     krateprintf(&badfprate,
446                                   "%s: FXRSTOR: illegal FP MXCSR %08x\n",
447                                   newtd->td_comm,
448                                   newtd->td_savefpu->sv_xmm.sv_env.en_mxcsr);
449                     newtd->td_savefpu->sv_xmm.sv_env.en_mxcsr &= npx_mxcsr_mask;
450                     lwpsignal(newtd->td_proc, newtd->td_lwp, SIGFPE);
451           }
452           fpurstor(newtd->td_savefpu, npx_xcr0_mask);
453 }
454 
455 /*
456  * Wrapper for the fnsave instruction to handle h/w bugs.  If there is an error
457  * pending, then fnsave generates a bogus IRQ13 on some systems.  Force
458  * any IRQ13 to be handled immediately, and then ignore it.  This routine is
459  * often called at splhigh so it must not use many system services.  In
460  * particular, it's much easier to install a special handler than to
461  * guarantee that it's safe to use npxintr() and its supporting code.
462  *
463  * WARNING!  This call is made during a switch and the MP lock will be
464  * setup for the new target thread rather then the current thread, so we
465  * cannot do anything here that depends on the *_mplock() functions as
466  * we may trip over their assertions.
467  *
468  * WARNING!  When using fxsave we MUST fninit after saving the FP state.  The
469  * kernel will always assume that the FP state is 'safe' (will not cause
470  * exceptions) for mmx/xmm use if npxthread is NULL.  The kernel must still
471  * setup a custom save area before actually using the FP unit, but it will
472  * not bother calling fninit.  This greatly improves kernel performance when
473  * it wishes to use the FP unit.
474  */
475 void
npxsave(union savefpu * addr)476 npxsave(union savefpu *addr)
477 {
478           struct mdglobaldata *md;
479 
480           md = mdcpu;
481           crit_enter();
482           stop_emulating();
483           fpusave(addr, npx_xcr0_mask);
484           md->gd_npxthread = NULL;
485           fninit();
486           fpurstor(&md->gd_zerofpu, npx_xcr0_mask);         /* security wipe */
487           start_emulating();
488           crit_exit();
489 }
490 
491 void
fpusave(union savefpu * addr,uint64_t mask)492 fpusave(union savefpu *addr, uint64_t mask)
493 {
494 #ifndef CPU_DISABLE_AVX
495           if (cpu_xsave)
496                     xsave(addr, mask);
497           else
498 #endif
499           if (cpu_fxsr)
500                     fxsave(addr);
501           else
502                     fnsave(addr);
503 }
504 
505 /*
506  * Save the FP state to the mcontext structure.
507  *
508  * WARNING: If you want to try to npxsave() directly to mctx->mc_fpregs,
509  * then it MUST be 16-byte aligned.  Currently this is not guarenteed.
510  */
511 void
npxpush(mcontext_t * mctx)512 npxpush(mcontext_t *mctx)
513 {
514           thread_t td = curthread;
515 
516           if (td->td_flags & TDF_USINGFP) {
517                     if (mdcpu->gd_npxthread == td) {
518                               /*
519                                * XXX Note: This is a bit inefficient if the signal
520                                * handler uses floating point, extra faults will
521                                * occur.
522                                */
523                               mctx->mc_ownedfp = _MC_FPOWNED_FPU;
524                               npxsave(td->td_savefpu);
525                     } else {
526                               mctx->mc_ownedfp = _MC_FPOWNED_PCB;
527                     }
528                     KKASSERT(sizeof(*td->td_savefpu) <= sizeof(mctx->mc_fpregs));
529                     bcopy(td->td_savefpu, mctx->mc_fpregs, sizeof(*td->td_savefpu));
530                     td->td_flags &= ~TDF_USINGFP;
531 #ifndef CPU_DISABLE_AVX
532                     if (npx_xcr0_mask & CPU_XFEATURE_YMM)
533                               mctx->mc_fpformat = _MC_FPFMT_YMM;
534                     else
535 #endif
536                     {
537                               if (cpu_fxsr)
538                                         mctx->mc_fpformat = _MC_FPFMT_XMM;
539                               else
540                                         mctx->mc_fpformat = _MC_FPFMT_387;
541                     }
542           } else {
543                     mctx->mc_ownedfp = _MC_FPOWNED_NONE;
544                     mctx->mc_fpformat = _MC_FPFMT_NODEV;
545           }
546 }
547 
548 /*
549  * Restore the FP state from the mcontext structure.
550  */
551 void
npxpop(mcontext_t * mctx)552 npxpop(mcontext_t *mctx)
553 {
554           thread_t td = curthread;
555 
556           switch (mctx->mc_ownedfp) {
557           case _MC_FPOWNED_NONE:
558                     /*
559                      * If the signal handler used the FP unit but the interrupted
560                      * code did not, release the FP unit.  Clear TDF_USINGFP will
561                      * force the FP unit to reinit so the interrupted code sees
562                      * a clean slate.
563                      */
564                     if (td->td_flags & TDF_USINGFP) {
565                               if (td == mdcpu->gd_npxthread)
566                                         npxsave(td->td_savefpu);
567                               td->td_flags &= ~TDF_USINGFP;
568                     }
569                     break;
570           case _MC_FPOWNED_FPU:
571           case _MC_FPOWNED_PCB:
572                     /*
573                      * Clear ownership of the FP unit and restore our saved state.
574                      *
575                      * NOTE: The signal handler may have set-up some FP state and
576                      * enabled the FP unit, so we have to restore no matter what.
577                      *
578                      * XXX: This is bit inefficient, if the code being returned
579                      * to is actively using the FP this results in multiple
580                      * kernel faults.
581                      *
582                      * WARNING: The saved state was exposed to userland and may
583                      * have to be sanitized to avoid a GP fault in the kernel.
584                      */
585                     if (td == mdcpu->gd_npxthread)
586                               npxsave(td->td_savefpu);
587                     KKASSERT(sizeof(*td->td_savefpu) <= sizeof(mctx->mc_fpregs));
588                     bcopy(mctx->mc_fpregs, td->td_savefpu, sizeof(*td->td_savefpu));
589                     if ((td->td_savefpu->sv_xmm.sv_env.en_mxcsr & ~npx_mxcsr_mask) &&
590                         cpu_fxsr) {
591                               krateprintf(&badfprate,
592                                             "pid %d (%s) signal return from user: "
593                                             "illegal FP MXCSR %08x\n",
594                                             td->td_proc->p_pid,
595                                             td->td_proc->p_comm,
596                                             td->td_savefpu->sv_xmm.sv_env.en_mxcsr);
597                     }
598                     td->td_flags |= TDF_USINGFP;
599                     break;
600           }
601 }
602 
603 /*
604  * Allow kernel to use FP unit.  This function is not re-entrant.
605  * Saves the current FP state and reinitializes the FP unit.
606  *
607  * XXX really not well optimized, goes through a lot unecessarily.
608  */
609 void
kernel_fpu_begin(void)610 kernel_fpu_begin(void)
611 {
612           thread_t td = curthread;
613 
614           KASSERT((td->td_flags & TDF_KERNELFP) == 0,
615                     ("Recursive call to kernel_fpu_begin()"));
616           atomic_set_int(&td->td_flags, TDF_KERNELFP);
617           if (td->td_kfpuctx == NULL) {
618                     td->td_kfpuctx = kmalloc(sizeof(*td->td_kfpuctx), M_FPUCTX,
619                                                    M_INTWAIT | M_ZERO | M_POWEROF2);
620           }
621           npxpush(td->td_kfpuctx);
622           npxdna();
623 }
624 
625 /*
626  * Indicate that the kernel is no longer using the FP unit.  Restores
627  * the previous FP state.
628  */
629 void
kernel_fpu_end(void)630 kernel_fpu_end(void)
631 {
632           thread_t td = curthread;
633 
634           KASSERT((td->td_flags & TDF_KERNELFP) != 0,
635                     ("kernel_fpu_end() without kernel_fpu_begin()"));
636           npxpop(td->td_kfpuctx);
637           atomic_clear_int(&td->td_flags, TDF_KERNELFP);
638 }
639 
640 /*
641  * On AuthenticAMD processors, the fxrstor instruction does not restore
642  * the x87's stored last instruction pointer, last data pointer, and last
643  * opcode values, except in the rare case in which the exception summary
644  * (ES) bit in the x87 status word is set to 1.
645  *
646  * In order to avoid leaking this information across processes, we clean
647  * these values by performing a dummy load before executing fxrstor().
648  */
649 static void
fpu_clean_state(void)650 fpu_clean_state(void)
651 {
652           u_short status;
653 
654           /*
655            * Clear the ES bit in the x87 status word if it is currently
656            * set, in order to avoid causing a fault in the upcoming load.
657            */
658           fnstsw(&status);
659           if (status & 0x80)
660                     fnclex();
661 
662           /*
663            * Load the dummy variable into the x87 stack.  This mangles
664            * the x87 stack, but we don't care since we're about to call
665            * fxrstor() anyway.
666            */
667           __asm __volatile("ffree %st(7); fldz");
668 }
669 
670 void
fpurstor(union savefpu * addr,uint64_t mask)671 fpurstor(union savefpu *addr, uint64_t mask)
672 {
673 #ifndef CPU_DISABLE_AVX
674           if (cpu_xsave)
675                     xrstor(addr, mask);
676           else
677 #endif
678           if (cpu_fxsr) {
679                     fpu_clean_state();
680                     fxrstor(addr);
681           } else {
682                     frstor(addr);
683           }
684 }
685