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