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