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