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