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