xref: /netbsd-src/sys/dev/ic/bha.c (revision 2a399c6883d870daece976daec6ffa7bb7f934ce)
1 /*	$NetBSD: bha.c,v 1.17 1997/11/04 05:58:26 thorpej Exp $	*/
2 
3 #undef BHADIAG
4 #ifdef DDB
5 #define	integrate
6 #else
7 #define	integrate	static inline
8 #endif
9 
10 /*-
11  * Copyright (c) 1997 The NetBSD Foundation, Inc.
12  * All rights reserved.
13  *
14  * This code is derived from software contributed to The NetBSD Foundation
15  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
16  * NASA Ames Research Center.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  * 3. All advertising materials mentioning features or use of this software
27  *    must display the following acknowledgement:
28  *	This product includes software developed by the NetBSD
29  *	Foundation, Inc. and its contributors.
30  * 4. Neither the name of The NetBSD Foundation nor the names of its
31  *    contributors may be used to endorse or promote products derived
32  *    from this software without specific prior written permission.
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
35  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
36  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
37  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
38  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
39  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
40  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
41  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
42  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
43  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
44  * POSSIBILITY OF SUCH DAMAGE.
45  */
46 
47 /*
48  * Copyright (c) 1994, 1996, 1997 Charles M. Hannum.  All rights reserved.
49  *
50  * Redistribution and use in source and binary forms, with or without
51  * modification, are permitted provided that the following conditions
52  * are met:
53  * 1. Redistributions of source code must retain the above copyright
54  *    notice, this list of conditions and the following disclaimer.
55  * 2. Redistributions in binary form must reproduce the above copyright
56  *    notice, this list of conditions and the following disclaimer in the
57  *    documentation and/or other materials provided with the distribution.
58  * 3. All advertising materials mentioning features or use of this software
59  *    must display the following acknowledgement:
60  *	This product includes software developed by Charles M. Hannum.
61  * 4. The name of the author may not be used to endorse or promote products
62  *    derived from this software without specific prior written permission.
63  *
64  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
65  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
66  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
67  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
68  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
69  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
70  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
71  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
72  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
73  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
74  */
75 
76 /*
77  * Originally written by Julian Elischer (julian@tfs.com)
78  * for TRW Financial Systems for use under the MACH(2.5) operating system.
79  *
80  * TRW Financial Systems, in accordance with their agreement with Carnegie
81  * Mellon University, makes this software available to CMU to distribute
82  * or use in any manner that they see fit as long as this message is kept with
83  * the software. For this reason TFS also grants any other persons or
84  * organisations permission to use or modify this software.
85  *
86  * TFS supplies this software to be publicly redistributed
87  * on the understanding that TFS is not responsible for the correct
88  * functioning of this software in any circumstances.
89  */
90 
91 #include <sys/types.h>
92 #include <sys/param.h>
93 #include <sys/systm.h>
94 #include <sys/kernel.h>
95 #include <sys/errno.h>
96 #include <sys/ioctl.h>
97 #include <sys/device.h>
98 #include <sys/malloc.h>
99 #include <sys/buf.h>
100 #include <sys/proc.h>
101 #include <sys/user.h>
102 
103 #include <machine/bus.h>
104 #include <machine/intr.h>
105 
106 #include <dev/scsipi/scsi_all.h>
107 #include <dev/scsipi/scsipi_all.h>
108 #include <dev/scsipi/scsiconf.h>
109 
110 #include <dev/ic/bhareg.h>
111 #include <dev/ic/bhavar.h>
112 
113 #ifndef DDB
114 #define Debugger() panic("should call debugger here (bha.c)")
115 #endif /* ! DDB */
116 
117 #define	BHA_MAXXFER	((BHA_NSEG - 1) << PGSHIFT)
118 
119 #ifdef BHADEBUG
120 int     bha_debug = 0;
121 #endif /* BHADEBUG */
122 
123 int bha_cmd __P((bus_space_tag_t, bus_space_handle_t, struct bha_softc *,
124 		 int, u_char *, int, u_char *));
125 integrate void bha_finish_ccbs __P((struct bha_softc *));
126 integrate void bha_reset_ccb __P((struct bha_softc *, struct bha_ccb *));
127 void bha_free_ccb __P((struct bha_softc *, struct bha_ccb *));
128 integrate int bha_init_ccb __P((struct bha_softc *, struct bha_ccb *));
129 struct bha_ccb *bha_get_ccb __P((struct bha_softc *, int));
130 struct bha_ccb *bha_ccb_phys_kv __P((struct bha_softc *, u_long));
131 void bha_queue_ccb __P((struct bha_softc *, struct bha_ccb *));
132 void bha_collect_mbo __P((struct bha_softc *));
133 void bha_start_ccbs __P((struct bha_softc *));
134 void bha_done __P((struct bha_softc *, struct bha_ccb *));
135 void bha_init __P((struct bha_softc *));
136 void bhaminphys __P((struct buf *));
137 int bha_scsi_cmd __P((struct scsipi_xfer *));
138 int bha_poll __P((struct bha_softc *, struct scsipi_xfer *, int));
139 void bha_timeout __P((void *arg));
140 int bha_create_ccbs __P((struct bha_softc *, void *, size_t, int));
141 void bha_enqueue __P((struct bha_softc *, struct scsipi_xfer *, int));
142 struct scsipi_xfer *bha_dequeue __P((struct bha_softc *));
143 
144 struct scsipi_adapter bha_switch = {
145 	bha_scsi_cmd,
146 	bhaminphys,
147 	0,
148 	0,
149 };
150 
151 /* the below structure is so we have a default dev struct for out link struct */
152 struct scsipi_device bha_dev = {
153 	NULL,			/* Use default error handler */
154 	NULL,			/* have a queue, served by this */
155 	NULL,			/* have no async handler */
156 	NULL,			/* Use default 'done' routine */
157 };
158 
159 struct cfdriver bha_cd = {
160 	NULL, "bha", DV_DULL
161 };
162 
163 #define BHA_RESET_TIMEOUT	2000	/* time to wait for reset (mSec) */
164 #define	BHA_ABORT_TIMEOUT	2000	/* time to wait for abort (mSec) */
165 
166 /* XXX Should put this in a better place. */
167 #define	offsetof(type, member)	((size_t)(&((type *)0)->member))
168 
169 /*
170  * Insert a scsipi_xfer into the software queue.  We overload xs->free_list
171  * to avoid having to allocate additional resources (since we're used
172  * only during resource shortages anyhow.
173  */
174 void
175 bha_enqueue(sc, xs, infront)
176 	struct bha_softc *sc;
177 	struct scsipi_xfer *xs;
178 	int infront;
179 {
180 
181 	if (infront || sc->sc_queue.lh_first == NULL) {
182 		if (sc->sc_queue.lh_first == NULL)
183 			sc->sc_queuelast = xs;
184 		LIST_INSERT_HEAD(&sc->sc_queue, xs, free_list);
185 		return;
186 	}
187 
188 	LIST_INSERT_AFTER(sc->sc_queuelast, xs, free_list);
189 	sc->sc_queuelast = xs;
190 }
191 
192 /*
193  * Pull a scsipi_xfer off the front of the software queue.
194  */
195 struct scsipi_xfer *
196 bha_dequeue(sc)
197 	struct bha_softc *sc;
198 {
199 	struct scsipi_xfer *xs;
200 
201 	xs = sc->sc_queue.lh_first;
202 	LIST_REMOVE(xs, free_list);
203 
204 	if (sc->sc_queue.lh_first == NULL)
205 		sc->sc_queuelast = NULL;
206 
207 	return (xs);
208 }
209 
210 /*
211  * bha_cmd(iot, ioh, sc, icnt, ibuf, ocnt, obuf)
212  *
213  * Activate Adapter command
214  *    icnt:   number of args (outbound bytes including opcode)
215  *    ibuf:   argument buffer
216  *    ocnt:   number of expected returned bytes
217  *    obuf:   result buffer
218  *    wait:   number of seconds to wait for response
219  *
220  * Performs an adapter command through the ports.  Not to be confused with a
221  * scsi command, which is read in via the dma; one of the adapter commands
222  * tells it to read in a scsi command.
223  */
224 int
225 bha_cmd(iot, ioh, sc, icnt, ibuf, ocnt, obuf)
226 	bus_space_tag_t iot;
227 	bus_space_handle_t ioh;
228 	struct bha_softc *sc;
229 	int icnt, ocnt;
230 	u_char *ibuf, *obuf;
231 {
232 	const char *name;
233 	register int i;
234 	int wait;
235 	u_char sts;
236 	u_char opcode = ibuf[0];
237 
238 	if (sc != NULL)
239 		name = sc->sc_dev.dv_xname;
240 	else
241 		name = "(bha probe)";
242 
243 	/*
244 	 * Calculate a reasonable timeout for the command.
245 	 */
246 	switch (opcode) {
247 	case BHA_INQUIRE_DEVICES:
248 	case BHA_INQUIRE_DEVICES_2:
249 		wait = 90 * 20000;
250 		break;
251 	default:
252 		wait = 1 * 20000;
253 		break;
254 	}
255 
256 	/*
257 	 * Wait for the adapter to go idle, unless it's one of
258 	 * the commands which don't need this
259 	 */
260 	if (opcode != BHA_MBO_INTR_EN) {
261 		for (i = 20000; i; i--) {	/* 1 sec? */
262 			sts = bus_space_read_1(iot, ioh, BHA_STAT_PORT);
263 			if (sts & BHA_STAT_IDLE)
264 				break;
265 			delay(50);
266 		}
267 		if (!i) {
268 			printf("%s: bha_cmd, host not idle(0x%x)\n",
269 			    name, sts);
270 			return (1);
271 		}
272 	}
273 	/*
274 	 * Now that it is idle, if we expect output, preflush the
275 	 * queue feeding to us.
276 	 */
277 	if (ocnt) {
278 		while ((bus_space_read_1(iot, ioh, BHA_STAT_PORT)) &
279 		    BHA_STAT_DF)
280 			bus_space_read_1(iot, ioh, BHA_DATA_PORT);
281 	}
282 	/*
283 	 * Output the command and the number of arguments given
284 	 * for each byte, first check the port is empty.
285 	 */
286 	while (icnt--) {
287 		for (i = wait; i; i--) {
288 			sts = bus_space_read_1(iot, ioh, BHA_STAT_PORT);
289 			if (!(sts & BHA_STAT_CDF))
290 				break;
291 			delay(50);
292 		}
293 		if (!i) {
294 			if (opcode != BHA_INQUIRE_REVISION)
295 				printf("%s: bha_cmd, cmd/data port full\n",
296 				    name);
297 			goto bad;
298 		}
299 		bus_space_write_1(iot, ioh, BHA_CMD_PORT, *ibuf++);
300 	}
301 	/*
302 	 * If we expect input, loop that many times, each time,
303 	 * looking for the data register to have valid data
304 	 */
305 	while (ocnt--) {
306 		for (i = wait; i; i--) {
307 			sts = bus_space_read_1(iot, ioh, BHA_STAT_PORT);
308 			if (sts & BHA_STAT_DF)
309 				break;
310 			delay(50);
311 		}
312 		if (!i) {
313 			if (opcode != BHA_INQUIRE_REVISION)
314 				printf("%s: bha_cmd, cmd/data port empty %d\n",
315 				    name, ocnt);
316 			goto bad;
317 		}
318 		*obuf++ = bus_space_read_1(iot, ioh, BHA_DATA_PORT);
319 	}
320 	/*
321 	 * Wait for the board to report a finished instruction.
322 	 * We may get an extra interrupt for the HACC signal, but this is
323 	 * unimportant.
324 	 */
325 	if (opcode != BHA_MBO_INTR_EN && opcode != BHA_MODIFY_IOPORT) {
326 		for (i = 20000; i; i--) {	/* 1 sec? */
327 			sts = bus_space_read_1(iot, ioh, BHA_INTR_PORT);
328 			/* XXX Need to save this in the interrupt handler? */
329 			if (sts & BHA_INTR_HACC)
330 				break;
331 			delay(50);
332 		}
333 		if (!i) {
334 			printf("%s: bha_cmd, host not finished(0x%x)\n",
335 			    name, sts);
336 			return (1);
337 		}
338 	}
339 	bus_space_write_1(iot, ioh, BHA_CTRL_PORT, BHA_CTRL_IRST);
340 	return (0);
341 
342 bad:
343 	bus_space_write_1(iot, ioh, BHA_CTRL_PORT, BHA_CTRL_SRST);
344 	return (1);
345 }
346 
347 /*
348  * Attach all the sub-devices we can find
349  */
350 void
351 bha_attach(sc, bpd)
352 	struct bha_softc *sc;
353 	struct bha_probe_data *bpd;
354 {
355 
356 	/*
357 	 * fill in the prototype scsipi_link.
358 	 */
359 	sc->sc_link.scsipi_scsi.channel = SCSI_CHANNEL_ONLY_ONE;
360 	sc->sc_link.adapter_softc = sc;
361 	sc->sc_link.scsipi_scsi.adapter_target = bpd->sc_scsi_dev;
362 	sc->sc_link.adapter = &bha_switch;
363 	sc->sc_link.device = &bha_dev;
364 	sc->sc_link.openings = 4;
365 	sc->sc_link.scsipi_scsi.max_target = bpd->sc_iswide ? 15 : 7;
366 	sc->sc_link.type = BUS_SCSI;
367 
368 	TAILQ_INIT(&sc->sc_free_ccb);
369 	TAILQ_INIT(&sc->sc_waiting_ccb);
370 	LIST_INIT(&sc->sc_queue);
371 
372 	bha_inquire_setup_information(sc);
373 
374 	printf("%s: model BT-%s, firmware %s\n", sc->sc_dev.dv_xname,
375 	    sc->sc_model, sc->sc_firmware);
376 
377 	bha_init(sc);
378 
379 	/*
380 	 * ask the adapter what subunits are present
381 	 */
382 	config_found(&sc->sc_dev, &sc->sc_link, scsiprint);
383 }
384 
385 integrate void
386 bha_finish_ccbs(sc)
387 	struct bha_softc *sc;
388 {
389 	struct bha_mbx_in *wmbi;
390 	struct bha_ccb *ccb;
391 	int i;
392 
393 	wmbi = wmbx->tmbi;
394 
395 	if (wmbi->stat == BHA_MBI_FREE) {
396 		for (i = 0; i < BHA_MBX_SIZE; i++) {
397 			if (wmbi->stat != BHA_MBI_FREE) {
398 				printf("%s: mbi not in round-robin order\n",
399 				    sc->sc_dev.dv_xname);
400 				goto AGAIN;
401 			}
402 			bha_nextmbx(wmbi, wmbx, mbi);
403 		}
404 #ifdef BHADIAGnot
405 		printf("%s: mbi interrupt with no full mailboxes\n",
406 		    sc->sc_dev.dv_xname);
407 #endif
408 		return;
409 	}
410 
411 AGAIN:
412 	do {
413 		ccb = bha_ccb_phys_kv(sc, phystol(wmbi->ccb_addr));
414 		if (!ccb) {
415 			printf("%s: bad mbi ccb pointer; skipping\n",
416 			    sc->sc_dev.dv_xname);
417 			goto next;
418 		}
419 
420 #ifdef BHADEBUG
421 		if (bha_debug) {
422 			u_char *cp = &ccb->scsi_cmd;
423 			printf("op=%x %x %x %x %x %x\n",
424 			    cp[0], cp[1], cp[2], cp[3], cp[4], cp[5]);
425 			printf("stat %x for mbi addr = 0x%08x, ",
426 			    wmbi->stat, wmbi);
427 			printf("ccb addr = 0x%x\n", ccb);
428 		}
429 #endif /* BHADEBUG */
430 
431 		switch (wmbi->stat) {
432 		case BHA_MBI_OK:
433 		case BHA_MBI_ERROR:
434 			if ((ccb->flags & CCB_ABORT) != 0) {
435 				/*
436 				 * If we already started an abort, wait for it
437 				 * to complete before clearing the CCB.  We
438 				 * could instead just clear CCB_SENDING, but
439 				 * what if the mailbox was already received?
440 				 * The worst that happens here is that we clear
441 				 * the CCB a bit later than we need to.  BFD.
442 				 */
443 				goto next;
444 			}
445 			break;
446 
447 		case BHA_MBI_ABORT:
448 		case BHA_MBI_UNKNOWN:
449 			/*
450 			 * Even if the CCB wasn't found, we clear it anyway.
451 			 * See preceeding comment.
452 			 */
453 			break;
454 
455 		default:
456 			printf("%s: bad mbi status %02x; skipping\n",
457 			    sc->sc_dev.dv_xname, wmbi->stat);
458 			goto next;
459 		}
460 
461 		untimeout(bha_timeout, ccb);
462 		bha_done(sc, ccb);
463 
464 	next:
465 		wmbi->stat = BHA_MBI_FREE;
466 		bha_nextmbx(wmbi, wmbx, mbi);
467 	} while (wmbi->stat != BHA_MBI_FREE);
468 
469 	wmbx->tmbi = wmbi;
470 }
471 
472 /*
473  * Catch an interrupt from the adaptor
474  */
475 int
476 bha_intr(arg)
477 	void *arg;
478 {
479 	struct bha_softc *sc = arg;
480 	bus_space_tag_t iot = sc->sc_iot;
481 	bus_space_handle_t ioh = sc->sc_ioh;
482 	u_char sts;
483 
484 #ifdef BHADEBUG
485 	printf("%s: bha_intr ", sc->sc_dev.dv_xname);
486 #endif /* BHADEBUG */
487 
488 	/*
489 	 * First acknowlege the interrupt, Then if it's not telling about
490 	 * a completed operation just return.
491 	 */
492 	sts = bus_space_read_1(iot, ioh, BHA_INTR_PORT);
493 	if ((sts & BHA_INTR_ANYINTR) == 0)
494 		return (0);
495 	bus_space_write_1(iot, ioh, BHA_CTRL_PORT, BHA_CTRL_IRST);
496 
497 #ifdef BHADIAG
498 	/* Make sure we clear CCB_SENDING before finishing a CCB. */
499 	bha_collect_mbo(sc);
500 #endif
501 
502 	/* Mail box out empty? */
503 	if (sts & BHA_INTR_MBOA) {
504 		struct bha_toggle toggle;
505 
506 		toggle.cmd.opcode = BHA_MBO_INTR_EN;
507 		toggle.cmd.enable = 0;
508 		bha_cmd(iot, ioh, sc,
509 		    sizeof(toggle.cmd), (u_char *)&toggle.cmd,
510 		    0, (u_char *)0);
511 		bha_start_ccbs(sc);
512 	}
513 
514 	/* Mail box in full? */
515 	if (sts & BHA_INTR_MBIF)
516 		bha_finish_ccbs(sc);
517 
518 	return (1);
519 }
520 
521 integrate void
522 bha_reset_ccb(sc, ccb)
523 	struct bha_softc *sc;
524 	struct bha_ccb *ccb;
525 {
526 
527 	ccb->flags = 0;
528 }
529 
530 /*
531  * A ccb is put onto the free list.
532  */
533 void
534 bha_free_ccb(sc, ccb)
535 	struct bha_softc *sc;
536 	struct bha_ccb *ccb;
537 {
538 	int s;
539 
540 	s = splbio();
541 
542 	bha_reset_ccb(sc, ccb);
543 	TAILQ_INSERT_HEAD(&sc->sc_free_ccb, ccb, chain);
544 
545 	/*
546 	 * If there were none, wake anybody waiting for one to come free,
547 	 * starting with queued entries.
548 	 */
549 	if (ccb->chain.tqe_next == 0)
550 		wakeup(&sc->sc_free_ccb);
551 
552 	splx(s);
553 }
554 
555 integrate int
556 bha_init_ccb(sc, ccb)
557 	struct bha_softc *sc;
558 	struct bha_ccb *ccb;
559 {
560 	bus_dma_tag_t dmat = sc->sc_dmat;
561 	int hashnum, error;
562 
563 	/*
564 	 * XXX Should we put a DIAGNOSTIC check for multiple
565 	 * XXX CCB inits here?
566 	 */
567 
568 	bzero(ccb, sizeof(struct bha_ccb));
569 
570 	/*
571 	 * Create DMA maps for this CCB.
572 	 */
573 	error = bus_dmamap_create(dmat, sizeof(struct bha_ccb), 1,
574 	    sizeof(struct bha_ccb), 0, BUS_DMA_NOWAIT | sc->sc_dmaflags,
575 	    &ccb->dmamap_self);
576 	if (error) {
577 		printf("%s: can't create ccb dmamap_self\n",
578 		    sc->sc_dev.dv_xname);
579 		return (error);
580 	}
581 
582 	error = bus_dmamap_create(dmat, BHA_MAXXFER, BHA_NSEG, BHA_MAXXFER,
583 	    0, BUS_DMA_NOWAIT|BUS_DMA_ALLOCNOW | sc->sc_dmaflags,
584 	    &ccb->dmamap_xfer);
585 	if (error) {
586 		printf("%s: can't create ccb dmamap_xfer\n",
587 		    sc->sc_dev.dv_xname);
588 		bus_dmamap_destroy(dmat, ccb->dmamap_self);
589 		return (error);
590 	}
591 
592 	/*
593 	 * Load the permanent DMA maps.
594 	 */
595 	error = bus_dmamap_load(dmat, ccb->dmamap_self, ccb,
596 	    sizeof(struct bha_ccb), NULL, BUS_DMA_NOWAIT);
597 	if (error) {
598 		printf("%s: can't load ccb dmamap_self\n",
599 		    sc->sc_dev.dv_xname);
600 		bus_dmamap_destroy(dmat, ccb->dmamap_self);
601 		bus_dmamap_destroy(dmat, ccb->dmamap_xfer);
602 		return (error);
603 	}
604 
605 	/*
606 	 * put in the phystokv hash table
607 	 * Never gets taken out.
608 	 */
609 	ccb->hashkey = ccb->dmamap_self->dm_segs[0].ds_addr;
610 	hashnum = CCB_HASH(ccb->hashkey);
611 	ccb->nexthash = sc->sc_ccbhash[hashnum];
612 	sc->sc_ccbhash[hashnum] = ccb;
613 	bha_reset_ccb(sc, ccb);
614 	return (0);
615 }
616 
617 /*
618  * Create a set of ccbs and add them to the free list.
619  */
620 int
621 bha_create_ccbs(sc, mem, size, max_ccbs)
622 	struct bha_softc *sc;
623 	void *mem;
624 	size_t size;
625 	int max_ccbs;
626 {
627 	bus_dma_segment_t seg;
628 	struct bha_ccb *ccb;
629 	int rseg, error;
630 
631 	if (sc->sc_numccbs >= BHA_CCB_MAX)
632 		return (0);
633 
634 	if (max_ccbs > BHA_CCB_MAX)
635 		max_ccbs = BHA_CCB_MAX;
636 
637 	if ((ccb = mem) != NULL)
638 		goto have_mem;
639 
640 	size = NBPG;
641 	error = bus_dmamem_alloc(sc->sc_dmat, size, NBPG, 0, &seg, 1, &rseg,
642 	    BUS_DMA_NOWAIT);
643 	if (error) {
644 		printf("%s: can't allocate memory for ccbs\n",
645 		    sc->sc_dev.dv_xname);
646 		return (error);
647 	}
648 
649 	error = bus_dmamem_map(sc->sc_dmat, &seg, rseg, size,
650 	    (caddr_t *)&ccb, BUS_DMA_NOWAIT|BUS_DMAMEM_NOSYNC);
651 	if (error) {
652 		printf("%s: can't map memory for ccbs\n",
653 		    sc->sc_dev.dv_xname);
654 		bus_dmamem_free(sc->sc_dmat, &seg, rseg);
655 		return (error);
656 	}
657 
658  have_mem:
659 	bzero(ccb, size);
660 	while (size > sizeof(struct bha_ccb) && sc->sc_numccbs < max_ccbs) {
661 		error = bha_init_ccb(sc, ccb);
662 		if (error) {
663 			printf("%s: can't initialize ccb\n",
664 			    sc->sc_dev.dv_xname);
665 			return (error);
666 		}
667 		TAILQ_INSERT_TAIL(&sc->sc_free_ccb, ccb, chain);
668 		(caddr_t)ccb += ALIGN(sizeof(struct bha_ccb));
669 		size -= ALIGN(sizeof(struct bha_ccb));
670 		sc->sc_numccbs++;
671 	}
672 
673 	return (0);
674 }
675 
676 /*
677  * Get a free ccb
678  *
679  * If there are none, see if we can allocate a new one.  If so, put it in
680  * the hash table too otherwise either return an error or sleep.
681  */
682 struct bha_ccb *
683 bha_get_ccb(sc, flags)
684 	struct bha_softc *sc;
685 	int flags;
686 {
687 	struct bha_ccb *ccb;
688 	int s;
689 
690 	s = splbio();
691 
692 	/*
693 	 * If we can and have to, sleep waiting for one to come free
694 	 * but only if we can't allocate a new one.
695 	 */
696 	for (;;) {
697 		ccb = sc->sc_free_ccb.tqh_first;
698 		if (ccb) {
699 			TAILQ_REMOVE(&sc->sc_free_ccb, ccb, chain);
700 			break;
701 		}
702 		if (sc->sc_numccbs < BHA_CCB_MAX) {
703 			/*
704 			 * bha_create_ccbs() might have managed to create
705 			 * one before it failed.  If so, don't abort,
706 			 * just grab it and continue to hobble along.
707 			 */
708 			if (bha_create_ccbs(sc, NULL, 0, BHA_CCB_MAX) != 0 &&
709 			    sc->sc_free_ccb.tqh_first == NULL) {
710 				printf("%s: can't allocate ccbs\n",
711 				    sc->sc_dev.dv_xname);
712 				goto out;
713 			}
714 			continue;
715 		}
716 		if ((flags & SCSI_NOSLEEP) != 0)
717 			goto out;
718 		tsleep(&sc->sc_free_ccb, PRIBIO, "bhaccb", 0);
719 	}
720 
721 	ccb->flags |= CCB_ALLOC;
722 
723 out:
724 	splx(s);
725 	return (ccb);
726 }
727 
728 /*
729  * Given a physical address, find the ccb that it corresponds to.
730  */
731 struct bha_ccb *
732 bha_ccb_phys_kv(sc, ccb_phys)
733 	struct bha_softc *sc;
734 	u_long ccb_phys;
735 {
736 	int hashnum = CCB_HASH(ccb_phys);
737 	struct bha_ccb *ccb = sc->sc_ccbhash[hashnum];
738 
739 	while (ccb) {
740 		if (ccb->hashkey == ccb_phys)
741 			break;
742 		ccb = ccb->nexthash;
743 	}
744 	return (ccb);
745 }
746 
747 /*
748  * Queue a CCB to be sent to the controller, and send it if possible.
749  */
750 void
751 bha_queue_ccb(sc, ccb)
752 	struct bha_softc *sc;
753 	struct bha_ccb *ccb;
754 {
755 
756 	TAILQ_INSERT_TAIL(&sc->sc_waiting_ccb, ccb, chain);
757 	bha_start_ccbs(sc);
758 }
759 
760 /*
761  * Garbage collect mailboxes that are no longer in use.
762  */
763 void
764 bha_collect_mbo(sc)
765 	struct bha_softc *sc;
766 {
767 	struct bha_mbx_out *wmbo;	/* Mail Box Out pointer */
768 #ifdef BHADIAG
769 	struct bha_ccb *ccb;
770 #endif
771 
772 	wmbo = wmbx->cmbo;
773 
774 	while (sc->sc_mbofull > 0) {
775 		if (wmbo->cmd != BHA_MBO_FREE)
776 			break;
777 
778 #ifdef BHADIAG
779 		ccb = bha_ccb_phys_kv(sc, phystol(wmbo->ccb_addr));
780 		ccb->flags &= ~CCB_SENDING;
781 #endif
782 
783 		--sc->sc_mbofull;
784 		bha_nextmbx(wmbo, wmbx, mbo);
785 	}
786 
787 	wmbx->cmbo = wmbo;
788 }
789 
790 /*
791  * Send as many CCBs as we have empty mailboxes for.
792  */
793 void
794 bha_start_ccbs(sc)
795 	struct bha_softc *sc;
796 {
797 	bus_space_tag_t iot = sc->sc_iot;
798 	bus_space_handle_t ioh = sc->sc_ioh;
799 	struct bha_mbx_out *wmbo;	/* Mail Box Out pointer */
800 	struct bha_ccb *ccb;
801 
802 	wmbo = wmbx->tmbo;
803 
804 	while ((ccb = sc->sc_waiting_ccb.tqh_first) != NULL) {
805 		if (sc->sc_mbofull >= BHA_MBX_SIZE) {
806 			bha_collect_mbo(sc);
807 			if (sc->sc_mbofull >= BHA_MBX_SIZE) {
808 				struct bha_toggle toggle;
809 
810 				toggle.cmd.opcode = BHA_MBO_INTR_EN;
811 				toggle.cmd.enable = 1;
812 				bha_cmd(iot, ioh, sc,
813 				    sizeof(toggle.cmd), (u_char *)&toggle.cmd,
814 				    0, (u_char *)0);
815 				break;
816 			}
817 		}
818 
819 		TAILQ_REMOVE(&sc->sc_waiting_ccb, ccb, chain);
820 #ifdef BHADIAG
821 		ccb->flags |= CCB_SENDING;
822 #endif
823 
824 		/* Link ccb to mbo. */
825 		ltophys(ccb->dmamap_self->dm_segs[0].ds_addr, wmbo->ccb_addr);
826 		if (ccb->flags & CCB_ABORT)
827 			wmbo->cmd = BHA_MBO_ABORT;
828 		else
829 			wmbo->cmd = BHA_MBO_START;
830 
831 		/* Tell the card to poll immediately. */
832 		bus_space_write_1(iot, ioh, BHA_CMD_PORT, BHA_START_SCSI);
833 
834 		if ((ccb->xs->flags & SCSI_POLL) == 0)
835 			timeout(bha_timeout, ccb, (ccb->timeout * hz) / 1000);
836 
837 		++sc->sc_mbofull;
838 		bha_nextmbx(wmbo, wmbx, mbo);
839 	}
840 
841 	wmbx->tmbo = wmbo;
842 }
843 
844 /*
845  * We have a ccb which has been processed by the
846  * adaptor, now we look to see how the operation
847  * went. Wake up the owner if waiting
848  */
849 void
850 bha_done(sc, ccb)
851 	struct bha_softc *sc;
852 	struct bha_ccb *ccb;
853 {
854 	bus_dma_tag_t dmat = sc->sc_dmat;
855 	struct scsipi_sense_data *s1, *s2;
856 	struct scsipi_xfer *xs = ccb->xs;
857 
858 	SC_DEBUG(xs->sc_link, SDEV_DB2, ("bha_done\n"));
859 
860 	/*
861 	 * If we were a data transfer, unload the map that described
862 	 * the data buffer.
863 	 */
864 	if (xs->datalen) {
865 		bus_dmamap_sync(dmat, ccb->dmamap_xfer,
866 		    (xs->flags & SCSI_DATA_IN) ? BUS_DMASYNC_POSTREAD :
867 		    BUS_DMASYNC_POSTWRITE);
868 		bus_dmamap_unload(dmat, ccb->dmamap_xfer);
869 	}
870 
871 	/*
872 	 * Otherwise, put the results of the operation
873 	 * into the xfer and call whoever started it
874 	 */
875 #ifdef BHADIAG
876 	if (ccb->flags & CCB_SENDING) {
877 		printf("%s: exiting ccb still in transit!\n",
878 		    sc->sc_dev.dv_xname);
879 		Debugger();
880 		return;
881 	}
882 #endif
883 	if ((ccb->flags & CCB_ALLOC) == 0) {
884 		printf("%s: exiting ccb not allocated!\n",
885 		    sc->sc_dev.dv_xname);
886 		Debugger();
887 		return;
888 	}
889 	if (xs->error == XS_NOERROR) {
890 		if (ccb->host_stat != BHA_OK) {
891 			switch (ccb->host_stat) {
892 			case BHA_SEL_TIMEOUT:	/* No response */
893 				xs->error = XS_SELTIMEOUT;
894 				break;
895 			default:	/* Other scsi protocol messes */
896 				printf("%s: host_stat %x\n",
897 				    sc->sc_dev.dv_xname, ccb->host_stat);
898 				xs->error = XS_DRIVER_STUFFUP;
899 				break;
900 			}
901 		} else if (ccb->target_stat != SCSI_OK) {
902 			switch (ccb->target_stat) {
903 			case SCSI_CHECK:
904 				s1 = &ccb->scsi_sense;
905 				s2 = &xs->sense.scsi_sense;
906 				*s2 = *s1;
907 				xs->error = XS_SENSE;
908 				break;
909 			case SCSI_BUSY:
910 				xs->error = XS_BUSY;
911 				break;
912 			default:
913 				printf("%s: target_stat %x\n",
914 				    sc->sc_dev.dv_xname, ccb->target_stat);
915 				xs->error = XS_DRIVER_STUFFUP;
916 				break;
917 			}
918 		} else
919 			xs->resid = 0;
920 	}
921 	bha_free_ccb(sc, ccb);
922 	xs->flags |= ITSDONE;
923 	scsipi_done(xs);
924 
925 	/*
926 	 * If there are queue entries in the software queue, try to
927 	 * run the first one.  We should be more or less guaranteed
928 	 * to succeed, since we just freed a CCB.
929 	 *
930 	 * NOTE: bha_scsi_cmd() relies on our calling it with
931 	 * the first entry in the queue.
932 	 */
933 	if ((xs = sc->sc_queue.lh_first) != NULL)
934 		(void) bha_scsi_cmd(xs);
935 }
936 
937 /*
938  * Find the board and find it's irq/drq
939  */
940 int
941 bha_find(iot, ioh, sc)
942 	bus_space_tag_t iot;
943 	bus_space_handle_t ioh;
944 	struct bha_probe_data *sc;
945 {
946 	int i, iswide;
947 	u_char sts;
948 	struct bha_extended_inquire inquire;
949 	struct bha_config config;
950 	int irq, drq;
951 
952 	/* Check something is at the ports we need to access */
953 	sts = bus_space_read_1(iot, ioh, BHA_STAT_PORT);
954 	if (sts == 0xFF)
955 		return (0);
956 
957 	/*
958 	 * Reset board, If it doesn't respond, assume
959 	 * that it's not there.. good for the probe
960 	 */
961 
962 	bus_space_write_1(iot, ioh, BHA_CTRL_PORT,
963 	    BHA_CTRL_HRST | BHA_CTRL_SRST);
964 
965 	delay(100);
966 	for (i = BHA_RESET_TIMEOUT; i; i--) {
967 		sts = bus_space_read_1(iot, ioh, BHA_STAT_PORT);
968 		if (sts == (BHA_STAT_IDLE | BHA_STAT_INIT))
969 			break;
970 		delay(1000);
971 	}
972 	if (!i) {
973 #ifdef BHADEBUG
974 		if (bha_debug)
975 			printf("bha_find: No answer from buslogic board\n");
976 #endif /* BHADEBUG */
977 		return (0);
978 	}
979 
980 	/*
981 	 * The BusLogic cards implement an Adaptec 1542 (aha)-compatible
982 	 * interface. The native bha interface is not compatible with
983 	 * an aha. 1542. We need to ensure that we never match an
984 	 * Adaptec 1542. We must also avoid sending Adaptec-compatible
985 	 * commands to a real bha, lest it go into 1542 emulation mode.
986 	 * (On an indirect bus like ISA, we should always probe for BusLogic
987 	 * interfaces  before Adaptec interfaces).
988 	 */
989 
990 	/*
991 	 * Make sure we don't match an AHA-1542A or AHA-1542B, by checking
992 	 * for an extended-geometry register.  The 1542[AB] don't have one.
993 	 */
994 	sts = bus_space_read_1(iot, ioh, BHA_EXTGEOM_PORT);
995 	if (sts == 0xFF)
996 		return (0);
997 
998 	/*
999 	 * Check that we actually know how to use this board.
1000 	 */
1001 	delay(1000);
1002 	inquire.cmd.opcode = BHA_INQUIRE_EXTENDED;
1003 	inquire.cmd.len = sizeof(inquire.reply);
1004 	i = bha_cmd(iot, ioh, (struct bha_softc *)0,
1005 	    sizeof(inquire.cmd), (u_char *)&inquire.cmd,
1006 	    sizeof(inquire.reply), (u_char *)&inquire.reply);
1007 
1008 	/*
1009 	 * Some 1542Cs (CP, perhaps not CF, may depend on firmware rev)
1010 	 * have the extended-geometry register and also respond to
1011 	 * BHA_INQUIRE_EXTENDED.  Make sure we never  match such cards,
1012 	 * by checking the size of the reply is what a BusLogic card returns.
1013 	 */
1014 	if (i) {
1015 #ifdef BHADEBUG
1016 		printf("bha_find: board returned %d instead of %d to %s\n",
1017 		       i, sizeof(inquire.reply), "INQUIRE_EXTENDED");
1018 #endif
1019 		return (0);
1020 	}
1021 
1022 	/* OK, we know we've found a buslogic adaptor. */
1023 
1024 	switch (inquire.reply.bus_type) {
1025 	case BHA_BUS_TYPE_24BIT:
1026 	case BHA_BUS_TYPE_32BIT:
1027 		break;
1028 	case BHA_BUS_TYPE_MCA:
1029 		/* We don't grok MicroChannel (yet). */
1030 		return (0);
1031 	default:
1032 		printf("bha_find: illegal bus type %c\n",
1033 		    inquire.reply.bus_type);
1034 		return (0);
1035 	}
1036 
1037 	/* Note if we have a wide bus. */
1038 	iswide = inquire.reply.scsi_flags & BHA_SCSI_WIDE;
1039 
1040 	/*
1041 	 * Assume we have a board at this stage setup dma channel from
1042 	 * jumpers and save int level
1043 	 */
1044 	delay(1000);
1045 	config.cmd.opcode = BHA_INQUIRE_CONFIG;
1046 	bha_cmd(iot, ioh, (struct bha_softc *)0,
1047 	    sizeof(config.cmd), (u_char *)&config.cmd,
1048 	    sizeof(config.reply), (u_char *)&config.reply);
1049 	switch (config.reply.chan) {
1050 	case EISADMA:
1051 		drq = -1;
1052 		break;
1053 	case CHAN0:
1054 		drq = 0;
1055 		break;
1056 	case CHAN5:
1057 		drq = 5;
1058 		break;
1059 	case CHAN6:
1060 		drq = 6;
1061 		break;
1062 	case CHAN7:
1063 		drq = 7;
1064 		break;
1065 	default:
1066 		printf("bha_find: illegal drq setting %x\n",
1067 		    config.reply.chan);
1068 		return (0);
1069 	}
1070 
1071 	switch (config.reply.intr) {
1072 	case INT9:
1073 		irq = 9;
1074 		break;
1075 	case INT10:
1076 		irq = 10;
1077 		break;
1078 	case INT11:
1079 		irq = 11;
1080 		break;
1081 	case INT12:
1082 		irq = 12;
1083 		break;
1084 	case INT14:
1085 		irq = 14;
1086 		break;
1087 	case INT15:
1088 		irq = 15;
1089 		break;
1090 	default:
1091 		printf("bha_find: illegal irq setting %x\n",
1092 		    config.reply.intr);
1093 		return (0);
1094 	}
1095 
1096 	/* if we want to fill in softc, do so now */
1097 	if (sc != NULL) {
1098 		sc->sc_irq = irq;
1099 		sc->sc_drq = drq;
1100 		sc->sc_scsi_dev = config.reply.scsi_dev;
1101 		sc->sc_iswide = iswide;
1102 	}
1103 
1104 	return (1);
1105 }
1106 
1107 
1108 /*
1109  * Disable the ISA-compatiblity ioports on  PCI bha devices,
1110  * to ensure they're not autoconfigured a second time as an ISA bha.
1111  */
1112 int
1113 bha_disable_isacompat(sc)
1114 	struct bha_softc *sc;
1115 {
1116 	struct bha_isadisable isa_disable;
1117 
1118 	isa_disable.cmd.opcode = BHA_MODIFY_IOPORT;
1119 	isa_disable.cmd.modifier = BHA_IOMODIFY_DISABLE1;
1120 	bha_cmd(sc->sc_iot, sc->sc_ioh, sc,
1121 	    sizeof(isa_disable.cmd), (u_char*)&isa_disable.cmd,
1122 	    0, (u_char *)0);
1123 	return (0);
1124 }
1125 
1126 
1127 /*
1128  * Start the board, ready for normal operation
1129  */
1130 void
1131 bha_init(sc)
1132 	struct bha_softc *sc;
1133 {
1134 	bus_space_tag_t iot = sc->sc_iot;
1135 	bus_space_handle_t ioh = sc->sc_ioh;
1136 	bus_dma_segment_t seg;
1137 	struct bha_devices devices;
1138 	struct bha_setup setup;
1139 	struct bha_mailbox mailbox;
1140 	struct bha_period period;
1141 	int i, j, initial_ccbs, rlen, rseg;
1142 
1143 	/* Enable round-robin scheme - appeared at firmware rev. 3.31. */
1144 	if (strcmp(sc->sc_firmware, "3.31") >= 0) {
1145 		struct bha_toggle toggle;
1146 
1147 		toggle.cmd.opcode = BHA_ROUND_ROBIN;
1148 		toggle.cmd.enable = 1;
1149 		bha_cmd(iot, ioh, sc,
1150 		    sizeof(toggle.cmd), (u_char *)&toggle.cmd,
1151 		    0, (u_char *)0);
1152 	}
1153 
1154 	/*
1155 	 * Inquire installed devices (to force synchronous negotiation).
1156 	 */
1157 
1158 	/*
1159 	 * Poll targets 0 - 7.
1160 	 */
1161 	devices.cmd.opcode = BHA_INQUIRE_DEVICES;
1162 	bha_cmd(iot, ioh, sc,
1163 	    sizeof(devices.cmd), (u_char *)&devices.cmd,
1164 	    sizeof(devices.reply), (u_char *)&devices.reply);
1165 
1166 	/* Count installed units. */
1167 	initial_ccbs = 0;
1168 	for (i = 0; i < 8; i++) {
1169 		for (j = 0; j < 8; j++) {
1170 			if (((devices.reply.lun_map[i] >> j) & 1) == 1)
1171 				initial_ccbs++;
1172 		}
1173 	}
1174 
1175 	/*
1176 	 * Poll targets 8 - 15 if we have a wide bus.
1177 	 */
1178 	if (ISWIDE(sc)) {
1179 		devices.cmd.opcode = BHA_INQUIRE_DEVICES_2;
1180 		bha_cmd(iot, ioh, sc,
1181 		    sizeof(devices.cmd), (u_char *)&devices.cmd,
1182 		    sizeof(devices.reply), (u_char *)&devices.reply);
1183 
1184 		for (i = 0; i < 8; i++) {
1185 			for (j = 0; j < 8; j++) {
1186 				if (((devices.reply.lun_map[i] >> j) & 1) == 1)
1187 					initial_ccbs++;
1188 			}
1189 		}
1190 	}
1191 
1192 	initial_ccbs *= sc->sc_link.openings;
1193 
1194 	/* Obtain setup information from. */
1195 	rlen = sizeof(setup.reply) +
1196 	    (ISWIDE(sc) ? sizeof(setup.reply_w) : 0);
1197 	setup.cmd.opcode = BHA_INQUIRE_SETUP;
1198 	setup.cmd.len = rlen;
1199 	bha_cmd(iot, ioh, sc,
1200 	    sizeof(setup.cmd), (u_char *)&setup.cmd,
1201 	    rlen, (u_char *)&setup.reply);
1202 
1203 	printf("%s: %s, %s\n",
1204 	    sc->sc_dev.dv_xname,
1205 	    setup.reply.sync_neg ? "sync" : "async",
1206 	    setup.reply.parity ? "parity" : "no parity");
1207 
1208 	for (i = 0; i < 8; i++)
1209 		period.reply.period[i] = setup.reply.sync[i].period * 5 + 20;
1210 	if (ISWIDE(sc)) {
1211 		for (i = 0; i < 8; i++)
1212 			period.reply_w.period[i] =
1213 			    setup.reply_w.sync[i].period * 5 + 20;
1214 	}
1215 
1216 	if (sc->sc_firmware[0] >= '3') {
1217 		rlen = sizeof(period.reply) +
1218 		    (ISWIDE(sc) ? sizeof(period.reply_w) : 0);
1219 		period.cmd.opcode = BHA_INQUIRE_PERIOD;
1220 		period.cmd.len = rlen;
1221 		bha_cmd(iot, ioh, sc,
1222 		    sizeof(period.cmd), (u_char *)&period.cmd,
1223 		    rlen, (u_char *)&period.reply);
1224 	}
1225 
1226 	for (i = 0; i < 8; i++) {
1227 		if (!setup.reply.sync[i].valid ||
1228 		    (!setup.reply.sync[i].offset &&
1229 		     !setup.reply.sync[i].period))
1230 			continue;
1231 		printf("%s targ %d: sync, offset %d, period %dnsec\n",
1232 		    sc->sc_dev.dv_xname, i,
1233 		    setup.reply.sync[i].offset, period.reply.period[i] * 10);
1234 	}
1235 	if (ISWIDE(sc)) {
1236 		for (i = 0; i < 8; i++) {
1237 			if (!setup.reply_w.sync[i].valid ||
1238 			    (!setup.reply_w.sync[i].offset &&
1239 			     !setup.reply_w.sync[i].period))
1240 				continue;
1241 			printf("%s targ %d: sync, offset %d, period %dnsec\n",
1242 			    sc->sc_dev.dv_xname, i + 8,
1243 			    setup.reply_w.sync[i].offset,
1244 			    period.reply_w.period[i] * 10);
1245 		}
1246 	}
1247 
1248 	/*
1249 	 * Allocate the mailbox.
1250 	 */
1251 	if (bus_dmamem_alloc(sc->sc_dmat, NBPG, NBPG, 0, &seg, 1,
1252 	    &rseg, BUS_DMA_NOWAIT) ||
1253 	    bus_dmamem_map(sc->sc_dmat, &seg, rseg, NBPG,
1254 	    (caddr_t *)&wmbx, BUS_DMA_NOWAIT|BUS_DMAMEM_NOSYNC))
1255 		panic("bha_init: can't create or map mailbox");
1256 
1257 	/*
1258 	 * Since DMA memory allocation is always rounded up to a
1259 	 * page size, create some ccbs from the leftovers.
1260 	 */
1261 	if (bha_create_ccbs(sc, ((caddr_t)wmbx) +
1262 	    ALIGN(sizeof(struct bha_mbx)),
1263 	    NBPG - ALIGN(sizeof(struct bha_mbx)), initial_ccbs))
1264 		panic("bha_init: can't create ccbs");
1265 
1266 	/*
1267 	 * Create and load the mailbox DMA map.
1268 	 */
1269 	if (bus_dmamap_create(sc->sc_dmat, sizeof(struct bha_mbx), 1,
1270 	    sizeof(struct bha_mbx), 0, BUS_DMA_NOWAIT | sc->sc_dmaflags,
1271 	    &sc->sc_dmamap_mbox) ||
1272 	    bus_dmamap_load(sc->sc_dmat, sc->sc_dmamap_mbox, wmbx,
1273 	    sizeof(struct bha_mbx), NULL, BUS_DMA_NOWAIT))
1274 		panic("bha_init: can't create or load mailbox dma map");
1275 
1276 	/*
1277 	 * Set up initial mail box for round-robin operation.
1278 	 */
1279 	for (i = 0; i < BHA_MBX_SIZE; i++) {
1280 		wmbx->mbo[i].cmd = BHA_MBO_FREE;
1281 		wmbx->mbi[i].stat = BHA_MBI_FREE;
1282 	}
1283 	wmbx->cmbo = wmbx->tmbo = &wmbx->mbo[0];
1284 	wmbx->tmbi = &wmbx->mbi[0];
1285 	sc->sc_mbofull = 0;
1286 
1287 	/* Initialize mail box. */
1288 	mailbox.cmd.opcode = BHA_MBX_INIT_EXTENDED;
1289 	mailbox.cmd.nmbx = BHA_MBX_SIZE;
1290 	ltophys(sc->sc_dmamap_mbox->dm_segs[0].ds_addr, mailbox.cmd.addr);
1291 	bha_cmd(iot, ioh, sc,
1292 	    sizeof(mailbox.cmd), (u_char *)&mailbox.cmd,
1293 	    0, (u_char *)0);
1294 }
1295 
1296 void
1297 bha_inquire_setup_information(sc)
1298 	struct bha_softc *sc;
1299 {
1300 	bus_space_tag_t iot = sc->sc_iot;
1301 	bus_space_handle_t ioh = sc->sc_ioh;
1302 	struct bha_model model;
1303 	struct bha_revision revision;
1304 	struct bha_digit digit;
1305 	char *p;
1306 
1307 	/*
1308 	 * Get the firmware revision.
1309 	 */
1310 	p = sc->sc_firmware;
1311 	revision.cmd.opcode = BHA_INQUIRE_REVISION;
1312 	bha_cmd(iot, ioh, sc,
1313 	    sizeof(revision.cmd), (u_char *)&revision.cmd,
1314 	    sizeof(revision.reply), (u_char *)&revision.reply);
1315 	*p++ = revision.reply.firm_revision;
1316 	*p++ = '.';
1317 	*p++ = revision.reply.firm_version;
1318 	digit.cmd.opcode = BHA_INQUIRE_REVISION_3;
1319 	bha_cmd(iot, ioh, sc,
1320 	    sizeof(digit.cmd), (u_char *)&digit.cmd,
1321 	    sizeof(digit.reply), (u_char *)&digit.reply);
1322 	*p++ = digit.reply.digit;
1323 	if (revision.reply.firm_revision >= '3' ||
1324 	    (revision.reply.firm_revision == '3' &&
1325 	     revision.reply.firm_version >= '3')) {
1326 		digit.cmd.opcode = BHA_INQUIRE_REVISION_4;
1327 		bha_cmd(iot, ioh, sc,
1328 		    sizeof(digit.cmd), (u_char *)&digit.cmd,
1329 		    sizeof(digit.reply), (u_char *)&digit.reply);
1330 		*p++ = digit.reply.digit;
1331 	}
1332 	while (p > sc->sc_firmware && (p[-1] == ' ' || p[-1] == '\0'))
1333 		p--;
1334 	*p = '\0';
1335 
1336 	/*
1337 	 * Get the model number.
1338 	 */
1339 	if (revision.reply.firm_revision >= '3') {
1340 		p = sc->sc_model;
1341 		model.cmd.opcode = BHA_INQUIRE_MODEL;
1342 		model.cmd.len = sizeof(model.reply);
1343 		bha_cmd(iot, ioh, sc,
1344 		    sizeof(model.cmd), (u_char *)&model.cmd,
1345 		    sizeof(model.reply), (u_char *)&model.reply);
1346 		*p++ = model.reply.id[0];
1347 		*p++ = model.reply.id[1];
1348 		*p++ = model.reply.id[2];
1349 		*p++ = model.reply.id[3];
1350 		while (p > sc->sc_model && (p[-1] == ' ' || p[-1] == '\0'))
1351 			p--;
1352 		*p++ = model.reply.version[0];
1353 		*p++ = model.reply.version[1];
1354 		while (p > sc->sc_model && (p[-1] == ' ' || p[-1] == '\0'))
1355 			p--;
1356 		*p = '\0';
1357 	} else
1358 		strcpy(sc->sc_model, "542B");
1359 }
1360 
1361 void
1362 bhaminphys(bp)
1363 	struct buf *bp;
1364 {
1365 
1366 	if (bp->b_bcount > BHA_MAXXFER)
1367 		bp->b_bcount = BHA_MAXXFER;
1368 	minphys(bp);
1369 }
1370 
1371 /*
1372  * start a scsi operation given the command and the data address.  Also needs
1373  * the unit, target and lu.
1374  */
1375 int
1376 bha_scsi_cmd(xs)
1377 	struct scsipi_xfer *xs;
1378 {
1379 	struct scsipi_link *sc_link = xs->sc_link;
1380 	struct bha_softc *sc = sc_link->adapter_softc;
1381 	bus_dma_tag_t dmat = sc->sc_dmat;
1382 	struct bha_ccb *ccb;
1383 	int error, seg, flags, s;
1384 	int fromqueue = 0, dontqueue = 0;
1385 
1386 	SC_DEBUG(sc_link, SDEV_DB2, ("bha_scsi_cmd\n"));
1387 
1388 	s = splbio();		/* protect the queue */
1389 
1390 	/*
1391 	 * If we're running the queue from bha_done(), we've been
1392 	 * called with the first queue entry as our argument.
1393 	 */
1394 	if (xs == sc->sc_queue.lh_first) {
1395 		xs = bha_dequeue(sc);
1396 		fromqueue = 1;
1397 		goto get_ccb;
1398 	}
1399 
1400 	/* Polled requests can't be queued for later. */
1401 	dontqueue = xs->flags & SCSI_POLL;
1402 
1403 	/*
1404 	 * If there are jobs in the queue, run them first.
1405 	 */
1406 	if (sc->sc_queue.lh_first != NULL) {
1407 		/*
1408 		 * If we can't queue, we have to abort, since
1409 		 * we have to preserve order.
1410 		 */
1411 		if (dontqueue) {
1412 			splx(s);
1413 			xs->error = XS_DRIVER_STUFFUP;
1414 			return (TRY_AGAIN_LATER);
1415 		}
1416 
1417 		/*
1418 		 * Swap with the first queue entry.
1419 		 */
1420 		bha_enqueue(sc, xs, 0);
1421 		xs = bha_dequeue(sc);
1422 		fromqueue = 1;
1423 	}
1424 
1425  get_ccb:
1426 	/*
1427 	 * get a ccb to use. If the transfer
1428 	 * is from a buf (possibly from interrupt time)
1429 	 * then we can't allow it to sleep
1430 	 */
1431 	flags = xs->flags;
1432 	if ((ccb = bha_get_ccb(sc, flags)) == NULL) {
1433 		/*
1434 		 * If we can't queue, we lose.
1435 		 */
1436 		if (dontqueue) {
1437 			splx(s);
1438 			xs->error = XS_DRIVER_STUFFUP;
1439 			return (TRY_AGAIN_LATER);
1440 		}
1441 
1442 		/*
1443 		 * Stuff ourselves into the queue, in front
1444 		 * if we came off in the first place.
1445 		 */
1446 		bha_enqueue(sc, xs, fromqueue);
1447 		splx(s);
1448 		return (SUCCESSFULLY_QUEUED);
1449 	}
1450 
1451 	splx(s);		/* done playing with the queue */
1452 
1453 	ccb->xs = xs;
1454 	ccb->timeout = xs->timeout;
1455 
1456 	/*
1457 	 * Put all the arguments for the xfer in the ccb
1458 	 */
1459 	if (flags & SCSI_RESET) {
1460 		ccb->opcode = BHA_RESET_CCB;
1461 		ccb->scsi_cmd_length = 0;
1462 	} else {
1463 		/* can't use S/G if zero length */
1464 		ccb->opcode = (xs->datalen ? BHA_INIT_SCAT_GATH_CCB
1465 					   : BHA_INITIATOR_CCB);
1466 		bcopy(xs->cmd, &ccb->scsi_cmd,
1467 		    ccb->scsi_cmd_length = xs->cmdlen);
1468 	}
1469 
1470 	if (xs->datalen) {
1471 		/*
1472 		 * Map the DMA transfer.
1473 		 */
1474 #ifdef TFS
1475 		if (flags & SCSI_DATA_UIO) {
1476 			error = bus_dmamap_load_uio(dmat,
1477 			    ccb->dmamap_xfer, (struct uio *)xs->data,
1478 			    (flags & SCSI_NOSLEEP) ? BUS_DMA_NOWAIT :
1479 			    BUS_DMA_WAITOK);
1480 		} else
1481 #endif /* TFS */
1482 		{
1483 			error = bus_dmamap_load(dmat,
1484 			    ccb->dmamap_xfer, xs->data, xs->datalen, NULL,
1485 			    (flags & SCSI_NOSLEEP) ? BUS_DMA_NOWAIT :
1486 			    BUS_DMA_WAITOK);
1487 		}
1488 
1489 		if (error) {
1490 			if (error == EFBIG) {
1491 				printf("%s: bha_scsi_cmd, more than %d"
1492 				    " dma segments\n",
1493 				    sc->sc_dev.dv_xname, BHA_NSEG);
1494 			} else {
1495 				printf("%s: bha_scsi_cmd, error %d loading"
1496 				    " dma map\n",
1497 				    sc->sc_dev.dv_xname, error);
1498 			}
1499 			goto bad;
1500 		}
1501 
1502 		bus_dmamap_sync(dmat, ccb->dmamap_xfer,
1503 		    (flags & SCSI_DATA_IN) ? BUS_DMASYNC_PREREAD :
1504 		    BUS_DMASYNC_PREWRITE);
1505 
1506 		/*
1507 		 * Load the hardware scatter/gather map with the
1508 		 * contents of the DMA map.
1509 		 */
1510 		for (seg = 0; seg < ccb->dmamap_xfer->dm_nsegs; seg++) {
1511 			ltophys(ccb->dmamap_xfer->dm_segs[seg].ds_addr,
1512 			    ccb->scat_gath[seg].seg_addr);
1513 			ltophys(ccb->dmamap_xfer->dm_segs[seg].ds_len,
1514 			    ccb->scat_gath[seg].seg_len);
1515 		}
1516 
1517 		ltophys(ccb->dmamap_self->dm_segs[0].ds_addr +
1518 		    offsetof(struct bha_ccb, scat_gath), ccb->data_addr);
1519 		ltophys(ccb->dmamap_xfer->dm_nsegs *
1520 		    sizeof(struct bha_scat_gath), ccb->data_length);
1521 	} else {
1522 		/*
1523 		 * No data xfer, use non S/G values.
1524 		 */
1525 		ltophys(0, ccb->data_addr);
1526 		ltophys(0, ccb->data_length);
1527 	}
1528 
1529 	ccb->data_out = 0;
1530 	ccb->data_in = 0;
1531 	ccb->target = sc_link->scsipi_scsi.target;
1532 	ccb->lun = sc_link->scsipi_scsi.lun;
1533 	ltophys(ccb->dmamap_self->dm_segs[0].ds_addr +
1534 	    offsetof(struct bha_ccb, scsi_sense), ccb->sense_ptr);
1535 	ccb->req_sense_length = sizeof(ccb->scsi_sense);
1536 	ccb->host_stat = 0x00;
1537 	ccb->target_stat = 0x00;
1538 	ccb->link_id = 0;
1539 	ltophys(0, ccb->link_addr);
1540 
1541 	s = splbio();
1542 	bha_queue_ccb(sc, ccb);
1543 	splx(s);
1544 
1545 	/*
1546 	 * Usually return SUCCESSFULLY QUEUED
1547 	 */
1548 	SC_DEBUG(sc_link, SDEV_DB3, ("cmd_sent\n"));
1549 	if ((flags & SCSI_POLL) == 0)
1550 		return (SUCCESSFULLY_QUEUED);
1551 
1552 	/*
1553 	 * If we can't use interrupts, poll on completion
1554 	 */
1555 	if (bha_poll(sc, xs, ccb->timeout)) {
1556 		bha_timeout(ccb);
1557 		if (bha_poll(sc, xs, ccb->timeout))
1558 			bha_timeout(ccb);
1559 	}
1560 	return (COMPLETE);
1561 
1562 bad:
1563 	xs->error = XS_DRIVER_STUFFUP;
1564 	bha_free_ccb(sc, ccb);
1565 	return (COMPLETE);
1566 }
1567 
1568 /*
1569  * Poll a particular unit, looking for a particular xs
1570  */
1571 int
1572 bha_poll(sc, xs, count)
1573 	struct bha_softc *sc;
1574 	struct scsipi_xfer *xs;
1575 	int count;
1576 {
1577 	bus_space_tag_t iot = sc->sc_iot;
1578 	bus_space_handle_t ioh = sc->sc_ioh;
1579 
1580 	/* timeouts are in msec, so we loop in 1000 usec cycles */
1581 	while (count) {
1582 		/*
1583 		 * If we had interrupts enabled, would we
1584 		 * have got an interrupt?
1585 		 */
1586 		if (bus_space_read_1(iot, ioh, BHA_INTR_PORT) &
1587 		    BHA_INTR_ANYINTR)
1588 			bha_intr(sc);
1589 		if (xs->flags & ITSDONE)
1590 			return (0);
1591 		delay(1000);	/* only happens in boot so ok */
1592 		count--;
1593 	}
1594 	return (1);
1595 }
1596 
1597 void
1598 bha_timeout(arg)
1599 	void *arg;
1600 {
1601 	struct bha_ccb *ccb = arg;
1602 	struct scsipi_xfer *xs = ccb->xs;
1603 	struct scsipi_link *sc_link = xs->sc_link;
1604 	struct bha_softc *sc = sc_link->adapter_softc;
1605 	int s;
1606 
1607 	scsi_print_addr(sc_link);
1608 	printf("timed out");
1609 
1610 	s = splbio();
1611 
1612 #ifdef BHADIAG
1613 	/*
1614 	 * If the ccb's mbx is not free, then the board has gone Far East?
1615 	 */
1616 	bha_collect_mbo(sc);
1617 	if (ccb->flags & CCB_SENDING) {
1618 		printf("%s: not taking commands!\n", sc->sc_dev.dv_xname);
1619 		Debugger();
1620 	}
1621 #endif
1622 
1623 	/*
1624 	 * If it has been through before, then
1625 	 * a previous abort has failed, don't
1626 	 * try abort again
1627 	 */
1628 	if (ccb->flags & CCB_ABORT) {
1629 		/* abort timed out */
1630 		printf(" AGAIN\n");
1631 		/* XXX Must reset! */
1632 	} else {
1633 		/* abort the operation that has timed out */
1634 		printf("\n");
1635 		ccb->xs->error = XS_TIMEOUT;
1636 		ccb->timeout = BHA_ABORT_TIMEOUT;
1637 		ccb->flags |= CCB_ABORT;
1638 		bha_queue_ccb(sc, ccb);
1639 	}
1640 
1641 	splx(s);
1642 }
1643