xref: /freebsd/sys/amd64/amd64/fpu.c (revision b7c60aadbbd5c846a250c05791fe7406d6d78bf4)
1 /*-
2  * Copyright (c) 1990 William Jolitz.
3  * Copyright (c) 1991 The Regents of the University of California.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 4. Neither the name of the University nor the names of its contributors
15  *    may be used to endorse or promote products derived from this software
16  *    without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  *	from: @(#)npx.c	7.2 (Berkeley) 5/12/91
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/bus.h>
39 #include <sys/kernel.h>
40 #include <sys/lock.h>
41 #include <sys/malloc.h>
42 #include <sys/module.h>
43 #include <sys/mutex.h>
44 #include <sys/mutex.h>
45 #include <sys/proc.h>
46 #include <sys/sysctl.h>
47 #include <machine/bus.h>
48 #include <sys/rman.h>
49 #include <sys/signalvar.h>
50 
51 #include <machine/cputypes.h>
52 #include <machine/frame.h>
53 #include <machine/intr_machdep.h>
54 #include <machine/md_var.h>
55 #include <machine/pcb.h>
56 #include <machine/psl.h>
57 #include <machine/resource.h>
58 #include <machine/specialreg.h>
59 #include <machine/segments.h>
60 #include <machine/ucontext.h>
61 
62 /*
63  * Floating point support.
64  */
65 
66 #if defined(__GNUCLIKE_ASM) && !defined(lint)
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	start_emulating()	__asm __volatile( \
77 				    "smsw %%ax; orb %0,%%al; lmsw %%ax" \
78 				    : : "n" (CR0_TS) : "ax")
79 #define	stop_emulating()	__asm __volatile("clts")
80 
81 static __inline void
82 xrstor(char *addr, uint64_t mask)
83 {
84 	uint32_t low, hi;
85 
86 	low = mask;
87 	hi = mask >> 32;
88 	/* xrstor (%rdi) */
89 	__asm __volatile(".byte	0x0f,0xae,0x2f" : :
90 	    "a" (low), "d" (hi), "D" (addr));
91 }
92 
93 static __inline void
94 xsave(char *addr, uint64_t mask)
95 {
96 	uint32_t low, hi;
97 
98 	low = mask;
99 	hi = mask >> 32;
100 	/* xsave (%rdi) */
101 	__asm __volatile(".byte	0x0f,0xae,0x27" : :
102 	    "a" (low), "d" (hi), "D" (addr) : "memory");
103 }
104 
105 static __inline void
106 xsetbv(uint32_t reg, uint64_t val)
107 {
108 	uint32_t low, hi;
109 
110 	low = val;
111 	hi = val >> 32;
112 	__asm __volatile(".byte 0x0f,0x01,0xd1" : :
113 	    "c" (reg), "a" (low), "d" (hi));
114 }
115 
116 #else	/* !(__GNUCLIKE_ASM && !lint) */
117 
118 void	fldcw(u_short cw);
119 void	fnclex(void);
120 void	fninit(void);
121 void	fnstcw(caddr_t addr);
122 void	fnstsw(caddr_t addr);
123 void	fxsave(caddr_t addr);
124 void	fxrstor(caddr_t addr);
125 void	ldmxcsr(u_int csr);
126 void	start_emulating(void);
127 void	stop_emulating(void);
128 void	xrstor(char *addr, uint64_t mask);
129 void	xsave(char *addr, uint64_t mask);
130 void	xsetbv(uint32_t reg, uint64_t val);
131 
132 #endif	/* __GNUCLIKE_ASM && !lint */
133 
134 #define GET_FPU_CW(thread) ((thread)->td_pcb->pcb_save->sv_env.en_cw)
135 #define GET_FPU_SW(thread) ((thread)->td_pcb->pcb_save->sv_env.en_sw)
136 
137 CTASSERT(sizeof(struct savefpu) == 512);
138 CTASSERT(sizeof(struct xstate_hdr) == 64);
139 CTASSERT(sizeof(struct savefpu_ymm) == 832);
140 
141 /*
142  * This requirement is to make it easier for asm code to calculate
143  * offset of the fpu save area from the pcb address. FPU save area
144  * must by 64-bytes aligned.
145  */
146 CTASSERT(sizeof(struct pcb) % XSAVE_AREA_ALIGN == 0);
147 
148 static	void	fpu_clean_state(void);
149 
150 SYSCTL_INT(_hw, HW_FLOATINGPT, floatingpoint, CTLFLAG_RD,
151     NULL, 1, "Floating point instructions executed in hardware");
152 
153 int use_xsave;			/* non-static for cpu_switch.S */
154 uint64_t xsave_mask;		/* the same */
155 static	struct savefpu *fpu_initialstate;
156 
157 void
158 fpusave(void *addr)
159 {
160 
161 	if (use_xsave)
162 		xsave((char *)addr, xsave_mask);
163 	else
164 		fxsave((char *)addr);
165 }
166 
167 static void
168 fpurestore(void *addr)
169 {
170 
171 	if (use_xsave)
172 		xrstor((char *)addr, xsave_mask);
173 	else
174 		fxrstor((char *)addr);
175 }
176 
177 /*
178  * Enable XSAVE if supported and allowed by user.
179  * Calculate the xsave_mask.
180  */
181 static void
182 fpuinit_bsp1(void)
183 {
184 	u_int cp[4];
185 	uint64_t xsave_mask_user;
186 
187 	if ((cpu_feature2 & CPUID2_XSAVE) != 0) {
188 		use_xsave = 1;
189 		TUNABLE_INT_FETCH("hw.use_xsave", &use_xsave);
190 	}
191 	if (!use_xsave)
192 		return;
193 
194 	cpuid_count(0xd, 0x0, cp);
195 	xsave_mask = XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE;
196 	if ((cp[0] & xsave_mask) != xsave_mask)
197 		panic("CPU0 does not support X87 or SSE: %x", cp[0]);
198 	xsave_mask = ((uint64_t)cp[3] << 32) | cp[0];
199 	xsave_mask_user = xsave_mask;
200 	TUNABLE_ULONG_FETCH("hw.xsave_mask", &xsave_mask_user);
201 	xsave_mask_user |= XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE;
202 	xsave_mask &= xsave_mask_user;
203 }
204 
205 /*
206  * Calculate the fpu save area size.
207  */
208 static void
209 fpuinit_bsp2(void)
210 {
211 	u_int cp[4];
212 
213 	if (use_xsave) {
214 		cpuid_count(0xd, 0x0, cp);
215 		cpu_max_ext_state_size = cp[1];
216 
217 		/*
218 		 * Reload the cpu_feature2, since we enabled OSXSAVE.
219 		 */
220 		do_cpuid(1, cp);
221 		cpu_feature2 = cp[2];
222 	} else
223 		cpu_max_ext_state_size = sizeof(struct savefpu);
224 }
225 
226 /*
227  * Initialize the floating point unit.
228  */
229 void
230 fpuinit(void)
231 {
232 	register_t saveintr;
233 	u_int mxcsr;
234 	u_short control;
235 
236 	if (IS_BSP())
237 		fpuinit_bsp1();
238 
239 	if (use_xsave) {
240 		load_cr4(rcr4() | CR4_XSAVE);
241 		xsetbv(XCR0, xsave_mask);
242 	}
243 
244 	/*
245 	 * XCR0 shall be set up before CPU can report the save area size.
246 	 */
247 	if (IS_BSP())
248 		fpuinit_bsp2();
249 
250 	/*
251 	 * It is too early for critical_enter() to work on AP.
252 	 */
253 	saveintr = intr_disable();
254 	stop_emulating();
255 	fninit();
256 	control = __INITIAL_FPUCW__;
257 	fldcw(control);
258 	mxcsr = __INITIAL_MXCSR__;
259 	ldmxcsr(mxcsr);
260 	start_emulating();
261 	intr_restore(saveintr);
262 }
263 
264 /*
265  * On the boot CPU we generate a clean state that is used to
266  * initialize the floating point unit when it is first used by a
267  * process.
268  */
269 static void
270 fpuinitstate(void *arg __unused)
271 {
272 	register_t saveintr;
273 
274 	fpu_initialstate = malloc(cpu_max_ext_state_size, M_DEVBUF,
275 	    M_WAITOK | M_ZERO);
276 	saveintr = intr_disable();
277 	stop_emulating();
278 
279 	fpusave(fpu_initialstate);
280 	if (fpu_initialstate->sv_env.en_mxcsr_mask)
281 		cpu_mxcsr_mask = fpu_initialstate->sv_env.en_mxcsr_mask;
282 	else
283 		cpu_mxcsr_mask = 0xFFBF;
284 
285 	/*
286 	 * The fninit instruction does not modify XMM registers.  The
287 	 * fpusave call dumped the garbage contained in the registers
288 	 * after reset to the initial state saved.  Clear XMM
289 	 * registers file image to make the startup program state and
290 	 * signal handler XMM register content predictable.
291 	 */
292 	bzero(&fpu_initialstate->sv_xmm[0], sizeof(struct xmmacc));
293 
294 	start_emulating();
295 	intr_restore(saveintr);
296 }
297 SYSINIT(fpuinitstate, SI_SUB_DRIVERS, SI_ORDER_ANY, fpuinitstate, NULL);
298 
299 /*
300  * Free coprocessor (if we have it).
301  */
302 void
303 fpuexit(struct thread *td)
304 {
305 
306 	critical_enter();
307 	if (curthread == PCPU_GET(fpcurthread)) {
308 		stop_emulating();
309 		fpusave(PCPU_GET(curpcb)->pcb_save);
310 		start_emulating();
311 		PCPU_SET(fpcurthread, 0);
312 	}
313 	critical_exit();
314 }
315 
316 int
317 fpuformat()
318 {
319 
320 	return (_MC_FPFMT_XMM);
321 }
322 
323 /*
324  * The following mechanism is used to ensure that the FPE_... value
325  * that is passed as a trapcode to the signal handler of the user
326  * process does not have more than one bit set.
327  *
328  * Multiple bits may be set if the user process modifies the control
329  * word while a status word bit is already set.  While this is a sign
330  * of bad coding, we have no choise than to narrow them down to one
331  * bit, since we must not send a trapcode that is not exactly one of
332  * the FPE_ macros.
333  *
334  * The mechanism has a static table with 127 entries.  Each combination
335  * of the 7 FPU status word exception bits directly translates to a
336  * position in this table, where a single FPE_... value is stored.
337  * This FPE_... value stored there is considered the "most important"
338  * of the exception bits and will be sent as the signal code.  The
339  * precedence of the bits is based upon Intel Document "Numerical
340  * Applications", Chapter "Special Computational Situations".
341  *
342  * The macro to choose one of these values does these steps: 1) Throw
343  * away status word bits that cannot be masked.  2) Throw away the bits
344  * currently masked in the control word, assuming the user isn't
345  * interested in them anymore.  3) Reinsert status word bit 7 (stack
346  * fault) if it is set, which cannot be masked but must be presered.
347  * 4) Use the remaining bits to point into the trapcode table.
348  *
349  * The 6 maskable bits in order of their preference, as stated in the
350  * above referenced Intel manual:
351  * 1  Invalid operation (FP_X_INV)
352  * 1a   Stack underflow
353  * 1b   Stack overflow
354  * 1c   Operand of unsupported format
355  * 1d   SNaN operand.
356  * 2  QNaN operand (not an exception, irrelavant here)
357  * 3  Any other invalid-operation not mentioned above or zero divide
358  *      (FP_X_INV, FP_X_DZ)
359  * 4  Denormal operand (FP_X_DNML)
360  * 5  Numeric over/underflow (FP_X_OFL, FP_X_UFL)
361  * 6  Inexact result (FP_X_IMP)
362  */
363 static char fpetable[128] = {
364 	0,
365 	FPE_FLTINV,	/*  1 - INV */
366 	FPE_FLTUND,	/*  2 - DNML */
367 	FPE_FLTINV,	/*  3 - INV | DNML */
368 	FPE_FLTDIV,	/*  4 - DZ */
369 	FPE_FLTINV,	/*  5 - INV | DZ */
370 	FPE_FLTDIV,	/*  6 - DNML | DZ */
371 	FPE_FLTINV,	/*  7 - INV | DNML | DZ */
372 	FPE_FLTOVF,	/*  8 - OFL */
373 	FPE_FLTINV,	/*  9 - INV | OFL */
374 	FPE_FLTUND,	/*  A - DNML | OFL */
375 	FPE_FLTINV,	/*  B - INV | DNML | OFL */
376 	FPE_FLTDIV,	/*  C - DZ | OFL */
377 	FPE_FLTINV,	/*  D - INV | DZ | OFL */
378 	FPE_FLTDIV,	/*  E - DNML | DZ | OFL */
379 	FPE_FLTINV,	/*  F - INV | DNML | DZ | OFL */
380 	FPE_FLTUND,	/* 10 - UFL */
381 	FPE_FLTINV,	/* 11 - INV | UFL */
382 	FPE_FLTUND,	/* 12 - DNML | UFL */
383 	FPE_FLTINV,	/* 13 - INV | DNML | UFL */
384 	FPE_FLTDIV,	/* 14 - DZ | UFL */
385 	FPE_FLTINV,	/* 15 - INV | DZ | UFL */
386 	FPE_FLTDIV,	/* 16 - DNML | DZ | UFL */
387 	FPE_FLTINV,	/* 17 - INV | DNML | DZ | UFL */
388 	FPE_FLTOVF,	/* 18 - OFL | UFL */
389 	FPE_FLTINV,	/* 19 - INV | OFL | UFL */
390 	FPE_FLTUND,	/* 1A - DNML | OFL | UFL */
391 	FPE_FLTINV,	/* 1B - INV | DNML | OFL | UFL */
392 	FPE_FLTDIV,	/* 1C - DZ | OFL | UFL */
393 	FPE_FLTINV,	/* 1D - INV | DZ | OFL | UFL */
394 	FPE_FLTDIV,	/* 1E - DNML | DZ | OFL | UFL */
395 	FPE_FLTINV,	/* 1F - INV | DNML | DZ | OFL | UFL */
396 	FPE_FLTRES,	/* 20 - IMP */
397 	FPE_FLTINV,	/* 21 - INV | IMP */
398 	FPE_FLTUND,	/* 22 - DNML | IMP */
399 	FPE_FLTINV,	/* 23 - INV | DNML | IMP */
400 	FPE_FLTDIV,	/* 24 - DZ | IMP */
401 	FPE_FLTINV,	/* 25 - INV | DZ | IMP */
402 	FPE_FLTDIV,	/* 26 - DNML | DZ | IMP */
403 	FPE_FLTINV,	/* 27 - INV | DNML | DZ | IMP */
404 	FPE_FLTOVF,	/* 28 - OFL | IMP */
405 	FPE_FLTINV,	/* 29 - INV | OFL | IMP */
406 	FPE_FLTUND,	/* 2A - DNML | OFL | IMP */
407 	FPE_FLTINV,	/* 2B - INV | DNML | OFL | IMP */
408 	FPE_FLTDIV,	/* 2C - DZ | OFL | IMP */
409 	FPE_FLTINV,	/* 2D - INV | DZ | OFL | IMP */
410 	FPE_FLTDIV,	/* 2E - DNML | DZ | OFL | IMP */
411 	FPE_FLTINV,	/* 2F - INV | DNML | DZ | OFL | IMP */
412 	FPE_FLTUND,	/* 30 - UFL | IMP */
413 	FPE_FLTINV,	/* 31 - INV | UFL | IMP */
414 	FPE_FLTUND,	/* 32 - DNML | UFL | IMP */
415 	FPE_FLTINV,	/* 33 - INV | DNML | UFL | IMP */
416 	FPE_FLTDIV,	/* 34 - DZ | UFL | IMP */
417 	FPE_FLTINV,	/* 35 - INV | DZ | UFL | IMP */
418 	FPE_FLTDIV,	/* 36 - DNML | DZ | UFL | IMP */
419 	FPE_FLTINV,	/* 37 - INV | DNML | DZ | UFL | IMP */
420 	FPE_FLTOVF,	/* 38 - OFL | UFL | IMP */
421 	FPE_FLTINV,	/* 39 - INV | OFL | UFL | IMP */
422 	FPE_FLTUND,	/* 3A - DNML | OFL | UFL | IMP */
423 	FPE_FLTINV,	/* 3B - INV | DNML | OFL | UFL | IMP */
424 	FPE_FLTDIV,	/* 3C - DZ | OFL | UFL | IMP */
425 	FPE_FLTINV,	/* 3D - INV | DZ | OFL | UFL | IMP */
426 	FPE_FLTDIV,	/* 3E - DNML | DZ | OFL | UFL | IMP */
427 	FPE_FLTINV,	/* 3F - INV | DNML | DZ | OFL | UFL | IMP */
428 	FPE_FLTSUB,	/* 40 - STK */
429 	FPE_FLTSUB,	/* 41 - INV | STK */
430 	FPE_FLTUND,	/* 42 - DNML | STK */
431 	FPE_FLTSUB,	/* 43 - INV | DNML | STK */
432 	FPE_FLTDIV,	/* 44 - DZ | STK */
433 	FPE_FLTSUB,	/* 45 - INV | DZ | STK */
434 	FPE_FLTDIV,	/* 46 - DNML | DZ | STK */
435 	FPE_FLTSUB,	/* 47 - INV | DNML | DZ | STK */
436 	FPE_FLTOVF,	/* 48 - OFL | STK */
437 	FPE_FLTSUB,	/* 49 - INV | OFL | STK */
438 	FPE_FLTUND,	/* 4A - DNML | OFL | STK */
439 	FPE_FLTSUB,	/* 4B - INV | DNML | OFL | STK */
440 	FPE_FLTDIV,	/* 4C - DZ | OFL | STK */
441 	FPE_FLTSUB,	/* 4D - INV | DZ | OFL | STK */
442 	FPE_FLTDIV,	/* 4E - DNML | DZ | OFL | STK */
443 	FPE_FLTSUB,	/* 4F - INV | DNML | DZ | OFL | STK */
444 	FPE_FLTUND,	/* 50 - UFL | STK */
445 	FPE_FLTSUB,	/* 51 - INV | UFL | STK */
446 	FPE_FLTUND,	/* 52 - DNML | UFL | STK */
447 	FPE_FLTSUB,	/* 53 - INV | DNML | UFL | STK */
448 	FPE_FLTDIV,	/* 54 - DZ | UFL | STK */
449 	FPE_FLTSUB,	/* 55 - INV | DZ | UFL | STK */
450 	FPE_FLTDIV,	/* 56 - DNML | DZ | UFL | STK */
451 	FPE_FLTSUB,	/* 57 - INV | DNML | DZ | UFL | STK */
452 	FPE_FLTOVF,	/* 58 - OFL | UFL | STK */
453 	FPE_FLTSUB,	/* 59 - INV | OFL | UFL | STK */
454 	FPE_FLTUND,	/* 5A - DNML | OFL | UFL | STK */
455 	FPE_FLTSUB,	/* 5B - INV | DNML | OFL | UFL | STK */
456 	FPE_FLTDIV,	/* 5C - DZ | OFL | UFL | STK */
457 	FPE_FLTSUB,	/* 5D - INV | DZ | OFL | UFL | STK */
458 	FPE_FLTDIV,	/* 5E - DNML | DZ | OFL | UFL | STK */
459 	FPE_FLTSUB,	/* 5F - INV | DNML | DZ | OFL | UFL | STK */
460 	FPE_FLTRES,	/* 60 - IMP | STK */
461 	FPE_FLTSUB,	/* 61 - INV | IMP | STK */
462 	FPE_FLTUND,	/* 62 - DNML | IMP | STK */
463 	FPE_FLTSUB,	/* 63 - INV | DNML | IMP | STK */
464 	FPE_FLTDIV,	/* 64 - DZ | IMP | STK */
465 	FPE_FLTSUB,	/* 65 - INV | DZ | IMP | STK */
466 	FPE_FLTDIV,	/* 66 - DNML | DZ | IMP | STK */
467 	FPE_FLTSUB,	/* 67 - INV | DNML | DZ | IMP | STK */
468 	FPE_FLTOVF,	/* 68 - OFL | IMP | STK */
469 	FPE_FLTSUB,	/* 69 - INV | OFL | IMP | STK */
470 	FPE_FLTUND,	/* 6A - DNML | OFL | IMP | STK */
471 	FPE_FLTSUB,	/* 6B - INV | DNML | OFL | IMP | STK */
472 	FPE_FLTDIV,	/* 6C - DZ | OFL | IMP | STK */
473 	FPE_FLTSUB,	/* 6D - INV | DZ | OFL | IMP | STK */
474 	FPE_FLTDIV,	/* 6E - DNML | DZ | OFL | IMP | STK */
475 	FPE_FLTSUB,	/* 6F - INV | DNML | DZ | OFL | IMP | STK */
476 	FPE_FLTUND,	/* 70 - UFL | IMP | STK */
477 	FPE_FLTSUB,	/* 71 - INV | UFL | IMP | STK */
478 	FPE_FLTUND,	/* 72 - DNML | UFL | IMP | STK */
479 	FPE_FLTSUB,	/* 73 - INV | DNML | UFL | IMP | STK */
480 	FPE_FLTDIV,	/* 74 - DZ | UFL | IMP | STK */
481 	FPE_FLTSUB,	/* 75 - INV | DZ | UFL | IMP | STK */
482 	FPE_FLTDIV,	/* 76 - DNML | DZ | UFL | IMP | STK */
483 	FPE_FLTSUB,	/* 77 - INV | DNML | DZ | UFL | IMP | STK */
484 	FPE_FLTOVF,	/* 78 - OFL | UFL | IMP | STK */
485 	FPE_FLTSUB,	/* 79 - INV | OFL | UFL | IMP | STK */
486 	FPE_FLTUND,	/* 7A - DNML | OFL | UFL | IMP | STK */
487 	FPE_FLTSUB,	/* 7B - INV | DNML | OFL | UFL | IMP | STK */
488 	FPE_FLTDIV,	/* 7C - DZ | OFL | UFL | IMP | STK */
489 	FPE_FLTSUB,	/* 7D - INV | DZ | OFL | UFL | IMP | STK */
490 	FPE_FLTDIV,	/* 7E - DNML | DZ | OFL | UFL | IMP | STK */
491 	FPE_FLTSUB,	/* 7F - INV | DNML | DZ | OFL | UFL | IMP | STK */
492 };
493 
494 /*
495  * Preserve the FP status word, clear FP exceptions, then generate a SIGFPE.
496  *
497  * Clearing exceptions is necessary mainly to avoid IRQ13 bugs.  We now
498  * depend on longjmp() restoring a usable state.  Restoring the state
499  * or examining it might fail if we didn't clear exceptions.
500  *
501  * The error code chosen will be one of the FPE_... macros. It will be
502  * sent as the second argument to old BSD-style signal handlers and as
503  * "siginfo_t->si_code" (second argument) to SA_SIGINFO signal handlers.
504  *
505  * XXX the FP state is not preserved across signal handlers.  So signal
506  * handlers cannot afford to do FP unless they preserve the state or
507  * longjmp() out.  Both preserving the state and longjmp()ing may be
508  * destroyed by IRQ13 bugs.  Clearing FP exceptions is not an acceptable
509  * solution for signals other than SIGFPE.
510  */
511 int
512 fputrap()
513 {
514 	u_short control, status;
515 
516 	critical_enter();
517 
518 	/*
519 	 * Interrupt handling (for another interrupt) may have pushed the
520 	 * state to memory.  Fetch the relevant parts of the state from
521 	 * wherever they are.
522 	 */
523 	if (PCPU_GET(fpcurthread) != curthread) {
524 		control = GET_FPU_CW(curthread);
525 		status = GET_FPU_SW(curthread);
526 	} else {
527 		fnstcw(&control);
528 		fnstsw(&status);
529 	}
530 
531 	if (PCPU_GET(fpcurthread) == curthread)
532 		fnclex();
533 	critical_exit();
534 	return (fpetable[status & ((~control & 0x3f) | 0x40)]);
535 }
536 
537 /*
538  * Implement device not available (DNA) exception
539  *
540  * It would be better to switch FP context here (if curthread != fpcurthread)
541  * and not necessarily for every context switch, but it is too hard to
542  * access foreign pcb's.
543  */
544 
545 static int err_count = 0;
546 
547 void
548 fpudna(void)
549 {
550 	struct pcb *pcb;
551 
552 	critical_enter();
553 	if (PCPU_GET(fpcurthread) == curthread) {
554 		printf("fpudna: fpcurthread == curthread %d times\n",
555 		    ++err_count);
556 		stop_emulating();
557 		critical_exit();
558 		return;
559 	}
560 	if (PCPU_GET(fpcurthread) != NULL) {
561 		printf("fpudna: fpcurthread = %p (%d), curthread = %p (%d)\n",
562 		       PCPU_GET(fpcurthread),
563 		       PCPU_GET(fpcurthread)->td_proc->p_pid,
564 		       curthread, curthread->td_proc->p_pid);
565 		panic("fpudna");
566 	}
567 	stop_emulating();
568 	/*
569 	 * Record new context early in case frstor causes a trap.
570 	 */
571 	PCPU_SET(fpcurthread, curthread);
572 	pcb = PCPU_GET(curpcb);
573 
574 	fpu_clean_state();
575 
576 	if ((pcb->pcb_flags & PCB_FPUINITDONE) == 0) {
577 		/*
578 		 * This is the first time this thread has used the FPU or
579 		 * the PCB doesn't contain a clean FPU state.  Explicitly
580 		 * load an initial state.
581 		 */
582 		fpurestore(fpu_initialstate);
583 		if (pcb->pcb_initial_fpucw != __INITIAL_FPUCW__)
584 			fldcw(pcb->pcb_initial_fpucw);
585 		if (PCB_USER_FPU(pcb))
586 			set_pcb_flags(pcb,
587 			    PCB_FPUINITDONE | PCB_USERFPUINITDONE);
588 		else
589 			set_pcb_flags(pcb, PCB_FPUINITDONE);
590 	} else
591 		fpurestore(pcb->pcb_save);
592 	critical_exit();
593 }
594 
595 void
596 fpudrop()
597 {
598 	struct thread *td;
599 
600 	td = PCPU_GET(fpcurthread);
601 	KASSERT(td == curthread, ("fpudrop: fpcurthread != curthread"));
602 	CRITICAL_ASSERT(td);
603 	PCPU_SET(fpcurthread, NULL);
604 	clear_pcb_flags(td->td_pcb, PCB_FPUINITDONE);
605 	start_emulating();
606 }
607 
608 /*
609  * Get the user state of the FPU into pcb->pcb_user_save without
610  * dropping ownership (if possible).  It returns the FPU ownership
611  * status.
612  */
613 int
614 fpugetregs(struct thread *td)
615 {
616 	struct pcb *pcb;
617 
618 	pcb = td->td_pcb;
619 	if ((pcb->pcb_flags & PCB_USERFPUINITDONE) == 0) {
620 		bcopy(fpu_initialstate, get_pcb_user_save_pcb(pcb),
621 		    cpu_max_ext_state_size);
622 		get_pcb_user_save_pcb(pcb)->sv_env.en_cw =
623 		    pcb->pcb_initial_fpucw;
624 		fpuuserinited(td);
625 		return (_MC_FPOWNED_PCB);
626 	}
627 	critical_enter();
628 	if (td == PCPU_GET(fpcurthread) && PCB_USER_FPU(pcb)) {
629 		fpusave(get_pcb_user_save_pcb(pcb));
630 		critical_exit();
631 		return (_MC_FPOWNED_FPU);
632 	} else {
633 		critical_exit();
634 		return (_MC_FPOWNED_PCB);
635 	}
636 }
637 
638 void
639 fpuuserinited(struct thread *td)
640 {
641 	struct pcb *pcb;
642 
643 	pcb = td->td_pcb;
644 	if (PCB_USER_FPU(pcb))
645 		set_pcb_flags(pcb,
646 		    PCB_FPUINITDONE | PCB_USERFPUINITDONE);
647 	else
648 		set_pcb_flags(pcb, PCB_FPUINITDONE);
649 }
650 
651 int
652 fpusetxstate(struct thread *td, char *xfpustate, size_t xfpustate_size)
653 {
654 	struct xstate_hdr *hdr, *ehdr;
655 	size_t len, max_len;
656 	uint64_t bv;
657 
658 	/* XXXKIB should we clear all extended state in xstate_bv instead ? */
659 	if (xfpustate == NULL)
660 		return (0);
661 	if (!use_xsave)
662 		return (EOPNOTSUPP);
663 
664 	len = xfpustate_size;
665 	if (len < sizeof(struct xstate_hdr))
666 		return (EINVAL);
667 	max_len = cpu_max_ext_state_size - sizeof(struct savefpu);
668 	if (len > max_len)
669 		return (EINVAL);
670 
671 	ehdr = (struct xstate_hdr *)xfpustate;
672 	bv = ehdr->xstate_bv;
673 
674 	/*
675 	 * Avoid #gp.
676 	 */
677 	if (bv & ~xsave_mask)
678 		return (EINVAL);
679 	if ((bv & (XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE)) !=
680 	    (XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE))
681 		return (EINVAL);
682 
683 	hdr = (struct xstate_hdr *)(get_pcb_user_save_td(td) + 1);
684 
685 	hdr->xstate_bv = bv;
686 	bcopy(xfpustate + sizeof(struct xstate_hdr),
687 	    (char *)(hdr + 1), len - sizeof(struct xstate_hdr));
688 
689 	return (0);
690 }
691 
692 /*
693  * Set the state of the FPU.
694  */
695 int
696 fpusetregs(struct thread *td, struct savefpu *addr, char *xfpustate,
697     size_t xfpustate_size)
698 {
699 	struct pcb *pcb;
700 	int error;
701 
702 	pcb = td->td_pcb;
703 	critical_enter();
704 	if (td == PCPU_GET(fpcurthread) && PCB_USER_FPU(pcb)) {
705 		error = fpusetxstate(td, xfpustate, xfpustate_size);
706 		if (error != 0) {
707 			critical_exit();
708 			return (error);
709 		}
710 		bcopy(addr, get_pcb_user_save_td(td), sizeof(*addr));
711 		fpurestore(get_pcb_user_save_td(td));
712 		critical_exit();
713 		set_pcb_flags(pcb, PCB_FPUINITDONE | PCB_USERFPUINITDONE);
714 	} else {
715 		critical_exit();
716 		error = fpusetxstate(td, xfpustate, xfpustate_size);
717 		if (error != 0)
718 			return (error);
719 		bcopy(addr, get_pcb_user_save_td(td), sizeof(*addr));
720 		fpuuserinited(td);
721 	}
722 	return (0);
723 }
724 
725 /*
726  * On AuthenticAMD processors, the fxrstor instruction does not restore
727  * the x87's stored last instruction pointer, last data pointer, and last
728  * opcode values, except in the rare case in which the exception summary
729  * (ES) bit in the x87 status word is set to 1.
730  *
731  * In order to avoid leaking this information across processes, we clean
732  * these values by performing a dummy load before executing fxrstor().
733  */
734 static void
735 fpu_clean_state(void)
736 {
737 	static float dummy_variable = 0.0;
738 	u_short status;
739 
740 	/*
741 	 * Clear the ES bit in the x87 status word if it is currently
742 	 * set, in order to avoid causing a fault in the upcoming load.
743 	 */
744 	fnstsw(&status);
745 	if (status & 0x80)
746 		fnclex();
747 
748 	/*
749 	 * Load the dummy variable into the x87 stack.  This mangles
750 	 * the x87 stack, but we don't care since we're about to call
751 	 * fxrstor() anyway.
752 	 */
753 	__asm __volatile("ffree %%st(7); flds %0" : : "m" (dummy_variable));
754 }
755 
756 /*
757  * This really sucks.  We want the acpi version only, but it requires
758  * the isa_if.h file in order to get the definitions.
759  */
760 #include "opt_isa.h"
761 #ifdef DEV_ISA
762 #include <isa/isavar.h>
763 /*
764  * This sucks up the legacy ISA support assignments from PNPBIOS/ACPI.
765  */
766 static struct isa_pnp_id fpupnp_ids[] = {
767 	{ 0x040cd041, "Legacy ISA coprocessor support" }, /* PNP0C04 */
768 	{ 0 }
769 };
770 
771 static int
772 fpupnp_probe(device_t dev)
773 {
774 	int result;
775 
776 	result = ISA_PNP_PROBE(device_get_parent(dev), dev, fpupnp_ids);
777 	if (result <= 0)
778 		device_quiet(dev);
779 	return (result);
780 }
781 
782 static int
783 fpupnp_attach(device_t dev)
784 {
785 
786 	return (0);
787 }
788 
789 static device_method_t fpupnp_methods[] = {
790 	/* Device interface */
791 	DEVMETHOD(device_probe,		fpupnp_probe),
792 	DEVMETHOD(device_attach,	fpupnp_attach),
793 	DEVMETHOD(device_detach,	bus_generic_detach),
794 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
795 	DEVMETHOD(device_suspend,	bus_generic_suspend),
796 	DEVMETHOD(device_resume,	bus_generic_resume),
797 
798 	{ 0, 0 }
799 };
800 
801 static driver_t fpupnp_driver = {
802 	"fpupnp",
803 	fpupnp_methods,
804 	1,			/* no softc */
805 };
806 
807 static devclass_t fpupnp_devclass;
808 
809 DRIVER_MODULE(fpupnp, acpi, fpupnp_driver, fpupnp_devclass, 0, 0);
810 #endif	/* DEV_ISA */
811 
812 static MALLOC_DEFINE(M_FPUKERN_CTX, "fpukern_ctx",
813     "Kernel contexts for FPU state");
814 
815 #define	FPU_KERN_CTX_FPUINITDONE 0x01
816 
817 struct fpu_kern_ctx {
818 	struct savefpu *prev;
819 	uint32_t flags;
820 	char hwstate1[];
821 };
822 
823 struct fpu_kern_ctx *
824 fpu_kern_alloc_ctx(u_int flags)
825 {
826 	struct fpu_kern_ctx *res;
827 	size_t sz;
828 
829 	sz = sizeof(struct fpu_kern_ctx) + XSAVE_AREA_ALIGN +
830 	    cpu_max_ext_state_size;
831 	res = malloc(sz, M_FPUKERN_CTX, ((flags & FPU_KERN_NOWAIT) ?
832 	    M_NOWAIT : M_WAITOK) | M_ZERO);
833 	return (res);
834 }
835 
836 void
837 fpu_kern_free_ctx(struct fpu_kern_ctx *ctx)
838 {
839 
840 	/* XXXKIB clear the memory ? */
841 	free(ctx, M_FPUKERN_CTX);
842 }
843 
844 static struct savefpu *
845 fpu_kern_ctx_savefpu(struct fpu_kern_ctx *ctx)
846 {
847 	vm_offset_t p;
848 
849 	p = (vm_offset_t)&ctx->hwstate1;
850 	p = roundup2(p, XSAVE_AREA_ALIGN);
851 	return ((struct savefpu *)p);
852 }
853 
854 int
855 fpu_kern_enter(struct thread *td, struct fpu_kern_ctx *ctx, u_int flags)
856 {
857 	struct pcb *pcb;
858 
859 	pcb = td->td_pcb;
860 	KASSERT(!PCB_USER_FPU(pcb) || pcb->pcb_save ==
861 	    get_pcb_user_save_pcb(pcb), ("mangled pcb_save"));
862 	ctx->flags = 0;
863 	if ((pcb->pcb_flags & PCB_FPUINITDONE) != 0)
864 		ctx->flags |= FPU_KERN_CTX_FPUINITDONE;
865 	fpuexit(td);
866 	ctx->prev = pcb->pcb_save;
867 	pcb->pcb_save = fpu_kern_ctx_savefpu(ctx);
868 	set_pcb_flags(pcb, PCB_KERNFPU);
869 	clear_pcb_flags(pcb, PCB_FPUINITDONE);
870 	return (0);
871 }
872 
873 int
874 fpu_kern_leave(struct thread *td, struct fpu_kern_ctx *ctx)
875 {
876 	struct pcb *pcb;
877 
878 	pcb = td->td_pcb;
879 	critical_enter();
880 	if (curthread == PCPU_GET(fpcurthread))
881 		fpudrop();
882 	critical_exit();
883 	pcb->pcb_save = ctx->prev;
884 	if (pcb->pcb_save == get_pcb_user_save_pcb(pcb)) {
885 		if ((pcb->pcb_flags & PCB_USERFPUINITDONE) != 0) {
886 			set_pcb_flags(pcb, PCB_FPUINITDONE);
887 			clear_pcb_flags(pcb, PCB_KERNFPU);
888 		} else
889 			clear_pcb_flags(pcb, PCB_FPUINITDONE | PCB_KERNFPU);
890 	} else {
891 		if ((ctx->flags & FPU_KERN_CTX_FPUINITDONE) != 0)
892 			set_pcb_flags(pcb, PCB_FPUINITDONE);
893 		else
894 			clear_pcb_flags(pcb, PCB_FPUINITDONE);
895 		KASSERT(!PCB_USER_FPU(pcb), ("unpaired fpu_kern_leave"));
896 	}
897 	return (0);
898 }
899 
900 int
901 fpu_kern_thread(u_int flags)
902 {
903 	struct pcb *pcb;
904 
905 	pcb = PCPU_GET(curpcb);
906 	KASSERT((curthread->td_pflags & TDP_KTHREAD) != 0,
907 	    ("Only kthread may use fpu_kern_thread"));
908 	KASSERT(pcb->pcb_save == get_pcb_user_save_pcb(pcb),
909 	    ("mangled pcb_save"));
910 	KASSERT(PCB_USER_FPU(pcb), ("recursive call"));
911 
912 	set_pcb_flags(pcb, PCB_KERNFPU);
913 	return (0);
914 }
915 
916 int
917 is_fpu_kern_thread(u_int flags)
918 {
919 
920 	if ((curthread->td_pflags & TDP_KTHREAD) == 0)
921 		return (0);
922 	return ((PCPU_GET(curpcb)->pcb_flags & PCB_KERNFPU) != 0);
923 }
924