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