xref: /freebsd/sys/amd64/amd64/fpu.c (revision acce5fa3dbe87ea953fb5060a03859e424398db8)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1990 William Jolitz.
5  * Copyright (c) 1991 The Regents of the University of California.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/bus.h>
36 #include <sys/domainset.h>
37 #include <sys/kernel.h>
38 #include <sys/lock.h>
39 #include <sys/malloc.h>
40 #include <sys/module.h>
41 #include <sys/mutex.h>
42 #include <sys/mutex.h>
43 #include <sys/proc.h>
44 #include <sys/sysctl.h>
45 #include <sys/sysent.h>
46 #include <sys/tslog.h>
47 #include <machine/bus.h>
48 #include <sys/rman.h>
49 #include <sys/signalvar.h>
50 #include <vm/uma.h>
51 
52 #include <machine/cputypes.h>
53 #include <machine/frame.h>
54 #include <machine/intr_machdep.h>
55 #include <machine/md_var.h>
56 #include <machine/pcb.h>
57 #include <machine/psl.h>
58 #include <machine/resource.h>
59 #include <machine/specialreg.h>
60 #include <machine/segments.h>
61 #include <machine/ucontext.h>
62 #include <x86/ifunc.h>
63 
64 /*
65  * Floating point support.
66  */
67 
68 #define	fldcw(cw)		__asm __volatile("fldcw %0" : : "m" (cw))
69 #define	fnclex()		__asm __volatile("fnclex")
70 #define	fninit()		__asm __volatile("fninit")
71 #define	fnstcw(addr)		__asm __volatile("fnstcw %0" : "=m" (*(addr)))
72 #define	fnstsw(addr)		__asm __volatile("fnstsw %0" : "=am" (*(addr)))
73 #define	fxrstor(addr)		__asm __volatile("fxrstor %0" : : "m" (*(addr)))
74 #define	fxsave(addr)		__asm __volatile("fxsave %0" : "=m" (*(addr)))
75 #define	ldmxcsr(csr)		__asm __volatile("ldmxcsr %0" : : "m" (csr))
76 #define	stmxcsr(addr)		__asm __volatile("stmxcsr %0" : "=m" (*(addr)))
77 
78 static __inline void
xrstor32(char * addr,uint64_t mask)79 xrstor32(char *addr, uint64_t mask)
80 {
81 	uint32_t low, hi;
82 
83 	low = mask;
84 	hi = mask >> 32;
85 	__asm __volatile("xrstor %0" : : "m" (*addr), "a" (low), "d" (hi));
86 }
87 
88 static __inline void
xrstor64(char * addr,uint64_t mask)89 xrstor64(char *addr, uint64_t mask)
90 {
91 	uint32_t low, hi;
92 
93 	low = mask;
94 	hi = mask >> 32;
95 	__asm __volatile("xrstor64 %0" : : "m" (*addr), "a" (low), "d" (hi));
96 }
97 
98 static __inline void
xsave32(char * addr,uint64_t mask)99 xsave32(char *addr, uint64_t mask)
100 {
101 	uint32_t low, hi;
102 
103 	low = mask;
104 	hi = mask >> 32;
105 	__asm __volatile("xsave %0" : "=m" (*addr) : "a" (low), "d" (hi) :
106 	    "memory");
107 }
108 
109 static __inline void
xsave64(char * addr,uint64_t mask)110 xsave64(char *addr, uint64_t mask)
111 {
112 	uint32_t low, hi;
113 
114 	low = mask;
115 	hi = mask >> 32;
116 	__asm __volatile("xsave64 %0" : "=m" (*addr) : "a" (low), "d" (hi) :
117 	    "memory");
118 }
119 
120 static __inline void
xsaveopt32(char * addr,uint64_t mask)121 xsaveopt32(char *addr, uint64_t mask)
122 {
123 	uint32_t low, hi;
124 
125 	low = mask;
126 	hi = mask >> 32;
127 	__asm __volatile("xsaveopt %0" : "=m" (*addr) : "a" (low), "d" (hi) :
128 	    "memory");
129 }
130 
131 static __inline void
xsaveopt64(char * addr,uint64_t mask)132 xsaveopt64(char *addr, uint64_t mask)
133 {
134 	uint32_t low, hi;
135 
136 	low = mask;
137 	hi = mask >> 32;
138 	__asm __volatile("xsaveopt64 %0" : "=m" (*addr) : "a" (low), "d" (hi) :
139 	    "memory");
140 }
141 
142 CTASSERT(sizeof(struct savefpu) == 512);
143 CTASSERT(sizeof(struct xstate_hdr) == 64);
144 CTASSERT(sizeof(struct savefpu_ymm) == 832);
145 
146 /*
147  * Ensure the copy of XCR0 saved in a core is contained in the padding
148  * area.
149  */
150 CTASSERT(X86_XSTATE_XCR0_OFFSET >= offsetof(struct savefpu, sv_pad) &&
151     X86_XSTATE_XCR0_OFFSET + sizeof(uint64_t) <= sizeof(struct savefpu));
152 
153 static	void	fpu_clean_state(void);
154 
155 SYSCTL_INT(_hw, HW_FLOATINGPT, floatingpoint, CTLFLAG_RD,
156     SYSCTL_NULL_INT_PTR, 1, "Floating point instructions executed in hardware");
157 
158 int use_xsave;			/* non-static for cpu_switch.S */
159 uint64_t xsave_mask;		/* the same */
160 static	uint64_t xsave_mask_supervisor;
161 static	uint64_t xsave_extensions;
162 static	uma_zone_t fpu_save_area_zone;
163 static	struct savefpu *fpu_initialstate;
164 
165 static struct xsave_area_elm_descr {
166 	u_int	offset;
167 	u_int	size;
168 	u_int	flags;
169 } *xsave_area_desc;
170 
171 static void
fpusave_xsaveopt64(void * addr)172 fpusave_xsaveopt64(void *addr)
173 {
174 	xsaveopt64((char *)addr, xsave_mask);
175 }
176 
177 static void
fpusave_xsaveopt3264(void * addr)178 fpusave_xsaveopt3264(void *addr)
179 {
180 	if (SV_CURPROC_FLAG(SV_ILP32))
181 		xsaveopt32((char *)addr, xsave_mask);
182 	else
183 		xsaveopt64((char *)addr, xsave_mask);
184 }
185 
186 static void
fpusave_xsave64(void * addr)187 fpusave_xsave64(void *addr)
188 {
189 	xsave64((char *)addr, xsave_mask);
190 }
191 
192 static void
fpusave_xsave3264(void * addr)193 fpusave_xsave3264(void *addr)
194 {
195 	if (SV_CURPROC_FLAG(SV_ILP32))
196 		xsave32((char *)addr, xsave_mask);
197 	else
198 		xsave64((char *)addr, xsave_mask);
199 }
200 
201 static void
fpurestore_xrstor64(void * addr)202 fpurestore_xrstor64(void *addr)
203 {
204 	xrstor64((char *)addr, xsave_mask);
205 }
206 
207 static void
fpurestore_xrstor3264(void * addr)208 fpurestore_xrstor3264(void *addr)
209 {
210 	if (SV_CURPROC_FLAG(SV_ILP32))
211 		xrstor32((char *)addr, xsave_mask);
212 	else
213 		xrstor64((char *)addr, xsave_mask);
214 }
215 
216 static void
fpusave_fxsave(void * addr)217 fpusave_fxsave(void *addr)
218 {
219 
220 	fxsave((char *)addr);
221 }
222 
223 static void
fpurestore_fxrstor(void * addr)224 fpurestore_fxrstor(void *addr)
225 {
226 
227 	fxrstor((char *)addr);
228 }
229 
230 DEFINE_IFUNC(, void, fpusave, (void *))
231 {
232 	u_int cp[4];
233 
234 	if (!use_xsave)
235 		return (fpusave_fxsave);
236 	cpuid_count(0xd, 0x1, cp);
237 	if ((cp[0] & CPUID_EXTSTATE_XSAVEOPT) != 0) {
238 		return ((cpu_stdext_feature & CPUID_STDEXT_NFPUSG) != 0 ?
239 		    fpusave_xsaveopt64 : fpusave_xsaveopt3264);
240 	}
241 	return ((cpu_stdext_feature & CPUID_STDEXT_NFPUSG) != 0 ?
242 	    fpusave_xsave64 : fpusave_xsave3264);
243 }
244 
245 DEFINE_IFUNC(, void, fpurestore, (void *))
246 {
247 	if (!use_xsave)
248 		return (fpurestore_fxrstor);
249 	return ((cpu_stdext_feature & CPUID_STDEXT_NFPUSG) != 0 ?
250 	    fpurestore_xrstor64 : fpurestore_xrstor3264);
251 }
252 
253 void
fpususpend(void * addr)254 fpususpend(void *addr)
255 {
256 	u_long cr0;
257 
258 	cr0 = rcr0();
259 	fpu_enable();
260 	fpusave(addr);
261 	load_cr0(cr0);
262 }
263 
264 void
fpuresume(void * addr)265 fpuresume(void *addr)
266 {
267 	u_long cr0;
268 
269 	cr0 = rcr0();
270 	fpu_enable();
271 	fninit();
272 	if (use_xsave)
273 		load_xcr(XCR0, xsave_mask);
274 	fpurestore(addr);
275 	load_cr0(cr0);
276 }
277 
278 /*
279  * Enable XSAVE if supported and allowed by user.
280  * Calculate the xsave_mask.
281  */
282 static void
fpuinit_bsp1(void)283 fpuinit_bsp1(void)
284 {
285 	u_int cp[4];
286 	uint64_t xsave_mask_user;
287 	bool old_wp;
288 
289 	if (!use_xsave)
290 		return;
291 	cpuid_count(0xd, 0x0, cp);
292 	xsave_mask = XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE;
293 	if ((cp[0] & xsave_mask) != xsave_mask)
294 		panic("CPU0 does not support X87 or SSE: %x", cp[0]);
295 	xsave_mask = ((uint64_t)cp[3] << 32) | cp[0];
296 	xsave_mask_user = xsave_mask;
297 	TUNABLE_ULONG_FETCH("hw.xsave_mask", &xsave_mask_user);
298 	xsave_mask_user |= XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE;
299 	xsave_mask &= xsave_mask_user;
300 	if ((xsave_mask & XFEATURE_AVX512) != XFEATURE_AVX512)
301 		xsave_mask &= ~XFEATURE_AVX512;
302 	if ((xsave_mask & XFEATURE_MPX) != XFEATURE_MPX)
303 		xsave_mask &= ~XFEATURE_MPX;
304 
305 	cpuid_count(0xd, 0x1, cp);
306 	if ((cp[0] & CPUID_EXTSTATE_XSAVEOPT) != 0) {
307 		/*
308 		 * Patch the XSAVE instruction in the cpu_switch code
309 		 * to XSAVEOPT.  We assume that XSAVE encoding used
310 		 * REX byte, and set the bit 4 of the r/m byte.
311 		 *
312 		 * It seems that some BIOSes give control to the OS
313 		 * with CR0.WP already set, making the kernel text
314 		 * read-only before cpu_startup().
315 		 */
316 		old_wp = disable_wp();
317 		ctx_switch_xsave32[3] |= 0x10;
318 		ctx_switch_xsave[3] |= 0x10;
319 		restore_wp(old_wp);
320 	}
321 	xsave_mask_supervisor = ((uint64_t)cp[3] << 32) | cp[2];
322 }
323 
324 /*
325  * Calculate the fpu save area size.
326  */
327 static void
fpuinit_bsp2(void)328 fpuinit_bsp2(void)
329 {
330 	u_int cp[4];
331 
332 	if (use_xsave) {
333 		cpuid_count(0xd, 0x0, cp);
334 		cpu_max_ext_state_size = cp[1];
335 
336 		/*
337 		 * Reload the cpu_feature2, since we enabled OSXSAVE.
338 		 */
339 		do_cpuid(1, cp);
340 		cpu_feature2 = cp[2];
341 	} else
342 		cpu_max_ext_state_size = sizeof(struct savefpu);
343 }
344 
345 /*
346  * Initialize the floating point unit.
347  */
348 void
fpuinit(void)349 fpuinit(void)
350 {
351 	register_t saveintr;
352 	uint64_t cr4;
353 	u_int mxcsr;
354 	u_short control;
355 
356 	TSENTER();
357 	if (IS_BSP())
358 		fpuinit_bsp1();
359 
360 	if (use_xsave) {
361 		cr4 = rcr4();
362 
363 		/*
364 		 * Revert enablement of PKRU if user disabled its
365 		 * saving on context switches by clearing the bit in
366 		 * the xsave mask.  Also redundantly clear the bit in
367 		 * cpu_stdext_feature2 to prevent pmap from ever
368 		 * trying to set the page table bits.
369 		 */
370 		if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0 &&
371 		    (xsave_mask & XFEATURE_ENABLED_PKRU) == 0) {
372 			cr4 &= ~CR4_PKE;
373 			cpu_stdext_feature2 &= ~CPUID_STDEXT2_PKU;
374 		}
375 
376 		load_cr4(cr4 | CR4_XSAVE);
377 		load_xcr(XCR0, xsave_mask);
378 	}
379 
380 	/*
381 	 * XCR0 shall be set up before CPU can report the save area size.
382 	 */
383 	if (IS_BSP())
384 		fpuinit_bsp2();
385 
386 	/*
387 	 * It is too early for critical_enter() to work on AP.
388 	 */
389 	saveintr = intr_disable();
390 	fpu_enable();
391 	fninit();
392 	control = __INITIAL_FPUCW__;
393 	fldcw(control);
394 	mxcsr = __INITIAL_MXCSR__;
395 	ldmxcsr(mxcsr);
396 	fpu_disable();
397 	intr_restore(saveintr);
398 	TSEXIT();
399 }
400 
401 /*
402  * On the boot CPU we generate a clean state that is used to
403  * initialize the floating point unit when it is first used by a
404  * process.
405  */
406 static void
fpuinitstate(void * arg __unused)407 fpuinitstate(void *arg __unused)
408 {
409 	uint64_t *xstate_bv;
410 	register_t saveintr;
411 	int cp[4], i, max_ext_n;
412 
413 	/* Do potentially blocking operations before disabling interrupts. */
414 	fpu_save_area_zone = uma_zcreate("FPU_save_area",
415 	    cpu_max_ext_state_size, NULL, NULL, NULL, NULL,
416 	    XSAVE_AREA_ALIGN - 1, 0);
417 	fpu_initialstate = uma_zalloc(fpu_save_area_zone, M_WAITOK | M_ZERO);
418 	if (use_xsave) {
419 		max_ext_n = flsl(xsave_mask | xsave_mask_supervisor);
420 		xsave_area_desc = malloc(max_ext_n * sizeof(struct
421 		    xsave_area_elm_descr), M_DEVBUF, M_WAITOK | M_ZERO);
422 	}
423 
424 	cpu_thread_alloc(&thread0);
425 
426 	saveintr = intr_disable();
427 	fpu_enable();
428 
429 	fpusave_fxsave(fpu_initialstate);
430 	if (fpu_initialstate->sv_env.en_mxcsr_mask)
431 		cpu_mxcsr_mask = fpu_initialstate->sv_env.en_mxcsr_mask;
432 	else
433 		cpu_mxcsr_mask = 0xFFBF;
434 
435 	/*
436 	 * The fninit instruction does not modify XMM registers or x87
437 	 * registers (MM/ST).  The fpusave call dumped the garbage
438 	 * contained in the registers after reset to the initial state
439 	 * saved.  Clear XMM and x87 registers file image to make the
440 	 * startup program state and signal handler XMM/x87 register
441 	 * content predictable.
442 	 */
443 	bzero(fpu_initialstate->sv_fp, sizeof(fpu_initialstate->sv_fp));
444 	bzero(fpu_initialstate->sv_xmm, sizeof(fpu_initialstate->sv_xmm));
445 
446 	/*
447 	 * Create a table describing the layout of the CPU Extended
448 	 * Save Area.  See Intel SDM rev. 075 Vol. 1 13.4.1 "Legacy
449 	 * Region of an XSAVE Area" for the source of offsets/sizes.
450 	 */
451 	if (use_xsave) {
452 		cpuid_count(0xd, 1, cp);
453 		xsave_extensions = cp[0];
454 
455 		xstate_bv = (uint64_t *)((char *)(fpu_initialstate + 1) +
456 		    offsetof(struct xstate_hdr, xstate_bv));
457 		*xstate_bv = XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE;
458 
459 		/* x87 state */
460 		xsave_area_desc[0].offset = 0;
461 		xsave_area_desc[0].size = 160;
462 		/* XMM */
463 		xsave_area_desc[1].offset = 160;
464 		xsave_area_desc[1].size = 416 - 160;
465 
466 		for (i = 2; i < max_ext_n; i++) {
467 			cpuid_count(0xd, i, cp);
468 			xsave_area_desc[i].size = cp[0];
469 			xsave_area_desc[i].offset = cp[1];
470 			xsave_area_desc[i].flags = cp[2];
471 		}
472 	}
473 
474 	fpu_disable();
475 	intr_restore(saveintr);
476 }
477 /* EFIRT needs this to be initialized before we can enter our EFI environment */
478 SYSINIT(fpuinitstate, SI_SUB_CPU, SI_ORDER_ANY, fpuinitstate, NULL);
479 
480 /*
481  * Free coprocessor (if we have it).
482  */
483 void
fpuexit(struct thread * td)484 fpuexit(struct thread *td)
485 {
486 
487 	critical_enter();
488 	if (curthread == PCPU_GET(fpcurthread)) {
489 		fpu_enable();
490 		fpusave(curpcb->pcb_save);
491 		fpu_disable();
492 		PCPU_SET(fpcurthread, NULL);
493 	}
494 	critical_exit();
495 }
496 
497 int
fpuformat(void)498 fpuformat(void)
499 {
500 
501 	return (_MC_FPFMT_XMM);
502 }
503 
504 /*
505  * The following mechanism is used to ensure that the FPE_... value
506  * that is passed as a trapcode to the signal handler of the user
507  * process does not have more than one bit set.
508  *
509  * Multiple bits may be set if the user process modifies the control
510  * word while a status word bit is already set.  While this is a sign
511  * of bad coding, we have no choice than to narrow them down to one
512  * bit, since we must not send a trapcode that is not exactly one of
513  * the FPE_ macros.
514  *
515  * The mechanism has a static table with 127 entries.  Each combination
516  * of the 7 FPU status word exception bits directly translates to a
517  * position in this table, where a single FPE_... value is stored.
518  * This FPE_... value stored there is considered the "most important"
519  * of the exception bits and will be sent as the signal code.  The
520  * precedence of the bits is based upon Intel Document "Numerical
521  * Applications", Chapter "Special Computational Situations".
522  *
523  * The macro to choose one of these values does these steps: 1) Throw
524  * away status word bits that cannot be masked.  2) Throw away the bits
525  * currently masked in the control word, assuming the user isn't
526  * interested in them anymore.  3) Reinsert status word bit 7 (stack
527  * fault) if it is set, which cannot be masked but must be presered.
528  * 4) Use the remaining bits to point into the trapcode table.
529  *
530  * The 6 maskable bits in order of their preference, as stated in the
531  * above referenced Intel manual:
532  * 1  Invalid operation (FP_X_INV)
533  * 1a   Stack underflow
534  * 1b   Stack overflow
535  * 1c   Operand of unsupported format
536  * 1d   SNaN operand.
537  * 2  QNaN operand (not an exception, irrelavant here)
538  * 3  Any other invalid-operation not mentioned above or zero divide
539  *      (FP_X_INV, FP_X_DZ)
540  * 4  Denormal operand (FP_X_DNML)
541  * 5  Numeric over/underflow (FP_X_OFL, FP_X_UFL)
542  * 6  Inexact result (FP_X_IMP)
543  */
544 static char fpetable[128] = {
545 	0,
546 	FPE_FLTINV,	/*  1 - INV */
547 	FPE_FLTUND,	/*  2 - DNML */
548 	FPE_FLTINV,	/*  3 - INV | DNML */
549 	FPE_FLTDIV,	/*  4 - DZ */
550 	FPE_FLTINV,	/*  5 - INV | DZ */
551 	FPE_FLTDIV,	/*  6 - DNML | DZ */
552 	FPE_FLTINV,	/*  7 - INV | DNML | DZ */
553 	FPE_FLTOVF,	/*  8 - OFL */
554 	FPE_FLTINV,	/*  9 - INV | OFL */
555 	FPE_FLTUND,	/*  A - DNML | OFL */
556 	FPE_FLTINV,	/*  B - INV | DNML | OFL */
557 	FPE_FLTDIV,	/*  C - DZ | OFL */
558 	FPE_FLTINV,	/*  D - INV | DZ | OFL */
559 	FPE_FLTDIV,	/*  E - DNML | DZ | OFL */
560 	FPE_FLTINV,	/*  F - INV | DNML | DZ | OFL */
561 	FPE_FLTUND,	/* 10 - UFL */
562 	FPE_FLTINV,	/* 11 - INV | UFL */
563 	FPE_FLTUND,	/* 12 - DNML | UFL */
564 	FPE_FLTINV,	/* 13 - INV | DNML | UFL */
565 	FPE_FLTDIV,	/* 14 - DZ | UFL */
566 	FPE_FLTINV,	/* 15 - INV | DZ | UFL */
567 	FPE_FLTDIV,	/* 16 - DNML | DZ | UFL */
568 	FPE_FLTINV,	/* 17 - INV | DNML | DZ | UFL */
569 	FPE_FLTOVF,	/* 18 - OFL | UFL */
570 	FPE_FLTINV,	/* 19 - INV | OFL | UFL */
571 	FPE_FLTUND,	/* 1A - DNML | OFL | UFL */
572 	FPE_FLTINV,	/* 1B - INV | DNML | OFL | UFL */
573 	FPE_FLTDIV,	/* 1C - DZ | OFL | UFL */
574 	FPE_FLTINV,	/* 1D - INV | DZ | OFL | UFL */
575 	FPE_FLTDIV,	/* 1E - DNML | DZ | OFL | UFL */
576 	FPE_FLTINV,	/* 1F - INV | DNML | DZ | OFL | UFL */
577 	FPE_FLTRES,	/* 20 - IMP */
578 	FPE_FLTINV,	/* 21 - INV | IMP */
579 	FPE_FLTUND,	/* 22 - DNML | IMP */
580 	FPE_FLTINV,	/* 23 - INV | DNML | IMP */
581 	FPE_FLTDIV,	/* 24 - DZ | IMP */
582 	FPE_FLTINV,	/* 25 - INV | DZ | IMP */
583 	FPE_FLTDIV,	/* 26 - DNML | DZ | IMP */
584 	FPE_FLTINV,	/* 27 - INV | DNML | DZ | IMP */
585 	FPE_FLTOVF,	/* 28 - OFL | IMP */
586 	FPE_FLTINV,	/* 29 - INV | OFL | IMP */
587 	FPE_FLTUND,	/* 2A - DNML | OFL | IMP */
588 	FPE_FLTINV,	/* 2B - INV | DNML | OFL | IMP */
589 	FPE_FLTDIV,	/* 2C - DZ | OFL | IMP */
590 	FPE_FLTINV,	/* 2D - INV | DZ | OFL | IMP */
591 	FPE_FLTDIV,	/* 2E - DNML | DZ | OFL | IMP */
592 	FPE_FLTINV,	/* 2F - INV | DNML | DZ | OFL | IMP */
593 	FPE_FLTUND,	/* 30 - UFL | IMP */
594 	FPE_FLTINV,	/* 31 - INV | UFL | IMP */
595 	FPE_FLTUND,	/* 32 - DNML | UFL | IMP */
596 	FPE_FLTINV,	/* 33 - INV | DNML | UFL | IMP */
597 	FPE_FLTDIV,	/* 34 - DZ | UFL | IMP */
598 	FPE_FLTINV,	/* 35 - INV | DZ | UFL | IMP */
599 	FPE_FLTDIV,	/* 36 - DNML | DZ | UFL | IMP */
600 	FPE_FLTINV,	/* 37 - INV | DNML | DZ | UFL | IMP */
601 	FPE_FLTOVF,	/* 38 - OFL | UFL | IMP */
602 	FPE_FLTINV,	/* 39 - INV | OFL | UFL | IMP */
603 	FPE_FLTUND,	/* 3A - DNML | OFL | UFL | IMP */
604 	FPE_FLTINV,	/* 3B - INV | DNML | OFL | UFL | IMP */
605 	FPE_FLTDIV,	/* 3C - DZ | OFL | UFL | IMP */
606 	FPE_FLTINV,	/* 3D - INV | DZ | OFL | UFL | IMP */
607 	FPE_FLTDIV,	/* 3E - DNML | DZ | OFL | UFL | IMP */
608 	FPE_FLTINV,	/* 3F - INV | DNML | DZ | OFL | UFL | IMP */
609 	FPE_FLTSUB,	/* 40 - STK */
610 	FPE_FLTSUB,	/* 41 - INV | STK */
611 	FPE_FLTUND,	/* 42 - DNML | STK */
612 	FPE_FLTSUB,	/* 43 - INV | DNML | STK */
613 	FPE_FLTDIV,	/* 44 - DZ | STK */
614 	FPE_FLTSUB,	/* 45 - INV | DZ | STK */
615 	FPE_FLTDIV,	/* 46 - DNML | DZ | STK */
616 	FPE_FLTSUB,	/* 47 - INV | DNML | DZ | STK */
617 	FPE_FLTOVF,	/* 48 - OFL | STK */
618 	FPE_FLTSUB,	/* 49 - INV | OFL | STK */
619 	FPE_FLTUND,	/* 4A - DNML | OFL | STK */
620 	FPE_FLTSUB,	/* 4B - INV | DNML | OFL | STK */
621 	FPE_FLTDIV,	/* 4C - DZ | OFL | STK */
622 	FPE_FLTSUB,	/* 4D - INV | DZ | OFL | STK */
623 	FPE_FLTDIV,	/* 4E - DNML | DZ | OFL | STK */
624 	FPE_FLTSUB,	/* 4F - INV | DNML | DZ | OFL | STK */
625 	FPE_FLTUND,	/* 50 - UFL | STK */
626 	FPE_FLTSUB,	/* 51 - INV | UFL | STK */
627 	FPE_FLTUND,	/* 52 - DNML | UFL | STK */
628 	FPE_FLTSUB,	/* 53 - INV | DNML | UFL | STK */
629 	FPE_FLTDIV,	/* 54 - DZ | UFL | STK */
630 	FPE_FLTSUB,	/* 55 - INV | DZ | UFL | STK */
631 	FPE_FLTDIV,	/* 56 - DNML | DZ | UFL | STK */
632 	FPE_FLTSUB,	/* 57 - INV | DNML | DZ | UFL | STK */
633 	FPE_FLTOVF,	/* 58 - OFL | UFL | STK */
634 	FPE_FLTSUB,	/* 59 - INV | OFL | UFL | STK */
635 	FPE_FLTUND,	/* 5A - DNML | OFL | UFL | STK */
636 	FPE_FLTSUB,	/* 5B - INV | DNML | OFL | UFL | STK */
637 	FPE_FLTDIV,	/* 5C - DZ | OFL | UFL | STK */
638 	FPE_FLTSUB,	/* 5D - INV | DZ | OFL | UFL | STK */
639 	FPE_FLTDIV,	/* 5E - DNML | DZ | OFL | UFL | STK */
640 	FPE_FLTSUB,	/* 5F - INV | DNML | DZ | OFL | UFL | STK */
641 	FPE_FLTRES,	/* 60 - IMP | STK */
642 	FPE_FLTSUB,	/* 61 - INV | IMP | STK */
643 	FPE_FLTUND,	/* 62 - DNML | IMP | STK */
644 	FPE_FLTSUB,	/* 63 - INV | DNML | IMP | STK */
645 	FPE_FLTDIV,	/* 64 - DZ | IMP | STK */
646 	FPE_FLTSUB,	/* 65 - INV | DZ | IMP | STK */
647 	FPE_FLTDIV,	/* 66 - DNML | DZ | IMP | STK */
648 	FPE_FLTSUB,	/* 67 - INV | DNML | DZ | IMP | STK */
649 	FPE_FLTOVF,	/* 68 - OFL | IMP | STK */
650 	FPE_FLTSUB,	/* 69 - INV | OFL | IMP | STK */
651 	FPE_FLTUND,	/* 6A - DNML | OFL | IMP | STK */
652 	FPE_FLTSUB,	/* 6B - INV | DNML | OFL | IMP | STK */
653 	FPE_FLTDIV,	/* 6C - DZ | OFL | IMP | STK */
654 	FPE_FLTSUB,	/* 6D - INV | DZ | OFL | IMP | STK */
655 	FPE_FLTDIV,	/* 6E - DNML | DZ | OFL | IMP | STK */
656 	FPE_FLTSUB,	/* 6F - INV | DNML | DZ | OFL | IMP | STK */
657 	FPE_FLTUND,	/* 70 - UFL | IMP | STK */
658 	FPE_FLTSUB,	/* 71 - INV | UFL | IMP | STK */
659 	FPE_FLTUND,	/* 72 - DNML | UFL | IMP | STK */
660 	FPE_FLTSUB,	/* 73 - INV | DNML | UFL | IMP | STK */
661 	FPE_FLTDIV,	/* 74 - DZ | UFL | IMP | STK */
662 	FPE_FLTSUB,	/* 75 - INV | DZ | UFL | IMP | STK */
663 	FPE_FLTDIV,	/* 76 - DNML | DZ | UFL | IMP | STK */
664 	FPE_FLTSUB,	/* 77 - INV | DNML | DZ | UFL | IMP | STK */
665 	FPE_FLTOVF,	/* 78 - OFL | UFL | IMP | STK */
666 	FPE_FLTSUB,	/* 79 - INV | OFL | UFL | IMP | STK */
667 	FPE_FLTUND,	/* 7A - DNML | OFL | UFL | IMP | STK */
668 	FPE_FLTSUB,	/* 7B - INV | DNML | OFL | UFL | IMP | STK */
669 	FPE_FLTDIV,	/* 7C - DZ | OFL | UFL | IMP | STK */
670 	FPE_FLTSUB,	/* 7D - INV | DZ | OFL | UFL | IMP | STK */
671 	FPE_FLTDIV,	/* 7E - DNML | DZ | OFL | UFL | IMP | STK */
672 	FPE_FLTSUB,	/* 7F - INV | DNML | DZ | OFL | UFL | IMP | STK */
673 };
674 
675 /*
676  * Read the FP status and control words, then generate si_code value
677  * for SIGFPE.  The error code chosen will be one of the
678  * FPE_... macros.  It will be sent as the second argument to old
679  * BSD-style signal handlers and as "siginfo_t->si_code" (second
680  * argument) to SA_SIGINFO signal handlers.
681  *
682  * Some time ago, we cleared the x87 exceptions with FNCLEX there.
683  * Clearing exceptions was necessary mainly to avoid IRQ13 bugs.  The
684  * usermode code which understands the FPU hardware enough to enable
685  * the exceptions, can also handle clearing the exception state in the
686  * handler.  The only consequence of not clearing the exception is the
687  * rethrow of the SIGFPE on return from the signal handler and
688  * reexecution of the corresponding instruction.
689  *
690  * For XMM traps, the exceptions were never cleared.
691  */
692 int
fputrap_x87(void)693 fputrap_x87(void)
694 {
695 	struct savefpu *pcb_save;
696 	u_short control, status;
697 
698 	critical_enter();
699 
700 	/*
701 	 * Interrupt handling (for another interrupt) may have pushed the
702 	 * state to memory.  Fetch the relevant parts of the state from
703 	 * wherever they are.
704 	 */
705 	if (PCPU_GET(fpcurthread) != curthread) {
706 		pcb_save = curpcb->pcb_save;
707 		control = pcb_save->sv_env.en_cw;
708 		status = pcb_save->sv_env.en_sw;
709 	} else {
710 		fnstcw(&control);
711 		fnstsw(&status);
712 	}
713 
714 	critical_exit();
715 	return (fpetable[status & ((~control & 0x3f) | 0x40)]);
716 }
717 
718 int
fputrap_sse(void)719 fputrap_sse(void)
720 {
721 	u_int mxcsr;
722 
723 	critical_enter();
724 	if (PCPU_GET(fpcurthread) != curthread)
725 		mxcsr = curpcb->pcb_save->sv_env.en_mxcsr;
726 	else
727 		stmxcsr(&mxcsr);
728 	critical_exit();
729 	return (fpetable[(mxcsr & (~mxcsr >> 7)) & 0x3f]);
730 }
731 
732 static void
restore_fpu_curthread(struct thread * td)733 restore_fpu_curthread(struct thread *td)
734 {
735 	struct pcb *pcb;
736 
737 	/*
738 	 * Record new context early in case frstor causes a trap.
739 	 */
740 	PCPU_SET(fpcurthread, td);
741 
742 	fpu_enable();
743 	fpu_clean_state();
744 	pcb = td->td_pcb;
745 
746 	if ((pcb->pcb_flags & PCB_FPUINITDONE) == 0) {
747 		/*
748 		 * This is the first time this thread has used the FPU or
749 		 * the PCB doesn't contain a clean FPU state.  Explicitly
750 		 * load an initial state.
751 		 *
752 		 * We prefer to restore the state from the actual save
753 		 * area in PCB instead of directly loading from
754 		 * fpu_initialstate, to ignite the XSAVEOPT
755 		 * tracking engine.
756 		 */
757 		bcopy(fpu_initialstate, pcb->pcb_save,
758 		    cpu_max_ext_state_size);
759 		fpurestore(pcb->pcb_save);
760 		if (pcb->pcb_initial_fpucw != __INITIAL_FPUCW__)
761 			fldcw(pcb->pcb_initial_fpucw);
762 		if (PCB_USER_FPU(pcb))
763 			set_pcb_flags(pcb, PCB_FPUINITDONE |
764 			    PCB_USERFPUINITDONE);
765 		else
766 			set_pcb_flags(pcb, PCB_FPUINITDONE);
767 	} else
768 		fpurestore(pcb->pcb_save);
769 }
770 
771 /*
772  * Device Not Available (DNA, #NM) exception handler.
773  *
774  * It would be better to switch FP context here (if curthread !=
775  * fpcurthread) and not necessarily for every context switch, but it
776  * is too hard to access foreign pcb's.
777  */
778 void
fpudna(void)779 fpudna(void)
780 {
781 	struct thread *td;
782 
783 	td = curthread;
784 	/*
785 	 * This handler is entered with interrupts enabled, so context
786 	 * switches may occur before critical_enter() is executed.  If
787 	 * a context switch occurs, then when we regain control, our
788 	 * state will have been completely restored.  The CPU may
789 	 * change underneath us, but the only part of our context that
790 	 * lives in the CPU is CR0.TS and that will be "restored" by
791 	 * setting it on the new CPU.
792 	 */
793 	critical_enter();
794 
795 	KASSERT((curpcb->pcb_flags & PCB_FPUNOSAVE) == 0,
796 	    ("fpudna while in fpu_kern_enter(FPU_KERN_NOCTX)"));
797 	if (__predict_false(PCPU_GET(fpcurthread) == td)) {
798 		/*
799 		 * Some virtual machines seems to set %cr0.TS at
800 		 * arbitrary moments.  Silently clear the TS bit
801 		 * regardless of the eager/lazy FPU context switch
802 		 * mode.
803 		 */
804 		fpu_enable();
805 	} else {
806 		if (__predict_false(PCPU_GET(fpcurthread) != NULL)) {
807 			panic(
808 		    "fpudna: fpcurthread = %p (%d), curthread = %p (%d)\n",
809 			    PCPU_GET(fpcurthread),
810 			    PCPU_GET(fpcurthread)->td_tid, td, td->td_tid);
811 		}
812 		restore_fpu_curthread(td);
813 	}
814 	critical_exit();
815 }
816 
817 void fpu_activate_sw(struct thread *td); /* Called from the context switch */
818 void
fpu_activate_sw(struct thread * td)819 fpu_activate_sw(struct thread *td)
820 {
821 
822 	if ((td->td_pflags & TDP_KTHREAD) != 0 || !PCB_USER_FPU(td->td_pcb)) {
823 		PCPU_SET(fpcurthread, NULL);
824 		fpu_disable();
825 	} else if (PCPU_GET(fpcurthread) != td) {
826 		restore_fpu_curthread(td);
827 	}
828 }
829 
830 void
fpudrop(void)831 fpudrop(void)
832 {
833 	struct thread *td;
834 
835 	td = PCPU_GET(fpcurthread);
836 	KASSERT(td == curthread, ("fpudrop: fpcurthread != curthread"));
837 	CRITICAL_ASSERT(td);
838 	PCPU_SET(fpcurthread, NULL);
839 	clear_pcb_flags(td->td_pcb, PCB_FPUINITDONE);
840 	fpu_disable();
841 }
842 
843 /*
844  * Get the user state of the FPU into pcb->pcb_user_save without
845  * dropping ownership (if possible).  It returns the FPU ownership
846  * status.
847  */
848 int
fpugetregs(struct thread * td)849 fpugetregs(struct thread *td)
850 {
851 	struct pcb *pcb;
852 	uint64_t *xstate_bv, bit;
853 	char *sa;
854 	struct savefpu *s;
855 	uint32_t mxcsr, mxcsr_mask;
856 	int max_ext_n, i, owned;
857 	bool do_mxcsr;
858 
859 	pcb = td->td_pcb;
860 	critical_enter();
861 	if ((pcb->pcb_flags & PCB_USERFPUINITDONE) == 0) {
862 		bcopy(fpu_initialstate, get_pcb_user_save_pcb(pcb),
863 		    cpu_max_ext_state_size);
864 		get_pcb_user_save_pcb(pcb)->sv_env.en_cw =
865 		    pcb->pcb_initial_fpucw;
866 		fpuuserinited(td);
867 		critical_exit();
868 		return (_MC_FPOWNED_PCB);
869 	}
870 	if (td == PCPU_GET(fpcurthread) && PCB_USER_FPU(pcb)) {
871 		fpusave(get_pcb_user_save_pcb(pcb));
872 		owned = _MC_FPOWNED_FPU;
873 	} else {
874 		owned = _MC_FPOWNED_PCB;
875 	}
876 	if (use_xsave) {
877 		/*
878 		 * Handle partially saved state.
879 		 */
880 		sa = (char *)get_pcb_user_save_pcb(pcb);
881 		xstate_bv = (uint64_t *)(sa + sizeof(struct savefpu) +
882 		    offsetof(struct xstate_hdr, xstate_bv));
883 		max_ext_n = flsl(xsave_mask);
884 		for (i = 0; i < max_ext_n; i++) {
885 			bit = 1ULL << i;
886 			if ((xsave_mask & bit) == 0 || (*xstate_bv & bit) != 0)
887 				continue;
888 			do_mxcsr = false;
889 			if (i == 0 && (*xstate_bv & (XFEATURE_ENABLED_SSE |
890 			    XFEATURE_ENABLED_AVX)) != 0) {
891 				/*
892 				 * x87 area was not saved by XSAVEOPT,
893 				 * but one of XMM or AVX was.  Then we need
894 				 * to preserve MXCSR from being overwritten
895 				 * with the default value.
896 				 */
897 				s = (struct savefpu *)sa;
898 				mxcsr = s->sv_env.en_mxcsr;
899 				mxcsr_mask = s->sv_env.en_mxcsr_mask;
900 				do_mxcsr = true;
901 			}
902 			bcopy((char *)fpu_initialstate +
903 			    xsave_area_desc[i].offset,
904 			    sa + xsave_area_desc[i].offset,
905 			    xsave_area_desc[i].size);
906 			if (do_mxcsr) {
907 				s->sv_env.en_mxcsr = mxcsr;
908 				s->sv_env.en_mxcsr_mask = mxcsr_mask;
909 			}
910 			*xstate_bv |= bit;
911 		}
912 	}
913 	critical_exit();
914 	return (owned);
915 }
916 
917 void
fpuuserinited(struct thread * td)918 fpuuserinited(struct thread *td)
919 {
920 	struct pcb *pcb;
921 
922 	CRITICAL_ASSERT(td);
923 	pcb = td->td_pcb;
924 	if (PCB_USER_FPU(pcb))
925 		set_pcb_flags(pcb,
926 		    PCB_FPUINITDONE | PCB_USERFPUINITDONE);
927 	else
928 		set_pcb_flags(pcb, PCB_FPUINITDONE);
929 }
930 
931 int
fpusetxstate(struct thread * td,char * xfpustate,size_t xfpustate_size)932 fpusetxstate(struct thread *td, char *xfpustate, size_t xfpustate_size)
933 {
934 	struct xstate_hdr *hdr, *ehdr;
935 	size_t len, max_len;
936 	uint64_t bv;
937 
938 	/* XXXKIB should we clear all extended state in xstate_bv instead ? */
939 	if (xfpustate == NULL)
940 		return (0);
941 	if (!use_xsave)
942 		return (EOPNOTSUPP);
943 
944 	len = xfpustate_size;
945 	if (len < sizeof(struct xstate_hdr))
946 		return (EINVAL);
947 	max_len = cpu_max_ext_state_size - sizeof(struct savefpu);
948 	if (len > max_len)
949 		return (EINVAL);
950 
951 	ehdr = (struct xstate_hdr *)xfpustate;
952 	bv = ehdr->xstate_bv;
953 
954 	/*
955 	 * Avoid #gp.
956 	 */
957 	if (bv & ~xsave_mask)
958 		return (EINVAL);
959 
960 	hdr = (struct xstate_hdr *)(get_pcb_user_save_td(td) + 1);
961 
962 	hdr->xstate_bv = bv;
963 	bcopy(xfpustate + sizeof(struct xstate_hdr),
964 	    (char *)(hdr + 1), len - sizeof(struct xstate_hdr));
965 
966 	return (0);
967 }
968 
969 /*
970  * Set the state of the FPU.
971  */
972 int
fpusetregs(struct thread * td,struct savefpu * addr,char * xfpustate,size_t xfpustate_size)973 fpusetregs(struct thread *td, struct savefpu *addr, char *xfpustate,
974     size_t xfpustate_size)
975 {
976 	struct pcb *pcb;
977 	int error;
978 
979 	addr->sv_env.en_mxcsr &= cpu_mxcsr_mask;
980 	pcb = td->td_pcb;
981 	error = 0;
982 	critical_enter();
983 	if (td == PCPU_GET(fpcurthread) && PCB_USER_FPU(pcb)) {
984 		error = fpusetxstate(td, xfpustate, xfpustate_size);
985 		if (error == 0) {
986 			bcopy(addr, get_pcb_user_save_td(td), sizeof(*addr));
987 			fpurestore(get_pcb_user_save_td(td));
988 			set_pcb_flags(pcb, PCB_FPUINITDONE |
989 			    PCB_USERFPUINITDONE);
990 		}
991 	} else {
992 		error = fpusetxstate(td, xfpustate, xfpustate_size);
993 		if (error == 0) {
994 			bcopy(addr, get_pcb_user_save_td(td), sizeof(*addr));
995 			fpuuserinited(td);
996 		}
997 	}
998 	critical_exit();
999 	return (error);
1000 }
1001 
1002 /*
1003  * On AuthenticAMD processors, the fxrstor instruction does not restore
1004  * the x87's stored last instruction pointer, last data pointer, and last
1005  * opcode values, except in the rare case in which the exception summary
1006  * (ES) bit in the x87 status word is set to 1.
1007  *
1008  * In order to avoid leaking this information across processes, we clean
1009  * these values by performing a dummy load before executing fxrstor().
1010  */
1011 static void
fpu_clean_state(void)1012 fpu_clean_state(void)
1013 {
1014 	static float dummy_variable = 0.0;
1015 	u_short status;
1016 
1017 	/*
1018 	 * Clear the ES bit in the x87 status word if it is currently
1019 	 * set, in order to avoid causing a fault in the upcoming load.
1020 	 */
1021 	fnstsw(&status);
1022 	if (status & 0x80)
1023 		fnclex();
1024 
1025 	/*
1026 	 * Load the dummy variable into the x87 stack.  This mangles
1027 	 * the x87 stack, but we don't care since we're about to call
1028 	 * fxrstor() anyway.
1029 	 */
1030 	__asm __volatile("ffree %%st(7); flds %0" : : "m" (dummy_variable));
1031 }
1032 
1033 /*
1034  * This really sucks.  We want the acpi version only, but it requires
1035  * the isa_if.h file in order to get the definitions.
1036  */
1037 #include "opt_isa.h"
1038 #ifdef DEV_ISA
1039 #include <isa/isavar.h>
1040 /*
1041  * This sucks up the legacy ISA support assignments from PNPBIOS/ACPI.
1042  */
1043 static struct isa_pnp_id fpupnp_ids[] = {
1044 	{ 0x040cd041, "Legacy ISA coprocessor support" }, /* PNP0C04 */
1045 	{ 0 }
1046 };
1047 
1048 static int
fpupnp_probe(device_t dev)1049 fpupnp_probe(device_t dev)
1050 {
1051 	int result;
1052 
1053 	result = ISA_PNP_PROBE(device_get_parent(dev), dev, fpupnp_ids);
1054 	if (result <= 0)
1055 		device_quiet(dev);
1056 	return (result);
1057 }
1058 
1059 static int
fpupnp_attach(device_t dev)1060 fpupnp_attach(device_t dev)
1061 {
1062 
1063 	return (0);
1064 }
1065 
1066 static device_method_t fpupnp_methods[] = {
1067 	/* Device interface */
1068 	DEVMETHOD(device_probe,		fpupnp_probe),
1069 	DEVMETHOD(device_attach,	fpupnp_attach),
1070 	{ 0, 0 }
1071 };
1072 
1073 static driver_t fpupnp_driver = {
1074 	"fpupnp",
1075 	fpupnp_methods,
1076 	1,			/* no softc */
1077 };
1078 
1079 DRIVER_MODULE(fpupnp, acpi, fpupnp_driver, 0, 0);
1080 ISA_PNP_INFO(fpupnp_ids);
1081 #endif	/* DEV_ISA */
1082 
1083 static MALLOC_DEFINE(M_FPUKERN_CTX, "fpukern_ctx",
1084     "Kernel contexts for FPU state");
1085 
1086 #define	FPU_KERN_CTX_FPUINITDONE 0x01
1087 #define	FPU_KERN_CTX_DUMMY	 0x02	/* avoided save for the kern thread */
1088 #define	FPU_KERN_CTX_INUSE	 0x04
1089 
1090 struct fpu_kern_ctx {
1091 	struct savefpu *prev;
1092 	uint32_t flags;
1093 	char hwstate1[];
1094 };
1095 
1096 static inline size_t __pure2
fpu_kern_alloc_sz(u_int max_est)1097 fpu_kern_alloc_sz(u_int max_est)
1098 {
1099 	return (sizeof(struct fpu_kern_ctx) + XSAVE_AREA_ALIGN + max_est);
1100 }
1101 
1102 static inline int __pure2
fpu_kern_malloc_flags(u_int fpflags)1103 fpu_kern_malloc_flags(u_int fpflags)
1104 {
1105 	return (((fpflags & FPU_KERN_NOWAIT) ? M_NOWAIT : M_WAITOK) | M_ZERO);
1106 }
1107 
1108 struct fpu_kern_ctx *
fpu_kern_alloc_ctx_domain(int domain,u_int flags)1109 fpu_kern_alloc_ctx_domain(int domain, u_int flags)
1110 {
1111 	return (malloc_domainset(fpu_kern_alloc_sz(cpu_max_ext_state_size),
1112 	    M_FPUKERN_CTX, DOMAINSET_PREF(domain),
1113 	    fpu_kern_malloc_flags(flags)));
1114 }
1115 
1116 struct fpu_kern_ctx *
fpu_kern_alloc_ctx(u_int flags)1117 fpu_kern_alloc_ctx(u_int flags)
1118 {
1119 	return (malloc(fpu_kern_alloc_sz(cpu_max_ext_state_size),
1120 	    M_FPUKERN_CTX, fpu_kern_malloc_flags(flags)));
1121 }
1122 
1123 void
fpu_kern_free_ctx(struct fpu_kern_ctx * ctx)1124 fpu_kern_free_ctx(struct fpu_kern_ctx *ctx)
1125 {
1126 
1127 	KASSERT((ctx->flags & FPU_KERN_CTX_INUSE) == 0, ("free'ing inuse ctx"));
1128 	/* XXXKIB clear the memory ? */
1129 	free(ctx, M_FPUKERN_CTX);
1130 }
1131 
1132 static struct savefpu *
fpu_kern_ctx_savefpu(struct fpu_kern_ctx * ctx)1133 fpu_kern_ctx_savefpu(struct fpu_kern_ctx *ctx)
1134 {
1135 	vm_offset_t p;
1136 
1137 	p = (vm_offset_t)&ctx->hwstate1;
1138 	p = roundup2(p, XSAVE_AREA_ALIGN);
1139 	return ((struct savefpu *)p);
1140 }
1141 
1142 void
fpu_kern_enter(struct thread * td,struct fpu_kern_ctx * ctx,u_int flags)1143 fpu_kern_enter(struct thread *td, struct fpu_kern_ctx *ctx, u_int flags)
1144 {
1145 	struct pcb *pcb;
1146 
1147 	pcb = td->td_pcb;
1148 	KASSERT((flags & FPU_KERN_NOCTX) != 0 || ctx != NULL,
1149 	    ("ctx is required when !FPU_KERN_NOCTX"));
1150 	KASSERT(ctx == NULL || (ctx->flags & FPU_KERN_CTX_INUSE) == 0,
1151 	    ("using inuse ctx"));
1152 	KASSERT((pcb->pcb_flags & PCB_FPUNOSAVE) == 0,
1153 	    ("recursive fpu_kern_enter while in PCB_FPUNOSAVE state"));
1154 
1155 	if ((flags & FPU_KERN_NOCTX) != 0) {
1156 		critical_enter();
1157 		fpu_enable();
1158 		if (curthread == PCPU_GET(fpcurthread)) {
1159 			fpusave(curpcb->pcb_save);
1160 			PCPU_SET(fpcurthread, NULL);
1161 		} else {
1162 			KASSERT(PCPU_GET(fpcurthread) == NULL,
1163 			    ("invalid fpcurthread"));
1164 		}
1165 
1166 		/*
1167 		 * This breaks XSAVEOPT tracker, but
1168 		 * PCB_FPUNOSAVE state is supposed to never need to
1169 		 * save FPU context at all.
1170 		 */
1171 		fpurestore(fpu_initialstate);
1172 		set_pcb_flags(pcb, PCB_KERNFPU | PCB_FPUNOSAVE |
1173 		    PCB_FPUINITDONE);
1174 		return;
1175 	}
1176 	if ((flags & FPU_KERN_KTHR) != 0 && is_fpu_kern_thread(0)) {
1177 		ctx->flags = FPU_KERN_CTX_DUMMY | FPU_KERN_CTX_INUSE;
1178 		return;
1179 	}
1180 	critical_enter();
1181 	KASSERT(!PCB_USER_FPU(pcb) || pcb->pcb_save ==
1182 	    get_pcb_user_save_pcb(pcb), ("mangled pcb_save"));
1183 	ctx->flags = FPU_KERN_CTX_INUSE;
1184 	if ((pcb->pcb_flags & PCB_FPUINITDONE) != 0)
1185 		ctx->flags |= FPU_KERN_CTX_FPUINITDONE;
1186 	fpuexit(td);
1187 	ctx->prev = pcb->pcb_save;
1188 	pcb->pcb_save = fpu_kern_ctx_savefpu(ctx);
1189 	set_pcb_flags(pcb, PCB_KERNFPU);
1190 	clear_pcb_flags(pcb, PCB_FPUINITDONE);
1191 	critical_exit();
1192 }
1193 
1194 int
fpu_kern_leave(struct thread * td,struct fpu_kern_ctx * ctx)1195 fpu_kern_leave(struct thread *td, struct fpu_kern_ctx *ctx)
1196 {
1197 	struct pcb *pcb;
1198 
1199 	pcb = td->td_pcb;
1200 
1201 	if ((pcb->pcb_flags & PCB_FPUNOSAVE) != 0) {
1202 		KASSERT(ctx == NULL, ("non-null ctx after FPU_KERN_NOCTX"));
1203 		KASSERT(PCPU_GET(fpcurthread) == NULL,
1204 		    ("non-NULL fpcurthread for PCB_FPUNOSAVE"));
1205 		CRITICAL_ASSERT(td);
1206 
1207 		clear_pcb_flags(pcb,  PCB_FPUNOSAVE | PCB_FPUINITDONE);
1208 		fpu_disable();
1209 	} else {
1210 		KASSERT((ctx->flags & FPU_KERN_CTX_INUSE) != 0,
1211 		    ("leaving not inuse ctx"));
1212 		ctx->flags &= ~FPU_KERN_CTX_INUSE;
1213 
1214 		if (is_fpu_kern_thread(0) &&
1215 		    (ctx->flags & FPU_KERN_CTX_DUMMY) != 0)
1216 			return (0);
1217 		KASSERT((ctx->flags & FPU_KERN_CTX_DUMMY) == 0,
1218 		    ("dummy ctx"));
1219 		critical_enter();
1220 		if (curthread == PCPU_GET(fpcurthread))
1221 			fpudrop();
1222 		pcb->pcb_save = ctx->prev;
1223 	}
1224 
1225 	if (pcb->pcb_save == get_pcb_user_save_pcb(pcb)) {
1226 		if ((pcb->pcb_flags & PCB_USERFPUINITDONE) != 0) {
1227 			set_pcb_flags(pcb, PCB_FPUINITDONE);
1228 			if ((pcb->pcb_flags & PCB_KERNFPU_THR) == 0)
1229 				clear_pcb_flags(pcb, PCB_KERNFPU);
1230 		} else if ((pcb->pcb_flags & PCB_KERNFPU_THR) == 0)
1231 			clear_pcb_flags(pcb, PCB_FPUINITDONE | PCB_KERNFPU);
1232 	} else {
1233 		if ((ctx->flags & FPU_KERN_CTX_FPUINITDONE) != 0)
1234 			set_pcb_flags(pcb, PCB_FPUINITDONE);
1235 		else
1236 			clear_pcb_flags(pcb, PCB_FPUINITDONE);
1237 		KASSERT(!PCB_USER_FPU(pcb), ("unpaired fpu_kern_leave"));
1238 	}
1239 	critical_exit();
1240 	return (0);
1241 }
1242 
1243 int
fpu_kern_thread(u_int flags)1244 fpu_kern_thread(u_int flags)
1245 {
1246 
1247 	KASSERT((curthread->td_pflags & TDP_KTHREAD) != 0,
1248 	    ("Only kthread may use fpu_kern_thread"));
1249 	KASSERT(curpcb->pcb_save == get_pcb_user_save_pcb(curpcb),
1250 	    ("mangled pcb_save"));
1251 	KASSERT(PCB_USER_FPU(curpcb), ("recursive call"));
1252 
1253 	set_pcb_flags(curpcb, PCB_KERNFPU | PCB_KERNFPU_THR);
1254 	return (0);
1255 }
1256 
1257 int
is_fpu_kern_thread(u_int flags)1258 is_fpu_kern_thread(u_int flags)
1259 {
1260 
1261 	if ((curthread->td_pflags & TDP_KTHREAD) == 0)
1262 		return (0);
1263 	return ((curpcb->pcb_flags & PCB_KERNFPU_THR) != 0);
1264 }
1265 
1266 /*
1267  * FPU save area alloc/free/init utility routines
1268  */
1269 struct savefpu *
fpu_save_area_alloc(void)1270 fpu_save_area_alloc(void)
1271 {
1272 
1273 	return (uma_zalloc(fpu_save_area_zone, M_WAITOK));
1274 }
1275 
1276 void
fpu_save_area_free(struct savefpu * fsa)1277 fpu_save_area_free(struct savefpu *fsa)
1278 {
1279 
1280 	uma_zfree(fpu_save_area_zone, fsa);
1281 }
1282 
1283 void
fpu_save_area_reset(struct savefpu * fsa)1284 fpu_save_area_reset(struct savefpu *fsa)
1285 {
1286 
1287 	bcopy(fpu_initialstate, fsa, cpu_max_ext_state_size);
1288 }
1289 
1290 static __inline void
xsave_extfeature_check(uint64_t feature,bool supervisor)1291 xsave_extfeature_check(uint64_t feature, bool supervisor)
1292 {
1293 #ifdef INVARIANTS
1294 	uint64_t mask;
1295 
1296 	mask = supervisor ? xsave_mask_supervisor : xsave_mask;
1297 	KASSERT((feature & (feature - 1)) == 0,
1298 	    ("%s: invalid XFEATURE 0x%lx", __func__, feature));
1299 	KASSERT(ilog2(feature) <= ilog2(mask),
1300 	    ("%s: unsupported %s XFEATURE 0x%lx", __func__,
1301 	    supervisor ? "supervisor" : "user", feature));
1302 #endif
1303 }
1304 
1305 static __inline void
xsave_extstate_bv_check(uint64_t xstate_bv,bool supervisor)1306 xsave_extstate_bv_check(uint64_t xstate_bv, bool supervisor)
1307 {
1308 #ifdef INVARIANTS
1309 	uint64_t mask;
1310 
1311 	mask = supervisor ? xsave_mask_supervisor : xsave_mask;
1312 	KASSERT(xstate_bv != 0 && ilog2(xstate_bv) <= ilog2(mask),
1313 	    ("%s: invalid XSTATE_BV 0x%lx", __func__, xstate_bv));
1314 #endif
1315 }
1316 
1317 /*
1318  * Returns whether the XFEATURE 'feature' is supported as a user state
1319  * or supervisor state component.
1320  */
1321 bool
xsave_extfeature_supported(uint64_t feature,bool supervisor)1322 xsave_extfeature_supported(uint64_t feature, bool supervisor)
1323 {
1324 	int idx;
1325 	uint64_t mask;
1326 
1327 	KASSERT(use_xsave, ("%s: XSAVE not supported", __func__));
1328 	xsave_extfeature_check(feature, supervisor);
1329 
1330 	mask = supervisor ? xsave_mask_supervisor : xsave_mask;
1331 	if ((mask & feature) == 0)
1332 		return (false);
1333 	idx = ilog2(feature);
1334 	return (((xsave_area_desc[idx].flags & CPUID_EXTSTATE_SUPERVISOR) != 0) ==
1335 	    supervisor);
1336 }
1337 
1338 /*
1339  * Returns whether the given XSAVE extension is supported.
1340  */
1341 bool
xsave_extension_supported(uint64_t extension)1342 xsave_extension_supported(uint64_t extension)
1343 {
1344 	KASSERT(use_xsave, ("%s: XSAVE not supported", __func__));
1345 
1346 	return ((xsave_extensions & extension) != 0);
1347 }
1348 
1349 /*
1350  * Returns offset for XFEATURE 'feature' given the requested feature bitmap
1351  * 'xstate_bv', and extended region format ('compact').
1352  */
1353 size_t
xsave_area_offset(uint64_t xstate_bv,uint64_t feature,bool compact,bool supervisor)1354 xsave_area_offset(uint64_t xstate_bv, uint64_t feature,
1355     bool compact, bool supervisor)
1356 {
1357 	int i, idx;
1358 	size_t offs;
1359 	struct xsave_area_elm_descr *xep;
1360 
1361 	KASSERT(use_xsave, ("%s: XSAVE not supported", __func__));
1362 	xsave_extstate_bv_check(xstate_bv, supervisor);
1363 	xsave_extfeature_check(feature, supervisor);
1364 
1365 	idx = ilog2(feature);
1366 	if (!compact)
1367 		return (xsave_area_desc[idx].offset);
1368 	offs = sizeof(struct savefpu) + sizeof(struct xstate_hdr);
1369 	xstate_bv &= ~(XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE);
1370 	while ((i = ffs(xstate_bv) - 1) > 0 && i < idx) {
1371 		xep = &xsave_area_desc[i];
1372 		if ((xep->flags & CPUID_EXTSTATE_ALIGNED) != 0)
1373 			offs = roundup2(offs, 64);
1374 		offs += xep->size;
1375 		xstate_bv &= ~((uint64_t)1 << i);
1376 	}
1377 
1378 	return (offs);
1379 }
1380 
1381 /*
1382  * Returns the XSAVE area size for the requested feature bitmap
1383  * 'xstate_bv' and extended region format ('compact').
1384  */
1385 size_t
xsave_area_size(uint64_t xstate_bv,bool compact,bool supervisor)1386 xsave_area_size(uint64_t xstate_bv, bool compact, bool supervisor)
1387 {
1388 	int last_idx;
1389 
1390 	KASSERT(use_xsave, ("%s: XSAVE not supported", __func__));
1391 	xsave_extstate_bv_check(xstate_bv, supervisor);
1392 
1393 	last_idx = ilog2(xstate_bv);
1394 
1395 	return (xsave_area_offset(xstate_bv, (uint64_t)1 << last_idx, compact, supervisor) +
1396 	    xsave_area_desc[last_idx].size);
1397 }
1398 
1399 size_t
xsave_area_hdr_offset(void)1400 xsave_area_hdr_offset(void)
1401 {
1402 	return (sizeof(struct savefpu));
1403 }
1404