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