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