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