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