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