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