npx.c revision 336963
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: stable/11/sys/i386/isa/npx.c 336963 2018-07-31 10:18:30Z kib $");
35
36#include "opt_cpu.h"
37#include "opt_isa.h"
38#include "opt_npx.h"
39
40#include <sys/param.h>
41#include <sys/systm.h>
42#include <sys/bus.h>
43#include <sys/kernel.h>
44#include <sys/lock.h>
45#include <sys/malloc.h>
46#include <sys/module.h>
47#include <sys/mutex.h>
48#include <sys/mutex.h>
49#include <sys/proc.h>
50#include <sys/smp.h>
51#include <sys/sysctl.h>
52#include <machine/bus.h>
53#include <sys/rman.h>
54#ifdef NPX_DEBUG
55#include <sys/syslog.h>
56#endif
57#include <sys/signalvar.h>
58#include <vm/uma.h>
59
60#include <machine/asmacros.h>
61#include <machine/cputypes.h>
62#include <machine/frame.h>
63#include <machine/md_var.h>
64#include <machine/pcb.h>
65#include <machine/psl.h>
66#include <machine/resource.h>
67#include <machine/specialreg.h>
68#include <machine/segments.h>
69#include <machine/ucontext.h>
70
71#include <machine/intr_machdep.h>
72
73#ifdef DEV_ISA
74#include <isa/isavar.h>
75#endif
76
77/*
78 * 387 and 287 Numeric Coprocessor Extension (NPX) Driver.
79 */
80
81#if defined(__GNUCLIKE_ASM) && !defined(lint)
82
83#define	fldcw(cw)		__asm __volatile("fldcw %0" : : "m" (cw))
84#define	fnclex()		__asm __volatile("fnclex")
85#define	fninit()		__asm __volatile("fninit")
86#define	fnsave(addr)		__asm __volatile("fnsave %0" : "=m" (*(addr)))
87#define	fnstcw(addr)		__asm __volatile("fnstcw %0" : "=m" (*(addr)))
88#define	fnstsw(addr)		__asm __volatile("fnstsw %0" : "=am" (*(addr)))
89#define	fp_divide_by_0()	__asm __volatile( \
90				    "fldz; fld1; fdiv %st,%st(1); fnop")
91#define	frstor(addr)		__asm __volatile("frstor %0" : : "m" (*(addr)))
92#define	fxrstor(addr)		__asm __volatile("fxrstor %0" : : "m" (*(addr)))
93#define	fxsave(addr)		__asm __volatile("fxsave %0" : "=m" (*(addr)))
94#define	ldmxcsr(csr)		__asm __volatile("ldmxcsr %0" : : "m" (csr))
95#define	stmxcsr(addr)		__asm __volatile("stmxcsr %0" : : "m" (*(addr)))
96
97static __inline void
98xrstor(char *addr, uint64_t mask)
99{
100	uint32_t low, hi;
101
102	low = mask;
103	hi = mask >> 32;
104	__asm __volatile("xrstor %0" : : "m" (*addr), "a" (low), "d" (hi));
105}
106
107static __inline void
108xsave(char *addr, uint64_t mask)
109{
110	uint32_t low, hi;
111
112	low = mask;
113	hi = mask >> 32;
114	__asm __volatile("xsave %0" : "=m" (*addr) : "a" (low), "d" (hi) :
115	    "memory");
116}
117
118static __inline void
119xsaveopt(char *addr, uint64_t mask)
120{
121	uint32_t low, hi;
122
123	low = mask;
124	hi = mask >> 32;
125	__asm __volatile("xsaveopt %0" : "=m" (*addr) : "a" (low), "d" (hi) :
126	    "memory");
127}
128#else	/* !(__GNUCLIKE_ASM && !lint) */
129
130void	fldcw(u_short cw);
131void	fnclex(void);
132void	fninit(void);
133void	fnsave(caddr_t addr);
134void	fnstcw(caddr_t addr);
135void	fnstsw(caddr_t addr);
136void	fp_divide_by_0(void);
137void	frstor(caddr_t addr);
138void	fxsave(caddr_t addr);
139void	fxrstor(caddr_t addr);
140void	ldmxcsr(u_int csr);
141void	stmxcsr(u_int *csr);
142void	xrstor(char *addr, uint64_t mask);
143void	xsave(char *addr, uint64_t mask);
144void	xsaveopt(char *addr, uint64_t mask);
145
146#endif	/* __GNUCLIKE_ASM && !lint */
147
148#define	start_emulating()	load_cr0(rcr0() | CR0_TS)
149#define	stop_emulating()	clts()
150
151#define GET_FPU_CW(thread) \
152	(cpu_fxsr ? \
153		(thread)->td_pcb->pcb_save->sv_xmm.sv_env.en_cw : \
154		(thread)->td_pcb->pcb_save->sv_87.sv_env.en_cw)
155#define GET_FPU_SW(thread) \
156	(cpu_fxsr ? \
157		(thread)->td_pcb->pcb_save->sv_xmm.sv_env.en_sw : \
158		(thread)->td_pcb->pcb_save->sv_87.sv_env.en_sw)
159#define SET_FPU_CW(savefpu, value) do { \
160	if (cpu_fxsr) \
161		(savefpu)->sv_xmm.sv_env.en_cw = (value); \
162	else \
163		(savefpu)->sv_87.sv_env.en_cw = (value); \
164} while (0)
165
166CTASSERT(sizeof(union savefpu) == 512);
167CTASSERT(sizeof(struct xstate_hdr) == 64);
168CTASSERT(sizeof(struct savefpu_ymm) == 832);
169
170/*
171 * This requirement is to make it easier for asm code to calculate
172 * offset of the fpu save area from the pcb address. FPU save area
173 * must be 64-byte aligned.
174 */
175CTASSERT(sizeof(struct pcb) % XSAVE_AREA_ALIGN == 0);
176
177/*
178 * Ensure the copy of XCR0 saved in a core is contained in the padding
179 * area.
180 */
181CTASSERT(X86_XSTATE_XCR0_OFFSET >= offsetof(struct savexmm, sv_pad) &&
182    X86_XSTATE_XCR0_OFFSET + sizeof(uint64_t) <= sizeof(struct savexmm));
183
184static	void	fpu_clean_state(void);
185
186static	void	fpusave(union savefpu *);
187static	void	fpurstor(union savefpu *);
188
189int	hw_float;
190
191SYSCTL_INT(_hw, HW_FLOATINGPT, floatingpoint, CTLFLAG_RD,
192    &hw_float, 0, "Floating point instructions executed in hardware");
193
194int lazy_fpu_switch = 0;
195SYSCTL_INT(_hw, OID_AUTO, lazy_fpu_switch, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
196    &lazy_fpu_switch, 0,
197    "Lazily load FPU context after context switch");
198
199int use_xsave;
200uint64_t xsave_mask;
201static	uma_zone_t fpu_save_area_zone;
202static	union savefpu *npx_initialstate;
203
204struct xsave_area_elm_descr {
205	u_int	offset;
206	u_int	size;
207} *xsave_area_desc;
208
209static int use_xsaveopt;
210
211static	volatile u_int		npx_traps_while_probing;
212
213alias_for_inthand_t probetrap;
214__asm("								\n\
215	.text							\n\
216	.p2align 2,0x90						\n\
217	.type	" __XSTRING(CNAME(probetrap)) ",@function	\n\
218" __XSTRING(CNAME(probetrap)) ":				\n\
219	ss							\n\
220	incl	" __XSTRING(CNAME(npx_traps_while_probing)) "	\n\
221	fnclex							\n\
222	iret							\n\
223");
224
225/*
226 * Determine if an FPU is present and how to use it.
227 */
228static int
229npx_probe(void)
230{
231	struct gate_descriptor save_idt_npxtrap;
232	u_short control, status;
233
234	/*
235	 * Modern CPUs all have an FPU that uses the INT16 interface
236	 * and provide a simple way to verify that, so handle the
237	 * common case right away.
238	 */
239	if (cpu_feature & CPUID_FPU) {
240		hw_float = 1;
241		return (1);
242	}
243
244	save_idt_npxtrap = idt[IDT_MF];
245	setidt(IDT_MF, probetrap, SDT_SYS386TGT, SEL_KPL,
246	    GSEL(GCODE_SEL, SEL_KPL));
247
248	/*
249	 * Don't trap while we're probing.
250	 */
251	stop_emulating();
252
253	/*
254	 * Finish resetting the coprocessor, if any.  If there is an error
255	 * pending, then we may get a bogus IRQ13, but npx_intr() will handle
256	 * it OK.  Bogus halts have never been observed, but we enabled
257	 * IRQ13 and cleared the BUSY# latch early to handle them anyway.
258	 */
259	fninit();
260
261	/*
262	 * Don't use fwait here because it might hang.
263	 * Don't use fnop here because it usually hangs if there is no FPU.
264	 */
265	DELAY(1000);		/* wait for any IRQ13 */
266#ifdef DIAGNOSTIC
267	if (npx_traps_while_probing != 0)
268		printf("fninit caused %u bogus npx trap(s)\n",
269		       npx_traps_while_probing);
270#endif
271	/*
272	 * Check for a status of mostly zero.
273	 */
274	status = 0x5a5a;
275	fnstsw(&status);
276	if ((status & 0xb8ff) == 0) {
277		/*
278		 * Good, now check for a proper control word.
279		 */
280		control = 0x5a5a;
281		fnstcw(&control);
282		if ((control & 0x1f3f) == 0x033f) {
283			/*
284			 * We have an npx, now divide by 0 to see if exception
285			 * 16 works.
286			 */
287			control &= ~(1 << 2);	/* enable divide by 0 trap */
288			fldcw(control);
289#ifdef FPU_ERROR_BROKEN
290			/*
291			 * FPU error signal doesn't work on some CPU
292			 * accelerator board.
293			 */
294			hw_float = 1;
295			return (1);
296#endif
297			npx_traps_while_probing = 0;
298			fp_divide_by_0();
299			if (npx_traps_while_probing != 0) {
300				/*
301				 * Good, exception 16 works.
302				 */
303				hw_float = 1;
304				goto cleanup;
305			}
306			printf(
307	"FPU does not use exception 16 for error reporting\n");
308			goto cleanup;
309		}
310	}
311
312	/*
313	 * Probe failed.  Floating point simply won't work.
314	 * Notify user and disable FPU/MMX/SSE instruction execution.
315	 */
316	printf("WARNING: no FPU!\n");
317	__asm __volatile("smsw %%ax; orb %0,%%al; lmsw %%ax" : :
318	    "n" (CR0_EM | CR0_MP) : "ax");
319
320cleanup:
321	idt[IDT_MF] = save_idt_npxtrap;
322	return (hw_float);
323}
324
325/*
326 * Enable XSAVE if supported and allowed by user.
327 * Calculate the xsave_mask.
328 */
329static void
330npxinit_bsp1(void)
331{
332	u_int cp[4];
333	uint64_t xsave_mask_user;
334
335	TUNABLE_INT_FETCH("hw.lazy_fpu_switch", &lazy_fpu_switch);
336	if (cpu_fxsr && (cpu_feature2 & CPUID2_XSAVE) != 0) {
337		use_xsave = 1;
338		TUNABLE_INT_FETCH("hw.use_xsave", &use_xsave);
339	}
340	if (!use_xsave)
341		return;
342
343	cpuid_count(0xd, 0x0, cp);
344	xsave_mask = XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE;
345	if ((cp[0] & xsave_mask) != xsave_mask)
346		panic("CPU0 does not support X87 or SSE: %x", cp[0]);
347	xsave_mask = ((uint64_t)cp[3] << 32) | cp[0];
348	xsave_mask_user = xsave_mask;
349	TUNABLE_QUAD_FETCH("hw.xsave_mask", &xsave_mask_user);
350	xsave_mask_user |= XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE;
351	xsave_mask &= xsave_mask_user;
352	if ((xsave_mask & XFEATURE_AVX512) != XFEATURE_AVX512)
353		xsave_mask &= ~XFEATURE_AVX512;
354	if ((xsave_mask & XFEATURE_MPX) != XFEATURE_MPX)
355		xsave_mask &= ~XFEATURE_MPX;
356
357	cpuid_count(0xd, 0x1, cp);
358	if ((cp[0] & CPUID_EXTSTATE_XSAVEOPT) != 0)
359		use_xsaveopt = 1;
360}
361
362/*
363
364 * Calculate the fpu save area size.
365 */
366static void
367npxinit_bsp2(void)
368{
369	u_int cp[4];
370
371	if (use_xsave) {
372		cpuid_count(0xd, 0x0, cp);
373		cpu_max_ext_state_size = cp[1];
374
375		/*
376		 * Reload the cpu_feature2, since we enabled OSXSAVE.
377		 */
378		do_cpuid(1, cp);
379		cpu_feature2 = cp[2];
380	} else
381		cpu_max_ext_state_size = sizeof(union savefpu);
382}
383
384/*
385 * Initialize floating point unit.
386 */
387void
388npxinit(bool bsp)
389{
390	static union savefpu dummy;
391	register_t saveintr;
392	u_int mxcsr;
393	u_short control;
394
395	if (bsp) {
396		if (!npx_probe())
397			return;
398		npxinit_bsp1();
399	}
400
401	if (use_xsave) {
402		load_cr4(rcr4() | CR4_XSAVE);
403		load_xcr(XCR0, xsave_mask);
404	}
405
406	/*
407	 * XCR0 shall be set up before CPU can report the save area size.
408	 */
409	if (bsp)
410		npxinit_bsp2();
411
412	/*
413	 * fninit has the same h/w bugs as fnsave.  Use the detoxified
414	 * fnsave to throw away any junk in the fpu.  fpusave() initializes
415	 * the fpu.
416	 *
417	 * It is too early for critical_enter() to work on AP.
418	 */
419	saveintr = intr_disable();
420	stop_emulating();
421	if (cpu_fxsr)
422		fninit();
423	else
424		fnsave(&dummy);
425	control = __INITIAL_NPXCW__;
426	fldcw(control);
427	if (cpu_fxsr) {
428		mxcsr = __INITIAL_MXCSR__;
429		ldmxcsr(mxcsr);
430	}
431	start_emulating();
432	intr_restore(saveintr);
433}
434
435/*
436 * On the boot CPU we generate a clean state that is used to
437 * initialize the floating point unit when it is first used by a
438 * process.
439 */
440static void
441npxinitstate(void *arg __unused)
442{
443	register_t saveintr;
444	int cp[4], i, max_ext_n;
445
446	if (!hw_float)
447		return;
448
449	npx_initialstate = malloc(cpu_max_ext_state_size, M_DEVBUF,
450	    M_WAITOK | M_ZERO);
451	saveintr = intr_disable();
452	stop_emulating();
453
454	fpusave(npx_initialstate);
455	if (cpu_fxsr) {
456		if (npx_initialstate->sv_xmm.sv_env.en_mxcsr_mask)
457			cpu_mxcsr_mask =
458			    npx_initialstate->sv_xmm.sv_env.en_mxcsr_mask;
459		else
460			cpu_mxcsr_mask = 0xFFBF;
461
462		/*
463		 * The fninit instruction does not modify XMM
464		 * registers or x87 registers (MM/ST).  The fpusave
465		 * call dumped the garbage contained in the registers
466		 * after reset to the initial state saved.  Clear XMM
467		 * and x87 registers file image to make the startup
468		 * program state and signal handler XMM/x87 register
469		 * content predictable.
470		 */
471		bzero(npx_initialstate->sv_xmm.sv_fp,
472		    sizeof(npx_initialstate->sv_xmm.sv_fp));
473		bzero(npx_initialstate->sv_xmm.sv_xmm,
474		    sizeof(npx_initialstate->sv_xmm.sv_xmm));
475	} else
476		bzero(npx_initialstate->sv_87.sv_ac,
477		    sizeof(npx_initialstate->sv_87.sv_ac));
478
479	/*
480	 * Create a table describing the layout of the CPU Extended
481	 * Save Area.
482	 */
483	if (use_xsave) {
484		if (xsave_mask >> 32 != 0)
485			max_ext_n = fls(xsave_mask >> 32) + 32;
486		else
487			max_ext_n = fls(xsave_mask);
488		xsave_area_desc = malloc(max_ext_n * sizeof(struct
489		    xsave_area_elm_descr), M_DEVBUF, M_WAITOK | M_ZERO);
490		/* x87 state */
491		xsave_area_desc[0].offset = 0;
492		xsave_area_desc[0].size = 160;
493		/* XMM */
494		xsave_area_desc[1].offset = 160;
495		xsave_area_desc[1].size = 288 - 160;
496
497		for (i = 2; i < max_ext_n; i++) {
498			cpuid_count(0xd, i, cp);
499			xsave_area_desc[i].offset = cp[1];
500			xsave_area_desc[i].size = cp[0];
501		}
502	}
503
504	fpu_save_area_zone = uma_zcreate("FPU_save_area",
505	    cpu_max_ext_state_size, NULL, NULL, NULL, NULL,
506	    XSAVE_AREA_ALIGN - 1, 0);
507
508	start_emulating();
509	intr_restore(saveintr);
510}
511SYSINIT(npxinitstate, SI_SUB_DRIVERS, SI_ORDER_ANY, npxinitstate, NULL);
512
513/*
514 * Free coprocessor (if we have it).
515 */
516void
517npxexit(struct thread *td)
518{
519
520	critical_enter();
521	if (curthread == PCPU_GET(fpcurthread)) {
522		stop_emulating();
523		fpusave(curpcb->pcb_save);
524		start_emulating();
525		PCPU_SET(fpcurthread, NULL);
526	}
527	critical_exit();
528#ifdef NPX_DEBUG
529	if (hw_float) {
530		u_int	masked_exceptions;
531
532		masked_exceptions = GET_FPU_CW(td) & GET_FPU_SW(td) & 0x7f;
533		/*
534		 * Log exceptions that would have trapped with the old
535		 * control word (overflow, divide by 0, and invalid operand).
536		 */
537		if (masked_exceptions & 0x0d)
538			log(LOG_ERR,
539	"pid %d (%s) exited with masked floating point exceptions 0x%02x\n",
540			    td->td_proc->p_pid, td->td_proc->p_comm,
541			    masked_exceptions);
542	}
543#endif
544}
545
546int
547npxformat(void)
548{
549
550	if (!hw_float)
551		return (_MC_FPFMT_NODEV);
552	if (cpu_fxsr)
553		return (_MC_FPFMT_XMM);
554	return (_MC_FPFMT_387);
555}
556
557/*
558 * The following mechanism is used to ensure that the FPE_... value
559 * that is passed as a trapcode to the signal handler of the user
560 * process does not have more than one bit set.
561 *
562 * Multiple bits may be set if the user process modifies the control
563 * word while a status word bit is already set.  While this is a sign
564 * of bad coding, we have no choise than to narrow them down to one
565 * bit, since we must not send a trapcode that is not exactly one of
566 * the FPE_ macros.
567 *
568 * The mechanism has a static table with 127 entries.  Each combination
569 * of the 7 FPU status word exception bits directly translates to a
570 * position in this table, where a single FPE_... value is stored.
571 * This FPE_... value stored there is considered the "most important"
572 * of the exception bits and will be sent as the signal code.  The
573 * precedence of the bits is based upon Intel Document "Numerical
574 * Applications", Chapter "Special Computational Situations".
575 *
576 * The macro to choose one of these values does these steps: 1) Throw
577 * away status word bits that cannot be masked.  2) Throw away the bits
578 * currently masked in the control word, assuming the user isn't
579 * interested in them anymore.  3) Reinsert status word bit 7 (stack
580 * fault) if it is set, which cannot be masked but must be presered.
581 * 4) Use the remaining bits to point into the trapcode table.
582 *
583 * The 6 maskable bits in order of their preference, as stated in the
584 * above referenced Intel manual:
585 * 1  Invalid operation (FP_X_INV)
586 * 1a   Stack underflow
587 * 1b   Stack overflow
588 * 1c   Operand of unsupported format
589 * 1d   SNaN operand.
590 * 2  QNaN operand (not an exception, irrelavant here)
591 * 3  Any other invalid-operation not mentioned above or zero divide
592 *      (FP_X_INV, FP_X_DZ)
593 * 4  Denormal operand (FP_X_DNML)
594 * 5  Numeric over/underflow (FP_X_OFL, FP_X_UFL)
595 * 6  Inexact result (FP_X_IMP)
596 */
597static char fpetable[128] = {
598	0,
599	FPE_FLTINV,	/*  1 - INV */
600	FPE_FLTUND,	/*  2 - DNML */
601	FPE_FLTINV,	/*  3 - INV | DNML */
602	FPE_FLTDIV,	/*  4 - DZ */
603	FPE_FLTINV,	/*  5 - INV | DZ */
604	FPE_FLTDIV,	/*  6 - DNML | DZ */
605	FPE_FLTINV,	/*  7 - INV | DNML | DZ */
606	FPE_FLTOVF,	/*  8 - OFL */
607	FPE_FLTINV,	/*  9 - INV | OFL */
608	FPE_FLTUND,	/*  A - DNML | OFL */
609	FPE_FLTINV,	/*  B - INV | DNML | OFL */
610	FPE_FLTDIV,	/*  C - DZ | OFL */
611	FPE_FLTINV,	/*  D - INV | DZ | OFL */
612	FPE_FLTDIV,	/*  E - DNML | DZ | OFL */
613	FPE_FLTINV,	/*  F - INV | DNML | DZ | OFL */
614	FPE_FLTUND,	/* 10 - UFL */
615	FPE_FLTINV,	/* 11 - INV | UFL */
616	FPE_FLTUND,	/* 12 - DNML | UFL */
617	FPE_FLTINV,	/* 13 - INV | DNML | UFL */
618	FPE_FLTDIV,	/* 14 - DZ | UFL */
619	FPE_FLTINV,	/* 15 - INV | DZ | UFL */
620	FPE_FLTDIV,	/* 16 - DNML | DZ | UFL */
621	FPE_FLTINV,	/* 17 - INV | DNML | DZ | UFL */
622	FPE_FLTOVF,	/* 18 - OFL | UFL */
623	FPE_FLTINV,	/* 19 - INV | OFL | UFL */
624	FPE_FLTUND,	/* 1A - DNML | OFL | UFL */
625	FPE_FLTINV,	/* 1B - INV | DNML | OFL | UFL */
626	FPE_FLTDIV,	/* 1C - DZ | OFL | UFL */
627	FPE_FLTINV,	/* 1D - INV | DZ | OFL | UFL */
628	FPE_FLTDIV,	/* 1E - DNML | DZ | OFL | UFL */
629	FPE_FLTINV,	/* 1F - INV | DNML | DZ | OFL | UFL */
630	FPE_FLTRES,	/* 20 - IMP */
631	FPE_FLTINV,	/* 21 - INV | IMP */
632	FPE_FLTUND,	/* 22 - DNML | IMP */
633	FPE_FLTINV,	/* 23 - INV | DNML | IMP */
634	FPE_FLTDIV,	/* 24 - DZ | IMP */
635	FPE_FLTINV,	/* 25 - INV | DZ | IMP */
636	FPE_FLTDIV,	/* 26 - DNML | DZ | IMP */
637	FPE_FLTINV,	/* 27 - INV | DNML | DZ | IMP */
638	FPE_FLTOVF,	/* 28 - OFL | IMP */
639	FPE_FLTINV,	/* 29 - INV | OFL | IMP */
640	FPE_FLTUND,	/* 2A - DNML | OFL | IMP */
641	FPE_FLTINV,	/* 2B - INV | DNML | OFL | IMP */
642	FPE_FLTDIV,	/* 2C - DZ | OFL | IMP */
643	FPE_FLTINV,	/* 2D - INV | DZ | OFL | IMP */
644	FPE_FLTDIV,	/* 2E - DNML | DZ | OFL | IMP */
645	FPE_FLTINV,	/* 2F - INV | DNML | DZ | OFL | IMP */
646	FPE_FLTUND,	/* 30 - UFL | IMP */
647	FPE_FLTINV,	/* 31 - INV | UFL | IMP */
648	FPE_FLTUND,	/* 32 - DNML | UFL | IMP */
649	FPE_FLTINV,	/* 33 - INV | DNML | UFL | IMP */
650	FPE_FLTDIV,	/* 34 - DZ | UFL | IMP */
651	FPE_FLTINV,	/* 35 - INV | DZ | UFL | IMP */
652	FPE_FLTDIV,	/* 36 - DNML | DZ | UFL | IMP */
653	FPE_FLTINV,	/* 37 - INV | DNML | DZ | UFL | IMP */
654	FPE_FLTOVF,	/* 38 - OFL | UFL | IMP */
655	FPE_FLTINV,	/* 39 - INV | OFL | UFL | IMP */
656	FPE_FLTUND,	/* 3A - DNML | OFL | UFL | IMP */
657	FPE_FLTINV,	/* 3B - INV | DNML | OFL | UFL | IMP */
658	FPE_FLTDIV,	/* 3C - DZ | OFL | UFL | IMP */
659	FPE_FLTINV,	/* 3D - INV | DZ | OFL | UFL | IMP */
660	FPE_FLTDIV,	/* 3E - DNML | DZ | OFL | UFL | IMP */
661	FPE_FLTINV,	/* 3F - INV | DNML | DZ | OFL | UFL | IMP */
662	FPE_FLTSUB,	/* 40 - STK */
663	FPE_FLTSUB,	/* 41 - INV | STK */
664	FPE_FLTUND,	/* 42 - DNML | STK */
665	FPE_FLTSUB,	/* 43 - INV | DNML | STK */
666	FPE_FLTDIV,	/* 44 - DZ | STK */
667	FPE_FLTSUB,	/* 45 - INV | DZ | STK */
668	FPE_FLTDIV,	/* 46 - DNML | DZ | STK */
669	FPE_FLTSUB,	/* 47 - INV | DNML | DZ | STK */
670	FPE_FLTOVF,	/* 48 - OFL | STK */
671	FPE_FLTSUB,	/* 49 - INV | OFL | STK */
672	FPE_FLTUND,	/* 4A - DNML | OFL | STK */
673	FPE_FLTSUB,	/* 4B - INV | DNML | OFL | STK */
674	FPE_FLTDIV,	/* 4C - DZ | OFL | STK */
675	FPE_FLTSUB,	/* 4D - INV | DZ | OFL | STK */
676	FPE_FLTDIV,	/* 4E - DNML | DZ | OFL | STK */
677	FPE_FLTSUB,	/* 4F - INV | DNML | DZ | OFL | STK */
678	FPE_FLTUND,	/* 50 - UFL | STK */
679	FPE_FLTSUB,	/* 51 - INV | UFL | STK */
680	FPE_FLTUND,	/* 52 - DNML | UFL | STK */
681	FPE_FLTSUB,	/* 53 - INV | DNML | UFL | STK */
682	FPE_FLTDIV,	/* 54 - DZ | UFL | STK */
683	FPE_FLTSUB,	/* 55 - INV | DZ | UFL | STK */
684	FPE_FLTDIV,	/* 56 - DNML | DZ | UFL | STK */
685	FPE_FLTSUB,	/* 57 - INV | DNML | DZ | UFL | STK */
686	FPE_FLTOVF,	/* 58 - OFL | UFL | STK */
687	FPE_FLTSUB,	/* 59 - INV | OFL | UFL | STK */
688	FPE_FLTUND,	/* 5A - DNML | OFL | UFL | STK */
689	FPE_FLTSUB,	/* 5B - INV | DNML | OFL | UFL | STK */
690	FPE_FLTDIV,	/* 5C - DZ | OFL | UFL | STK */
691	FPE_FLTSUB,	/* 5D - INV | DZ | OFL | UFL | STK */
692	FPE_FLTDIV,	/* 5E - DNML | DZ | OFL | UFL | STK */
693	FPE_FLTSUB,	/* 5F - INV | DNML | DZ | OFL | UFL | STK */
694	FPE_FLTRES,	/* 60 - IMP | STK */
695	FPE_FLTSUB,	/* 61 - INV | IMP | STK */
696	FPE_FLTUND,	/* 62 - DNML | IMP | STK */
697	FPE_FLTSUB,	/* 63 - INV | DNML | IMP | STK */
698	FPE_FLTDIV,	/* 64 - DZ | IMP | STK */
699	FPE_FLTSUB,	/* 65 - INV | DZ | IMP | STK */
700	FPE_FLTDIV,	/* 66 - DNML | DZ | IMP | STK */
701	FPE_FLTSUB,	/* 67 - INV | DNML | DZ | IMP | STK */
702	FPE_FLTOVF,	/* 68 - OFL | IMP | STK */
703	FPE_FLTSUB,	/* 69 - INV | OFL | IMP | STK */
704	FPE_FLTUND,	/* 6A - DNML | OFL | IMP | STK */
705	FPE_FLTSUB,	/* 6B - INV | DNML | OFL | IMP | STK */
706	FPE_FLTDIV,	/* 6C - DZ | OFL | IMP | STK */
707	FPE_FLTSUB,	/* 6D - INV | DZ | OFL | IMP | STK */
708	FPE_FLTDIV,	/* 6E - DNML | DZ | OFL | IMP | STK */
709	FPE_FLTSUB,	/* 6F - INV | DNML | DZ | OFL | IMP | STK */
710	FPE_FLTUND,	/* 70 - UFL | IMP | STK */
711	FPE_FLTSUB,	/* 71 - INV | UFL | IMP | STK */
712	FPE_FLTUND,	/* 72 - DNML | UFL | IMP | STK */
713	FPE_FLTSUB,	/* 73 - INV | DNML | UFL | IMP | STK */
714	FPE_FLTDIV,	/* 74 - DZ | UFL | IMP | STK */
715	FPE_FLTSUB,	/* 75 - INV | DZ | UFL | IMP | STK */
716	FPE_FLTDIV,	/* 76 - DNML | DZ | UFL | IMP | STK */
717	FPE_FLTSUB,	/* 77 - INV | DNML | DZ | UFL | IMP | STK */
718	FPE_FLTOVF,	/* 78 - OFL | UFL | IMP | STK */
719	FPE_FLTSUB,	/* 79 - INV | OFL | UFL | IMP | STK */
720	FPE_FLTUND,	/* 7A - DNML | OFL | UFL | IMP | STK */
721	FPE_FLTSUB,	/* 7B - INV | DNML | OFL | UFL | IMP | STK */
722	FPE_FLTDIV,	/* 7C - DZ | OFL | UFL | IMP | STK */
723	FPE_FLTSUB,	/* 7D - INV | DZ | OFL | UFL | IMP | STK */
724	FPE_FLTDIV,	/* 7E - DNML | DZ | OFL | UFL | IMP | STK */
725	FPE_FLTSUB,	/* 7F - INV | DNML | DZ | OFL | UFL | IMP | STK */
726};
727
728/*
729 * Read the FP status and control words, then generate si_code value
730 * for SIGFPE.  The error code chosen will be one of the
731 * FPE_... macros.  It will be sent as the second argument to old
732 * BSD-style signal handlers and as "siginfo_t->si_code" (second
733 * argument) to SA_SIGINFO signal handlers.
734 *
735 * Some time ago, we cleared the x87 exceptions with FNCLEX there.
736 * Clearing exceptions was necessary mainly to avoid IRQ13 bugs.  The
737 * usermode code which understands the FPU hardware enough to enable
738 * the exceptions, can also handle clearing the exception state in the
739 * handler.  The only consequence of not clearing the exception is the
740 * rethrow of the SIGFPE on return from the signal handler and
741 * reexecution of the corresponding instruction.
742 *
743 * For XMM traps, the exceptions were never cleared.
744 */
745int
746npxtrap_x87(void)
747{
748	u_short control, status;
749
750	if (!hw_float) {
751		printf(
752	"npxtrap_x87: fpcurthread = %p, curthread = %p, hw_float = %d\n",
753		       PCPU_GET(fpcurthread), curthread, hw_float);
754		panic("npxtrap from nowhere");
755	}
756	critical_enter();
757
758	/*
759	 * Interrupt handling (for another interrupt) may have pushed the
760	 * state to memory.  Fetch the relevant parts of the state from
761	 * wherever they are.
762	 */
763	if (PCPU_GET(fpcurthread) != curthread) {
764		control = GET_FPU_CW(curthread);
765		status = GET_FPU_SW(curthread);
766	} else {
767		fnstcw(&control);
768		fnstsw(&status);
769	}
770	critical_exit();
771	return (fpetable[status & ((~control & 0x3f) | 0x40)]);
772}
773
774int
775npxtrap_sse(void)
776{
777	u_int mxcsr;
778
779	if (!hw_float) {
780		printf(
781	"npxtrap_sse: fpcurthread = %p, curthread = %p, hw_float = %d\n",
782		       PCPU_GET(fpcurthread), curthread, hw_float);
783		panic("npxtrap from nowhere");
784	}
785	critical_enter();
786	if (PCPU_GET(fpcurthread) != curthread)
787		mxcsr = curthread->td_pcb->pcb_save->sv_xmm.sv_env.en_mxcsr;
788	else
789		stmxcsr(&mxcsr);
790	critical_exit();
791	return (fpetable[(mxcsr & (~mxcsr >> 7)) & 0x3f]);
792}
793
794static void
795restore_npx_curthread(struct thread *td, struct pcb *pcb)
796{
797
798	/*
799	 * Record new context early in case frstor causes a trap.
800	 */
801	PCPU_SET(fpcurthread, td);
802
803	stop_emulating();
804	if (cpu_fxsr)
805		fpu_clean_state();
806
807	if ((pcb->pcb_flags & PCB_NPXINITDONE) == 0) {
808		/*
809		 * This is the first time this thread has used the FPU or
810		 * the PCB doesn't contain a clean FPU state.  Explicitly
811		 * load an initial state.
812		 *
813		 * We prefer to restore the state from the actual save
814		 * area in PCB instead of directly loading from
815		 * npx_initialstate, to ignite the XSAVEOPT
816		 * tracking engine.
817		 */
818		bcopy(npx_initialstate, pcb->pcb_save, cpu_max_ext_state_size);
819		fpurstor(pcb->pcb_save);
820		if (pcb->pcb_initial_npxcw != __INITIAL_NPXCW__)
821			fldcw(pcb->pcb_initial_npxcw);
822		pcb->pcb_flags |= PCB_NPXINITDONE;
823		if (PCB_USER_FPU(pcb))
824			pcb->pcb_flags |= PCB_NPXUSERINITDONE;
825	} else {
826		fpurstor(pcb->pcb_save);
827	}
828}
829
830/*
831 * Implement device not available (DNA) exception
832 *
833 * It would be better to switch FP context here (if curthread != fpcurthread)
834 * and not necessarily for every context switch, but it is too hard to
835 * access foreign pcb's.
836 */
837int
838npxdna(void)
839{
840	struct thread *td;
841
842	if (!hw_float)
843		return (0);
844	td = curthread;
845	critical_enter();
846	if (__predict_false(PCPU_GET(fpcurthread) == td)) {
847		/*
848		 * Some virtual machines seems to set %cr0.TS at
849		 * arbitrary moments.  Silently clear the TS bit
850		 * regardless of the eager/lazy FPU context switch
851		 * mode.
852		 */
853		stop_emulating();
854	} else {
855		if (__predict_false(PCPU_GET(fpcurthread) != NULL)) {
856			printf(
857		    "npxdna: fpcurthread = %p (%d), curthread = %p (%d)\n",
858			    PCPU_GET(fpcurthread),
859			    PCPU_GET(fpcurthread)->td_proc->p_pid,
860			    td, td->td_proc->p_pid);
861			panic("npxdna");
862		}
863		restore_npx_curthread(td, td->td_pcb);
864	}
865	critical_exit();
866	return (1);
867}
868
869/*
870 * Wrapper for fpusave() called from context switch routines.
871 *
872 * npxsave() must be called with interrupts disabled, so that it clears
873 * fpcurthread atomically with saving the state.  We require callers to do the
874 * disabling, since most callers need to disable interrupts anyway to call
875 * npxsave() atomically with checking fpcurthread.
876 */
877void
878npxsave(addr)
879	union savefpu *addr;
880{
881
882	stop_emulating();
883	if (use_xsaveopt)
884		xsaveopt((char *)addr, xsave_mask);
885	else
886		fpusave(addr);
887}
888
889void npxswitch(struct thread *td, struct pcb *pcb);
890void
891npxswitch(struct thread *td, struct pcb *pcb)
892{
893
894	if (lazy_fpu_switch || (td->td_pflags & TDP_KTHREAD) != 0 ||
895	    !PCB_USER_FPU(pcb)) {
896		start_emulating();
897		PCPU_SET(fpcurthread, NULL);
898	} else if (PCPU_GET(fpcurthread) != td) {
899		restore_npx_curthread(td, pcb);
900	}
901}
902
903/*
904 * Unconditionally save the current co-processor state across suspend and
905 * resume.
906 */
907void
908npxsuspend(union savefpu *addr)
909{
910	register_t cr0;
911
912	if (!hw_float)
913		return;
914	if (PCPU_GET(fpcurthread) == NULL) {
915		bcopy(npx_initialstate, addr, cpu_max_ext_state_size);
916		return;
917	}
918	cr0 = rcr0();
919	stop_emulating();
920	fpusave(addr);
921	load_cr0(cr0);
922}
923
924void
925npxresume(union savefpu *addr)
926{
927	register_t cr0;
928
929	if (!hw_float)
930		return;
931
932	cr0 = rcr0();
933	npxinit(false);
934	stop_emulating();
935	fpurstor(addr);
936	load_cr0(cr0);
937}
938
939void
940npxdrop(void)
941{
942	struct thread *td;
943
944	/*
945	 * Discard pending exceptions in the !cpu_fxsr case so that unmasked
946	 * ones don't cause a panic on the next frstor.
947	 */
948	if (!cpu_fxsr)
949		fnclex();
950
951	td = PCPU_GET(fpcurthread);
952	KASSERT(td == curthread, ("fpudrop: fpcurthread != curthread"));
953	CRITICAL_ASSERT(td);
954	PCPU_SET(fpcurthread, NULL);
955	td->td_pcb->pcb_flags &= ~PCB_NPXINITDONE;
956	start_emulating();
957}
958
959/*
960 * Get the user state of the FPU into pcb->pcb_user_save without
961 * dropping ownership (if possible).  It returns the FPU ownership
962 * status.
963 */
964int
965npxgetregs(struct thread *td)
966{
967	struct pcb *pcb;
968	uint64_t *xstate_bv, bit;
969	char *sa;
970	int max_ext_n, i;
971	int owned;
972
973	if (!hw_float)
974		return (_MC_FPOWNED_NONE);
975
976	pcb = td->td_pcb;
977	critical_enter();
978	if ((pcb->pcb_flags & PCB_NPXINITDONE) == 0) {
979		bcopy(npx_initialstate, get_pcb_user_save_pcb(pcb),
980		    cpu_max_ext_state_size);
981		SET_FPU_CW(get_pcb_user_save_pcb(pcb), pcb->pcb_initial_npxcw);
982		npxuserinited(td);
983		critical_exit();
984		return (_MC_FPOWNED_PCB);
985	}
986	if (td == PCPU_GET(fpcurthread)) {
987		fpusave(get_pcb_user_save_pcb(pcb));
988		if (!cpu_fxsr)
989			/*
990			 * fnsave initializes the FPU and destroys whatever
991			 * context it contains.  Make sure the FPU owner
992			 * starts with a clean state next time.
993			 */
994			npxdrop();
995		owned = _MC_FPOWNED_FPU;
996	} else {
997		owned = _MC_FPOWNED_PCB;
998	}
999	if (use_xsave) {
1000		/*
1001		 * Handle partially saved state.
1002		 */
1003		sa = (char *)get_pcb_user_save_pcb(pcb);
1004		xstate_bv = (uint64_t *)(sa + sizeof(union savefpu) +
1005		    offsetof(struct xstate_hdr, xstate_bv));
1006		if (xsave_mask >> 32 != 0)
1007			max_ext_n = fls(xsave_mask >> 32) + 32;
1008		else
1009			max_ext_n = fls(xsave_mask);
1010		for (i = 0; i < max_ext_n; i++) {
1011			bit = 1ULL << i;
1012			if ((xsave_mask & bit) == 0 || (*xstate_bv & bit) != 0)
1013				continue;
1014			bcopy((char *)npx_initialstate +
1015			    xsave_area_desc[i].offset,
1016			    sa + xsave_area_desc[i].offset,
1017			    xsave_area_desc[i].size);
1018			*xstate_bv |= bit;
1019		}
1020	}
1021	critical_exit();
1022	return (owned);
1023}
1024
1025void
1026npxuserinited(struct thread *td)
1027{
1028	struct pcb *pcb;
1029
1030	CRITICAL_ASSERT(td);
1031	pcb = td->td_pcb;
1032	if (PCB_USER_FPU(pcb))
1033		pcb->pcb_flags |= PCB_NPXINITDONE;
1034	pcb->pcb_flags |= PCB_NPXUSERINITDONE;
1035}
1036
1037int
1038npxsetxstate(struct thread *td, char *xfpustate, size_t xfpustate_size)
1039{
1040	struct xstate_hdr *hdr, *ehdr;
1041	size_t len, max_len;
1042	uint64_t bv;
1043
1044	/* XXXKIB should we clear all extended state in xstate_bv instead ? */
1045	if (xfpustate == NULL)
1046		return (0);
1047	if (!use_xsave)
1048		return (EOPNOTSUPP);
1049
1050	len = xfpustate_size;
1051	if (len < sizeof(struct xstate_hdr))
1052		return (EINVAL);
1053	max_len = cpu_max_ext_state_size - sizeof(union savefpu);
1054	if (len > max_len)
1055		return (EINVAL);
1056
1057	ehdr = (struct xstate_hdr *)xfpustate;
1058	bv = ehdr->xstate_bv;
1059
1060	/*
1061	 * Avoid #gp.
1062	 */
1063	if (bv & ~xsave_mask)
1064		return (EINVAL);
1065
1066	hdr = (struct xstate_hdr *)(get_pcb_user_save_td(td) + 1);
1067
1068	hdr->xstate_bv = bv;
1069	bcopy(xfpustate + sizeof(struct xstate_hdr),
1070	    (char *)(hdr + 1), len - sizeof(struct xstate_hdr));
1071
1072	return (0);
1073}
1074
1075int
1076npxsetregs(struct thread *td, union savefpu *addr, char *xfpustate,
1077	size_t xfpustate_size)
1078{
1079	struct pcb *pcb;
1080	int error;
1081
1082	if (!hw_float)
1083		return (ENXIO);
1084
1085	if (cpu_fxsr)
1086		addr->sv_xmm.sv_env.en_mxcsr &= cpu_mxcsr_mask;
1087	pcb = td->td_pcb;
1088	error = 0;
1089	critical_enter();
1090	if (td == PCPU_GET(fpcurthread) && PCB_USER_FPU(pcb)) {
1091		error = npxsetxstate(td, xfpustate, xfpustate_size);
1092		if (error == 0) {
1093			if (!cpu_fxsr)
1094				fnclex();	/* As in npxdrop(). */
1095			bcopy(addr, get_pcb_user_save_td(td), sizeof(*addr));
1096			fpurstor(get_pcb_user_save_td(td));
1097			pcb->pcb_flags |= PCB_NPXUSERINITDONE | PCB_NPXINITDONE;
1098		}
1099	} else {
1100		error = npxsetxstate(td, xfpustate, xfpustate_size);
1101		if (error == 0) {
1102			bcopy(addr, get_pcb_user_save_td(td), sizeof(*addr));
1103			npxuserinited(td);
1104		}
1105	}
1106	critical_exit();
1107	return (error);
1108}
1109
1110static void
1111fpusave(addr)
1112	union savefpu *addr;
1113{
1114
1115	if (use_xsave)
1116		xsave((char *)addr, xsave_mask);
1117	else if (cpu_fxsr)
1118		fxsave(addr);
1119	else
1120		fnsave(addr);
1121}
1122
1123static void
1124npx_fill_fpregs_xmm1(struct savexmm *sv_xmm, struct save87 *sv_87)
1125{
1126	struct env87 *penv_87;
1127	struct envxmm *penv_xmm;
1128	int i;
1129
1130	penv_87 = &sv_87->sv_env;
1131	penv_xmm = &sv_xmm->sv_env;
1132
1133	/* FPU control/status */
1134	penv_87->en_cw = penv_xmm->en_cw;
1135	penv_87->en_sw = penv_xmm->en_sw;
1136	penv_87->en_fip = penv_xmm->en_fip;
1137	penv_87->en_fcs = penv_xmm->en_fcs;
1138	penv_87->en_opcode = penv_xmm->en_opcode;
1139	penv_87->en_foo = penv_xmm->en_foo;
1140	penv_87->en_fos = penv_xmm->en_fos;
1141
1142	/* FPU registers and tags */
1143	penv_87->en_tw = 0xffff;
1144	for (i = 0; i < 8; ++i) {
1145		sv_87->sv_ac[i] = sv_xmm->sv_fp[i].fp_acc;
1146		if ((penv_xmm->en_tw & (1 << i)) != 0)
1147			/* zero and special are set as valid */
1148			penv_87->en_tw &= ~(3 << i * 2);
1149	}
1150}
1151
1152void
1153npx_fill_fpregs_xmm(struct savexmm *sv_xmm, struct save87 *sv_87)
1154{
1155
1156	bzero(sv_87, sizeof(*sv_87));
1157	npx_fill_fpregs_xmm1(sv_xmm, sv_87);
1158}
1159
1160void
1161npx_set_fpregs_xmm(struct save87 *sv_87, struct savexmm *sv_xmm)
1162{
1163	struct env87 *penv_87;
1164	struct envxmm *penv_xmm;
1165	int i;
1166
1167	penv_87 = &sv_87->sv_env;
1168	penv_xmm = &sv_xmm->sv_env;
1169
1170	/* FPU control/status */
1171	penv_xmm->en_cw = penv_87->en_cw;
1172	penv_xmm->en_sw = penv_87->en_sw;
1173	penv_xmm->en_fip = penv_87->en_fip;
1174	penv_xmm->en_fcs = penv_87->en_fcs;
1175	penv_xmm->en_opcode = penv_87->en_opcode;
1176	penv_xmm->en_foo = penv_87->en_foo;
1177	penv_xmm->en_fos = penv_87->en_fos;
1178
1179	/*
1180	 * FPU registers and tags.
1181	 * Abridged  /  Full translation (values in binary), see FXSAVE spec.
1182	 * 0		11
1183	 * 1		00, 01, 10
1184	 */
1185	penv_xmm->en_tw = 0;
1186	for (i = 0; i < 8; ++i) {
1187		sv_xmm->sv_fp[i].fp_acc = sv_87->sv_ac[i];
1188		if ((penv_87->en_tw & (3 << i * 2)) != (3 << i * 2))
1189			penv_xmm->en_tw |= 1 << i;
1190	}
1191}
1192
1193void
1194npx_get_fsave(void *addr)
1195{
1196	struct thread *td;
1197	union savefpu *sv;
1198
1199	td = curthread;
1200	npxgetregs(td);
1201	sv = get_pcb_user_save_td(td);
1202	if (cpu_fxsr)
1203		npx_fill_fpregs_xmm1(&sv->sv_xmm, addr);
1204	else
1205		bcopy(sv, addr, sizeof(struct env87) +
1206		    sizeof(struct fpacc87[8]));
1207}
1208
1209int
1210npx_set_fsave(void *addr)
1211{
1212	union savefpu sv;
1213	int error;
1214
1215	bzero(&sv, sizeof(sv));
1216	if (cpu_fxsr)
1217		npx_set_fpregs_xmm(addr, &sv.sv_xmm);
1218	else
1219		bcopy(addr, &sv, sizeof(struct env87) +
1220		    sizeof(struct fpacc87[8]));
1221	error = npxsetregs(curthread, &sv, NULL, 0);
1222	return (error);
1223}
1224
1225/*
1226 * On AuthenticAMD processors, the fxrstor instruction does not restore
1227 * the x87's stored last instruction pointer, last data pointer, and last
1228 * opcode values, except in the rare case in which the exception summary
1229 * (ES) bit in the x87 status word is set to 1.
1230 *
1231 * In order to avoid leaking this information across processes, we clean
1232 * these values by performing a dummy load before executing fxrstor().
1233 */
1234static void
1235fpu_clean_state(void)
1236{
1237	static float dummy_variable = 0.0;
1238	u_short status;
1239
1240	/*
1241	 * Clear the ES bit in the x87 status word if it is currently
1242	 * set, in order to avoid causing a fault in the upcoming load.
1243	 */
1244	fnstsw(&status);
1245	if (status & 0x80)
1246		fnclex();
1247
1248	/*
1249	 * Load the dummy variable into the x87 stack.  This mangles
1250	 * the x87 stack, but we don't care since we're about to call
1251	 * fxrstor() anyway.
1252	 */
1253	__asm __volatile("ffree %%st(7); flds %0" : : "m" (dummy_variable));
1254}
1255
1256static void
1257fpurstor(union savefpu *addr)
1258{
1259
1260	if (use_xsave)
1261		xrstor((char *)addr, xsave_mask);
1262	else if (cpu_fxsr)
1263		fxrstor(addr);
1264	else
1265		frstor(addr);
1266}
1267
1268#ifdef DEV_ISA
1269/*
1270 * This sucks up the legacy ISA support assignments from PNPBIOS/ACPI.
1271 */
1272static struct isa_pnp_id npxisa_ids[] = {
1273	{ 0x040cd041, "Legacy ISA coprocessor support" }, /* PNP0C04 */
1274	{ 0 }
1275};
1276
1277static int
1278npxisa_probe(device_t dev)
1279{
1280	int result;
1281	if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, npxisa_ids)) <= 0) {
1282		device_quiet(dev);
1283	}
1284	return(result);
1285}
1286
1287static int
1288npxisa_attach(device_t dev)
1289{
1290	return (0);
1291}
1292
1293static device_method_t npxisa_methods[] = {
1294	/* Device interface */
1295	DEVMETHOD(device_probe,		npxisa_probe),
1296	DEVMETHOD(device_attach,	npxisa_attach),
1297	DEVMETHOD(device_detach,	bus_generic_detach),
1298	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1299	DEVMETHOD(device_suspend,	bus_generic_suspend),
1300	DEVMETHOD(device_resume,	bus_generic_resume),
1301
1302	{ 0, 0 }
1303};
1304
1305static driver_t npxisa_driver = {
1306	"npxisa",
1307	npxisa_methods,
1308	1,			/* no softc */
1309};
1310
1311static devclass_t npxisa_devclass;
1312
1313DRIVER_MODULE(npxisa, isa, npxisa_driver, npxisa_devclass, 0, 0);
1314#ifndef PC98
1315DRIVER_MODULE(npxisa, acpi, npxisa_driver, npxisa_devclass, 0, 0);
1316#endif
1317#endif /* DEV_ISA */
1318
1319static MALLOC_DEFINE(M_FPUKERN_CTX, "fpukern_ctx",
1320    "Kernel contexts for FPU state");
1321
1322#define	FPU_KERN_CTX_NPXINITDONE 0x01
1323#define	FPU_KERN_CTX_DUMMY	 0x02
1324#define	FPU_KERN_CTX_INUSE	 0x04
1325
1326struct fpu_kern_ctx {
1327	union savefpu *prev;
1328	uint32_t flags;
1329	char hwstate1[];
1330};
1331
1332struct fpu_kern_ctx *
1333fpu_kern_alloc_ctx(u_int flags)
1334{
1335	struct fpu_kern_ctx *res;
1336	size_t sz;
1337
1338	sz = sizeof(struct fpu_kern_ctx) + XSAVE_AREA_ALIGN +
1339	    cpu_max_ext_state_size;
1340	res = malloc(sz, M_FPUKERN_CTX, ((flags & FPU_KERN_NOWAIT) ?
1341	    M_NOWAIT : M_WAITOK) | M_ZERO);
1342	return (res);
1343}
1344
1345void
1346fpu_kern_free_ctx(struct fpu_kern_ctx *ctx)
1347{
1348
1349	KASSERT((ctx->flags & FPU_KERN_CTX_INUSE) == 0, ("free'ing inuse ctx"));
1350	/* XXXKIB clear the memory ? */
1351	free(ctx, M_FPUKERN_CTX);
1352}
1353
1354static union savefpu *
1355fpu_kern_ctx_savefpu(struct fpu_kern_ctx *ctx)
1356{
1357	vm_offset_t p;
1358
1359	p = (vm_offset_t)&ctx->hwstate1;
1360	p = roundup2(p, XSAVE_AREA_ALIGN);
1361	return ((union savefpu *)p);
1362}
1363
1364int
1365fpu_kern_enter(struct thread *td, struct fpu_kern_ctx *ctx, u_int flags)
1366{
1367	struct pcb *pcb;
1368
1369	KASSERT((ctx->flags & FPU_KERN_CTX_INUSE) == 0, ("using inuse ctx"));
1370
1371	if ((flags & FPU_KERN_KTHR) != 0 && is_fpu_kern_thread(0)) {
1372		ctx->flags = FPU_KERN_CTX_DUMMY | FPU_KERN_CTX_INUSE;
1373		return (0);
1374	}
1375	pcb = td->td_pcb;
1376	critical_enter();
1377	KASSERT(!PCB_USER_FPU(pcb) || pcb->pcb_save ==
1378	    get_pcb_user_save_pcb(pcb), ("mangled pcb_save"));
1379	ctx->flags = FPU_KERN_CTX_INUSE;
1380	if ((pcb->pcb_flags & PCB_NPXINITDONE) != 0)
1381		ctx->flags |= FPU_KERN_CTX_NPXINITDONE;
1382	npxexit(td);
1383	ctx->prev = pcb->pcb_save;
1384	pcb->pcb_save = fpu_kern_ctx_savefpu(ctx);
1385	pcb->pcb_flags |= PCB_KERNNPX;
1386	pcb->pcb_flags &= ~PCB_NPXINITDONE;
1387	critical_exit();
1388	return (0);
1389}
1390
1391int
1392fpu_kern_leave(struct thread *td, struct fpu_kern_ctx *ctx)
1393{
1394	struct pcb *pcb;
1395
1396	KASSERT((ctx->flags & FPU_KERN_CTX_INUSE) != 0,
1397	    ("leaving not inuse ctx"));
1398	ctx->flags &= ~FPU_KERN_CTX_INUSE;
1399
1400	if (is_fpu_kern_thread(0) && (ctx->flags & FPU_KERN_CTX_DUMMY) != 0)
1401		return (0);
1402	pcb = td->td_pcb;
1403	critical_enter();
1404	if (curthread == PCPU_GET(fpcurthread))
1405		npxdrop();
1406	pcb->pcb_save = ctx->prev;
1407	if (pcb->pcb_save == get_pcb_user_save_pcb(pcb)) {
1408		if ((pcb->pcb_flags & PCB_NPXUSERINITDONE) != 0)
1409			pcb->pcb_flags |= PCB_NPXINITDONE;
1410		else
1411			pcb->pcb_flags &= ~PCB_NPXINITDONE;
1412		pcb->pcb_flags &= ~PCB_KERNNPX;
1413	} else {
1414		if ((ctx->flags & FPU_KERN_CTX_NPXINITDONE) != 0)
1415			pcb->pcb_flags |= PCB_NPXINITDONE;
1416		else
1417			pcb->pcb_flags &= ~PCB_NPXINITDONE;
1418		KASSERT(!PCB_USER_FPU(pcb), ("unpaired fpu_kern_leave"));
1419	}
1420	critical_exit();
1421	return (0);
1422}
1423
1424int
1425fpu_kern_thread(u_int flags)
1426{
1427
1428	KASSERT((curthread->td_pflags & TDP_KTHREAD) != 0,
1429	    ("Only kthread may use fpu_kern_thread"));
1430	KASSERT(curpcb->pcb_save == get_pcb_user_save_pcb(curpcb),
1431	    ("mangled pcb_save"));
1432	KASSERT(PCB_USER_FPU(curpcb), ("recursive call"));
1433
1434	curpcb->pcb_flags |= PCB_KERNNPX;
1435	return (0);
1436}
1437
1438int
1439is_fpu_kern_thread(u_int flags)
1440{
1441
1442	if ((curthread->td_pflags & TDP_KTHREAD) == 0)
1443		return (0);
1444	return ((curpcb->pcb_flags & PCB_KERNNPX) != 0);
1445}
1446
1447/*
1448 * FPU save area alloc/free/init utility routines
1449 */
1450union savefpu *
1451fpu_save_area_alloc(void)
1452{
1453
1454	return (uma_zalloc(fpu_save_area_zone, 0));
1455}
1456
1457void
1458fpu_save_area_free(union savefpu *fsa)
1459{
1460
1461	uma_zfree(fpu_save_area_zone, fsa);
1462}
1463
1464void
1465fpu_save_area_reset(union savefpu *fsa)
1466{
1467
1468	bcopy(npx_initialstate, fsa, cpu_max_ext_state_size);
1469}
1470