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