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