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