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