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