xref: /freebsd/sys/amd64/amd64/fpu.c (revision 628f583ce90d3587595c2f4dd16d57eec3511af3)
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. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *	This product includes software developed by the University of
17  *	California, Berkeley and its contributors.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	from: @(#)npx.c	7.2 (Berkeley) 5/12/91
35  * $FreeBSD$
36  */
37 
38 #include "opt_cpu.h"
39 #include "opt_debug_npx.h"
40 #include "opt_isa.h"
41 #include "opt_math_emulate.h"
42 #include "opt_npx.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/bus.h>
47 #include <sys/kernel.h>
48 #include <sys/lock.h>
49 #include <sys/malloc.h>
50 #include <sys/module.h>
51 #include <sys/mutex.h>
52 #include <sys/mutex.h>
53 #include <sys/proc.h>
54 #include <sys/sysctl.h>
55 #include <machine/bus.h>
56 #include <sys/rman.h>
57 #ifdef NPX_DEBUG
58 #include <sys/syslog.h>
59 #endif
60 #include <sys/signalvar.h>
61 #include <sys/user.h>
62 
63 #ifndef SMP
64 #include <machine/asmacros.h>
65 #endif
66 #include <machine/cputypes.h>
67 #include <machine/frame.h>
68 #include <machine/md_var.h>
69 #include <machine/pcb.h>
70 #include <machine/psl.h>
71 #ifndef SMP
72 #include <machine/clock.h>
73 #endif
74 #include <machine/resource.h>
75 #include <machine/specialreg.h>
76 #include <machine/segments.h>
77 #include <machine/ucontext.h>
78 
79 #ifndef SMP
80 #include <i386/isa/icu.h>
81 #ifdef PC98
82 #include <pc98/pc98/pc98.h>
83 #else
84 #include <i386/isa/isa.h>
85 #endif
86 #endif
87 #include <i386/isa/intr_machdep.h>
88 #ifdef DEV_ISA
89 #include <isa/isavar.h>
90 #endif
91 
92 #if !defined(CPU_ENABLE_SSE) && defined(I686_CPU)
93 #define CPU_ENABLE_SSE
94 #endif
95 #if defined(CPU_DISABLE_SSE)
96 #undef CPU_ENABLE_SSE
97 #endif
98 
99 /*
100  * 387 and 287 Numeric Coprocessor Extension (NPX) Driver.
101  */
102 
103 /* Configuration flags. */
104 #define	NPX_DISABLE_I586_OPTIMIZED_BCOPY	(1 << 0)
105 #define	NPX_DISABLE_I586_OPTIMIZED_BZERO	(1 << 1)
106 #define	NPX_DISABLE_I586_OPTIMIZED_COPYIO	(1 << 2)
107 #define	NPX_PREFER_EMULATOR			(1 << 3)
108 
109 #if defined(__GNUC__) && !defined(lint)
110 
111 #define	fldcw(addr)		__asm("fldcw %0" : : "m" (*(addr)))
112 #define	fnclex()		__asm("fnclex")
113 #define	fninit()		__asm("fninit")
114 #define	fnsave(addr)		__asm __volatile("fnsave %0" : "=m" (*(addr)))
115 #define	fnstcw(addr)		__asm __volatile("fnstcw %0" : "=m" (*(addr)))
116 #define	fnstsw(addr)		__asm __volatile("fnstsw %0" : "=m" (*(addr)))
117 #define	fp_divide_by_0()	__asm("fldz; fld1; fdiv %st,%st(1); fnop")
118 #define	frstor(addr)		__asm("frstor %0" : : "m" (*(addr)))
119 #ifdef CPU_ENABLE_SSE
120 #define	fxrstor(addr)		__asm("fxrstor %0" : : "m" (*(addr)))
121 #define	fxsave(addr)		__asm __volatile("fxsave %0" : "=m" (*(addr)))
122 #endif
123 #define	start_emulating()	__asm("smsw %%ax; orb %0,%%al; lmsw %%ax" \
124 				      : : "n" (CR0_TS) : "ax")
125 #define	stop_emulating()	__asm("clts")
126 
127 #else	/* not __GNUC__ */
128 
129 void	fldcw(caddr_t addr);
130 void	fnclex(void);
131 void	fninit(void);
132 void	fnsave(caddr_t addr);
133 void	fnstcw(caddr_t addr);
134 void	fnstsw(caddr_t addr);
135 void	fp_divide_by_0(void);
136 void	frstor(caddr_t addr);
137 #ifdef CPU_ENABLE_SSE
138 void	fxsave(caddr_t addr);
139 void	fxrstor(caddr_t addr);
140 #endif
141 void	start_emulating(void);
142 void	stop_emulating(void);
143 
144 #endif	/* __GNUC__ */
145 
146 #ifdef CPU_ENABLE_SSE
147 #define GET_FPU_CW(thread) \
148 	(cpu_fxsr ? \
149 		(thread)->td_pcb->pcb_save.sv_xmm.sv_env.en_cw : \
150 		(thread)->td_pcb->pcb_save.sv_87.sv_env.en_cw)
151 #define GET_FPU_SW(thread) \
152 	(cpu_fxsr ? \
153 		(thread)->td_pcb->pcb_save.sv_xmm.sv_env.en_sw : \
154 		(thread)->td_pcb->pcb_save.sv_87.sv_env.en_sw)
155 #else /* CPU_ENABLE_SSE */
156 #define GET_FPU_CW(thread) \
157 	(thread->td_pcb->pcb_save.sv_87.sv_env.en_cw)
158 #define GET_FPU_SW(thread) \
159 	(thread->td_pcb->pcb_save.sv_87.sv_env.en_sw)
160 #endif /* CPU_ENABLE_SSE */
161 
162 typedef u_char bool_t;
163 
164 static	void	fpusave(union savefpu *);
165 static	void	fpurstor(union savefpu *);
166 static	int	npx_attach(device_t dev);
167 static	void	npx_identify(driver_t *driver, device_t parent);
168 #ifndef SMP
169 static	void	npx_intr(void *);
170 #endif
171 static	int	npx_probe(device_t dev);
172 #ifdef I586_CPU_XXX
173 static	long	timezero(const char *funcname,
174 		    void (*func)(void *buf, size_t len));
175 #endif /* I586_CPU */
176 
177 int	hw_float;		/* XXX currently just alias for npx_exists */
178 
179 SYSCTL_INT(_hw,HW_FLOATINGPT, floatingpoint,
180 	CTLFLAG_RD, &hw_float, 0,
181 	"Floatingpoint instructions executed in hardware");
182 
183 #ifndef SMP
184 static	volatile u_int		npx_intrs_while_probing;
185 static	volatile u_int		npx_traps_while_probing;
186 #endif
187 
188 static	union savefpu		npx_cleanstate;
189 static	bool_t			npx_cleanstate_ready;
190 static	bool_t			npx_ex16;
191 static	bool_t			npx_exists;
192 static	bool_t			npx_irq13;
193 
194 #ifndef SMP
195 alias_for_inthand_t probetrap;
196 __asm("								\n\
197 	.text							\n\
198 	.p2align 2,0x90						\n\
199 	.type	" __XSTRING(CNAME(probetrap)) ",@function	\n\
200 " __XSTRING(CNAME(probetrap)) ":				\n\
201 	ss							\n\
202 	incl	" __XSTRING(CNAME(npx_traps_while_probing)) "	\n\
203 	fnclex							\n\
204 	iret							\n\
205 ");
206 #endif /* SMP */
207 
208 /*
209  * Identify routine.  Create a connection point on our parent for probing.
210  */
211 static void
212 npx_identify(driver, parent)
213 	driver_t *driver;
214 	device_t parent;
215 {
216 	device_t child;
217 
218 	child = BUS_ADD_CHILD(parent, 0, "npx", 0);
219 	if (child == NULL)
220 		panic("npx_identify");
221 }
222 
223 #ifndef SMP
224 /*
225  * Do minimal handling of npx interrupts to convert them to traps.
226  */
227 static void
228 npx_intr(dummy)
229 	void *dummy;
230 {
231 	struct thread *td;
232 
233 #ifndef SMP
234 	npx_intrs_while_probing++;
235 #endif
236 
237 	/*
238 	 * The BUSY# latch must be cleared in all cases so that the next
239 	 * unmasked npx exception causes an interrupt.
240 	 */
241 #ifdef PC98
242 	outb(0xf8, 0);
243 #else
244 	outb(0xf0, 0);
245 #endif
246 
247 	/*
248 	 * fpcurthread is normally non-null here.  In that case, schedule an
249 	 * AST to finish the exception handling in the correct context
250 	 * (this interrupt may occur after the thread has entered the
251 	 * kernel via a syscall or an interrupt).  Otherwise, the npx
252 	 * state of the thread that caused this interrupt must have been
253 	 * pushed to the thread's pcb, and clearing of the busy latch
254 	 * above has finished the (essentially null) handling of this
255 	 * interrupt.  Control will eventually return to the instruction
256 	 * that caused it and it will repeat.  We will eventually (usually
257 	 * soon) win the race to handle the interrupt properly.
258 	 */
259 	td = PCPU_GET(fpcurthread);
260 	if (td != NULL) {
261 		td->td_pcb->pcb_flags |= PCB_NPXTRAP;
262 		mtx_lock_spin(&sched_lock);
263 		td->td_flags |= TDF_ASTPENDING;
264 		mtx_unlock_spin(&sched_lock);
265 	}
266 }
267 #endif /* !SMP */
268 
269 /*
270  * Probe routine.  Initialize cr0 to give correct behaviour for [f]wait
271  * whether the device exists or not (XXX should be elsewhere).  Set flags
272  * to tell npxattach() what to do.  Modify device struct if npx doesn't
273  * need to use interrupts.  Return 0 if device exists.
274  */
275 static int
276 npx_probe(dev)
277 	device_t dev;
278 {
279 #ifndef SMP
280 	struct gate_descriptor save_idt_npxtrap;
281 	struct resource *ioport_res, *irq_res;
282 	void *irq_cookie;
283 	int ioport_rid, irq_num, irq_rid;
284 	u_short control;
285 	u_short status;
286 
287 	save_idt_npxtrap = idt[16];
288 	setidt(16, probetrap, SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
289 	ioport_rid = 0;
290 	ioport_res = bus_alloc_resource(dev, SYS_RES_IOPORT, &ioport_rid,
291 	    IO_NPX, IO_NPX, IO_NPXSIZE, RF_ACTIVE);
292 	if (ioport_res == NULL)
293 		panic("npx: can't get ports");
294 #ifdef PC98
295 	if (resource_int_value("npx", 0, "irq", &irq_num) != 0)
296 		irq_num = 8;
297 #else
298 	if (resource_int_value("npx", 0, "irq", &irq_num) != 0)
299 		irq_num = 13;
300 #endif
301 	irq_rid = 0;
302 	irq_res = bus_alloc_resource(dev, SYS_RES_IRQ, &irq_rid, irq_num,
303 	    irq_num, 1, RF_ACTIVE);
304 	if (irq_res == NULL)
305 		panic("npx: can't get IRQ");
306 	if (bus_setup_intr(dev, irq_res, INTR_TYPE_MISC | INTR_FAST, npx_intr,
307 	    NULL, &irq_cookie) != 0)
308 		panic("npx: can't create intr");
309 #endif /* !SMP */
310 
311 	/*
312 	 * Partially reset the coprocessor, if any.  Some BIOS's don't reset
313 	 * it after a warm boot.
314 	 */
315 #ifdef PC98
316 	outb(0xf8,0);
317 #else
318 	outb(0xf1, 0);		/* full reset on some systems, NOP on others */
319 	outb(0xf0, 0);		/* clear BUSY# latch */
320 #endif
321 	/*
322 	 * Prepare to trap all ESC (i.e., NPX) instructions and all WAIT
323 	 * instructions.  We must set the CR0_MP bit and use the CR0_TS
324 	 * bit to control the trap, because setting the CR0_EM bit does
325 	 * not cause WAIT instructions to trap.  It's important to trap
326 	 * WAIT instructions - otherwise the "wait" variants of no-wait
327 	 * control instructions would degenerate to the "no-wait" variants
328 	 * after FP context switches but work correctly otherwise.  It's
329 	 * particularly important to trap WAITs when there is no NPX -
330 	 * otherwise the "wait" variants would always degenerate.
331 	 *
332 	 * Try setting CR0_NE to get correct error reporting on 486DX's.
333 	 * Setting it should fail or do nothing on lesser processors.
334 	 */
335 	load_cr0(rcr0() | CR0_MP | CR0_NE);
336 	/*
337 	 * But don't trap while we're probing.
338 	 */
339 	stop_emulating();
340 	/*
341 	 * Finish resetting the coprocessor, if any.  If there is an error
342 	 * pending, then we may get a bogus IRQ13, but npx_intr() will handle
343 	 * it OK.  Bogus halts have never been observed, but we enabled
344 	 * IRQ13 and cleared the BUSY# latch early to handle them anyway.
345 	 */
346 	fninit();
347 
348 	device_set_desc(dev, "math processor");
349 
350 #ifdef SMP
351 
352 	/*
353 	 * Exception 16 MUST work for SMP.
354 	 */
355 	npx_ex16 = hw_float = npx_exists = 1;
356 	return (0);
357 
358 #else /* !SMP */
359 
360 	/*
361 	 * Don't use fwait here because it might hang.
362 	 * Don't use fnop here because it usually hangs if there is no FPU.
363 	 */
364 	DELAY(1000);		/* wait for any IRQ13 */
365 #ifdef DIAGNOSTIC
366 	if (npx_intrs_while_probing != 0)
367 		printf("fninit caused %u bogus npx interrupt(s)\n",
368 		       npx_intrs_while_probing);
369 	if (npx_traps_while_probing != 0)
370 		printf("fninit caused %u bogus npx trap(s)\n",
371 		       npx_traps_while_probing);
372 #endif
373 	/*
374 	 * Check for a status of mostly zero.
375 	 */
376 	status = 0x5a5a;
377 	fnstsw(&status);
378 	if ((status & 0xb8ff) == 0) {
379 		/*
380 		 * Good, now check for a proper control word.
381 		 */
382 		control = 0x5a5a;
383 		fnstcw(&control);
384 		if ((control & 0x1f3f) == 0x033f) {
385 			hw_float = npx_exists = 1;
386 			/*
387 			 * We have an npx, now divide by 0 to see if exception
388 			 * 16 works.
389 			 */
390 			control &= ~(1 << 2);	/* enable divide by 0 trap */
391 			fldcw(&control);
392 #ifdef FPU_ERROR_BROKEN
393 			/*
394 			 * FPU error signal doesn't work on some CPU
395 			 * accelerator board.
396 			 */
397 			npx_ex16 = 1;
398 			return (0);
399 #endif
400 			npx_traps_while_probing = npx_intrs_while_probing = 0;
401 			fp_divide_by_0();
402 			if (npx_traps_while_probing != 0) {
403 				/*
404 				 * Good, exception 16 works.
405 				 */
406 				npx_ex16 = 1;
407 				goto no_irq13;
408 			}
409 			if (npx_intrs_while_probing != 0) {
410 				/*
411 				 * Bad, we are stuck with IRQ13.
412 				 */
413 				npx_irq13 = 1;
414 				idt[16] = save_idt_npxtrap;
415 				return (0);
416 			}
417 			/*
418 			 * Worse, even IRQ13 is broken.  Use emulator.
419 			 */
420 		}
421 	}
422 	/*
423 	 * Probe failed, but we want to get to npxattach to initialize the
424 	 * emulator and say that it has been installed.  XXX handle devices
425 	 * that aren't really devices better.
426 	 */
427 	/* FALLTHROUGH */
428 no_irq13:
429 	idt[16] = save_idt_npxtrap;
430 	bus_teardown_intr(dev, irq_res, irq_cookie);
431 
432 	/*
433 	 * XXX hack around brokenness of bus_teardown_intr().  If we left the
434 	 * irq active then we would get it instead of exception 16.
435 	 */
436 	{
437 		register_t crit;
438 
439 		crit = intr_disable();
440 		mtx_lock_spin(&icu_lock);
441 		INTRDIS(1 << irq_num);
442 		mtx_unlock_spin(&icu_lock);
443 		intr_restore(crit);
444 	}
445 
446 	bus_release_resource(dev, SYS_RES_IRQ, irq_rid, irq_res);
447 	bus_release_resource(dev, SYS_RES_IOPORT, ioport_rid, ioport_res);
448 	return (0);
449 
450 #endif /* SMP */
451 }
452 
453 /*
454  * Attach routine - announce which it is, and wire into system
455  */
456 static int
457 npx_attach(dev)
458 	device_t dev;
459 {
460 	int flags;
461 	register_t s;
462 
463 	if (resource_int_value("npx", 0, "flags", &flags) != 0)
464 		flags = 0;
465 
466 	if (flags)
467 		device_printf(dev, "flags 0x%x ", flags);
468 	if (npx_irq13) {
469 		device_printf(dev, "using IRQ 13 interface\n");
470 	} else {
471 #if defined(MATH_EMULATE) || defined(GPL_MATH_EMULATE)
472 		if (npx_ex16) {
473 			if (!(flags & NPX_PREFER_EMULATOR))
474 				device_printf(dev, "INT 16 interface\n");
475 			else {
476 				device_printf(dev, "FPU exists, but flags request "
477 				    "emulator\n");
478 				hw_float = npx_exists = 0;
479 			}
480 		} else if (npx_exists) {
481 			device_printf(dev, "error reporting broken; using 387 emulator\n");
482 			hw_float = npx_exists = 0;
483 		} else
484 			device_printf(dev, "387 emulator\n");
485 #else
486 		if (npx_ex16) {
487 			device_printf(dev, "INT 16 interface\n");
488 			if (flags & NPX_PREFER_EMULATOR) {
489 				device_printf(dev, "emulator requested, but none compiled "
490 				    "into kernel, using FPU\n");
491 			}
492 		} else
493 			device_printf(dev, "no 387 emulator in kernel and no FPU!\n");
494 #endif
495 	}
496 	npxinit(__INITIAL_NPXCW__);
497 
498 	if (npx_cleanstate_ready == 0) {
499 		s = intr_disable();
500 		stop_emulating();
501 		fpusave(&npx_cleanstate);
502 		start_emulating();
503 		npx_cleanstate_ready = 1;
504 		intr_restore(s);
505 	}
506 #ifdef I586_CPU_XXX
507 	if (cpu_class == CPUCLASS_586 && npx_ex16 && npx_exists &&
508 	    timezero("i586_bzero()", i586_bzero) <
509 	    timezero("bzero()", bzero) * 4 / 5) {
510 		if (!(flags & NPX_DISABLE_I586_OPTIMIZED_BCOPY))
511 			bcopy_vector = i586_bcopy;
512 		if (!(flags & NPX_DISABLE_I586_OPTIMIZED_BZERO))
513 			bzero_vector = i586_bzero;
514 		if (!(flags & NPX_DISABLE_I586_OPTIMIZED_COPYIO)) {
515 			copyin_vector = i586_copyin;
516 			copyout_vector = i586_copyout;
517 		}
518 	}
519 #endif
520 
521 	return (0);		/* XXX unused */
522 }
523 
524 /*
525  * Initialize floating point unit.
526  */
527 void
528 npxinit(control)
529 	u_short control;
530 {
531 	static union savefpu dummy;
532 	register_t savecrit;
533 
534 	if (!npx_exists)
535 		return;
536 	/*
537 	 * fninit has the same h/w bugs as fnsave.  Use the detoxified
538 	 * fnsave to throw away any junk in the fpu.  npxsave() initializes
539 	 * the fpu and sets fpcurthread = NULL as important side effects.
540 	 */
541 	savecrit = intr_disable();
542 	npxsave(&dummy);
543 	stop_emulating();
544 #ifdef CPU_ENABLE_SSE
545 	/* XXX npxsave() doesn't actually initialize the fpu in the SSE case. */
546 	if (cpu_fxsr)
547 		fninit();
548 #endif
549 	fldcw(&control);
550 	start_emulating();
551 	intr_restore(savecrit);
552 }
553 
554 /*
555  * Free coprocessor (if we have it).
556  */
557 void
558 npxexit(td)
559 	struct thread *td;
560 {
561 	register_t savecrit;
562 
563 	savecrit = intr_disable();
564 	if (curthread == PCPU_GET(fpcurthread))
565 		npxsave(&PCPU_GET(curpcb)->pcb_save);
566 	intr_restore(savecrit);
567 #ifdef NPX_DEBUG
568 	if (npx_exists) {
569 		u_int	masked_exceptions;
570 
571 		masked_exceptions = GET_FPU_CW(td) & GET_FPU_SW(td) & 0x7f;
572 		/*
573 		 * Log exceptions that would have trapped with the old
574 		 * control word (overflow, divide by 0, and invalid operand).
575 		 */
576 		if (masked_exceptions & 0x0d)
577 			log(LOG_ERR,
578 	"pid %d (%s) exited with masked floating point exceptions 0x%02x\n",
579 			    td->td_proc->p_pid, td->td_proc->p_comm,
580 			    masked_exceptions);
581 	}
582 #endif
583 }
584 
585 int
586 npxformat()
587 {
588 
589 	if (!npx_exists)
590 		return (_MC_FPFMT_NODEV);
591 #ifdef	CPU_ENABLE_SSE
592 	if (cpu_fxsr)
593 		return (_MC_FPFMT_XMM);
594 #endif
595 	return (_MC_FPFMT_387);
596 }
597 
598 /*
599  * The following mechanism is used to ensure that the FPE_... value
600  * that is passed as a trapcode to the signal handler of the user
601  * process does not have more than one bit set.
602  *
603  * Multiple bits may be set if the user process modifies the control
604  * word while a status word bit is already set.  While this is a sign
605  * of bad coding, we have no choise than to narrow them down to one
606  * bit, since we must not send a trapcode that is not exactly one of
607  * the FPE_ macros.
608  *
609  * The mechanism has a static table with 127 entries.  Each combination
610  * of the 7 FPU status word exception bits directly translates to a
611  * position in this table, where a single FPE_... value is stored.
612  * This FPE_... value stored there is considered the "most important"
613  * of the exception bits and will be sent as the signal code.  The
614  * precedence of the bits is based upon Intel Document "Numerical
615  * Applications", Chapter "Special Computational Situations".
616  *
617  * The macro to choose one of these values does these steps: 1) Throw
618  * away status word bits that cannot be masked.  2) Throw away the bits
619  * currently masked in the control word, assuming the user isn't
620  * interested in them anymore.  3) Reinsert status word bit 7 (stack
621  * fault) if it is set, which cannot be masked but must be presered.
622  * 4) Use the remaining bits to point into the trapcode table.
623  *
624  * The 6 maskable bits in order of their preference, as stated in the
625  * above referenced Intel manual:
626  * 1  Invalid operation (FP_X_INV)
627  * 1a   Stack underflow
628  * 1b   Stack overflow
629  * 1c   Operand of unsupported format
630  * 1d   SNaN operand.
631  * 2  QNaN operand (not an exception, irrelavant here)
632  * 3  Any other invalid-operation not mentioned above or zero divide
633  *      (FP_X_INV, FP_X_DZ)
634  * 4  Denormal operand (FP_X_DNML)
635  * 5  Numeric over/underflow (FP_X_OFL, FP_X_UFL)
636  * 6  Inexact result (FP_X_IMP)
637  */
638 static char fpetable[128] = {
639 	0,
640 	FPE_FLTINV,	/*  1 - INV */
641 	FPE_FLTUND,	/*  2 - DNML */
642 	FPE_FLTINV,	/*  3 - INV | DNML */
643 	FPE_FLTDIV,	/*  4 - DZ */
644 	FPE_FLTINV,	/*  5 - INV | DZ */
645 	FPE_FLTDIV,	/*  6 - DNML | DZ */
646 	FPE_FLTINV,	/*  7 - INV | DNML | DZ */
647 	FPE_FLTOVF,	/*  8 - OFL */
648 	FPE_FLTINV,	/*  9 - INV | OFL */
649 	FPE_FLTUND,	/*  A - DNML | OFL */
650 	FPE_FLTINV,	/*  B - INV | DNML | OFL */
651 	FPE_FLTDIV,	/*  C - DZ | OFL */
652 	FPE_FLTINV,	/*  D - INV | DZ | OFL */
653 	FPE_FLTDIV,	/*  E - DNML | DZ | OFL */
654 	FPE_FLTINV,	/*  F - INV | DNML | DZ | OFL */
655 	FPE_FLTUND,	/* 10 - UFL */
656 	FPE_FLTINV,	/* 11 - INV | UFL */
657 	FPE_FLTUND,	/* 12 - DNML | UFL */
658 	FPE_FLTINV,	/* 13 - INV | DNML | UFL */
659 	FPE_FLTDIV,	/* 14 - DZ | UFL */
660 	FPE_FLTINV,	/* 15 - INV | DZ | UFL */
661 	FPE_FLTDIV,	/* 16 - DNML | DZ | UFL */
662 	FPE_FLTINV,	/* 17 - INV | DNML | DZ | UFL */
663 	FPE_FLTOVF,	/* 18 - OFL | UFL */
664 	FPE_FLTINV,	/* 19 - INV | OFL | UFL */
665 	FPE_FLTUND,	/* 1A - DNML | OFL | UFL */
666 	FPE_FLTINV,	/* 1B - INV | DNML | OFL | UFL */
667 	FPE_FLTDIV,	/* 1C - DZ | OFL | UFL */
668 	FPE_FLTINV,	/* 1D - INV | DZ | OFL | UFL */
669 	FPE_FLTDIV,	/* 1E - DNML | DZ | OFL | UFL */
670 	FPE_FLTINV,	/* 1F - INV | DNML | DZ | OFL | UFL */
671 	FPE_FLTRES,	/* 20 - IMP */
672 	FPE_FLTINV,	/* 21 - INV | IMP */
673 	FPE_FLTUND,	/* 22 - DNML | IMP */
674 	FPE_FLTINV,	/* 23 - INV | DNML | IMP */
675 	FPE_FLTDIV,	/* 24 - DZ | IMP */
676 	FPE_FLTINV,	/* 25 - INV | DZ | IMP */
677 	FPE_FLTDIV,	/* 26 - DNML | DZ | IMP */
678 	FPE_FLTINV,	/* 27 - INV | DNML | DZ | IMP */
679 	FPE_FLTOVF,	/* 28 - OFL | IMP */
680 	FPE_FLTINV,	/* 29 - INV | OFL | IMP */
681 	FPE_FLTUND,	/* 2A - DNML | OFL | IMP */
682 	FPE_FLTINV,	/* 2B - INV | DNML | OFL | IMP */
683 	FPE_FLTDIV,	/* 2C - DZ | OFL | IMP */
684 	FPE_FLTINV,	/* 2D - INV | DZ | OFL | IMP */
685 	FPE_FLTDIV,	/* 2E - DNML | DZ | OFL | IMP */
686 	FPE_FLTINV,	/* 2F - INV | DNML | DZ | OFL | IMP */
687 	FPE_FLTUND,	/* 30 - UFL | IMP */
688 	FPE_FLTINV,	/* 31 - INV | UFL | IMP */
689 	FPE_FLTUND,	/* 32 - DNML | UFL | IMP */
690 	FPE_FLTINV,	/* 33 - INV | DNML | UFL | IMP */
691 	FPE_FLTDIV,	/* 34 - DZ | UFL | IMP */
692 	FPE_FLTINV,	/* 35 - INV | DZ | UFL | IMP */
693 	FPE_FLTDIV,	/* 36 - DNML | DZ | UFL | IMP */
694 	FPE_FLTINV,	/* 37 - INV | DNML | DZ | UFL | IMP */
695 	FPE_FLTOVF,	/* 38 - OFL | UFL | IMP */
696 	FPE_FLTINV,	/* 39 - INV | OFL | UFL | IMP */
697 	FPE_FLTUND,	/* 3A - DNML | OFL | UFL | IMP */
698 	FPE_FLTINV,	/* 3B - INV | DNML | OFL | UFL | IMP */
699 	FPE_FLTDIV,	/* 3C - DZ | OFL | UFL | IMP */
700 	FPE_FLTINV,	/* 3D - INV | DZ | OFL | UFL | IMP */
701 	FPE_FLTDIV,	/* 3E - DNML | DZ | OFL | UFL | IMP */
702 	FPE_FLTINV,	/* 3F - INV | DNML | DZ | OFL | UFL | IMP */
703 	FPE_FLTSUB,	/* 40 - STK */
704 	FPE_FLTSUB,	/* 41 - INV | STK */
705 	FPE_FLTUND,	/* 42 - DNML | STK */
706 	FPE_FLTSUB,	/* 43 - INV | DNML | STK */
707 	FPE_FLTDIV,	/* 44 - DZ | STK */
708 	FPE_FLTSUB,	/* 45 - INV | DZ | STK */
709 	FPE_FLTDIV,	/* 46 - DNML | DZ | STK */
710 	FPE_FLTSUB,	/* 47 - INV | DNML | DZ | STK */
711 	FPE_FLTOVF,	/* 48 - OFL | STK */
712 	FPE_FLTSUB,	/* 49 - INV | OFL | STK */
713 	FPE_FLTUND,	/* 4A - DNML | OFL | STK */
714 	FPE_FLTSUB,	/* 4B - INV | DNML | OFL | STK */
715 	FPE_FLTDIV,	/* 4C - DZ | OFL | STK */
716 	FPE_FLTSUB,	/* 4D - INV | DZ | OFL | STK */
717 	FPE_FLTDIV,	/* 4E - DNML | DZ | OFL | STK */
718 	FPE_FLTSUB,	/* 4F - INV | DNML | DZ | OFL | STK */
719 	FPE_FLTUND,	/* 50 - UFL | STK */
720 	FPE_FLTSUB,	/* 51 - INV | UFL | STK */
721 	FPE_FLTUND,	/* 52 - DNML | UFL | STK */
722 	FPE_FLTSUB,	/* 53 - INV | DNML | UFL | STK */
723 	FPE_FLTDIV,	/* 54 - DZ | UFL | STK */
724 	FPE_FLTSUB,	/* 55 - INV | DZ | UFL | STK */
725 	FPE_FLTDIV,	/* 56 - DNML | DZ | UFL | STK */
726 	FPE_FLTSUB,	/* 57 - INV | DNML | DZ | UFL | STK */
727 	FPE_FLTOVF,	/* 58 - OFL | UFL | STK */
728 	FPE_FLTSUB,	/* 59 - INV | OFL | UFL | STK */
729 	FPE_FLTUND,	/* 5A - DNML | OFL | UFL | STK */
730 	FPE_FLTSUB,	/* 5B - INV | DNML | OFL | UFL | STK */
731 	FPE_FLTDIV,	/* 5C - DZ | OFL | UFL | STK */
732 	FPE_FLTSUB,	/* 5D - INV | DZ | OFL | UFL | STK */
733 	FPE_FLTDIV,	/* 5E - DNML | DZ | OFL | UFL | STK */
734 	FPE_FLTSUB,	/* 5F - INV | DNML | DZ | OFL | UFL | STK */
735 	FPE_FLTRES,	/* 60 - IMP | STK */
736 	FPE_FLTSUB,	/* 61 - INV | IMP | STK */
737 	FPE_FLTUND,	/* 62 - DNML | IMP | STK */
738 	FPE_FLTSUB,	/* 63 - INV | DNML | IMP | STK */
739 	FPE_FLTDIV,	/* 64 - DZ | IMP | STK */
740 	FPE_FLTSUB,	/* 65 - INV | DZ | IMP | STK */
741 	FPE_FLTDIV,	/* 66 - DNML | DZ | IMP | STK */
742 	FPE_FLTSUB,	/* 67 - INV | DNML | DZ | IMP | STK */
743 	FPE_FLTOVF,	/* 68 - OFL | IMP | STK */
744 	FPE_FLTSUB,	/* 69 - INV | OFL | IMP | STK */
745 	FPE_FLTUND,	/* 6A - DNML | OFL | IMP | STK */
746 	FPE_FLTSUB,	/* 6B - INV | DNML | OFL | IMP | STK */
747 	FPE_FLTDIV,	/* 6C - DZ | OFL | IMP | STK */
748 	FPE_FLTSUB,	/* 6D - INV | DZ | OFL | IMP | STK */
749 	FPE_FLTDIV,	/* 6E - DNML | DZ | OFL | IMP | STK */
750 	FPE_FLTSUB,	/* 6F - INV | DNML | DZ | OFL | IMP | STK */
751 	FPE_FLTUND,	/* 70 - UFL | IMP | STK */
752 	FPE_FLTSUB,	/* 71 - INV | UFL | IMP | STK */
753 	FPE_FLTUND,	/* 72 - DNML | UFL | IMP | STK */
754 	FPE_FLTSUB,	/* 73 - INV | DNML | UFL | IMP | STK */
755 	FPE_FLTDIV,	/* 74 - DZ | UFL | IMP | STK */
756 	FPE_FLTSUB,	/* 75 - INV | DZ | UFL | IMP | STK */
757 	FPE_FLTDIV,	/* 76 - DNML | DZ | UFL | IMP | STK */
758 	FPE_FLTSUB,	/* 77 - INV | DNML | DZ | UFL | IMP | STK */
759 	FPE_FLTOVF,	/* 78 - OFL | UFL | IMP | STK */
760 	FPE_FLTSUB,	/* 79 - INV | OFL | UFL | IMP | STK */
761 	FPE_FLTUND,	/* 7A - DNML | OFL | UFL | IMP | STK */
762 	FPE_FLTSUB,	/* 7B - INV | DNML | OFL | UFL | IMP | STK */
763 	FPE_FLTDIV,	/* 7C - DZ | OFL | UFL | IMP | STK */
764 	FPE_FLTSUB,	/* 7D - INV | DZ | OFL | UFL | IMP | STK */
765 	FPE_FLTDIV,	/* 7E - DNML | DZ | OFL | UFL | IMP | STK */
766 	FPE_FLTSUB,	/* 7F - INV | DNML | DZ | OFL | UFL | IMP | STK */
767 };
768 
769 /*
770  * Preserve the FP status word, clear FP exceptions, then generate a SIGFPE.
771  *
772  * Clearing exceptions is necessary mainly to avoid IRQ13 bugs.  We now
773  * depend on longjmp() restoring a usable state.  Restoring the state
774  * or examining it might fail if we didn't clear exceptions.
775  *
776  * The error code chosen will be one of the FPE_... macros. It will be
777  * sent as the second argument to old BSD-style signal handlers and as
778  * "siginfo_t->si_code" (second argument) to SA_SIGINFO signal handlers.
779  *
780  * XXX the FP state is not preserved across signal handlers.  So signal
781  * handlers cannot afford to do FP unless they preserve the state or
782  * longjmp() out.  Both preserving the state and longjmp()ing may be
783  * destroyed by IRQ13 bugs.  Clearing FP exceptions is not an acceptable
784  * solution for signals other than SIGFPE.
785  */
786 int
787 npxtrap()
788 {
789 	register_t savecrit;
790 	u_short control, status;
791 
792 	if (!npx_exists) {
793 		printf("npxtrap: fpcurthread = %p, curthread = %p, npx_exists = %d\n",
794 		       PCPU_GET(fpcurthread), curthread, npx_exists);
795 		panic("npxtrap from nowhere");
796 	}
797 	savecrit = intr_disable();
798 
799 	/*
800 	 * Interrupt handling (for another interrupt) may have pushed the
801 	 * state to memory.  Fetch the relevant parts of the state from
802 	 * wherever they are.
803 	 */
804 	if (PCPU_GET(fpcurthread) != curthread) {
805 		control = GET_FPU_CW(curthread);
806 		status = GET_FPU_SW(curthread);
807 	} else {
808 		fnstcw(&control);
809 		fnstsw(&status);
810 	}
811 
812 	if (PCPU_GET(fpcurthread) == curthread)
813 		fnclex();
814 	intr_restore(savecrit);
815 	return (fpetable[status & ((~control & 0x3f) | 0x40)]);
816 }
817 
818 /*
819  * Implement device not available (DNA) exception
820  *
821  * It would be better to switch FP context here (if curthread != fpcurthread)
822  * and not necessarily for every context switch, but it is too hard to
823  * access foreign pcb's.
824  */
825 
826 static int err_count = 0;
827 
828 int
829 npxdna()
830 {
831 	struct pcb *pcb;
832 	register_t s;
833 	u_short control;
834 
835 	if (!npx_exists)
836 		return (0);
837 	if (PCPU_GET(fpcurthread) == curthread) {
838 		printf("npxdna: fpcurthread == curthread %d times\n",
839 		    ++err_count);
840 		stop_emulating();
841 		return (1);
842 	}
843 	if (PCPU_GET(fpcurthread) != NULL) {
844 		printf("npxdna: fpcurthread = %p (%d), curthread = %p (%d)\n",
845 		       PCPU_GET(fpcurthread),
846 		       PCPU_GET(fpcurthread)->td_proc->p_pid,
847 		       curthread, curthread->td_proc->p_pid);
848 		panic("npxdna");
849 	}
850 	s = intr_disable();
851 	stop_emulating();
852 	/*
853 	 * Record new context early in case frstor causes an IRQ13.
854 	 */
855 	PCPU_SET(fpcurthread, curthread);
856 	pcb = PCPU_GET(curpcb);
857 
858 	if ((pcb->pcb_flags & PCB_NPXINITDONE) == 0) {
859 		/*
860 		 * This is the first time this thread has used the FPU or
861 		 * the PCB doesn't contain a clean FPU state.  Explicitly
862 		 * initialize the FPU and load the default control word.
863 		 */
864 		fninit();
865 		control = __INITIAL_NPXCW__;
866 		fldcw(&control);
867 		pcb->pcb_flags |= PCB_NPXINITDONE;
868 	} else {
869 		/*
870 		 * The following frstor may cause an IRQ13 when the state
871 		 * being restored has a pending error.  The error will
872 		 * appear to have been triggered by the current (npx) user
873 		 * instruction even when that instruction is a no-wait
874 		 * instruction that should not trigger an error (e.g.,
875 		 * fnclex).  On at least one 486 system all of the no-wait
876 		 * instructions are broken the same as frstor, so our
877 		 * treatment does not amplify the breakage.  On at least
878 		 * one 386/Cyrix 387 system, fnclex works correctly while
879 		 * frstor and fnsave are broken, so our treatment breaks
880 		 * fnclex if it is the first FPU instruction after a context
881 		 * switch.
882 		 */
883 		fpurstor(&pcb->pcb_save);
884 	}
885 	intr_restore(s);
886 
887 	return (1);
888 }
889 
890 /*
891  * Wrapper for fnsave instruction, partly to handle hardware bugs.  When npx
892  * exceptions are reported via IRQ13, spurious IRQ13's may be triggered by
893  * no-wait npx instructions.  See the Intel application note AP-578 for
894  * details.  This doesn't cause any additional complications here.  IRQ13's
895  * are inherently asynchronous unless the CPU is frozen to deliver them --
896  * one that started in userland may be delivered many instructions later,
897  * after the process has entered the kernel.  It may even be delivered after
898  * the fnsave here completes.  A spurious IRQ13 for the fnsave is handled in
899  * the same way as a very-late-arriving non-spurious IRQ13 from user mode:
900  * it is normally ignored at first because we set fpcurthread to NULL; it is
901  * normally retriggered in npxdna() after return to user mode.
902  *
903  * npxsave() must be called with interrupts disabled, so that it clears
904  * fpcurthread atomically with saving the state.  We require callers to do the
905  * disabling, since most callers need to disable interrupts anyway to call
906  * npxsave() atomically with checking fpcurthread.
907  *
908  * A previous version of npxsave() went to great lengths to excecute fnsave
909  * with interrupts enabled in case executing it froze the CPU.  This case
910  * can't happen, at least for Intel CPU/NPX's.  Spurious IRQ13's don't imply
911  * spurious freezes.
912  */
913 void
914 npxsave(addr)
915 	union savefpu *addr;
916 {
917 
918 	stop_emulating();
919 	fpusave(addr);
920 
921 	start_emulating();
922 	PCPU_SET(fpcurthread, NULL);
923 }
924 
925 /*
926  * This should be called with interrupts disabled and only when the owning
927  * FPU thread is non-null.
928  */
929 void
930 npxdrop()
931 {
932 	struct thread *td;
933 
934 	td = PCPU_GET(fpcurthread);
935 	PCPU_SET(fpcurthread, NULL);
936 	td->td_pcb->pcb_flags &= ~PCB_NPXINITDONE;
937 	start_emulating();
938 }
939 
940 /*
941  * Get the state of the FPU without dropping ownership (if possible).
942  * It returns the FPU ownership status.
943  */
944 int
945 npxgetregs(td, addr)
946 	struct thread *td;
947 	union savefpu *addr;
948 {
949 	register_t s;
950 
951 	if (!npx_exists)
952 		return (_MC_FPOWNED_NONE);
953 
954 	if ((td->td_pcb->pcb_flags & PCB_NPXINITDONE) == 0) {
955 		if (npx_cleanstate_ready)
956 			bcopy(&npx_cleanstate, addr, sizeof(npx_cleanstate));
957 		else
958 			bzero(addr, sizeof(*addr));
959 		return (_MC_FPOWNED_NONE);
960 	}
961 	s = intr_disable();
962 	if (td == PCPU_GET(fpcurthread)) {
963 		fpusave(addr);
964 #ifdef CPU_ENABLE_SSE
965 		if (!cpu_fxsr)
966 #endif
967 			/*
968 			 * fnsave initializes the FPU and destroys whatever
969 			 * context it contains.  Make sure the FPU owner
970 			 * starts with a clean state next time.
971 			 */
972 			npxdrop();
973 		intr_restore(s);
974 		return (_MC_FPOWNED_FPU);
975 	} else {
976 		intr_restore(s);
977 		bcopy(&td->td_pcb->pcb_save, addr, sizeof(*addr));
978 		return (_MC_FPOWNED_PCB);
979 	}
980 }
981 
982 /*
983  * Set the state of the FPU.
984  */
985 void
986 npxsetregs(td, addr)
987 	struct thread *td;
988 	union savefpu *addr;
989 {
990 	register_t s;
991 
992 	if (!npx_exists)
993 		return;
994 
995 	s = intr_disable();
996 	if (td == PCPU_GET(fpcurthread)) {
997 		fpurstor(addr);
998 		intr_restore(s);
999 	} else {
1000 		intr_restore(s);
1001 		bcopy(addr, &td->td_pcb->pcb_save, sizeof(*addr));
1002 	}
1003 	curthread->td_pcb->pcb_flags |= PCB_NPXINITDONE;
1004 }
1005 
1006 static void
1007 fpusave(addr)
1008 	union savefpu *addr;
1009 {
1010 
1011 #ifdef CPU_ENABLE_SSE
1012 	if (cpu_fxsr)
1013 		fxsave(addr);
1014 	else
1015 #endif
1016 		fnsave(addr);
1017 }
1018 
1019 static void
1020 fpurstor(addr)
1021 	union savefpu *addr;
1022 {
1023 
1024 #ifdef CPU_ENABLE_SSE
1025 	if (cpu_fxsr)
1026 		fxrstor(addr);
1027 	else
1028 #endif
1029 		frstor(addr);
1030 }
1031 
1032 #ifdef I586_CPU_XXX
1033 static long
1034 timezero(funcname, func)
1035 	const char *funcname;
1036 	void (*func)(void *buf, size_t len);
1037 
1038 {
1039 	void *buf;
1040 #define	BUFSIZE		1048576
1041 	long usec;
1042 	struct timeval finish, start;
1043 
1044 	buf = malloc(BUFSIZE, M_TEMP, M_NOWAIT);
1045 	if (buf == NULL)
1046 		return (BUFSIZE);
1047 	microtime(&start);
1048 	(*func)(buf, BUFSIZE);
1049 	microtime(&finish);
1050 	usec = 1000000 * (finish.tv_sec - start.tv_sec) +
1051 	    finish.tv_usec - start.tv_usec;
1052 	if (usec <= 0)
1053 		usec = 1;
1054 	if (bootverbose)
1055 		printf("%s bandwidth = %u kBps\n", funcname,
1056 		    (u_int32_t)(((BUFSIZE >> 10) * 1000000) / usec));
1057 	free(buf, M_TEMP);
1058 	return (usec);
1059 }
1060 #endif /* I586_CPU */
1061 
1062 static device_method_t npx_methods[] = {
1063 	/* Device interface */
1064 	DEVMETHOD(device_identify,	npx_identify),
1065 	DEVMETHOD(device_probe,		npx_probe),
1066 	DEVMETHOD(device_attach,	npx_attach),
1067 	DEVMETHOD(device_detach,	bus_generic_detach),
1068 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1069 	DEVMETHOD(device_suspend,	bus_generic_suspend),
1070 	DEVMETHOD(device_resume,	bus_generic_resume),
1071 
1072 	{ 0, 0 }
1073 };
1074 
1075 static driver_t npx_driver = {
1076 	"npx",
1077 	npx_methods,
1078 	1,			/* no softc */
1079 };
1080 
1081 static devclass_t npx_devclass;
1082 
1083 #ifdef DEV_ISA
1084 /*
1085  * We prefer to attach to the root nexus so that the usual case (exception 16)
1086  * doesn't describe the processor as being `on isa'.
1087  */
1088 DRIVER_MODULE(npx, nexus, npx_driver, npx_devclass, 0, 0);
1089 
1090 /*
1091  * This sucks up the legacy ISA support assignments from PNPBIOS/ACPI.
1092  */
1093 static struct isa_pnp_id npxisa_ids[] = {
1094 	{ 0x040cd041, "Legacy ISA coprocessor support" }, /* PNP0C04 */
1095 	{ 0 }
1096 };
1097 
1098 static int
1099 npxisa_probe(device_t dev)
1100 {
1101 	int result;
1102 	if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, npxisa_ids)) <= 0) {
1103 		device_quiet(dev);
1104 	}
1105 	return(result);
1106 }
1107 
1108 static int
1109 npxisa_attach(device_t dev)
1110 {
1111 	return (0);
1112 }
1113 
1114 static device_method_t npxisa_methods[] = {
1115 	/* Device interface */
1116 	DEVMETHOD(device_probe,		npxisa_probe),
1117 	DEVMETHOD(device_attach,	npxisa_attach),
1118 	DEVMETHOD(device_detach,	bus_generic_detach),
1119 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1120 	DEVMETHOD(device_suspend,	bus_generic_suspend),
1121 	DEVMETHOD(device_resume,	bus_generic_resume),
1122 
1123 	{ 0, 0 }
1124 };
1125 
1126 static driver_t npxisa_driver = {
1127 	"npxisa",
1128 	npxisa_methods,
1129 	1,			/* no softc */
1130 };
1131 
1132 static devclass_t npxisa_devclass;
1133 
1134 DRIVER_MODULE(npxisa, isa, npxisa_driver, npxisa_devclass, 0, 0);
1135 #ifndef PC98
1136 DRIVER_MODULE(npxisa, acpi, npxisa_driver, npxisa_devclass, 0, 0);
1137 #endif
1138 #endif /* DEV_ISA */
1139