fpu.c revision 238914
162053Smarkm/*-
2128059Smarkm * Copyright (c) 1990 William Jolitz.
362053Smarkm * Copyright (c) 1991 The Regents of the University of California.
462053Smarkm * All rights reserved.
562053Smarkm *
662053Smarkm * Redistribution and use in source and binary forms, with or without
762053Smarkm * modification, are permitted provided that the following conditions
862053Smarkm * are met:
962053Smarkm * 1. Redistributions of source code must retain the above copyright
1062053Smarkm *    notice, this list of conditions and the following disclaimer.
1162053Smarkm * 2. Redistributions in binary form must reproduce the above copyright
1262053Smarkm *    notice, this list of conditions and the following disclaimer in the
1362053Smarkm *    documentation and/or other materials provided with the distribution.
1462053Smarkm * 4. Neither the name of the University nor the names of its contributors
1562053Smarkm *    may be used to endorse or promote products derived from this software
1662053Smarkm *    without specific prior written permission.
1762053Smarkm *
1862053Smarkm * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
1962053Smarkm * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2062053Smarkm * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2162053Smarkm * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2262053Smarkm * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2362053Smarkm * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2462053Smarkm * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2562053Smarkm * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2662053Smarkm * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2762053Smarkm * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28119418Sobrien * SUCH DAMAGE.
29119418Sobrien *
30119418Sobrien *	from: @(#)npx.c	7.2 (Berkeley) 5/12/91
3162053Smarkm */
3262053Smarkm
3376166Smarkm#include <sys/cdefs.h>
3462053Smarkm__FBSDID("$FreeBSD: head/sys/amd64/amd64/fpu.c 238914 2012-07-30 19:26:02Z kib $");
3576166Smarkm
3674771Smarkm#include <sys/param.h>
3762053Smarkm#include <sys/systm.h>
3874072Smarkm#include <sys/bus.h>
3976166Smarkm#include <sys/kernel.h>
4062053Smarkm#include <sys/lock.h>
41129876Sphk#include <sys/malloc.h>
4276166Smarkm#include <sys/module.h>
4367112Smarkm#include <sys/mutex.h>
44164033Srwatson#include <sys/mutex.h>
4583366Sjulian#include <sys/proc.h>
4670834Swollman#include <sys/sysctl.h>
4776166Smarkm#include <machine/bus.h>
4876166Smarkm#include <sys/rman.h>
4974072Smarkm#include <sys/signalvar.h>
5062053Smarkm
5174072Smarkm#include <machine/cputypes.h>
5262053Smarkm#include <machine/frame.h>
5374072Smarkm#include <machine/intr_machdep.h>
5462053Smarkm#include <machine/md_var.h>
55122871Smarkm#include <machine/pcb.h>
5662053Smarkm#include <machine/psl.h>
57128059Smarkm#include <machine/resource.h>
58128059Smarkm#include <machine/specialreg.h>
59128059Smarkm#include <machine/segments.h>
60128059Smarkm#include <machine/ucontext.h>
61128059Smarkm
62122871Smarkm/*
6362053Smarkm * Floating point support.
64128059Smarkm */
65128059Smarkm
66128059Smarkm#if defined(__GNUCLIKE_ASM) && !defined(lint)
67128059Smarkm
68128059Smarkm#define	fldcw(cw)		__asm __volatile("fldcw %0" : : "m" (cw))
69128059Smarkm#define	fnclex()		__asm __volatile("fnclex")
70128059Smarkm#define	fninit()		__asm __volatile("fninit")
7162053Smarkm#define	fnstcw(addr)		__asm __volatile("fnstcw %0" : "=m" (*(addr)))
7262053Smarkm#define	fnstsw(addr)		__asm __volatile("fnstsw %0" : "=am" (*(addr)))
73128059Smarkm#define	fxrstor(addr)		__asm __volatile("fxrstor %0" : : "m" (*(addr)))
7474072Smarkm#define	fxsave(addr)		__asm __volatile("fxsave %0" : "=m" (*(addr)))
7562053Smarkm#define	ldmxcsr(csr)		__asm __volatile("ldmxcsr %0" : : "m" (csr))
76130585Sphk#define	stmxcsr(addr)		__asm __volatile("stmxcsr %0" : : "m" (*(addr)))
7762053Smarkm
78128059Smarkmstatic __inline void
79128059Smarkmxrstor(char *addr, uint64_t mask)
80128059Smarkm{
8174072Smarkm	uint32_t low, hi;
8274072Smarkm
8362053Smarkm	low = mask;
8491600Smarkm	hi = mask >> 32;
8562053Smarkm	__asm __volatile("xrstor %0" : : "m" (*addr), "a" (low), "d" (hi));
86130585Sphk}
87128059Smarkm
8869172Smarkmstatic __inline void
89164033Srwatsonxsave(char *addr, uint64_t mask)
90128059Smarkm{
91128059Smarkm	uint32_t low, hi;
92128059Smarkm
9383976Srwatson	low = mask;
94128321Smarkm	hi = mask >> 32;
95128059Smarkm	__asm __volatile("xsave %0" : "=m" (*addr) : "a" (low), "d" (hi) :
9669172Smarkm	    "memory");
9769172Smarkm}
9891600Smarkm
9969172Smarkm#else	/* !(__GNUCLIKE_ASM && !lint) */
100130585Sphk
10162053Smarkmvoid	fldcw(u_short cw);
102128059Smarkmvoid	fnclex(void);
103128367Smarkmvoid	fninit(void);
10462053Smarkmvoid	fnstcw(caddr_t addr);
105128059Smarkmvoid	fnstsw(caddr_t addr);
106153575Spsvoid	fxsave(caddr_t addr);
107153575Spsvoid	fxrstor(caddr_t addr);
108128059Smarkmvoid	ldmxcsr(u_int csr);
109128059Smarkmvoid	stmxcsr(u_int *csr);
110128059Smarkmvoid	xrstor(char *addr, uint64_t mask);
111128367Smarkmvoid	xsave(char *addr, uint64_t mask);
112128367Smarkm
113128367Smarkm#endif	/* __GNUCLIKE_ASM && !lint */
114128059Smarkm
115128059Smarkm#define	start_emulating()	load_cr0(rcr0() | CR0_TS)
116128059Smarkm#define	stop_emulating()	clts()
117128059Smarkm
118128059SmarkmCTASSERT(sizeof(struct savefpu) == 512);
119128367SmarkmCTASSERT(sizeof(struct xstate_hdr) == 64);
120128367SmarkmCTASSERT(sizeof(struct savefpu_ymm) == 832);
121128367Smarkm
12267286Speter/*
123128151Smarkm * This requirement is to make it easier for asm code to calculate
124128059Smarkm * offset of the fpu save area from the pcb address. FPU save area
12562053Smarkm * must be 64-byte aligned.
12662053Smarkm */
12791600SmarkmCTASSERT(sizeof(struct pcb) % XSAVE_AREA_ALIGN == 0);
12862053Smarkm
129130585Sphkstatic	void	fpu_clean_state(void);
13062053Smarkm
131128059SmarkmSYSCTL_INT(_hw, HW_FLOATINGPT, floatingpoint, CTLFLAG_RD,
132128367Smarkm    NULL, 1, "Floating point instructions executed in hardware");
13362053Smarkm
134128367Smarkmstatic int use_xsaveopt;
135128367Smarkmint use_xsave;			/* non-static for cpu_switch.S */
13662053Smarkmuint64_t xsave_mask;		/* the same */
137128059Smarkmstatic	struct savefpu *fpu_initialstate;
13862765Smarkm
13962053Smarkmstruct xsave_area_elm_descr {
14062053Smarkm	u_int	offset;
141128059Smarkm	u_int	size;
14262053Smarkm} *xsave_area_desc;
143128321Smarkm
144128367Smarkmvoid
145128367Smarkmfpusave(void *addr)
146128059Smarkm{
14762053Smarkm
14862053Smarkm	if (use_xsave)
14991600Smarkm		xsave((char *)addr, xsave_mask);
15062053Smarkm	else
151130585Sphk		fxsave((char *)addr);
15291600Smarkm}
15365686Smarkm
154128059Smarkmstatic void
155128059Smarkmfpurestore(void *addr)
15674771Smarkm{
157128059Smarkm
15874771Smarkm	if (use_xsave)
15974771Smarkm		xrstor((char *)addr, xsave_mask);
160128059Smarkm	else
16174771Smarkm		fxrstor((char *)addr);
162128059Smarkm}
16374771Smarkm
164128059Smarkm/*
16565686Smarkm * Enable XSAVE if supported and allowed by user.
16665686Smarkm * Calculate the xsave_mask.
16791600Smarkm */
16865686Smarkmstatic void
169130585Sphkfpuinit_bsp1(void)
17067112Smarkm{
171128059Smarkm	u_int cp[4];
17267112Smarkm	uint64_t xsave_mask_user;
17367112Smarkm
17474072Smarkm	if ((cpu_feature2 & CPUID2_XSAVE) != 0) {
17567112Smarkm		use_xsave = 1;
17667112Smarkm		TUNABLE_INT_FETCH("hw.use_xsave", &use_xsave);
177153575Sps	}
17867112Smarkm	if (!use_xsave)
179128059Smarkm		return;
18067112Smarkm
18167112Smarkm	cpuid_count(0xd, 0x0, cp);
18291600Smarkm	xsave_mask = XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE;
18367112Smarkm	if ((cp[0] & xsave_mask) != xsave_mask)
18491600Smarkm		panic("CPU0 does not support X87 or SSE: %x", cp[0]);
18562053Smarkm	xsave_mask = ((uint64_t)cp[3] << 32) | cp[0];
186128059Smarkm	xsave_mask_user = xsave_mask;
18765686Smarkm	TUNABLE_ULONG_FETCH("hw.xsave_mask", &xsave_mask_user);
188128059Smarkm	xsave_mask_user |= XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE;
18962053Smarkm	xsave_mask &= xsave_mask_user;
190128059Smarkm
191128059Smarkm	cpuid_count(0xd, 0x1, cp);
19271037Smarkm	if ((cp[0] & CPUID_EXTSTATE_XSAVEOPT) != 0) {
193131398Sjhb		/*
194131398Sjhb		 * Patch the XSAVE instruction in the cpu_switch code
195131398Sjhb		 * to XSAVEOPT.  We assume that XSAVE encoding used
19671037Smarkm		 * REX byte, and set the bit 4 of the r/m byte.
197128059Smarkm		 */
198128059Smarkm		ctx_switch_xsave[3] |= 0x10;
199128059Smarkm		use_xsaveopt = 1;
20074072Smarkm	}
201128059Smarkm}
20274072Smarkm
20362053Smarkm/*
204128059Smarkm * Calculate the fpu save area size.
20574072Smarkm */
206128059Smarkmstatic void
20774072Smarkmfpuinit_bsp2(void)
208128059Smarkm{
209122871Smarkm	u_int cp[4];
21062053Smarkm
211128059Smarkm	if (use_xsave) {
21262053Smarkm		cpuid_count(0xd, 0x0, cp);
213132199Sphk		cpu_max_ext_state_size = cp[1];
214132199Sphk
215132199Sphk		/*
216132199Sphk		 * Reload the cpu_feature2, since we enabled OSXSAVE.
21762053Smarkm		 */
218128059Smarkm		do_cpuid(1, cp);
21962053Smarkm		cpu_feature2 = cp[2];
22062053Smarkm	} else
22162053Smarkm		cpu_max_ext_state_size = sizeof(struct savefpu);
222133036Smarkm}
223
224/*
225 * Initialize the floating point unit.
226 */
227void
228fpuinit(void)
229{
230	register_t saveintr;
231	u_int mxcsr;
232	u_short control;
233
234	if (IS_BSP())
235		fpuinit_bsp1();
236
237	if (use_xsave) {
238		load_cr4(rcr4() | CR4_XSAVE);
239		load_xcr(XCR0, xsave_mask);
240	}
241
242	/*
243	 * XCR0 shall be set up before CPU can report the save area size.
244	 */
245	if (IS_BSP())
246		fpuinit_bsp2();
247
248	/*
249	 * It is too early for critical_enter() to work on AP.
250	 */
251	saveintr = intr_disable();
252	stop_emulating();
253	fninit();
254	control = __INITIAL_FPUCW__;
255	fldcw(control);
256	mxcsr = __INITIAL_MXCSR__;
257	ldmxcsr(mxcsr);
258	start_emulating();
259	intr_restore(saveintr);
260}
261
262/*
263 * On the boot CPU we generate a clean state that is used to
264 * initialize the floating point unit when it is first used by a
265 * process.
266 */
267static void
268fpuinitstate(void *arg __unused)
269{
270	register_t saveintr;
271	int cp[4], i, max_ext_n;
272
273	fpu_initialstate = malloc(cpu_max_ext_state_size, M_DEVBUF,
274	    M_WAITOK | M_ZERO);
275	saveintr = intr_disable();
276	stop_emulating();
277
278	fpusave(fpu_initialstate);
279	if (fpu_initialstate->sv_env.en_mxcsr_mask)
280		cpu_mxcsr_mask = fpu_initialstate->sv_env.en_mxcsr_mask;
281	else
282		cpu_mxcsr_mask = 0xFFBF;
283
284	/*
285	 * The fninit instruction does not modify XMM registers.  The
286	 * fpusave call dumped the garbage contained in the registers
287	 * after reset to the initial state saved.  Clear XMM
288	 * registers file image to make the startup program state and
289	 * signal handler XMM register content predictable.
290	 */
291	bzero(&fpu_initialstate->sv_xmm[0], sizeof(struct xmmacc));
292
293	/*
294	 * Create a table describing the layout of the CPU Extended
295	 * Save Area.
296	 */
297	if (use_xsaveopt) {
298		max_ext_n = flsl(xsave_mask);
299		xsave_area_desc = malloc(max_ext_n * sizeof(struct
300		    xsave_area_elm_descr), M_DEVBUF, M_WAITOK | M_ZERO);
301		/* x87 state */
302		xsave_area_desc[0].offset = 0;
303		xsave_area_desc[0].size = 160;
304		/* XMM */
305		xsave_area_desc[1].offset = 160;
306		xsave_area_desc[1].size = 288 - 160;
307
308		for (i = 2; i < max_ext_n; i++) {
309			cpuid_count(0xd, i, cp);
310			xsave_area_desc[i].offset = cp[1];
311			xsave_area_desc[i].size = cp[0];
312		}
313	}
314
315	start_emulating();
316	intr_restore(saveintr);
317}
318SYSINIT(fpuinitstate, SI_SUB_DRIVERS, SI_ORDER_ANY, fpuinitstate, NULL);
319
320/*
321 * Free coprocessor (if we have it).
322 */
323void
324fpuexit(struct thread *td)
325{
326
327	critical_enter();
328	if (curthread == PCPU_GET(fpcurthread)) {
329		stop_emulating();
330		fpusave(curpcb->pcb_save);
331		start_emulating();
332		PCPU_SET(fpcurthread, 0);
333	}
334	critical_exit();
335}
336
337int
338fpuformat()
339{
340
341	return (_MC_FPFMT_XMM);
342}
343
344/*
345 * The following mechanism is used to ensure that the FPE_... value
346 * that is passed as a trapcode to the signal handler of the user
347 * process does not have more than one bit set.
348 *
349 * Multiple bits may be set if the user process modifies the control
350 * word while a status word bit is already set.  While this is a sign
351 * of bad coding, we have no choise than to narrow them down to one
352 * bit, since we must not send a trapcode that is not exactly one of
353 * the FPE_ macros.
354 *
355 * The mechanism has a static table with 127 entries.  Each combination
356 * of the 7 FPU status word exception bits directly translates to a
357 * position in this table, where a single FPE_... value is stored.
358 * This FPE_... value stored there is considered the "most important"
359 * of the exception bits and will be sent as the signal code.  The
360 * precedence of the bits is based upon Intel Document "Numerical
361 * Applications", Chapter "Special Computational Situations".
362 *
363 * The macro to choose one of these values does these steps: 1) Throw
364 * away status word bits that cannot be masked.  2) Throw away the bits
365 * currently masked in the control word, assuming the user isn't
366 * interested in them anymore.  3) Reinsert status word bit 7 (stack
367 * fault) if it is set, which cannot be masked but must be presered.
368 * 4) Use the remaining bits to point into the trapcode table.
369 *
370 * The 6 maskable bits in order of their preference, as stated in the
371 * above referenced Intel manual:
372 * 1  Invalid operation (FP_X_INV)
373 * 1a   Stack underflow
374 * 1b   Stack overflow
375 * 1c   Operand of unsupported format
376 * 1d   SNaN operand.
377 * 2  QNaN operand (not an exception, irrelavant here)
378 * 3  Any other invalid-operation not mentioned above or zero divide
379 *      (FP_X_INV, FP_X_DZ)
380 * 4  Denormal operand (FP_X_DNML)
381 * 5  Numeric over/underflow (FP_X_OFL, FP_X_UFL)
382 * 6  Inexact result (FP_X_IMP)
383 */
384static char fpetable[128] = {
385	0,
386	FPE_FLTINV,	/*  1 - INV */
387	FPE_FLTUND,	/*  2 - DNML */
388	FPE_FLTINV,	/*  3 - INV | DNML */
389	FPE_FLTDIV,	/*  4 - DZ */
390	FPE_FLTINV,	/*  5 - INV | DZ */
391	FPE_FLTDIV,	/*  6 - DNML | DZ */
392	FPE_FLTINV,	/*  7 - INV | DNML | DZ */
393	FPE_FLTOVF,	/*  8 - OFL */
394	FPE_FLTINV,	/*  9 - INV | OFL */
395	FPE_FLTUND,	/*  A - DNML | OFL */
396	FPE_FLTINV,	/*  B - INV | DNML | OFL */
397	FPE_FLTDIV,	/*  C - DZ | OFL */
398	FPE_FLTINV,	/*  D - INV | DZ | OFL */
399	FPE_FLTDIV,	/*  E - DNML | DZ | OFL */
400	FPE_FLTINV,	/*  F - INV | DNML | DZ | OFL */
401	FPE_FLTUND,	/* 10 - UFL */
402	FPE_FLTINV,	/* 11 - INV | UFL */
403	FPE_FLTUND,	/* 12 - DNML | UFL */
404	FPE_FLTINV,	/* 13 - INV | DNML | UFL */
405	FPE_FLTDIV,	/* 14 - DZ | UFL */
406	FPE_FLTINV,	/* 15 - INV | DZ | UFL */
407	FPE_FLTDIV,	/* 16 - DNML | DZ | UFL */
408	FPE_FLTINV,	/* 17 - INV | DNML | DZ | UFL */
409	FPE_FLTOVF,	/* 18 - OFL | UFL */
410	FPE_FLTINV,	/* 19 - INV | OFL | UFL */
411	FPE_FLTUND,	/* 1A - DNML | OFL | UFL */
412	FPE_FLTINV,	/* 1B - INV | DNML | OFL | UFL */
413	FPE_FLTDIV,	/* 1C - DZ | OFL | UFL */
414	FPE_FLTINV,	/* 1D - INV | DZ | OFL | UFL */
415	FPE_FLTDIV,	/* 1E - DNML | DZ | OFL | UFL */
416	FPE_FLTINV,	/* 1F - INV | DNML | DZ | OFL | UFL */
417	FPE_FLTRES,	/* 20 - IMP */
418	FPE_FLTINV,	/* 21 - INV | IMP */
419	FPE_FLTUND,	/* 22 - DNML | IMP */
420	FPE_FLTINV,	/* 23 - INV | DNML | IMP */
421	FPE_FLTDIV,	/* 24 - DZ | IMP */
422	FPE_FLTINV,	/* 25 - INV | DZ | IMP */
423	FPE_FLTDIV,	/* 26 - DNML | DZ | IMP */
424	FPE_FLTINV,	/* 27 - INV | DNML | DZ | IMP */
425	FPE_FLTOVF,	/* 28 - OFL | IMP */
426	FPE_FLTINV,	/* 29 - INV | OFL | IMP */
427	FPE_FLTUND,	/* 2A - DNML | OFL | IMP */
428	FPE_FLTINV,	/* 2B - INV | DNML | OFL | IMP */
429	FPE_FLTDIV,	/* 2C - DZ | OFL | IMP */
430	FPE_FLTINV,	/* 2D - INV | DZ | OFL | IMP */
431	FPE_FLTDIV,	/* 2E - DNML | DZ | OFL | IMP */
432	FPE_FLTINV,	/* 2F - INV | DNML | DZ | OFL | IMP */
433	FPE_FLTUND,	/* 30 - UFL | IMP */
434	FPE_FLTINV,	/* 31 - INV | UFL | IMP */
435	FPE_FLTUND,	/* 32 - DNML | UFL | IMP */
436	FPE_FLTINV,	/* 33 - INV | DNML | UFL | IMP */
437	FPE_FLTDIV,	/* 34 - DZ | UFL | IMP */
438	FPE_FLTINV,	/* 35 - INV | DZ | UFL | IMP */
439	FPE_FLTDIV,	/* 36 - DNML | DZ | UFL | IMP */
440	FPE_FLTINV,	/* 37 - INV | DNML | DZ | UFL | IMP */
441	FPE_FLTOVF,	/* 38 - OFL | UFL | IMP */
442	FPE_FLTINV,	/* 39 - INV | OFL | UFL | IMP */
443	FPE_FLTUND,	/* 3A - DNML | OFL | UFL | IMP */
444	FPE_FLTINV,	/* 3B - INV | DNML | OFL | UFL | IMP */
445	FPE_FLTDIV,	/* 3C - DZ | OFL | UFL | IMP */
446	FPE_FLTINV,	/* 3D - INV | DZ | OFL | UFL | IMP */
447	FPE_FLTDIV,	/* 3E - DNML | DZ | OFL | UFL | IMP */
448	FPE_FLTINV,	/* 3F - INV | DNML | DZ | OFL | UFL | IMP */
449	FPE_FLTSUB,	/* 40 - STK */
450	FPE_FLTSUB,	/* 41 - INV | STK */
451	FPE_FLTUND,	/* 42 - DNML | STK */
452	FPE_FLTSUB,	/* 43 - INV | DNML | STK */
453	FPE_FLTDIV,	/* 44 - DZ | STK */
454	FPE_FLTSUB,	/* 45 - INV | DZ | STK */
455	FPE_FLTDIV,	/* 46 - DNML | DZ | STK */
456	FPE_FLTSUB,	/* 47 - INV | DNML | DZ | STK */
457	FPE_FLTOVF,	/* 48 - OFL | STK */
458	FPE_FLTSUB,	/* 49 - INV | OFL | STK */
459	FPE_FLTUND,	/* 4A - DNML | OFL | STK */
460	FPE_FLTSUB,	/* 4B - INV | DNML | OFL | STK */
461	FPE_FLTDIV,	/* 4C - DZ | OFL | STK */
462	FPE_FLTSUB,	/* 4D - INV | DZ | OFL | STK */
463	FPE_FLTDIV,	/* 4E - DNML | DZ | OFL | STK */
464	FPE_FLTSUB,	/* 4F - INV | DNML | DZ | OFL | STK */
465	FPE_FLTUND,	/* 50 - UFL | STK */
466	FPE_FLTSUB,	/* 51 - INV | UFL | STK */
467	FPE_FLTUND,	/* 52 - DNML | UFL | STK */
468	FPE_FLTSUB,	/* 53 - INV | DNML | UFL | STK */
469	FPE_FLTDIV,	/* 54 - DZ | UFL | STK */
470	FPE_FLTSUB,	/* 55 - INV | DZ | UFL | STK */
471	FPE_FLTDIV,	/* 56 - DNML | DZ | UFL | STK */
472	FPE_FLTSUB,	/* 57 - INV | DNML | DZ | UFL | STK */
473	FPE_FLTOVF,	/* 58 - OFL | UFL | STK */
474	FPE_FLTSUB,	/* 59 - INV | OFL | UFL | STK */
475	FPE_FLTUND,	/* 5A - DNML | OFL | UFL | STK */
476	FPE_FLTSUB,	/* 5B - INV | DNML | OFL | UFL | STK */
477	FPE_FLTDIV,	/* 5C - DZ | OFL | UFL | STK */
478	FPE_FLTSUB,	/* 5D - INV | DZ | OFL | UFL | STK */
479	FPE_FLTDIV,	/* 5E - DNML | DZ | OFL | UFL | STK */
480	FPE_FLTSUB,	/* 5F - INV | DNML | DZ | OFL | UFL | STK */
481	FPE_FLTRES,	/* 60 - IMP | STK */
482	FPE_FLTSUB,	/* 61 - INV | IMP | STK */
483	FPE_FLTUND,	/* 62 - DNML | IMP | STK */
484	FPE_FLTSUB,	/* 63 - INV | DNML | IMP | STK */
485	FPE_FLTDIV,	/* 64 - DZ | IMP | STK */
486	FPE_FLTSUB,	/* 65 - INV | DZ | IMP | STK */
487	FPE_FLTDIV,	/* 66 - DNML | DZ | IMP | STK */
488	FPE_FLTSUB,	/* 67 - INV | DNML | DZ | IMP | STK */
489	FPE_FLTOVF,	/* 68 - OFL | IMP | STK */
490	FPE_FLTSUB,	/* 69 - INV | OFL | IMP | STK */
491	FPE_FLTUND,	/* 6A - DNML | OFL | IMP | STK */
492	FPE_FLTSUB,	/* 6B - INV | DNML | OFL | IMP | STK */
493	FPE_FLTDIV,	/* 6C - DZ | OFL | IMP | STK */
494	FPE_FLTSUB,	/* 6D - INV | DZ | OFL | IMP | STK */
495	FPE_FLTDIV,	/* 6E - DNML | DZ | OFL | IMP | STK */
496	FPE_FLTSUB,	/* 6F - INV | DNML | DZ | OFL | IMP | STK */
497	FPE_FLTUND,	/* 70 - UFL | IMP | STK */
498	FPE_FLTSUB,	/* 71 - INV | UFL | IMP | STK */
499	FPE_FLTUND,	/* 72 - DNML | UFL | IMP | STK */
500	FPE_FLTSUB,	/* 73 - INV | DNML | UFL | IMP | STK */
501	FPE_FLTDIV,	/* 74 - DZ | UFL | IMP | STK */
502	FPE_FLTSUB,	/* 75 - INV | DZ | UFL | IMP | STK */
503	FPE_FLTDIV,	/* 76 - DNML | DZ | UFL | IMP | STK */
504	FPE_FLTSUB,	/* 77 - INV | DNML | DZ | UFL | IMP | STK */
505	FPE_FLTOVF,	/* 78 - OFL | UFL | IMP | STK */
506	FPE_FLTSUB,	/* 79 - INV | OFL | UFL | IMP | STK */
507	FPE_FLTUND,	/* 7A - DNML | OFL | UFL | IMP | STK */
508	FPE_FLTSUB,	/* 7B - INV | DNML | OFL | UFL | IMP | STK */
509	FPE_FLTDIV,	/* 7C - DZ | OFL | UFL | IMP | STK */
510	FPE_FLTSUB,	/* 7D - INV | DZ | OFL | UFL | IMP | STK */
511	FPE_FLTDIV,	/* 7E - DNML | DZ | OFL | UFL | IMP | STK */
512	FPE_FLTSUB,	/* 7F - INV | DNML | DZ | OFL | UFL | IMP | STK */
513};
514
515/*
516 * Read the FP status and control words, then generate si_code value
517 * for SIGFPE.  The error code chosen will be one of the
518 * FPE_... macros.  It will be sent as the second argument to old
519 * BSD-style signal handlers and as "siginfo_t->si_code" (second
520 * argument) to SA_SIGINFO signal handlers.
521 *
522 * Some time ago, we cleared the x87 exceptions with FNCLEX there.
523 * Clearing exceptions was necessary mainly to avoid IRQ13 bugs.  The
524 * usermode code which understands the FPU hardware enough to enable
525 * the exceptions, can also handle clearing the exception state in the
526 * handler.  The only consequence of not clearing the exception is the
527 * rethrow of the SIGFPE on return from the signal handler and
528 * reexecution of the corresponding instruction.
529 *
530 * For XMM traps, the exceptions were never cleared.
531 */
532int
533fputrap_x87(void)
534{
535	struct savefpu *pcb_save;
536	u_short control, status;
537
538	critical_enter();
539
540	/*
541	 * Interrupt handling (for another interrupt) may have pushed the
542	 * state to memory.  Fetch the relevant parts of the state from
543	 * wherever they are.
544	 */
545	if (PCPU_GET(fpcurthread) != curthread) {
546		pcb_save = curpcb->pcb_save;
547		control = pcb_save->sv_env.en_cw;
548		status = pcb_save->sv_env.en_sw;
549	} else {
550		fnstcw(&control);
551		fnstsw(&status);
552	}
553
554	critical_exit();
555	return (fpetable[status & ((~control & 0x3f) | 0x40)]);
556}
557
558int
559fputrap_sse(void)
560{
561	u_int mxcsr;
562
563	critical_enter();
564	if (PCPU_GET(fpcurthread) != curthread)
565		mxcsr = curpcb->pcb_save->sv_env.en_mxcsr;
566	else
567		stmxcsr(&mxcsr);
568	critical_exit();
569	return (fpetable[(mxcsr & (~mxcsr >> 7)) & 0x3f]);
570}
571
572/*
573 * Implement device not available (DNA) exception
574 *
575 * It would be better to switch FP context here (if curthread != fpcurthread)
576 * and not necessarily for every context switch, but it is too hard to
577 * access foreign pcb's.
578 */
579
580static int err_count = 0;
581
582void
583fpudna(void)
584{
585
586	critical_enter();
587	if (PCPU_GET(fpcurthread) == curthread) {
588		printf("fpudna: fpcurthread == curthread %d times\n",
589		    ++err_count);
590		stop_emulating();
591		critical_exit();
592		return;
593	}
594	if (PCPU_GET(fpcurthread) != NULL) {
595		printf("fpudna: fpcurthread = %p (%d), curthread = %p (%d)\n",
596		       PCPU_GET(fpcurthread),
597		       PCPU_GET(fpcurthread)->td_proc->p_pid,
598		       curthread, curthread->td_proc->p_pid);
599		panic("fpudna");
600	}
601	stop_emulating();
602	/*
603	 * Record new context early in case frstor causes a trap.
604	 */
605	PCPU_SET(fpcurthread, curthread);
606
607	fpu_clean_state();
608
609	if ((curpcb->pcb_flags & PCB_FPUINITDONE) == 0) {
610		/*
611		 * This is the first time this thread has used the FPU or
612		 * the PCB doesn't contain a clean FPU state.  Explicitly
613		 * load an initial state.
614		 *
615		 * We prefer to restore the state from the actual save
616		 * area in PCB instead of directly loading from
617		 * fpu_initialstate, to ignite the XSAVEOPT
618		 * tracking engine.
619		 */
620		bcopy(fpu_initialstate, curpcb->pcb_save, cpu_max_ext_state_size);
621		fpurestore(curpcb->pcb_save);
622		if (curpcb->pcb_initial_fpucw != __INITIAL_FPUCW__)
623			fldcw(curpcb->pcb_initial_fpucw);
624		if (PCB_USER_FPU(curpcb))
625			set_pcb_flags(curpcb,
626			    PCB_FPUINITDONE | PCB_USERFPUINITDONE);
627		else
628			set_pcb_flags(curpcb, PCB_FPUINITDONE);
629	} else
630		fpurestore(curpcb->pcb_save);
631	critical_exit();
632}
633
634void
635fpudrop()
636{
637	struct thread *td;
638
639	td = PCPU_GET(fpcurthread);
640	KASSERT(td == curthread, ("fpudrop: fpcurthread != curthread"));
641	CRITICAL_ASSERT(td);
642	PCPU_SET(fpcurthread, NULL);
643	clear_pcb_flags(td->td_pcb, PCB_FPUINITDONE);
644	start_emulating();
645}
646
647/*
648 * Get the user state of the FPU into pcb->pcb_user_save without
649 * dropping ownership (if possible).  It returns the FPU ownership
650 * status.
651 */
652int
653fpugetregs(struct thread *td)
654{
655	struct pcb *pcb;
656	uint64_t *xstate_bv, bit;
657	char *sa;
658	int max_ext_n, i;
659
660	pcb = td->td_pcb;
661	if ((pcb->pcb_flags & PCB_USERFPUINITDONE) == 0) {
662		bcopy(fpu_initialstate, get_pcb_user_save_pcb(pcb),
663		    cpu_max_ext_state_size);
664		get_pcb_user_save_pcb(pcb)->sv_env.en_cw =
665		    pcb->pcb_initial_fpucw;
666		fpuuserinited(td);
667		return (_MC_FPOWNED_PCB);
668	}
669	critical_enter();
670	if (td == PCPU_GET(fpcurthread) && PCB_USER_FPU(pcb)) {
671		fpusave(get_pcb_user_save_pcb(pcb));
672		critical_exit();
673		return (_MC_FPOWNED_FPU);
674	} else {
675		critical_exit();
676		if (use_xsaveopt) {
677			/*
678			 * Handle partially saved state.
679			 */
680			sa = (char *)get_pcb_user_save_pcb(pcb);
681			xstate_bv = (uint64_t *)(sa + sizeof(struct savefpu) +
682			    offsetof(struct xstate_hdr, xstate_bv));
683			max_ext_n = flsl(xsave_mask);
684			for (i = 0; i < max_ext_n; i++) {
685				bit = 1 << i;
686				if ((*xstate_bv & bit) != 0)
687					continue;
688				bcopy((char *)fpu_initialstate +
689				    xsave_area_desc[i].offset,
690				    sa + xsave_area_desc[i].offset,
691				    xsave_area_desc[i].size);
692				*xstate_bv |= bit;
693			}
694		}
695		return (_MC_FPOWNED_PCB);
696	}
697}
698
699void
700fpuuserinited(struct thread *td)
701{
702	struct pcb *pcb;
703
704	pcb = td->td_pcb;
705	if (PCB_USER_FPU(pcb))
706		set_pcb_flags(pcb,
707		    PCB_FPUINITDONE | PCB_USERFPUINITDONE);
708	else
709		set_pcb_flags(pcb, PCB_FPUINITDONE);
710}
711
712int
713fpusetxstate(struct thread *td, char *xfpustate, size_t xfpustate_size)
714{
715	struct xstate_hdr *hdr, *ehdr;
716	size_t len, max_len;
717	uint64_t bv;
718
719	/* XXXKIB should we clear all extended state in xstate_bv instead ? */
720	if (xfpustate == NULL)
721		return (0);
722	if (!use_xsave)
723		return (EOPNOTSUPP);
724
725	len = xfpustate_size;
726	if (len < sizeof(struct xstate_hdr))
727		return (EINVAL);
728	max_len = cpu_max_ext_state_size - sizeof(struct savefpu);
729	if (len > max_len)
730		return (EINVAL);
731
732	ehdr = (struct xstate_hdr *)xfpustate;
733	bv = ehdr->xstate_bv;
734
735	/*
736	 * Avoid #gp.
737	 */
738	if (bv & ~xsave_mask)
739		return (EINVAL);
740	if ((bv & (XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE)) !=
741	    (XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE))
742		return (EINVAL);
743
744	hdr = (struct xstate_hdr *)(get_pcb_user_save_td(td) + 1);
745
746	hdr->xstate_bv = bv;
747	bcopy(xfpustate + sizeof(struct xstate_hdr),
748	    (char *)(hdr + 1), len - sizeof(struct xstate_hdr));
749
750	return (0);
751}
752
753/*
754 * Set the state of the FPU.
755 */
756int
757fpusetregs(struct thread *td, struct savefpu *addr, char *xfpustate,
758    size_t xfpustate_size)
759{
760	struct pcb *pcb;
761	int error;
762
763	pcb = td->td_pcb;
764	critical_enter();
765	if (td == PCPU_GET(fpcurthread) && PCB_USER_FPU(pcb)) {
766		error = fpusetxstate(td, xfpustate, xfpustate_size);
767		if (error != 0) {
768			critical_exit();
769			return (error);
770		}
771		bcopy(addr, get_pcb_user_save_td(td), sizeof(*addr));
772		fpurestore(get_pcb_user_save_td(td));
773		critical_exit();
774		set_pcb_flags(pcb, PCB_FPUINITDONE | PCB_USERFPUINITDONE);
775	} else {
776		critical_exit();
777		error = fpusetxstate(td, xfpustate, xfpustate_size);
778		if (error != 0)
779			return (error);
780		bcopy(addr, get_pcb_user_save_td(td), sizeof(*addr));
781		fpuuserinited(td);
782	}
783	return (0);
784}
785
786/*
787 * On AuthenticAMD processors, the fxrstor instruction does not restore
788 * the x87's stored last instruction pointer, last data pointer, and last
789 * opcode values, except in the rare case in which the exception summary
790 * (ES) bit in the x87 status word is set to 1.
791 *
792 * In order to avoid leaking this information across processes, we clean
793 * these values by performing a dummy load before executing fxrstor().
794 */
795static void
796fpu_clean_state(void)
797{
798	static float dummy_variable = 0.0;
799	u_short status;
800
801	/*
802	 * Clear the ES bit in the x87 status word if it is currently
803	 * set, in order to avoid causing a fault in the upcoming load.
804	 */
805	fnstsw(&status);
806	if (status & 0x80)
807		fnclex();
808
809	/*
810	 * Load the dummy variable into the x87 stack.  This mangles
811	 * the x87 stack, but we don't care since we're about to call
812	 * fxrstor() anyway.
813	 */
814	__asm __volatile("ffree %%st(7); flds %0" : : "m" (dummy_variable));
815}
816
817/*
818 * This really sucks.  We want the acpi version only, but it requires
819 * the isa_if.h file in order to get the definitions.
820 */
821#include "opt_isa.h"
822#ifdef DEV_ISA
823#include <isa/isavar.h>
824/*
825 * This sucks up the legacy ISA support assignments from PNPBIOS/ACPI.
826 */
827static struct isa_pnp_id fpupnp_ids[] = {
828	{ 0x040cd041, "Legacy ISA coprocessor support" }, /* PNP0C04 */
829	{ 0 }
830};
831
832static int
833fpupnp_probe(device_t dev)
834{
835	int result;
836
837	result = ISA_PNP_PROBE(device_get_parent(dev), dev, fpupnp_ids);
838	if (result <= 0)
839		device_quiet(dev);
840	return (result);
841}
842
843static int
844fpupnp_attach(device_t dev)
845{
846
847	return (0);
848}
849
850static device_method_t fpupnp_methods[] = {
851	/* Device interface */
852	DEVMETHOD(device_probe,		fpupnp_probe),
853	DEVMETHOD(device_attach,	fpupnp_attach),
854	DEVMETHOD(device_detach,	bus_generic_detach),
855	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
856	DEVMETHOD(device_suspend,	bus_generic_suspend),
857	DEVMETHOD(device_resume,	bus_generic_resume),
858
859	{ 0, 0 }
860};
861
862static driver_t fpupnp_driver = {
863	"fpupnp",
864	fpupnp_methods,
865	1,			/* no softc */
866};
867
868static devclass_t fpupnp_devclass;
869
870DRIVER_MODULE(fpupnp, acpi, fpupnp_driver, fpupnp_devclass, 0, 0);
871#endif	/* DEV_ISA */
872
873static MALLOC_DEFINE(M_FPUKERN_CTX, "fpukern_ctx",
874    "Kernel contexts for FPU state");
875
876#define	FPU_KERN_CTX_FPUINITDONE 0x01
877
878struct fpu_kern_ctx {
879	struct savefpu *prev;
880	uint32_t flags;
881	char hwstate1[];
882};
883
884struct fpu_kern_ctx *
885fpu_kern_alloc_ctx(u_int flags)
886{
887	struct fpu_kern_ctx *res;
888	size_t sz;
889
890	sz = sizeof(struct fpu_kern_ctx) + XSAVE_AREA_ALIGN +
891	    cpu_max_ext_state_size;
892	res = malloc(sz, M_FPUKERN_CTX, ((flags & FPU_KERN_NOWAIT) ?
893	    M_NOWAIT : M_WAITOK) | M_ZERO);
894	return (res);
895}
896
897void
898fpu_kern_free_ctx(struct fpu_kern_ctx *ctx)
899{
900
901	/* XXXKIB clear the memory ? */
902	free(ctx, M_FPUKERN_CTX);
903}
904
905static struct savefpu *
906fpu_kern_ctx_savefpu(struct fpu_kern_ctx *ctx)
907{
908	vm_offset_t p;
909
910	p = (vm_offset_t)&ctx->hwstate1;
911	p = roundup2(p, XSAVE_AREA_ALIGN);
912	return ((struct savefpu *)p);
913}
914
915int
916fpu_kern_enter(struct thread *td, struct fpu_kern_ctx *ctx, u_int flags)
917{
918	struct pcb *pcb;
919
920	pcb = td->td_pcb;
921	KASSERT(!PCB_USER_FPU(pcb) || pcb->pcb_save ==
922	    get_pcb_user_save_pcb(pcb), ("mangled pcb_save"));
923	ctx->flags = 0;
924	if ((pcb->pcb_flags & PCB_FPUINITDONE) != 0)
925		ctx->flags |= FPU_KERN_CTX_FPUINITDONE;
926	fpuexit(td);
927	ctx->prev = pcb->pcb_save;
928	pcb->pcb_save = fpu_kern_ctx_savefpu(ctx);
929	set_pcb_flags(pcb, PCB_KERNFPU);
930	clear_pcb_flags(pcb, PCB_FPUINITDONE);
931	return (0);
932}
933
934int
935fpu_kern_leave(struct thread *td, struct fpu_kern_ctx *ctx)
936{
937	struct pcb *pcb;
938
939	pcb = td->td_pcb;
940	critical_enter();
941	if (curthread == PCPU_GET(fpcurthread))
942		fpudrop();
943	critical_exit();
944	pcb->pcb_save = ctx->prev;
945	if (pcb->pcb_save == get_pcb_user_save_pcb(pcb)) {
946		if ((pcb->pcb_flags & PCB_USERFPUINITDONE) != 0) {
947			set_pcb_flags(pcb, PCB_FPUINITDONE);
948			clear_pcb_flags(pcb, PCB_KERNFPU);
949		} else
950			clear_pcb_flags(pcb, PCB_FPUINITDONE | PCB_KERNFPU);
951	} else {
952		if ((ctx->flags & FPU_KERN_CTX_FPUINITDONE) != 0)
953			set_pcb_flags(pcb, PCB_FPUINITDONE);
954		else
955			clear_pcb_flags(pcb, PCB_FPUINITDONE);
956		KASSERT(!PCB_USER_FPU(pcb), ("unpaired fpu_kern_leave"));
957	}
958	return (0);
959}
960
961int
962fpu_kern_thread(u_int flags)
963{
964
965	KASSERT((curthread->td_pflags & TDP_KTHREAD) != 0,
966	    ("Only kthread may use fpu_kern_thread"));
967	KASSERT(curpcb->pcb_save == get_pcb_user_save_pcb(curpcb),
968	    ("mangled pcb_save"));
969	KASSERT(PCB_USER_FPU(curpcb), ("recursive call"));
970
971	set_pcb_flags(curpcb, PCB_KERNFPU);
972	return (0);
973}
974
975int
976is_fpu_kern_thread(u_int flags)
977{
978
979	if ((curthread->td_pflags & TDP_KTHREAD) == 0)
980		return (0);
981	return ((curpcb->pcb_flags & PCB_KERNFPU) != 0);
982}
983