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