isa.c revision 593
1/*-
2 * Copyright (c) 1991 The Regents of the University of California.
3 * All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * William Jolitz.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 *    must display the following acknowledgement:
18 *	This product includes software developed by the University of
19 *	California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 *	from: @(#)isa.c	7.2 (Berkeley) 5/13/91
37 *	$Id$
38 */
39
40/*
41 * code to manage AT bus
42 *
43 * 92/08/18  Frank P. MacLachlan (fpm@crash.cts.com):
44 * Fixed uninitialized variable problem and added code to deal
45 * with DMA page boundaries in isa_dmarangecheck().  Fixed word
46 * mode DMA count compution and reorganized DMA setup code in
47 * isa_dmastart()
48 */
49
50#include "param.h"
51#include "systm.h"
52#include "conf.h"
53#include "file.h"
54#include "buf.h"
55#include "uio.h"
56#include "syslog.h"
57#include "malloc.h"
58#include "rlist.h"
59#include "machine/segments.h"
60#include "vm/vm.h"
61#include "i386/isa/isa_device.h"
62#include "i386/isa/isa.h"
63#include "i386/isa/icu.h"
64#include "i386/isa/ic/i8237.h"
65#include "i386/isa/ic/i8042.h"
66
67/*
68**  Register definitions for DMA controller 1 (channels 0..3):
69*/
70#define	DMA1_CHN(c)	(IO_DMA1 + 1*(2*(c)))	/* addr reg for channel c */
71#define	DMA1_SMSK	(IO_DMA1 + 1*10)	/* single mask register */
72#define	DMA1_MODE	(IO_DMA1 + 1*11)	/* mode register */
73#define	DMA1_FFC	(IO_DMA1 + 1*12)	/* clear first/last FF */
74
75/*
76**  Register definitions for DMA controller 2 (channels 4..7):
77*/
78#define	DMA2_CHN(c)	(IO_DMA1 + 2*(2*(c)))	/* addr reg for channel c */
79#define	DMA2_SMSK	(IO_DMA2 + 2*10)	/* single mask register */
80#define	DMA2_MODE	(IO_DMA2 + 2*11)	/* mode register */
81#define	DMA2_FFC	(IO_DMA2 + 2*12)	/* clear first/last FF */
82
83int config_isadev __P((struct isa_device *, u_int *));
84
85/*
86 * print a conflict message
87 */
88void
89conflict(dvp, tmpdvp, item, reason, format)
90	struct isa_device	*dvp, *tmpdvp;
91	int			item;
92	char			*reason;
93	char			*format;
94{
95	printf("%s%d not probed due to %s conflict with %s%d at ",
96		dvp->id_driver->name, dvp->id_unit, reason,
97		tmpdvp->id_driver->name, tmpdvp->id_unit);
98	printf(format, item);
99	printf("\n");
100}
101
102/*
103 * Check to see if things are alread in use, like IRQ's, I/O addresses
104 * and Memory addresses.
105 */
106int
107haveseen(dvp, tmpdvp)
108	struct	isa_device *dvp, *tmpdvp;
109{
110	int	status = 0;
111
112	/*
113	 * Only check against devices that have already been found
114	 */
115	if (tmpdvp->id_alive) {
116		/*
117		 * Check for I/O address conflict.  We can only check the
118		 * starting address of the device against the range of the
119		 * device that has already been probed since we do not
120		 * know how many I/O addresses this device uses.
121		 */
122		if (tmpdvp->id_alive != -1) {
123			if ((dvp->id_iobase >= tmpdvp->id_iobase) &&
124			    (dvp->id_iobase <=
125				  (tmpdvp->id_iobase + tmpdvp->id_alive - 1))) {
126				conflict(dvp, tmpdvp, dvp->id_iobase,
127					 "I/O address", "0x%x");
128				status = 1;
129			}
130		}
131		/*
132		 * Check for Memory address conflict.  We can check for
133		 * range overlap, but it will not catch all cases since the
134		 * driver may adjust the msize paramater during probe, for
135		 * now we just check that the starting address does not
136		 * fall within any allocated region.
137		 * XXX could add a second check after the probe for overlap,
138		 * since at that time we would know the full range.
139		 * XXX KERNBASE is a hack, we should have vaddr in the table!
140		 */
141		if(tmpdvp->id_maddr) {
142			if((KERNBASE + dvp->id_maddr >= tmpdvp->id_maddr) &&
143			   (KERNBASE + dvp->id_maddr <=
144			   (tmpdvp->id_maddr + tmpdvp->id_msize - 1))) {
145				conflict(dvp, tmpdvp, dvp->id_maddr, "maddr",
146					"0x%x");
147				status = 1;
148			}
149		}
150		/*
151		 * Check for IRQ conflicts.
152		 */
153		if(tmpdvp->id_irq) {
154			if (tmpdvp->id_irq == dvp->id_irq) {
155				conflict(dvp, tmpdvp, ffs(dvp->id_irq) - 1,
156					"irq", "%d");
157				status = 1;
158			}
159		}
160		/*
161		 * Check for DRQ conflicts.
162		 */
163		if(tmpdvp->id_drq != -1) {
164			if (tmpdvp->id_drq == dvp->id_drq) {
165				conflict(dvp, tmpdvp, dvp->id_drq,
166					"drq", "%d");
167				status = 1;
168			}
169		}
170	}
171	return (status);
172}
173
174/*
175 * Search through all the isa_devtab_* tables looking for anything that
176 * conflicts with the current device.
177 */
178int
179haveseen_isadev(dvp)
180	struct isa_device *dvp;
181{
182	struct isa_device *tmpdvp;
183	int	status = 0;
184
185	for (tmpdvp = isa_devtab_tty; tmpdvp->id_driver; tmpdvp++) {
186		status |= haveseen(dvp, tmpdvp);
187	}
188	for (tmpdvp = isa_devtab_bio; tmpdvp->id_driver; tmpdvp++) {
189		status |= haveseen(dvp, tmpdvp);
190	}
191	for (tmpdvp = isa_devtab_net; tmpdvp->id_driver; tmpdvp++) {
192		status |= haveseen(dvp, tmpdvp);
193	}
194	for (tmpdvp = isa_devtab_null; tmpdvp->id_driver; tmpdvp++) {
195		status |= haveseen(dvp, tmpdvp);
196	}
197	return(status);
198}
199
200/*
201 * Configure all ISA devices
202 */
203void
204isa_configure() {
205	struct isa_device *dvp;
206
207	enable_intr();
208	splhigh();
209	INTREN(IRQ_SLAVE);
210	printf("Probing for devices on the ISA bus:\n");
211	for (dvp = isa_devtab_tty; dvp->id_driver; dvp++) {
212		if (!haveseen_isadev(dvp))
213			config_isadev(dvp,&ttymask);
214	}
215	for (dvp = isa_devtab_bio; dvp->id_driver; dvp++) {
216		if (!haveseen_isadev(dvp))
217			config_isadev(dvp,&biomask);
218	}
219	for (dvp = isa_devtab_net; dvp->id_driver; dvp++) {
220		if (!haveseen_isadev(dvp))
221			config_isadev(dvp,&netmask);
222	}
223	for (dvp = isa_devtab_null; dvp->id_driver; dvp++) {
224		if (!haveseen_isadev(dvp))
225			config_isadev(dvp,(u_int *) NULL);
226	}
227/*
228 * XXX We should really add the tty device to netmask when the line is
229 * switched to SLIPDISC, and then remove it when it is switched away from
230 * SLIPDISC.  No need to block out ALL ttys during a splnet when only one
231 * of them is running slip.
232 */
233#include "sl.h"
234#if NSL > 0
235	netmask |= ttymask;
236	ttymask |= netmask;
237#endif
238	/* biomask |= ttymask ;  can some tty devices use buffers? */
239	printf("biomask %x ttymask %x netmask %x\n", biomask, ttymask, netmask);
240	splnone();
241}
242
243/*
244 * Configure an ISA device.
245 */
246config_isadev(isdp, mp)
247	struct isa_device *isdp;
248	u_int *mp;
249{
250	struct isa_driver *dp = isdp->id_driver;
251
252	if (isdp->id_maddr) {
253		extern u_int atdevbase;
254
255		isdp->id_maddr -= 0xa0000; /* XXX should be a define */
256		isdp->id_maddr += atdevbase;
257	}
258	isdp->id_alive = (*dp->probe)(isdp);
259	if (isdp->id_alive) {
260		/*
261		 * Only print the I/O address range if id_alive != -1
262		 * Right now this is a temporary fix just for the new
263		 * NPX code so that if it finds a 486 that can use trap
264		 * 16 it will not report I/O addresses.
265		 * Rod Grimes 04/26/94
266		 */
267		printf("%s%d", dp->name, isdp->id_unit);
268		if (isdp->id_alive != -1) {
269 			printf(" at 0x%x", isdp->id_iobase);
270 			if ((isdp->id_iobase + isdp->id_alive - 1) !=
271 			     isdp->id_iobase) {
272 				printf("-0x%x",
273				       isdp->id_iobase +
274				       isdp->id_alive - 1);
275			}
276		}
277		if(isdp->id_irq)
278			printf(" irq %d", ffs(isdp->id_irq) - 1);
279		if (isdp->id_drq != -1)
280			printf(" drq %d", isdp->id_drq);
281		if (isdp->id_maddr)
282			printf(" maddr 0x%x", kvtop(isdp->id_maddr));
283		if (isdp->id_msize)
284			printf(" msize %d", isdp->id_msize);
285		if (isdp->id_flags)
286			printf(" flags 0x%x", isdp->id_flags);
287		if (isdp->id_iobase < 0x100)
288			printf(" on motherboard\n");
289		else
290			printf(" on isa\n");
291
292		(*dp->attach)(isdp);
293
294		if(isdp->id_irq) {
295			int intrno;
296
297			intrno = ffs(isdp->id_irq)-1;
298			setidt(ICU_OFFSET+intrno, isdp->id_intr,
299				 SDT_SYS386IGT, SEL_KPL);
300			if(mp) {
301				INTRMASK(*mp,isdp->id_irq);
302			}
303			INTREN(isdp->id_irq);
304		}
305	} else {
306		printf("%s%d not found", dp->name, isdp->id_unit);
307		if (isdp->id_iobase) {
308			printf(" at 0x%x", isdp->id_iobase);
309		}
310		printf("\n");
311	}
312}
313
314#define	IDTVEC(name)	__CONCAT(X,name)
315/* default interrupt vector table entries */
316extern	IDTVEC(intr0), IDTVEC(intr1), IDTVEC(intr2), IDTVEC(intr3),
317	IDTVEC(intr4), IDTVEC(intr5), IDTVEC(intr6), IDTVEC(intr7),
318	IDTVEC(intr8), IDTVEC(intr9), IDTVEC(intr10), IDTVEC(intr11),
319	IDTVEC(intr12), IDTVEC(intr13), IDTVEC(intr14), IDTVEC(intr15);
320
321static *defvec[16] = {
322	&IDTVEC(intr0), &IDTVEC(intr1), &IDTVEC(intr2), &IDTVEC(intr3),
323	&IDTVEC(intr4), &IDTVEC(intr5), &IDTVEC(intr6), &IDTVEC(intr7),
324	&IDTVEC(intr8), &IDTVEC(intr9), &IDTVEC(intr10), &IDTVEC(intr11),
325	&IDTVEC(intr12), &IDTVEC(intr13), &IDTVEC(intr14), &IDTVEC(intr15) };
326
327/* out of range default interrupt vector gate entry */
328extern	IDTVEC(intrdefault);
329
330/*
331 * Fill in default interrupt table (in case of spuruious interrupt
332 * during configuration of kernel, setup interrupt control unit
333 */
334isa_defaultirq() {
335	int i;
336
337	/* icu vectors */
338	for (i = NRSVIDT ; i < NRSVIDT+ICU_LEN ; i++)
339		setidt(i, defvec[i],  SDT_SYS386IGT, SEL_KPL);
340
341	/* out of range vectors */
342	for (i = NRSVIDT; i < NIDT; i++)
343		setidt(i, &IDTVEC(intrdefault), SDT_SYS386IGT, SEL_KPL);
344
345	/* initialize 8259's */
346	outb(IO_ICU1, 0x11);		/* reset; program device, four bytes */
347	outb(IO_ICU1+1, NRSVIDT);	/* starting at this vector index */
348	outb(IO_ICU1+1, 1<<2);		/* slave on line 2 */
349#ifdef AUTO_EOI_1
350	outb(IO_ICU1+1, 2 | 1);		/* auto EOI, 8086 mode */
351#else
352	outb(IO_ICU1+1, 1);		/* 8086 mode */
353#endif
354	outb(IO_ICU1+1, 0xff);		/* leave interrupts masked */
355	outb(IO_ICU1, 0x0a);		/* default to IRR on read */
356	outb(IO_ICU1, 0xc0 | (3 - 1));	/* pri order 3-7, 0-2 (com2 first) */
357
358	outb(IO_ICU2, 0x11);		/* reset; program device, four bytes */
359	outb(IO_ICU2+1, NRSVIDT+8);	/* staring at this vector index */
360	outb(IO_ICU2+1,2);		/* my slave id is 2 */
361#ifdef AUTO_EOI_2
362	outb(IO_ICU2+1, 2 | 1);		/* auto EOI, 8086 mode */
363#else
364	outb(IO_ICU2+1,1);		/* 8086 mode */
365#endif
366	outb(IO_ICU2+1, 0xff);		/* leave interrupts masked */
367	outb(IO_ICU2, 0x0a);		/* default to IRR on read */
368}
369
370/* region of physical memory known to be contiguous */
371vm_offset_t isaphysmem;
372static caddr_t dma_bounce[8];		/* XXX */
373static char bounced[8];		/* XXX */
374#define MAXDMASZ 512		/* XXX */
375
376/* high byte of address is stored in this port for i-th dma channel */
377static short dmapageport[8] =
378	{ 0x87, 0x83, 0x81, 0x82, 0x8f, 0x8b, 0x89, 0x8a };
379
380/*
381 * isa_dmacascade(): program 8237 DMA controller channel to accept
382 * external dma control by a board.
383 */
384void isa_dmacascade(unsigned chan)
385{
386	if (chan > 7)
387		panic("isa_dmacascade: impossible request");
388
389	/* set dma channel mode, and set dma channel mode */
390	if ((chan & 4) == 0) {
391		outb(DMA1_MODE, DMA37MD_CASCADE | chan);
392		outb(DMA1_SMSK, chan);
393	} else {
394		outb(DMA2_MODE, DMA37MD_CASCADE | (chan & 3));
395		outb(DMA2_SMSK, chan & 3);
396	}
397}
398
399/*
400 * isa_dmastart(): program 8237 DMA controller channel, avoid page alignment
401 * problems by using a bounce buffer.
402 */
403void isa_dmastart(int flags, caddr_t addr, unsigned nbytes, unsigned chan)
404{	vm_offset_t phys;
405	int waport;
406	caddr_t newaddr;
407
408	if (    chan > 7
409	    || (chan < 4 && nbytes > (1<<16))
410	    || (chan >= 4 && (nbytes > (1<<17) || (u_int)addr & 1)))
411		panic("isa_dmastart: impossible request");
412
413	if (isa_dmarangecheck(addr, nbytes, chan)) {
414		if (dma_bounce[chan] == 0)
415			dma_bounce[chan] =
416				/*(caddr_t)malloc(MAXDMASZ, M_TEMP, M_WAITOK);*/
417				(caddr_t) isaphysmem + NBPG*chan;
418		bounced[chan] = 1;
419		newaddr = dma_bounce[chan];
420		*(int *) newaddr = 0;	/* XXX */
421
422		/* copy bounce buffer on write */
423		if (!(flags & B_READ))
424			bcopy(addr, newaddr, nbytes);
425		addr = newaddr;
426	}
427
428	/* translate to physical */
429	phys = pmap_extract(pmap_kernel(), (vm_offset_t)addr);
430
431	if ((chan & 4) == 0) {
432		/*
433		 * Program one of DMA channels 0..3.  These are
434		 * byte mode channels.
435		 */
436		/* set dma channel mode, and reset address ff */
437		if (flags & B_READ)
438			outb(DMA1_MODE, DMA37MD_SINGLE|DMA37MD_WRITE|chan);
439		else
440			outb(DMA1_MODE, DMA37MD_SINGLE|DMA37MD_READ|chan);
441		outb(DMA1_FFC, 0);
442
443		/* send start address */
444		waport =  DMA1_CHN(chan);
445		outb(waport, phys);
446		outb(waport, phys>>8);
447		outb(dmapageport[chan], phys>>16);
448
449		/* send count */
450		outb(waport + 1, --nbytes);
451		outb(waport + 1, nbytes>>8);
452
453		/* unmask channel */
454		outb(DMA1_SMSK, chan);
455	} else {
456		/*
457		 * Program one of DMA channels 4..7.  These are
458		 * word mode channels.
459		 */
460		/* set dma channel mode, and reset address ff */
461		if (flags & B_READ)
462			outb(DMA2_MODE, DMA37MD_SINGLE|DMA37MD_WRITE|(chan&3));
463		else
464			outb(DMA2_MODE, DMA37MD_SINGLE|DMA37MD_READ|(chan&3));
465		outb(DMA2_FFC, 0);
466
467		/* send start address */
468		waport = DMA2_CHN(chan - 4);
469		outb(waport, phys>>1);
470		outb(waport, phys>>9);
471		outb(dmapageport[chan], phys>>16);
472
473		/* send count */
474		nbytes >>= 1;
475		outb(waport + 2, --nbytes);
476		outb(waport + 2, nbytes>>8);
477
478		/* unmask channel */
479		outb(DMA2_SMSK, chan & 3);
480	}
481}
482
483void isa_dmadone(int flags, caddr_t addr, int nbytes, int chan)
484{
485
486	/* copy bounce buffer on read */
487	/*if ((flags & (B_PHYS|B_READ)) == (B_PHYS|B_READ))*/
488	if (bounced[chan]) {
489		bcopy(dma_bounce[chan], addr, nbytes);
490		bounced[chan] = 0;
491	}
492}
493
494/*
495 * Check for problems with the address range of a DMA transfer
496 * (non-contiguous physical pages, outside of bus address space,
497 * crossing DMA page boundaries).
498 * Return true if special handling needed.
499 */
500
501isa_dmarangecheck(caddr_t va, unsigned length, unsigned chan) {
502	vm_offset_t phys, priorpage = 0, endva;
503	u_int dma_pgmsk = (chan & 4) ?  ~(128*1024-1) : ~(64*1024-1);
504
505	endva = (vm_offset_t)round_page(va + length);
506	for (; va < (caddr_t) endva ; va += NBPG) {
507		phys = trunc_page(pmap_extract(pmap_kernel(), (vm_offset_t)va));
508#define ISARAM_END	RAM_END
509		if (phys == 0)
510			panic("isa_dmacheck: no physical page present");
511		if (phys > ISARAM_END)
512			return (1);
513		if (priorpage) {
514			if (priorpage + NBPG != phys)
515				return (1);
516			/* check if crossing a DMA page boundary */
517			if (((u_int)priorpage ^ (u_int)phys) & dma_pgmsk)
518				return (1);
519		}
520		priorpage = phys;
521	}
522	return (0);
523}
524
525/* head of queue waiting for physmem to become available */
526struct buf isa_physmemq;
527
528/* blocked waiting for resource to become free for exclusive use */
529static isaphysmemflag;
530/* if waited for and call requested when free (B_CALL) */
531static void (*isaphysmemunblock)(); /* needs to be a list */
532
533/*
534 * Allocate contiguous physical memory for transfer, returning
535 * a *virtual* address to region. May block waiting for resource.
536 * (assumed to be called at splbio())
537 */
538caddr_t
539isa_allocphysmem(caddr_t va, unsigned length, void (*func)()) {
540
541	isaphysmemunblock = func;
542	while (isaphysmemflag & B_BUSY) {
543		isaphysmemflag |= B_WANTED;
544		sleep(&isaphysmemflag, PRIBIO);
545	}
546	isaphysmemflag |= B_BUSY;
547
548	return((caddr_t)isaphysmem);
549}
550
551/*
552 * Free contiguous physical memory used for transfer.
553 * (assumed to be called at splbio())
554 */
555void
556isa_freephysmem(caddr_t va, unsigned length) {
557
558	isaphysmemflag &= ~B_BUSY;
559	if (isaphysmemflag & B_WANTED) {
560		isaphysmemflag &= B_WANTED;
561		wakeup(&isaphysmemflag);
562		if (isaphysmemunblock)
563			(*isaphysmemunblock)();
564	}
565}
566
567/*
568 * Handle a NMI, possibly a machine check.
569 * return true to panic system, false to ignore.
570 */
571isa_nmi(cd) {
572
573	log(LOG_CRIT, "\nNMI port 61 %x, port 70 %x\n", inb(0x61), inb(0x70));
574	return(0);
575}
576
577/*
578 * Caught a stray interrupt, notify
579 */
580isa_strayintr(d) {
581
582	/* DON'T BOTHER FOR NOW! */
583	/* for some reason, we get bursts of intr #7, even if not enabled! */
584	/*
585	 * Well the reason you got bursts of intr #7 is because someone
586	 * raised an interrupt line and dropped it before the 8259 could
587	 * prioritize it.  This is documented in the intel data book.  This
588	 * means you have BAD hardware!  I have changed this so that only
589	 * the first 5 get logged, then it quits logging them, and puts
590	 * out a special message. rgrimes 3/25/1993
591	 */
592	extern u_long intrcnt_stray;
593
594	intrcnt_stray++;
595	if (intrcnt_stray <= 5)
596		log(LOG_ERR,"ISA strayintr %x\n", d);
597	if (intrcnt_stray == 5)
598		log(LOG_CRIT,"Too many ISA strayintr not logging any more\n");
599}
600
601/*
602 * Wait "n" microseconds.
603 * Relies on timer 1 counting down from (TIMER_FREQ / hz) at
604 * (1 * TIMER_FREQ) Hz.
605 * Note: timer had better have been programmed before this is first used!
606 * (The standard programming causes the timer to generate a square wave and
607 * the counter is decremented twice every cycle.)
608 */
609#define	CF		(1 * TIMER_FREQ)
610#define	TIMER_FREQ	1193182	/* XXX - should be elsewhere */
611
612extern int hz;			/* XXX - should be elsewhere */
613
614int DELAY(n)
615	int n;
616{
617	int counter_limit;
618	int prev_tick;
619	int tick;
620	int ticks_left;
621	int sec;
622	int usec;
623
624#ifdef DELAYDEBUG
625	int getit_calls = 1;
626	int n1;
627	static int state = 0;
628
629	if (state == 0) {
630		state = 1;
631		for (n1 = 1; n1 <= 10000000; n1 *= 10)
632			DELAY(n1);
633		state = 2;
634	}
635	if (state == 1)
636		printf("DELAY(%d)...", n);
637#endif
638
639	/*
640	 * Read the counter first, so that the rest of the setup overhead is
641	 * counted.  Guess the initial overhead is 20 usec (on most systems it
642	 * takes about 1.5 usec for each of the i/o's in getit().  The loop
643	 * takes about 6 usec on a 486/33 and 13 usec on a 386/20.  The
644	 * multiplications and divisions to scale the count take a while).
645	 */
646	prev_tick = getit(0, 0);
647	n -= 20;
648
649	/*
650	 * Calculate (n * (CF / 1e6)) without using floating point and without
651	 * any avoidable overflows.
652	 */
653	sec = n / 1000000;
654	usec = n - sec * 1000000;
655	ticks_left = sec * CF
656		     + usec * (CF / 1000000)
657		     + usec * ((CF % 1000000) / 1000) / 1000
658		     + usec * (CF % 1000) / 1000000;
659
660	counter_limit = TIMER_FREQ / hz;
661	while (ticks_left > 0) {
662		tick = getit(0, 0);
663#ifdef DELAYDEBUG
664		++getit_calls;
665#endif
666		if (tick > prev_tick)
667			ticks_left -= prev_tick - (tick - counter_limit);
668		else
669			ticks_left -= prev_tick - tick;
670		prev_tick = tick;
671	}
672#ifdef DELAYDEBUG
673	if (state == 1)
674		printf(" %d calls to getit() at %d usec each\n",
675		       getit_calls, (n + 5) / getit_calls);
676#endif
677}
678
679getit(unit, timer) {
680	int high;
681	int low;
682
683	/*
684	 * XXX - isa.h defines bogus timers.  There's no such timer as
685	 * IO_TIMER_2 = 0x48.  There's a timer in the CMOS RAM chip but
686	 * its interface is quite different.  Neither timer is an 8252.
687	 * We actually only call this with unit = 0 and timer = 0.  It
688	 * could be static...
689	 */
690	/*
691	 * Protect ourself against interrupts.
692	 * XXX - sysbeep() and sysbeepstop() need protection.
693	 */
694	disable_intr();
695	/*
696	 * Latch the count for 'timer' (cc00xxxx, c = counter, x = any).
697	 */
698	outb(IO_TIMER1 + 3, timer << 6);
699
700	low = inb(IO_TIMER1 + timer);
701	high = inb(IO_TIMER1 + timer);
702	enable_intr();
703	return ((high << 8) | low);
704}
705
706static beeping;
707static
708sysbeepstop(f)
709{
710	/* disable counter 2 */
711	outb(0x61, inb(0x61) & 0xFC);
712	if (f)
713		timeout(sysbeepstop, 0, f);
714	else
715		beeping = 0;
716}
717
718void sysbeep(int pitch, int period)
719{
720
721	outb(0x61, inb(0x61) | 3);	/* enable counter 2 */
722	/*
723	 * XXX - move timer stuff to clock.c.
724	 * Program counter 2:
725	 * ccaammmb, c counter, a = access, m = mode, b = BCD
726	 * 1011x110, 11 for aa = LSB then MSB, x11 for mmm = square wave.
727	 */
728	outb(0x43, 0xb6);	/* set command for counter 2, 2 byte write */
729
730	outb(0x42, pitch);
731	outb(0x42, (pitch>>8));
732
733	if (!beeping) {
734		beeping = period;
735		timeout(sysbeepstop, period/2, period);
736	}
737}
738
739/*
740 * Pass command to keyboard controller (8042)
741 */
742unsigned kbc_8042cmd(val) {
743
744	while (inb(KBSTATP)&KBS_IBF);
745	if (val) outb(KBCMDP, val);
746	while (inb(KBSTATP)&KBS_IBF);
747	return (inb(KBDATAP));
748}
749
750/*
751 * find an ISA device in a given isa_devtab_* table, given
752 * the table to search, the expected id_driver entry, and the unit number.
753 *
754 * this function is defined in isa_device.h, and this location is debatable;
755 * i put it there because it's useless w/o, and directly operates on
756 * the other stuff in that file.
757 *
758 */
759
760struct isa_device *find_isadev(table, driverp, unit)
761     struct isa_device *table;
762     struct isa_driver *driverp;
763     int unit;
764{
765  if (driverp == NULL) /* sanity check */
766    return NULL;
767
768  while ((table->id_driver != driverp) || (table->id_unit != unit)) {
769    if (table->id_driver == 0)
770      return NULL;
771
772    table++;
773  }
774
775  return table;
776}
777
778/*
779 * Return nonzero if a (masked) irq is pending for a given device.
780 */
781int
782isa_irq_pending(dvp)
783	struct isa_device *dvp;
784{
785	unsigned id_irq;
786
787	id_irq = (unsigned short) dvp->id_irq;	/* XXX silly type in struct */
788	if (id_irq & 0xff)
789		return (inb(IO_ICU1) & id_irq);
790	return (inb(IO_ICU2) & (id_irq >> 8));
791}
792