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