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