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