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