Home | History | Annotate | Line # | Download | only in ic
aic7xxx.c revision 1.8
      1 /*	$NetBSD: aic7xxx.c,v 1.8 1996/05/20 00:58:07 thorpej Exp $	*/
      2 
      3 /*
      4  * Generic driver for the aic7xxx based adaptec SCSI controllers
      5  * Product specific probe and attach routines can be found in:
      6  * i386/eisa/aic7770.c	27/284X and aic7770 motherboard controllers
      7  * pci/aic7870.c	3940, 2940, aic7870 and aic7850 controllers
      8  *
      9  * Copyright (c) 1994, 1995, 1996 Justin T. Gibbs.
     10  * All rights reserved.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice immediately at the beginning of the file, without modification,
     17  *    this list of conditions, and the following disclaimer.
     18  * 2. Redistributions in binary form must reproduce the above copyright
     19  *    notice, this list of conditions and the following disclaimer in the
     20  *    documentation and/or other materials provided with the distribution.
     21  * 3. The name of the author may not be used to endorse or promote products
     22  *    derived from this software without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE FOR
     28  * 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 /*
     37  * TODO:
     38  *	Implement Target Mode
     39  *
     40  * A few notes on how SCB paging works...
     41  *
     42  * SCB paging takes advantage of the fact that devices stay disconnected
     43  * from the bus a relatively long time and that while they're disconnected,
     44  * having the SCBs for that device down on the host adapter is of little use.
     45  * Instead we copy the SCB back up into kernel memory and reuse the SCB slot
     46  * on the card to schedule another transaction.  This can be a real payoff
     47  * when doing random I/O to tagged queueing devices since there are more
     48  * transactions active at once for the device to sort for optimal seek
     49  * reduction. The algorithm goes like this...
     50  *
     51  * At the sequencer level:
     52  * 1) Disconnected SCBs are threaded onto a doubly linked list, headed by
     53  *    DISCONNECTED_SCBH using the SCB_NEXT and SCB_PREV fields.  The most
     54  *    recently disconnected device is always at the head.
     55  *
     56  * 2) The SCB has an added field SCB_TAG that corresponds to the kernel
     57  *    SCB number (ie 0-254).
     58  *
     59  * 3) When a command is queued, the hardware index of the SCB it was downloaded
     60  *    into is placed into the QINFIFO for easy indexing by the sequencer.
     61  *
     62  * 4) The tag field is used as the tag for tagged-queueing, for determining
     63  *    the related kernel SCB, and is the value put into the QOUTFIFO
     64  *    so the kernel doesn't have to upload the SCB to determine the kernel SCB
     65  *    that completed on command completes.
     66  *
     67  * 5) When a reconnect occurs, the sequencer must scan the SCB array (even
     68  *    in the tag case) looking for the appropriate SCB and if it can't find
     69  *    it, it interrupts the kernel so it can page the SCB in.
     70  *
     71  * 6) If the sequencer is successful in finding the SCB, it removes it from
     72  *    the doubly linked list of disconnected SCBS.
     73  *
     74  * At the kernel level:
     75  * 1) There are four queues that a kernel SCB may reside on:
     76  *	free_scbs - SCBs that are not in use and have a hardware slot assigned
     77  *		    to them.
     78  *      page_scbs - SCBs that are not in use and need to have a hardware slot
     79  *		    assigned to them (i.e. they will most likely cause a page
     80  *		    out event).
     81  *	waiting_scbs - SCBs that are active, don't have an assigned hardware
     82  *		    slot assigned to them and are waiting for either a
     83  *		    disconnection or a command complete to free up a slot.
     84  *	assigned_scbs - SCBs that were in the waiting_scbs queue, but were
     85  *		    assigned a slot by ahc_free_scb.
     86  *
     87  * 2) When a new request comes in, an SCB is allocated from the free_scbs or
     88  *    page_scbs queue with preference to SCBs on the free_scbs queue.
     89  *
     90  * 3) If there are no free slots (we retrieved the SCB off of the page_scbs
     91  *    queue), the SCB is inserted onto the tail of the waiting_scbs list and
     92  *    we attempt to run this queue down.
     93  *
     94  * 4) ahc_run_waiing_queues() looks at both the assigned_scbs and waiting_scbs
     95  *    queues.  In the case of the assigned_scbs, the commands are immediately
     96  *    downloaded and started.  For waiting_scbs, we page in all that we can
     97  *    ensuring we don't create a resource deadlock (see comments in
     98  *    ahc_run_waing_queues()).
     99  *
    100  * 5) After we handle a bunch of command completes, we also try running the
    101  *    queues since many SCBs may have disconnected since the last command
    102  *    was started and we have at least one free slot on the card.
    103  *
    104  * 6) ahc_free_scb looks at the waiting_scbs queue for a transaction
    105  *    requiring a slot and moves it to the assigned_scbs queue if it
    106  *    finds one.  Otherwise it puts the current SCB onto the free_scbs
    107  *    queue for later use.
    108  *
    109  * 7) The driver handles page-in requests from the sequencer in response to
    110  *    the NO_MATCH sequencer interrupt.  For tagged commands, the approprite
    111  *    SCB is easily found since the tag is a direct index into our kernel SCB
    112  *    array.  For non-tagged commands, we keep a separate array of 16 pointers
    113  *    that point to the single possible SCB that was paged out for that target.
    114  */
    115 
    116 #include <sys/param.h>
    117 #include <sys/systm.h>
    118 #if defined(__NetBSD__)
    119 #include <sys/device.h>
    120 #include <machine/bus.h>
    121 #include <machine/intr.h>
    122 #endif /* defined(__NetBSD__) */
    123 
    124 #include <sys/malloc.h>
    125 #include <sys/buf.h>
    126 #include <sys/proc.h>
    127 
    128 #include <scsi/scsi_all.h>
    129 #if defined(__NetBSD__)
    130 #include <scsi/scsi_debug.h>
    131 #endif
    132 #include <scsi/scsiconf.h>
    133 
    134 #if defined(__FreeBSD__)
    135 #include <machine/clock.h>
    136 #endif
    137 
    138 #include <vm/vm.h>
    139 #include <vm/vm_param.h>
    140 #include <vm/pmap.h>
    141 
    142 #if defined(__FreeBSD__)
    143 #include <i386/scsi/aic7xxx.h>
    144 
    145 #include <dev/aic7xxx/aic7xxx_reg.h>
    146 #endif /* defined(__FreeBSD__) */
    147 
    148 #if defined(__NetBSD__)
    149 #include <dev/ic/aic7xxxreg.h>
    150 #include <dev/ic/aic7xxxvar.h>
    151 
    152 #define bootverbose	1
    153 
    154 #define DEBUGTARG	DEBUGTARGET
    155 #if DEBUGTARG < 0	/* Negative numbrs for disabling cause warnings */
    156 #undef DEBUGTARG
    157 #define DEBUGTARG	9
    158 #endif
    159 #endif /* defined(__NetBSD__) */
    160 
    161 #define PAGESIZ NBPG
    162 
    163 #include <sys/kernel.h>
    164 #define KVTOPHYS(x)   vtophys(x)
    165 
    166 #define MIN(a,b) ((a < b) ? a : b)
    167 #define ALL_TARGETS -1
    168 
    169 #if defined(__FreeBSD__)
    170 u_long ahc_unit = 0;
    171 #endif
    172 
    173 #ifdef AHC_DEBUG
    174 static int     ahc_debug = AHC_SHOWSENSE;
    175 #endif
    176 
    177 #ifdef AHC_BROKEN_CACHE
    178 int ahc_broken_cache = 1;
    179 
    180 /*
    181  * "wbinvd" cause writing back whole cache (both CPU internal & external)
    182  * to memory, so that the instruction takes a lot of time.
    183  * This makes machine slow.
    184  */
    185 #define	INVALIDATE_CACHE()	__asm __volatile("wbinvd")
    186 #endif
    187 
    188 /**** bit definitions for SCSIDEF ****/
    189 #define	HSCSIID		0x07		/* our SCSI ID */
    190 #define HWSCSIID	0x0f		/* our SCSI ID if Wide Bus */
    191 
    192 static void	 ahcminphys __P((struct buf *bp));
    193 static int32_t	 ahc_scsi_cmd __P((struct scsi_xfer *xs));
    194 
    195 static struct scsi_adapter ahc_switch =
    196 {
    197         ahc_scsi_cmd,
    198         ahcminphys,
    199         0,
    200         0,
    201 #if defined(__FreeBSD__)
    202         0,
    203         "ahc",
    204         { 0, 0 }
    205 #endif
    206 };
    207 
    208 /* the below structure is so we have a default dev struct for our link struct */
    209 static struct scsi_device ahc_dev =
    210 {
    211     NULL,                       /* Use default error handler */
    212     NULL,                       /* have a queue, served by this */
    213     NULL,                       /* have no async handler */
    214     NULL,                       /* Use default 'done' routine */
    215 #if defined(__FreeBSD__)
    216     "ahc",
    217     0,
    218     { 0, 0 }
    219 #endif
    220 };
    221 
    222 /*
    223  * Since the sequencer can disable pausing in a critical section, we
    224  * must loop until it actually stops.
    225  * XXX Should add a timeout in here??
    226  */
    227 #define PAUSE_SEQUENCER(ahc)					\
    228 	AHC_OUTB(ahc, HCNTRL, ahc->pause);			\
    229 								\
    230 	while ((AHC_INB(ahc, HCNTRL) & PAUSE) == 0)		\
    231 		;
    232 
    233 #define UNPAUSE_SEQUENCER(ahc)					\
    234 	AHC_OUTB(ahc, HCNTRL, ahc->unpause )
    235 
    236 /*
    237  * Restart the sequencer program from address zero
    238  */
    239 #define RESTART_SEQUENCER(ahc)						\
    240 	do {								\
    241 		AHC_OUTB(ahc, SEQCTL, SEQRESET|FASTMODE);		\
    242 	} while (AHC_INB(ahc, SEQADDR0) != 0 &&				\
    243 		 AHC_INB(ahc, SEQADDR1) != 0);				\
    244 									\
    245 	UNPAUSE_SEQUENCER(ahc);
    246 
    247 #if defined(__NetBSD__)
    248 /*
    249  * Is device which is pointed by sc_link connected on second scsi bus ?
    250  */
    251 #define	IS_SCSIBUS_B(ahc, sc_link)	\
    252 	((sc_link)->scsibus == (ahc)->sc_link_b.scsibus)
    253 
    254 /*
    255  * convert FreeBSD's SCSI symbols to NetBSD's
    256  */
    257 #define	SCSI_NOMASK	SCSI_POLL
    258 #define	opennings	openings
    259 #endif
    260 
    261 static u_char	ahc_abort_wscb __P((struct ahc_data *ahc, struct scb *scbp,
    262 				    u_char prev,
    263 				    u_char timedout_scb, u_int32_t xs_error));
    264 static void	ahc_add_waiting_scb __P((struct ahc_data *ahc,
    265 					 struct scb *scb));
    266 static void	ahc_done __P((struct ahc_data *ahc, struct scb *scbp));
    267 static void	ahc_free_scb __P((struct ahc_data *ahc, struct scb *scb,
    268 				  int flags));
    269 static inline void ahc_send_scb __P((struct ahc_data *ahc, struct scb *scb));
    270 static inline void ahc_fetch_scb __P((struct ahc_data *ahc, struct scb *scb));
    271 static inline void ahc_page_scb __P((struct ahc_data *ahc, struct scb *out_scb,
    272 				struct scb *in_scb));
    273 static inline void ahc_run_waiting_queues __P((struct ahc_data *ahc));
    274 static struct scb *
    275 		ahc_get_scb __P((struct ahc_data *ahc, int flags));
    276 static void	ahc_loadseq __P((struct ahc_data *ahc));
    277 static int	ahc_match_scb __P((struct scb *scb, int target, char channel));
    278 static int	ahc_poll __P((struct ahc_data *ahc, int wait));
    279 #ifdef AHC_DEBUG
    280 static void	ahc_print_scb __P((struct scb *scb));
    281 #endif
    282 static int	ahc_reset_channel __P((struct ahc_data *ahc, char channel,
    283 				       u_char timedout_scb, u_int32_t xs_error,
    284 				       u_char initiate_reset));
    285 static int	ahc_reset_device __P((struct ahc_data *ahc, int target,
    286 				      char channel, u_char timedout_scb,
    287 				      u_int32_t xs_error));
    288 static void	ahc_reset_current_bus __P((struct ahc_data *ahc));
    289 static void	ahc_run_done_queue __P((struct ahc_data *ahc));
    290 static void	ahc_scsirate __P((struct ahc_data* ahc, u_char *scsirate,
    291 				  int period, int offset, int target));
    292 #if defined(__FreeBSD__)
    293 static timeout_t
    294 		ahc_timeout;
    295 #elif defined(__NetBSD__)
    296 static void	ahc_timeout __P((void *));
    297 #endif
    298 static void	ahc_busy_target __P((struct ahc_data *ahc,
    299 				     int target, char channel));
    300 static void	ahc_unbusy_target __P((struct ahc_data *ahc,
    301 				       int target, char channel));
    302 
    303 #if defined(__FreeBSD__)
    304 
    305 char *ahc_name(ahc)
    306 	struct ahc_data *ahc;
    307 {
    308 	static char name[10];
    309 
    310 	sprintf(name, "ahc%d", ahc->unit);
    311 	return (name);
    312 }
    313 
    314 #elif defined(__NetBSD__)
    315 struct cfdriver ahc_cd = {
    316 	NULL, "ahc", DV_DULL
    317 };
    318 #endif
    319 
    320 #ifdef  AHC_DEBUG
    321 static void
    322 ahc_print_scb(scb)
    323         struct scb *scb;
    324 {
    325         printf("scb:%p control:0x%x tcl:0x%x cmdlen:%d cmdpointer:0x%lx\n"
    326 	    ,scb
    327 	    ,scb->control
    328 	    ,scb->tcl
    329 	    ,scb->cmdlen
    330 	    ,scb->cmdpointer );
    331         printf("        datlen:%d data:0x%lx segs:0x%x segp:0x%lx\n"
    332 	    ,scb->datalen
    333 	    ,scb->data
    334 	    ,scb->SG_segment_count
    335 	    ,scb->SG_list_pointer);
    336 	printf("	sg_addr:%lx sg_len:%ld\n"
    337 	    ,scb->ahc_dma[0].addr
    338 	    ,scb->ahc_dma[0].len);
    339 }
    340 
    341 #endif
    342 
    343 static struct {
    344         u_char errno;
    345 	char *errmesg;
    346 } hard_error[] = {
    347 	{ ILLHADDR,  "Illegal Host Access" },
    348 	{ ILLSADDR,  "Illegal Sequencer Address referrenced" },
    349 	{ ILLOPCODE, "Illegal Opcode in sequencer program" },
    350 	{ PARERR,    "Sequencer Ram Parity Error" }
    351 };
    352 
    353 
    354 /*
    355  * Valid SCSIRATE values.  (p. 3-17)
    356  * Provides a mapping of tranfer periods in ns to the proper value to
    357  * stick in the scsiscfr reg to use that transfer rate.
    358  */
    359 static struct {
    360 	short sxfr;
    361 	/* Rates in Ultra mode have bit 8 of sxfr set */
    362 #define		ULTRA_SXFR 0x100
    363 	short period; /* in ns */
    364 	char *rate;
    365 } ahc_syncrates[] = {
    366 	{ 0x100,  50, "20.0"  },
    367 	{ 0x110,  62, "16.0"  },
    368 	{ 0x120,  75, "13.4"  },
    369 	{ 0x130, 175,  "5.7"  },
    370 	{ 0x140, 200,  "5.0"  },
    371 	{ 0x150, 225,  "4.4"  },
    372 	{ 0x160, 250,  "4.0"  },
    373 	{ 0x170, 275,  "3.6"  },
    374 	{ 0x000, 100, "10.0"  },
    375 	{ 0x010, 125,  "8.0"  },
    376 	{ 0x020, 150,  "6.67" },
    377 	{ 0x030, 175,  "5.7"  },
    378 	{ 0x040, 200,  "5.0"  },
    379 	{ 0x050, 225,  "4.4"  },
    380 	{ 0x060, 250,  "4.0"  },
    381 	{ 0x070, 275,  "3.6"  }
    382 };
    383 
    384 static int ahc_num_syncrates =
    385 	sizeof(ahc_syncrates) / sizeof(ahc_syncrates[0]);
    386 
    387 /*
    388  * Allocate a controller structures for a new device and initialize it.
    389  * ahc_reset should be called before now since we assume that the card
    390  * is paused.
    391  *
    392  */
    393 #if defined(__FreeBSD__)
    394 struct ahc_data *
    395 ahc_alloc(unit, iobase, type, flags)
    396 	int unit;
    397 	u_long iobase;
    398 #elif defined(__NetBSD__)
    399 void
    400 ahc_construct(ahc, bc, ioh, type, flags)
    401 	struct  ahc_data *ahc;
    402 	bus_chipset_tag_t bc;
    403 	bus_io_handle_t ioh;
    404 #endif
    405 	ahc_type type;
    406 	ahc_flag flags;
    407 {
    408 
    409 	/*
    410 	 * find unit and check we have that many defined
    411 	 */
    412 
    413 #if defined(__FreeBSD__)
    414 	struct  ahc_data *ahc;
    415 
    416 	/*
    417 	 * Allocate a storage area for us
    418 	 */
    419 
    420 	ahc = malloc(sizeof(struct ahc_data), M_TEMP, M_NOWAIT);
    421 	if (!ahc) {
    422 		printf("ahc%d: cannot malloc!\n", unit);
    423 		return NULL;
    424 	}
    425 	bzero(ahc, sizeof(struct ahc_data));
    426 #endif
    427 	SIMPLEQ_INIT(&ahc->free_scbs);
    428 	SIMPLEQ_INIT(&ahc->page_scbs);
    429 	SIMPLEQ_INIT(&ahc->waiting_scbs);
    430 	SIMPLEQ_INIT(&ahc->assigned_scbs);
    431 #if defined(__FreeBSD__)
    432 	ahc->unit = unit;
    433 	ahc->baseport = iobase;
    434 #elif defined(__NetBSD__)
    435 	ahc->sc_bc = bc;
    436 	ahc->sc_ioh = ioh;
    437 #endif
    438 	ahc->type = type;
    439 	ahc->flags = flags;
    440 	ahc->unpause = (AHC_INB(ahc, HCNTRL) & IRQMS) | INTEN;
    441 	ahc->pause = ahc->unpause | PAUSE;
    442 
    443 #if defined(__FreeBSD__)
    444 	return (ahc);
    445 #endif
    446 }
    447 
    448 void
    449 ahc_free(ahc)
    450 	struct ahc_data *ahc;
    451 {
    452 #if defined(__FreeBSD__)
    453 	free(ahc, M_DEVBUF);
    454 	return;
    455 #endif
    456 }
    457 
    458 void
    459 #if defined(__FreeBSD__)
    460 ahc_reset(iobase)
    461 	u_long iobase;
    462 #elif defined(__NetBSD__)
    463 ahc_reset(devname, bc, ioh)
    464 	char *devname;
    465 	bus_chipset_tag_t bc;
    466 	bus_io_handle_t ioh;
    467 #endif
    468 {
    469         u_char hcntrl;
    470 	int wait;
    471 
    472 	/* Retain the IRQ type accross the chip reset */
    473 #if defined(__FreeBSD__)
    474 	hcntrl = (inb(HCNTRL + iobase) & IRQMS) | INTEN;
    475 
    476 	outb(HCNTRL + iobase, CHIPRST | PAUSE);
    477 #elif defined(__NetBSD__)
    478 	hcntrl = (bus_io_read_1(bc, ioh, HCNTRL) & IRQMS) | INTEN;
    479 
    480 	bus_io_write_1(bc, ioh, HCNTRL, CHIPRST | PAUSE);
    481 #endif
    482 	/*
    483 	 * Ensure that the reset has finished
    484 	 */
    485 	wait = 1000;
    486 #if defined(__FreeBSD__)
    487 	while (--wait && !(inb(HCNTRL + iobase) & CHIPRSTACK))
    488 #elif defined(__NetBSD__)
    489 	while (--wait && !(bus_io_read_1(bc, ioh, HCNTRL) & CHIPRSTACK))
    490 #endif
    491 		DELAY(1000);
    492 	if(wait == 0) {
    493 #if defined(__FreeBSD__)
    494 		printf("ahc at 0x%lx: WARNING - Failed chip reset!  "
    495 		       "Trying to initialize anyway.\n", iobase);
    496 #elif defined(__NetBSD__)
    497 		printf("%s: WARNING - Failed chip reset!  "
    498 		       "Trying to initialize anyway.\n", devname);
    499 #endif
    500 	}
    501 #if defined(__FreeBSD__)
    502 	outb(HCNTRL + iobase, hcntrl | PAUSE);
    503 #elif defined(__NetBSD__)
    504 	bus_io_write_1(bc, ioh, HCNTRL, hcntrl | PAUSE);
    505 #endif
    506 }
    507 
    508 /*
    509  * Look up the valid period to SCSIRATE conversion in our table.
    510  */
    511 static void
    512 ahc_scsirate(ahc, scsirate, period, offset, target )
    513 	struct	ahc_data *ahc;
    514 	u_char	*scsirate;
    515 	short	period;
    516 	u_char	offset;
    517 	int	target;
    518 {
    519 	int i;
    520 
    521 	for (i = 0; i < ahc_num_syncrates; i++) {
    522 
    523 		if ((ahc_syncrates[i].period - period) >= 0) {
    524 			/*
    525 			 * Watch out for Ultra speeds when ultra is not
    526 			 * enabled and vice-versa.
    527 			 */
    528 			if (ahc->type & AHC_ULTRA) {
    529 				if (!(ahc_syncrates[i].sxfr & ULTRA_SXFR))
    530 					break; /* Use Async */
    531 			}
    532 			else {
    533 				if (ahc_syncrates[i].sxfr & ULTRA_SXFR) {
    534 					/*
    535 					 * This should only happen if the
    536 					 * drive is the first to negotiate
    537 					 * and chooses a high rate.  We'll
    538 					 * just move down the table util
    539 					 * we hit a non ultra speed.
    540 					 */
    541 					continue;
    542 				}
    543 			}
    544 			*scsirate = (ahc_syncrates[i].sxfr) | (offset & 0x0f);
    545 			if(bootverbose) {
    546 				printf("%s: target %d synchronous at %sMHz,"
    547 				       " offset = 0x%x\n",
    548 				        ahc_name(ahc), target,
    549 					ahc_syncrates[i].rate, offset );
    550 			}
    551 			return;
    552 		}
    553 	}
    554 	/* Default to asyncronous transfers.  Also reject this SDTR request. */
    555 	*scsirate = 0;
    556 	if(bootverbose) {
    557 		printf("%s: target %d using asyncronous transfers\n",
    558 			ahc_name(ahc), target );
    559 	}
    560 }
    561 
    562 #if defined(__NetBSD__)
    563 int
    564 ahcprint(aux, name)
    565 	void *aux;
    566 	char *name;
    567 {
    568 
    569 	if (name != NULL)
    570 		printf("%s: scsibus ", name);
    571 	return UNCONF;
    572 }
    573 #endif
    574 
    575 /*
    576  * Attach all the sub-devices we can find
    577  */
    578 int
    579 ahc_attach(ahc)
    580 	struct ahc_data *ahc;
    581 {
    582 	struct scsibus_data *scbus;
    583 
    584 #ifdef AHC_BROKEN_CACHE
    585 	if (cpu_class == CPUCLASS_386)	/* doesn't have "wbinvd" instruction */
    586 		ahc_broken_cache = 0;
    587 #endif
    588 	/*
    589 	 * fill in the prototype scsi_links.
    590 	 */
    591 #if defined(__FreeBSD__)
    592 	ahc->sc_link.adapter_unit = ahc->unit;
    593 	ahc->sc_link.adapter_targ = ahc->our_id;
    594 	ahc->sc_link.fordriver = 0;
    595 #elif defined(__NetBSD__)
    596 	ahc->sc_link.adapter_target = ahc->our_id;
    597 #endif
    598 	ahc->sc_link.adapter_softc = ahc;
    599 	ahc->sc_link.adapter = &ahc_switch;
    600 	ahc->sc_link.opennings = 2;
    601 	ahc->sc_link.device = &ahc_dev;
    602 	ahc->sc_link.flags = DEBUGLEVEL;
    603 
    604 	if(ahc->type & AHC_TWIN) {
    605 		/* Configure the second scsi bus */
    606 		ahc->sc_link_b = ahc->sc_link;
    607 #if defined(__FreeBSD__)
    608 		ahc->sc_link_b.adapter_targ = ahc->our_id_b;
    609 		ahc->sc_link_b.adapter_bus = 1;
    610 		ahc->sc_link_b.fordriver = (void *)SELBUSB;
    611 #elif defined(__NetBSD__)
    612 		ahc->sc_link_b.adapter_target = ahc->our_id_b;
    613 #endif
    614 	}
    615 
    616 
    617 #if defined(__FreeBSD__)
    618 	/*
    619 	 * Prepare the scsibus_data area for the upperlevel
    620 	 * scsi code.
    621 	 */
    622 	scbus = scsi_alloc_bus();
    623 	if(!scbus)
    624 		return 0;
    625 	scbus->adapter_link = (ahc->flags & AHC_CHANNEL_B_PRIMARY) ?
    626 				&ahc->sc_link_b : &ahc->sc_link;
    627 	if(ahc->type & AHC_WIDE)
    628 		scbus->maxtarg = 15;
    629 
    630 	/*
    631 	 * ask the adapter what subunits are present
    632 	 */
    633 	if(bootverbose)
    634 		printf("ahc%d: Probing channel %c\n", ahc->unit,
    635 			(ahc->flags & AHC_CHANNEL_B_PRIMARY) ? 'B' : 'A');
    636 	scsi_attachdevs(scbus);
    637 	scbus = NULL;	/* Upper-level SCSI code owns this now */
    638 
    639 	if(ahc->type & AHC_TWIN) {
    640 		scbus =  scsi_alloc_bus();
    641 		if(!scbus)
    642 			return 0;
    643 		scbus->adapter_link = (ahc->flags & AHC_CHANNEL_B_PRIMARY) ?
    644 					&ahc->sc_link : &ahc->sc_link_b;
    645 		if(ahc->type & AHC_WIDE)
    646 			scbus->maxtarg = 15;
    647 		if(bootverbose)
    648 			printf("ahc%d: Probing Channel %c\n", ahc->unit,
    649 			       (ahc->flags & AHC_CHANNEL_B_PRIMARY) ? 'A': 'B');
    650 		scsi_attachdevs(scbus);
    651 		scbus = NULL;	/* Upper-level SCSI code owns this now */
    652 	}
    653 #elif defined(__NetBSD__)
    654 	/*
    655 	 * XXX - Update MI SCSI code
    656 	 *
    657 	 * if(ahc->type & AHC_WIDE)
    658 	 *	max target of both channel A and B = 15;
    659 	 */
    660 
    661 	/*
    662 	 * ask the adapter what subunits are present
    663 	 */
    664 	if ((ahc->flags & AHC_CHANNEL_B_PRIMARY) == 0) {
    665 		/* make IS_SCSIBUS_B() == false, while probing channel A */
    666 		ahc->sc_link_b.scsibus = 0xff;
    667 
    668 		if (ahc->type & AHC_TWIN)
    669 			printf("%s: Probing channel A\n", ahc_name(ahc));
    670 		config_found((void *)ahc, &ahc->sc_link, ahcprint);
    671 		if (ahc->type & AHC_TWIN) {
    672 			printf("%s: Probing channel B\n", ahc_name(ahc));
    673 			config_found((void *)ahc, &ahc->sc_link_b, ahcprint);
    674 		}
    675 	} else {
    676 		/*
    677 		 * if implementation of IS_SCSIBUS_B() is changed to use
    678 		 * ahc->sc_link.scsibus, then "ahc->sc_link.scsibus = 0xff;"
    679 		 * is needed, here.
    680 		 */
    681 
    682 		/* assert(ahc->type & AHC_TWIN); */
    683 		printf("%s: Probing channel B\n", ahc_name(ahc));
    684 		config_found((void *)ahc, &ahc->sc_link_b, ahcprint);
    685 		printf("%s: Probing channel A\n", ahc_name(ahc));
    686 		config_found((void *)ahc, &ahc->sc_link, ahcprint);
    687 	}
    688 #endif
    689 	return 1;
    690 }
    691 
    692 /*
    693  * Send an SCB down to the card via PIO.
    694  * We assume that the proper SCB is already selected in SCBPTR.
    695  */
    696 static inline void
    697 ahc_send_scb(ahc, scb)
    698         struct	ahc_data *ahc;
    699         struct	scb *scb;
    700 {
    701 	AHC_OUTB(ahc, SCBCNT, SCBAUTO);
    702 	if( ahc->type == AHC_284 )
    703 		/* Can only do 8bit PIO */
    704 		AHC_OUTSB(ahc, SCBARRAY, scb, SCB_PIO_TRANSFER_SIZE);
    705 	else
    706 		AHC_OUTSL(ahc, SCBARRAY, scb,
    707 		      (SCB_PIO_TRANSFER_SIZE + 3) / 4);
    708 	AHC_OUTB(ahc, SCBCNT, 0);
    709 }
    710 
    711 /*
    712  * Retrieve an SCB from the card via PIO.
    713  * We assume that the proper SCB is already selected in SCBPTR.
    714  */
    715 static inline void
    716 ahc_fetch_scb(ahc, scb)
    717 	struct	ahc_data *ahc;
    718 	struct	scb *scb;
    719 {
    720 	AHC_OUTB(ahc, SCBCNT, 0x80);	/* SCBAUTO */
    721 
    722 	/* Can only do 8bit PIO for reads */
    723 	AHC_INSB(ahc, SCBARRAY, scb, SCB_PIO_TRANSFER_SIZE);
    724 
    725 	AHC_OUTB(ahc, SCBCNT, 0);
    726 }
    727 
    728 /*
    729  * Swap in_scbp for out_scbp down in the cards SCB array.
    730  * We assume that the SCB for out_scbp is already selected in SCBPTR.
    731  */
    732 static inline void
    733 ahc_page_scb(ahc, out_scbp, in_scbp)
    734 	struct ahc_data *ahc;
    735 	struct scb *out_scbp;
    736 	struct scb *in_scbp;
    737 {
    738 	/* Page-out */
    739 	ahc_fetch_scb(ahc, out_scbp);
    740 	out_scbp->flags |= SCB_PAGED_OUT;
    741 	if(!(out_scbp->control & TAG_ENB))
    742 	{
    743 		/* Stick in non-tagged array */
    744 		int index =  (out_scbp->tcl >> 4)
    745 			   | (out_scbp->tcl & SELBUSB);
    746 		ahc->pagedout_ntscbs[index] = out_scbp;
    747 	}
    748 
    749 	/* Page-in */
    750 	in_scbp->position = out_scbp->position;
    751 	out_scbp->position = SCB_LIST_NULL;
    752 	ahc_send_scb(ahc, in_scbp);
    753 	in_scbp->flags &= ~SCB_PAGED_OUT;
    754 }
    755 
    756 static inline void
    757 ahc_run_waiting_queues(ahc)
    758 	struct ahc_data *ahc;
    759 {
    760 	struct scb* scb;
    761 	u_char cur_scb;
    762 
    763 	if(!(ahc->assigned_scbs.sqh_first || ahc->waiting_scbs.sqh_first))
    764 		return;
    765 
    766 	PAUSE_SEQUENCER(ahc);
    767 	cur_scb = AHC_INB(ahc, SCBPTR);
    768 
    769 	/*
    770 	 * First handle SCBs that are waiting but have been
    771 	 * assigned a slot.
    772 	 */
    773 	while((scb = ahc->assigned_scbs.sqh_first) != NULL) {
    774 		SIMPLEQ_REMOVE_HEAD(&ahc->assigned_scbs, scb, links);
    775 		AHC_OUTB(ahc, SCBPTR, scb->position);
    776 		ahc_send_scb(ahc, scb);
    777 
    778 		/* Mark this as an active command */
    779 		scb->flags = SCB_ACTIVE;
    780 
    781 		AHC_OUTB(ahc, QINFIFO, scb->position);
    782 		if (!(scb->xs->flags & SCSI_NOMASK)) {
    783 			timeout(ahc_timeout, (caddr_t)scb,
    784 				(scb->xs->timeout * hz) / 1000);
    785 		}
    786 		SC_DEBUG(scb->xs->sc_link, SDEV_DB3, ("cmd_sent\n"));
    787 	}
    788 	/* Now deal with SCBs that require paging */
    789 	if((scb = ahc->waiting_scbs.sqh_first) != NULL) {
    790 		u_char disc_scb = AHC_INB(ahc, DISCONNECTED_SCBH);
    791 		u_char active = AHC_INB(ahc, FLAGS) & (SELECTED|IDENTIFY_SEEN);
    792 		int count = 0;
    793 
    794 		do {
    795 			u_char next_scb;
    796 
    797 			/* Attempt to page this SCB in */
    798 			if(disc_scb == SCB_LIST_NULL)
    799 				break;
    800 
    801 			/*
    802 			 * Advance disc_scb to the next on in the
    803 			 * list.
    804 			 */
    805 			AHC_OUTB(ahc, SCBPTR, disc_scb);
    806 			next_scb = AHC_INB(ahc, SCB_NEXT);
    807 
    808 			/*
    809 			 * We have to be careful about when we allow
    810 			 * an SCB to be paged out.  There must always
    811 			 * be at least one slot availible for a
    812 			 * reconnecting target in case it references
    813 			 * an SCB that has been paged out.  Our
    814 			 * heuristic is that either the disconnected
    815 			 * list has at least two entries in it or
    816 			 * there is one entry and the sequencer is
    817 			 * activily working on an SCB which implies that
    818 			 * it will either complete or disconnect before
    819 			 * another reconnection can occur.
    820 			 */
    821 			if((next_scb != SCB_LIST_NULL) || active)
    822 			{
    823 				u_char out_scbi;
    824 				struct scb* out_scbp;
    825 
    826 				SIMPLEQ_REMOVE_HEAD(&ahc->waiting_scbs, scb,
    827 				    links);
    828 
    829 				/*
    830 				 * Find the in-core SCB for the one
    831 				 * we're paging out.
    832 				 */
    833 				out_scbi = AHC_INB(ahc, SCB_TAG);
    834 				out_scbp = ahc->scbarray[out_scbi];
    835 
    836 				/* Do the page out */
    837 				ahc_page_scb(ahc, out_scbp, scb);
    838 
    839 				/* Mark this as an active command */
    840 				scb->flags = SCB_ACTIVE;
    841 
    842 				/* Queue the command */
    843 				AHC_OUTB(ahc, QINFIFO, scb->position);
    844 				if (!(scb->xs->flags & SCSI_NOMASK)) {
    845 					timeout(ahc_timeout, (caddr_t)scb,
    846 						(scb->xs->timeout * hz) / 1000);
    847 				}
    848 				SC_DEBUG(scb->xs->sc_link, SDEV_DB3,
    849 					("cmd_paged-in\n"));
    850 				count++;
    851 
    852 				/* Advance to the next disconnected SCB */
    853 				disc_scb = next_scb;
    854 			}
    855 			else
    856 				break;
    857 		} while((scb = ahc->waiting_scbs.sqh_first) != NULL);
    858 
    859 		if(count) {
    860 			/*
    861 			 * Update the head of the disconnected list.
    862 			 */
    863 			AHC_OUTB(ahc, DISCONNECTED_SCBH, disc_scb);
    864 			if(disc_scb != SCB_LIST_NULL) {
    865 				AHC_OUTB(ahc, SCBPTR, disc_scb);
    866 				AHC_OUTB(ahc, SCB_PREV, SCB_LIST_NULL);
    867 			}
    868 		}
    869 	}
    870 	/* Restore old position */
    871 	AHC_OUTB(ahc, SCBPTR, cur_scb);
    872 	UNPAUSE_SEQUENCER(ahc);
    873 }
    874 
    875 /*
    876  * Add this SCB to the head of the "waiting for selection" list.
    877  */
    878 static
    879 void ahc_add_waiting_scb(ahc, scb)
    880 	struct ahc_data *ahc;
    881 	struct scb *scb;
    882 {
    883 	u_char next;
    884 	u_char curscb;
    885 
    886 	curscb = AHC_INB(ahc, SCBPTR);
    887 	next = AHC_INB(ahc, WAITING_SCBH);
    888 
    889 	AHC_OUTB(ahc, SCBPTR, scb->position);
    890 	AHC_OUTB(ahc, SCB_NEXT, next);
    891 	AHC_OUTB(ahc, WAITING_SCBH, scb->position);
    892 
    893 	AHC_OUTB(ahc, SCBPTR, curscb);
    894 }
    895 
    896 /*
    897  * Catch an interrupt from the adapter
    898  */
    899 #if defined(__FreeBSD__)
    900 void
    901 #elif defined (__NetBSD__)
    902 int
    903 #endif
    904 ahc_intr(arg)
    905         void *arg;
    906 {
    907 	int     intstat;
    908 	u_char	status;
    909 	struct scb *scb = NULL;
    910 	struct scsi_xfer *xs = NULL;
    911 	struct ahc_data *ahc = (struct ahc_data *)arg;
    912 
    913         intstat = AHC_INB(ahc, INTSTAT);
    914 	/*
    915 	 * Is this interrupt for me? or for
    916 	 * someone who is sharing my interrupt
    917 	 */
    918 	if (!(intstat & INT_PEND))
    919 #if defined(__FreeBSD__)
    920 		return;
    921 #elif defined(__NetBSD__)
    922 		return 0;
    923 #endif
    924 
    925         if (intstat & BRKADRINT) {
    926 		/* We upset the sequencer :-( */
    927 
    928 		/* Lookup the error message */
    929 		int i, error = AHC_INB(ahc, ERROR);
    930 		int num_errors =  sizeof(hard_error)/sizeof(hard_error[0]);
    931 		for(i = 0; error != 1 && i < num_errors; i++)
    932 			error >>= 1;
    933                 panic("%s: brkadrint, %s at seqaddr = 0x%x\n",
    934 		      ahc_name(ahc), hard_error[i].errmesg,
    935 		      (AHC_INB(ahc, SEQADDR1) << 8) |
    936 		      AHC_INB(ahc, SEQADDR0));
    937         }
    938         if (intstat & SEQINT) {
    939 		/*
    940 		 * This code isn't used by the SCB page-in code.  It
    941 		 * should probably be moved to cut out the extra
    942 		 * inb.
    943 		 */
    944 		u_short targ_mask;
    945 		u_char target = (AHC_INB(ahc, SCSIID) >> 4) & 0x0f;
    946 		u_char scratch_offset = target;
    947 		char channel =
    948 			AHC_INB(ahc, SBLKCTL) & SELBUSB ? 'B': 'A';
    949 
    950 		if (channel == 'B')
    951 			scratch_offset += 8;
    952 		targ_mask = (0x01 << scratch_offset);
    953 
    954                 switch (intstat & SEQINT_MASK) {
    955                     case BAD_PHASE:
    956                         panic("%s:%c:%d: unknown scsi bus phase.  "
    957 			      "Attempting to continue\n",
    958 			      ahc_name(ahc), channel, target);
    959                         break;
    960                     case SEND_REJECT:
    961 			{
    962 				u_char rejbyte = AHC_INB(ahc, REJBYTE);
    963 				if(( rejbyte & 0xf0) == 0x20) {
    964 					/* Tagged Message */
    965 					printf("\n%s:%c:%d: Tagged message "
    966 						"received without identify. "
    967 						"Disabling tagged commands "
    968 						"for this target.\n",
    969 						ahc_name(ahc),
    970 					        channel, target);
    971 					ahc->tagenable &= ~targ_mask;
    972 				}
    973 				else
    974 					printf("%s:%c:%d: Warning - "
    975 					       "unknown message recieved from "
    976 					       "target (0x%x - 0x%x).  Rejecting\n",
    977 						ahc_name(ahc), channel, target,
    978 						rejbyte,
    979 					        AHC_INB(ahc, REJBYTE_EXT));
    980 				break;
    981 			}
    982                     case NO_IDENT:
    983                         panic("%s:%c:%d: Target did not send an IDENTIFY "
    984 			      "message. SAVED_TCL == 0x%x\n",
    985                               ahc_name(ahc), channel, target,
    986 			      AHC_INB(ahc, SAVED_TCL));
    987 			break;
    988                     case NO_MATCH:
    989 			if(ahc->flags & AHC_PAGESCBS) {
    990 				/* SCB Page-in request */
    991 				u_char tag;
    992 				u_char next;
    993 				u_char disc_scb;
    994 				struct scb *outscb;
    995 				u_char arg_1 = AHC_INB(ahc, ARG_1);
    996 				if(arg_1 == SCB_LIST_NULL) {
    997 					/* Non-tagged command */
    998 					int index = target |
    999 						(channel == 'B' ? SELBUSB : 0);
   1000 					scb = ahc->pagedout_ntscbs[index];
   1001 				}
   1002 				else
   1003 					scb = ahc->scbarray[arg_1];
   1004 
   1005 				/*
   1006 				 * Now to pick the SCB to page out.
   1007 				 * Either take a free SCB, an assigned SCB,
   1008 				 * an SCB that just completed, the first
   1009 				 * one on the disconnected SCB list, or
   1010 				 * as a last resort a queued SCB.
   1011 				 */
   1012 				if((outscb = ahc->free_scbs.sqh_first) != NULL) {
   1013 					SIMPLEQ_REMOVE_HEAD(&ahc->free_scbs,
   1014 					    outscb, links);
   1015 					scb->position = outscb->position;
   1016 					outscb->position = SCB_LIST_NULL;
   1017 					SIMPLEQ_INSERT_HEAD(&ahc->page_scbs,
   1018 					    outscb, links);
   1019 					AHC_OUTB(ahc, SCBPTR, scb->position);
   1020 					ahc_send_scb(ahc, scb);
   1021 					scb->flags &= ~SCB_PAGED_OUT;
   1022 					goto pagein_done;
   1023 				}
   1024 				if((outscb = ahc->assigned_scbs.sqh_first) != NULL) {
   1025 					SIMPLEQ_REMOVE_HEAD(&ahc->assigned_scbs,
   1026 					    outscb, links);
   1027 					scb->position = outscb->position;
   1028 					outscb->position = SCB_LIST_NULL;
   1029 					SIMPLEQ_INSERT_HEAD(&ahc->waiting_scbs,
   1030 					    outscb, links);
   1031 					outscb->flags = SCB_WAITINGQ;
   1032 					AHC_OUTB(ahc, SCBPTR, scb->position);
   1033 					ahc_send_scb(ahc, scb);
   1034 					scb->flags &= ~SCB_PAGED_OUT;
   1035 					goto pagein_done;
   1036 				}
   1037 				if(intstat & CMDCMPLT) {
   1038 					int   scb_index;
   1039 
   1040 					printf("PIC\n");
   1041 					AHC_OUTB(ahc, CLRINT, CLRCMDINT);
   1042 					scb_index = AHC_INB(ahc, QOUTFIFO);
   1043 					if(!(AHC_INB(ahc, QOUTCNT) & ahc->qcntmask))
   1044 						intstat &= ~CMDCMPLT;
   1045 
   1046 					outscb = ahc->scbarray[scb_index];
   1047 					if (!outscb || !(outscb->flags & SCB_ACTIVE)) {
   1048 						printf("%s: WARNING "
   1049 						       "no command for scb %d (cmdcmplt)\n",
   1050 							ahc_name(ahc),
   1051 						        scb_index);
   1052 						/* Fall through in hopes of finding another SCB */
   1053 					}
   1054 					else {
   1055 						scb->position = outscb->position;
   1056 						outscb->position = SCB_LIST_NULL;
   1057 						AHC_OUTB(ahc, SCBPTR, scb->position);
   1058 						ahc_send_scb(ahc, scb);
   1059 						scb->flags &= ~SCB_PAGED_OUT;
   1060 						untimeout(ahc_timeout, (caddr_t)outscb);
   1061 						ahc_done(ahc, outscb);
   1062 						goto pagein_done;
   1063 					}
   1064 				}
   1065 				disc_scb = AHC_INB(ahc, DISCONNECTED_SCBH);
   1066 				if(disc_scb != SCB_LIST_NULL) {
   1067 					AHC_OUTB(ahc, SCBPTR, disc_scb);
   1068 					tag = AHC_INB(ahc, SCB_TAG);
   1069 					outscb = ahc->scbarray[tag];
   1070 					next = AHC_INB(ahc, SCB_NEXT);
   1071 					if(next != SCB_LIST_NULL) {
   1072 						AHC_OUTB(ahc, SCBPTR, next);
   1073 						AHC_OUTB(ahc, SCB_PREV,
   1074 						     SCB_LIST_NULL);
   1075 						AHC_OUTB(ahc, SCBPTR, disc_scb);
   1076 					}
   1077 					AHC_OUTB(ahc, DISCONNECTED_SCBH, next);
   1078 					ahc_page_scb(ahc, outscb, scb);
   1079 				}
   1080 				else if(AHC_INB(ahc, QINCNT) & ahc->qcntmask) {
   1081 					/* Pull one of our queued commands as a last resort */
   1082 					disc_scb = AHC_INB(ahc, QINFIFO);
   1083 					AHC_OUTB(ahc, SCBPTR, disc_scb);
   1084 					tag = AHC_INB(ahc, SCB_TAG);
   1085 					outscb = ahc->scbarray[tag];
   1086 					if((outscb->control & 0x23) != TAG_ENB) {
   1087 						/*
   1088 						 * This is not a simple tagged command
   1089 						 * so its position in the queue
   1090 						 * matters.  Take the command at the
   1091 						 * end of the queue instead.
   1092 						 */
   1093 						int i;
   1094 						int saved_queue[AHC_SCB_MAX];
   1095 						int queued = AHC_INB(ahc, QINCNT) & ahc->qcntmask;
   1096 
   1097 						/* Count the command we removed already */
   1098 						saved_queue[0] = disc_scb;
   1099 						queued++;
   1100 
   1101 						/* Empty the input queue */
   1102 						for (i = 1; i < queued; i++)
   1103 							saved_queue[i] = AHC_INB(ahc, QINFIFO);
   1104 
   1105 						/* Put everyone back put the last entry */
   1106 						queued--;
   1107 						for (i = 0; i < queued; i++)
   1108 							AHC_OUTB(ahc, QINFIFO, saved_queue[i]);
   1109 
   1110 						AHC_OUTB(ahc, SCBPTR, saved_queue[queued]);
   1111 						tag = AHC_INB(ahc, SCB_TAG);
   1112 						outscb = ahc->scbarray[tag];
   1113 					}
   1114 					untimeout(ahc_timeout, (caddr_t)outscb);
   1115 					scb->position = outscb->position;
   1116 					outscb->position = SCB_LIST_NULL;
   1117 					SIMPLEQ_INSERT_HEAD(&ahc->waiting_scbs,
   1118 							   outscb, links);
   1119 					outscb->flags = SCB_WAITINGQ;
   1120 					ahc_send_scb(ahc, scb);
   1121 					scb->flags &= ~SCB_PAGED_OUT;
   1122 				}
   1123 				else
   1124 					panic("Page-in request with no candidates");
   1125 pagein_done:
   1126 				AHC_OUTB(ahc, RETURN_1, SCB_PAGEDIN);
   1127 			}
   1128 			else {
   1129 				printf("%s:%c:%d: no active SCB for "
   1130 				       "reconnecting target - "
   1131 				       "issuing ABORT\n",
   1132 				       ahc_name(ahc), channel, target);
   1133 				printf("SAVED_TCL == 0x%x\n",
   1134 					AHC_INB(ahc, SAVED_TCL));
   1135 				ahc_unbusy_target(ahc, target, channel);
   1136 				AHC_OUTB(ahc, SCB_CONTROL, 0);
   1137 				AHC_OUTB(ahc, CLRSINT1, CLRSELTIMEO);
   1138 				AHC_OUTB(ahc, RETURN_1, 0);
   1139 			}
   1140 			break;
   1141                     case SDTR_MSG:
   1142 			{
   1143 				short period;
   1144 				u_char offset, rate;
   1145 				u_char targ_scratch;
   1146 				u_char maxoffset;
   1147 	                        /*
   1148 				 * Help the sequencer to translate the
   1149 				 * negotiated transfer rate.  Transfer is
   1150 				 * 1/4 the period in ns as is returned by
   1151 				 * the sync negotiation message.  So, we must
   1152 				 * multiply by four
   1153 				 */
   1154 	                        period = AHC_INB(ahc, ARG_1) << 2;
   1155 				offset = AHC_INB(ahc, ACCUM);
   1156 				targ_scratch = AHC_INB(ahc, TARG_SCRATCH
   1157 						   + scratch_offset);
   1158 				if(targ_scratch & WIDEXFER)
   1159 					maxoffset = 0x08;
   1160 				else
   1161 					maxoffset = 0x0f;
   1162 				ahc_scsirate(ahc, &rate, period,
   1163 					     MIN(offset,maxoffset),
   1164 					    target);
   1165 				/* Preserve the WideXfer flag */
   1166 				targ_scratch = rate | (targ_scratch & WIDEXFER);
   1167 				AHC_OUTB(ahc, TARG_SCRATCH + scratch_offset,
   1168 				     targ_scratch);
   1169 				AHC_OUTB(ahc, SCSIRATE, targ_scratch);
   1170 				if( (targ_scratch & 0x0f) == 0 )
   1171 				{
   1172 					/*
   1173 					 * The requested rate was so low
   1174 					 * that asyncronous transfers are
   1175 					 * faster (not to mention the
   1176 					 * controller won't support them),
   1177 					 * so we issue a message reject to
   1178 					 * ensure we go to asyncronous
   1179 					 * transfers.
   1180 					 */
   1181 					AHC_OUTB(ahc, RETURN_1, SEND_REJ);
   1182 				}
   1183 				/* See if we initiated Sync Negotiation */
   1184 				else if(ahc->sdtrpending & targ_mask)
   1185 				{
   1186 					/*
   1187 					 * Don't send an SDTR back to
   1188 					 * the target
   1189 					 */
   1190 					AHC_OUTB(ahc, RETURN_1, 0);
   1191 				}
   1192 				else{
   1193 					/*
   1194 					 * Send our own SDTR in reply
   1195 					 */
   1196 #ifdef AHC_DEBUG
   1197 					if(ahc_debug & AHC_SHOWMISC)
   1198 						printf("Sending SDTR!!\n");
   1199 #endif
   1200 					AHC_OUTB(ahc, RETURN_1, SEND_SDTR);
   1201 				}
   1202 				/*
   1203 				 * Negate the flags
   1204 				 */
   1205 				ahc->needsdtr &= ~targ_mask;
   1206 				ahc->sdtrpending &= ~targ_mask;
   1207 	                        break;
   1208 			}
   1209                     case WDTR_MSG:
   1210 			{
   1211 				u_char scratch, bus_width;
   1212 
   1213 				bus_width = AHC_INB(ahc, ARG_1);
   1214 
   1215 				scratch = AHC_INB(ahc, TARG_SCRATCH
   1216 					      + scratch_offset);
   1217 
   1218 				if(ahc->wdtrpending & targ_mask)
   1219 				{
   1220 					/*
   1221 					 * Don't send a WDTR back to the
   1222 					 * target, since we asked first.
   1223 					 */
   1224 					AHC_OUTB(ahc, RETURN_1, 0);
   1225 					switch(bus_width)
   1226 					{
   1227 						case BUS_8_BIT:
   1228 						    scratch &= 0x7f;
   1229 						    break;
   1230 						case BUS_16_BIT:
   1231 						    if(bootverbose)
   1232 		        				printf("%s: target "
   1233 							       "%d using 16Bit "
   1234 							       "transfers\n",
   1235 							       ahc_name(ahc),
   1236 							       target);
   1237 						    scratch |= 0x80;
   1238 						    break;
   1239 						case BUS_32_BIT:
   1240 						    /*
   1241 						     * How can we do 32bit
   1242 						     * transfers on a 16bit
   1243 						     * bus?
   1244 						     */
   1245 						    AHC_OUTB(ahc, RETURN_1,
   1246 							 SEND_REJ);
   1247 		        			    printf("%s: target "
   1248 						           "%d requested 32Bit "
   1249 						           "transfers.  "
   1250 							   "Rejecting...\n",
   1251 							   ahc_name(ahc),
   1252 							   target);
   1253 						    break;
   1254 						default:
   1255 						    break;
   1256 					}
   1257 				}
   1258 				else {
   1259 					/*
   1260 					 * Send our own WDTR in reply
   1261 					 */
   1262 					switch(bus_width)
   1263 					{
   1264 						case BUS_8_BIT:
   1265 							scratch &= 0x7f;
   1266 							break;
   1267 						case BUS_32_BIT:
   1268 						case BUS_16_BIT:
   1269 						    if(ahc->type & AHC_WIDE) {
   1270 							/* Negotiate 16_BITS */
   1271 							bus_width = BUS_16_BIT;
   1272 							if(bootverbose)
   1273 							    printf("%s: "
   1274 								"target %d "
   1275 								"using 16Bit "
   1276 							        "transfers\n",
   1277 								ahc_name(ahc),
   1278 								target);
   1279 						 	scratch |= 0x80;
   1280 						    }
   1281 						    else
   1282 							bus_width = BUS_8_BIT;
   1283 						    break;
   1284 						default:
   1285 						    break;
   1286 					}
   1287 					AHC_OUTB(ahc, RETURN_1,
   1288 						bus_width | SEND_WDTR);
   1289 				}
   1290 				ahc->needwdtr &= ~targ_mask;
   1291 				ahc->wdtrpending &= ~targ_mask;
   1292 				AHC_OUTB(ahc, TARG_SCRATCH + scratch_offset,
   1293 				     scratch);
   1294 				AHC_OUTB(ahc, SCSIRATE, scratch);
   1295 	                        break;
   1296 			}
   1297 		    case REJECT_MSG:
   1298 			{
   1299 				/*
   1300 				 * What we care about here is if we had an
   1301 				 * outstanding SDTR or WDTR message for this
   1302 				 * target.  If we did, this is a signal that
   1303 				 * the target is refusing negotiation.
   1304 				 */
   1305 
   1306 				u_char targ_scratch;
   1307 
   1308 				targ_scratch = AHC_INB(ahc, TARG_SCRATCH
   1309 						   + scratch_offset);
   1310 
   1311 				if(ahc->wdtrpending & targ_mask){
   1312 					/* note 8bit xfers and clear flag */
   1313 					targ_scratch &= 0x7f;
   1314 					ahc->needwdtr &= ~targ_mask;
   1315 					ahc->wdtrpending &= ~targ_mask;
   1316         				printf("%s:%c:%d: refuses "
   1317 					       "WIDE negotiation.  Using "
   1318 					       "8bit transfers\n",
   1319 						ahc_name(ahc),
   1320 					        channel, target);
   1321 				}
   1322 				else if(ahc->sdtrpending & targ_mask){
   1323 					/* note asynch xfers and clear flag */
   1324 					targ_scratch &= 0xf0;
   1325 					ahc->needsdtr &= ~targ_mask;
   1326 					ahc->sdtrpending &= ~targ_mask;
   1327         				printf("%s:%c:%d: refuses "
   1328 					       "syncronous negotiation.  Using "
   1329 					       "asyncronous transfers\n",
   1330 						ahc_name(ahc),
   1331 					        channel, target);
   1332 				}
   1333 				else {
   1334 					/*
   1335 					 * Otherwise, we ignore it.
   1336 					 */
   1337 #ifdef AHC_DEBUG
   1338 					if(ahc_debug & AHC_SHOWMISC)
   1339 						printf("%s:%c:%d: Message "
   1340 						       "reject -- ignored\n",
   1341 							ahc_name(ahc),
   1342 						        channel, target);
   1343 #endif
   1344 					break;
   1345 				}
   1346 				AHC_OUTB(ahc, TARG_SCRATCH + scratch_offset,
   1347 				     targ_scratch);
   1348 				AHC_OUTB(ahc, SCSIRATE, targ_scratch);
   1349 				break;
   1350 			}
   1351                     case BAD_STATUS:
   1352 			{
   1353 			  int	scb_index;
   1354 
   1355 			  /* The sequencer will notify us when a command
   1356 			   * has an error that would be of interest to
   1357 			   * the kernel.  This allows us to leave the sequencer
   1358 			   * running in the common case of command completes
   1359 			   * without error.
   1360 			   */
   1361 
   1362   			  scb_index = AHC_INB(ahc, SCB_TAG);
   1363 			  scb = ahc->scbarray[scb_index];
   1364 
   1365 			  /*
   1366 			   * Set the default return value to 0 (don't
   1367 			   * send sense).  The sense code will change
   1368 			   * this if needed and this reduces code
   1369 			   * duplication.
   1370 			   */
   1371 			  AHC_OUTB(ahc, RETURN_1, 0);
   1372 		 	  if (!(scb && (scb->flags & SCB_ACTIVE))) {
   1373 				printf("%s:%c:%d: ahc_intr - referenced scb "
   1374 				       "not valid during seqint 0x%x scb(%d)\n",
   1375 				       ahc_name(ahc),
   1376 				       channel, target, intstat,
   1377 				       scb_index);
   1378 			      goto clear;
   1379 			  }
   1380 
   1381 			  xs = scb->xs;
   1382 
   1383 			  scb->status = AHC_INB(ahc, SCB_TARGET_STATUS);
   1384 
   1385 #ifdef AHC_DEBUG
   1386 			  if((ahc_debug & AHC_SHOWSCBS)
   1387 			    && xs->sc_link->target == DEBUGTARG)
   1388 				ahc_print_scb(scb);
   1389 #endif
   1390 			  xs->status = scb->status;
   1391 			  switch(scb->status){
   1392 			    case SCSI_OK:
   1393 				printf("%s: Interrupted for staus of"
   1394 					" 0???\n", ahc_name(ahc));
   1395 				break;
   1396 			    case SCSI_CHECK:
   1397 #ifdef AHC_DEBUG
   1398 				if(ahc_debug & AHC_SHOWSENSE)
   1399 				{
   1400 					sc_print_addr(xs->sc_link);
   1401 					printf("requests Check Status\n");
   1402 				}
   1403 #endif
   1404 
   1405 				if((xs->error == XS_NOERROR) &&
   1406 				    !(scb->flags & SCB_SENSE)) {
   1407 					struct ahc_dma_seg *sg = scb->ahc_dma;
   1408 					struct scsi_sense *sc = &(scb->sense_cmd);
   1409 #ifdef AHC_DEBUG
   1410 					if(ahc_debug & AHC_SHOWSENSE)
   1411 					{
   1412 						sc_print_addr(xs->sc_link);
   1413 						printf("Sending Sense\n");
   1414 					}
   1415 #endif
   1416 #if defined(__FreeBSD__)
   1417 					sc->op_code = REQUEST_SENSE;
   1418 #elif defined(__NetBSD__)
   1419 					sc->opcode = REQUEST_SENSE;
   1420 #endif
   1421 					sc->byte2 =  xs->sc_link->lun << 5;
   1422 					sc->length = sizeof(struct scsi_sense_data);
   1423 					sc->control = 0;
   1424 
   1425 					sg->addr = KVTOPHYS(&xs->sense);
   1426 					sg->len = sizeof(struct scsi_sense_data);
   1427 
   1428 					scb->control &= DISCENB;
   1429 					scb->status = 0;
   1430 					scb->SG_segment_count = 1;
   1431 					scb->SG_list_pointer = KVTOPHYS(sg);
   1432 			                scb->data = sg->addr;
   1433 					scb->datalen = sg->len;
   1434 #ifdef AHC_BROKEN_CACHE
   1435 					if (ahc_broken_cache)
   1436 						INVALIDATE_CACHE();
   1437 #endif
   1438 					scb->cmdpointer = KVTOPHYS(sc);
   1439 					scb->cmdlen = sizeof(*sc);
   1440 
   1441 					scb->flags |= SCB_SENSE;
   1442 					ahc_send_scb(ahc, scb);
   1443 					/*
   1444 					 * Ensure that the target is "BUSY"
   1445 					 * so we don't get overlapping
   1446 					 * commands if we happen to be doing
   1447 					 * tagged I/O.
   1448 					 */
   1449 					ahc_busy_target(ahc, target, channel);
   1450 
   1451 					/*
   1452 					 * Make us the next command to run
   1453 					 */
   1454 					ahc_add_waiting_scb(ahc, scb);
   1455 					AHC_OUTB(ahc, RETURN_1, SEND_SENSE);
   1456 					break;
   1457 				}
   1458 				/*
   1459 				 * Clear the SCB_SENSE Flag and have
   1460 				 * the sequencer do a normal command
   1461 				 * complete with either a "DRIVER_STUFFUP"
   1462 				 * error or whatever other error condition
   1463 				 * we already had.
   1464 				 */
   1465 				scb->flags &= ~SCB_SENSE;
   1466 				if(xs->error == XS_NOERROR)
   1467 					xs->error = XS_DRIVER_STUFFUP;
   1468 				break;
   1469 			    case SCSI_BUSY:
   1470 				xs->error = XS_BUSY;
   1471 				sc_print_addr(xs->sc_link);
   1472 				printf("Target Busy\n");
   1473 				break;
   1474 #if defined(__FreeBSD__)
   1475 			    case SCSI_QUEUE_FULL:
   1476 				/*
   1477 				 * The upper level SCSI code will eventually
   1478 				 * handle this properly.
   1479 				 */
   1480 				sc_print_addr(xs->sc_link);
   1481 				printf("Queue Full\n");
   1482 				scb->flags = SCB_ASSIGNEDQ;
   1483 				SIMPLEQ_INSERT_TAIL(&ahc->assigned_scbs,
   1484 						   scb, links);
   1485 				break;
   1486 #elif defined(__NetBSD__)
   1487 				 /*
   1488 				  * XXX -
   1489 				  *	Do we need to handle this ?
   1490 				  *	But FreeBSD MI SCSI code seems to
   1491 				  *	do nothing about this.
   1492 				  */
   1493 #endif
   1494 			    default:
   1495 				sc_print_addr(xs->sc_link);
   1496 				printf("unexpected targ_status: %x\n",
   1497 					scb->status);
   1498 				xs->error = XS_DRIVER_STUFFUP;
   1499 				break;
   1500 			}
   1501 			break;
   1502 		  }
   1503 		  case RESIDUAL:
   1504 		  {
   1505 			int   scb_index;
   1506 			scb_index = AHC_INB(ahc, SCB_TAG);
   1507 			scb = ahc->scbarray[scb_index];
   1508 			xs = scb->xs;
   1509 			/*
   1510 			 * Don't clobber valid resid info with
   1511 			 * a resid coming from a check sense
   1512 			 * operation.
   1513 			 */
   1514 			if(!(scb->flags & SCB_SENSE)) {
   1515 				int resid_sgs;
   1516 
   1517 				/*
   1518 				 * Remainder of the SG where the transfer
   1519 				 * stopped.
   1520 				 */
   1521 				xs->resid =
   1522 					(AHC_INB(ahc, SCB_RESID_DCNT2)<<16) |
   1523 					(AHC_INB(ahc, SCB_RESID_DCNT1)<<8)  |
   1524 					 AHC_INB(ahc, SCB_RESID_DCNT0);
   1525 
   1526 				/*
   1527 				 * Add up the contents of all residual
   1528 				 * SG segments that are after the SG where
   1529 				 * the transfer stopped.
   1530 				 */
   1531 				resid_sgs = AHC_INB(ahc, SCB_RESID_SGCNT) - 1;
   1532 				while(resid_sgs > 0) {
   1533 					int sg;
   1534 
   1535 					sg = scb->SG_segment_count - resid_sgs;
   1536 					xs->resid += scb->ahc_dma[sg].len;
   1537 					resid_sgs--;
   1538 				}
   1539 
   1540 #if defined(__FreeBSD__)
   1541 				xs->flags |= SCSI_RESID_VALID;
   1542 #elif defined(__NetBSD__)
   1543 				/* XXX - Update to do this right */
   1544 #endif
   1545 #ifdef AHC_DEBUG
   1546 				if(ahc_debug & AHC_SHOWMISC) {
   1547 					sc_print_addr(xs->sc_link);
   1548 					printf("Handled Residual of %ld bytes\n"
   1549 						,xs->resid);
   1550 				}
   1551 #endif
   1552 			}
   1553 			break;
   1554 		  }
   1555 		  case ABORT_TAG:
   1556 		  {
   1557 			int   scb_index;
   1558 			scb_index = AHC_INB(ahc, SCB_TAG);
   1559 			scb = ahc->scbarray[scb_index];
   1560 			xs = scb->xs;
   1561 			/*
   1562 			 * We didn't recieve a valid tag back from
   1563 			 * the target on a reconnect.
   1564 			 */
   1565 			sc_print_addr(xs->sc_link);
   1566 			printf("invalid tag recieved -- sending ABORT_TAG\n");
   1567 			xs->error = XS_DRIVER_STUFFUP;
   1568 			untimeout(ahc_timeout, (caddr_t)scb);
   1569 			ahc_done(ahc, scb);
   1570 			break;
   1571 		  }
   1572 		  case AWAITING_MSG:
   1573 		  {
   1574 			int   scb_index;
   1575 			scb_index = AHC_INB(ahc, SCB_TAG);
   1576 			scb = ahc->scbarray[scb_index];
   1577 			/*
   1578 			 * This SCB had a zero length command, informing
   1579 			 * the sequencer that we wanted to send a special
   1580 			 * message to this target.  We only do this for
   1581 			 * BUS_DEVICE_RESET messages currently.
   1582 			 */
   1583 			if(scb->flags & SCB_DEVICE_RESET)
   1584 			{
   1585 				AHC_OUTB(ahc, MSG0,
   1586 					MSG_BUS_DEVICE_RESET);
   1587 				AHC_OUTB(ahc, MSG_LEN, 1);
   1588 				printf("Bus Device Reset Message Sent\n");
   1589 			}
   1590 			else
   1591 				panic("ahc_intr: AWAITING_MSG for an SCB that "
   1592 					"does not have a waiting message");
   1593 			break;
   1594 		  }
   1595 		  case IMMEDDONE:
   1596 		  {
   1597 			/*
   1598 			 * Take care of device reset messages
   1599 			 */
   1600 			u_char scbindex = AHC_INB(ahc, SCB_TAG);
   1601 			scb = ahc->scbarray[scbindex];
   1602 			if(scb->flags & SCB_DEVICE_RESET) {
   1603 				u_char targ_scratch;
   1604 				int found;
   1605 				/*
   1606 				 * Go back to async/narrow transfers and
   1607 				 * renegotiate.
   1608 				 */
   1609 				ahc_unbusy_target(ahc, target, channel);
   1610 				ahc->needsdtr |= ahc->needsdtr_orig & targ_mask;
   1611 				ahc->needwdtr |= ahc->needwdtr_orig & targ_mask;
   1612 				ahc->sdtrpending &= ~targ_mask;
   1613 				ahc->wdtrpending &= ~targ_mask;
   1614 				targ_scratch = AHC_INB(ahc, TARG_SCRATCH
   1615 							+ scratch_offset);
   1616 				targ_scratch &= SXFR;
   1617 				AHC_OUTB(ahc, TARG_SCRATCH + scratch_offset,
   1618 					targ_scratch);
   1619 				found = ahc_reset_device(ahc, target,
   1620 						channel, SCB_LIST_NULL,
   1621 						XS_NOERROR);
   1622 				sc_print_addr(scb->xs->sc_link);
   1623 				printf("Bus Device Reset delivered. "
   1624 					"%d SCBs aborted\n", found);
   1625 				ahc->in_timeout = FALSE;
   1626 				ahc_run_done_queue(ahc);
   1627 			}
   1628 			else
   1629 				panic("ahc_intr: Immediate complete for "
   1630 				      "unknown operation.");
   1631 			break;
   1632 		  }
   1633 #if NOT_YET
   1634 		  /* XXX Fill these in later */
   1635 		  case MESG_BUFFER_BUSY:
   1636 			break;
   1637 		  case MSGIN_PHASEMIS:
   1638 			break;
   1639 #endif
   1640 		  default:
   1641 			printf("ahc_intr: seqint, "
   1642 			       "intstat == 0x%x, scsisigi = 0x%x\n",
   1643 			       intstat, AHC_INB(ahc, SCSISIGI));
   1644 			break;
   1645 		}
   1646 clear:
   1647 		/*
   1648 		 * Clear the upper byte that holds SEQINT status
   1649 		 * codes and clear the SEQINT bit.
   1650 		 */
   1651 		AHC_OUTB(ahc, CLRINT, CLRSEQINT);
   1652 
   1653 		/*
   1654 		 *  The sequencer is paused immediately on
   1655 		 *  a SEQINT, so we should restart it when
   1656 		 *  we leave this section.
   1657 		 */
   1658 		UNPAUSE_SEQUENCER(ahc);
   1659 	   }
   1660 
   1661 
   1662 	   if (intstat & SCSIINT) {
   1663 
   1664 		int scb_index = AHC_INB(ahc, SCB_TAG);
   1665 		status = AHC_INB(ahc, SSTAT1);
   1666 
   1667 		scb = ahc->scbarray[scb_index];
   1668 		if (scb != NULL) /* XXX - is this case exist ? */
   1669 			xs = scb->xs;
   1670 
   1671 		if (status & SCSIRSTI) {
   1672 			char channel;
   1673 			channel = AHC_INB(ahc, SBLKCTL);
   1674 			channel = channel & SELBUSB ? 'B' : 'A';
   1675 			printf("%s: Someone reset channel %c\n",
   1676 				ahc_name(ahc), channel);
   1677 			ahc_reset_channel(ahc,
   1678 					  channel,
   1679 					  SCB_LIST_NULL,
   1680 					  XS_BUSY,
   1681 					  /* Initiate Reset */FALSE);
   1682 			scb = NULL;
   1683 		}
   1684 		else if (!(scb && (scb->flags & SCB_ACTIVE))){
   1685 			printf("%s: ahc_intr - referenced scb not "
   1686 			       "valid during scsiint 0x%x scb(%d)\n",
   1687 				ahc_name(ahc), status, scb_index);
   1688 			AHC_OUTB(ahc, CLRSINT1, status);
   1689 			UNPAUSE_SEQUENCER(ahc);
   1690 			AHC_OUTB(ahc, CLRINT, CLRSCSIINT);
   1691 			scb = NULL;
   1692 		}
   1693 		else if (status & SCSIPERR) {
   1694 			/*
   1695 			 * Determine the bus phase and
   1696 			 * queue an appropriate message
   1697 			 */
   1698 			char	*phase;
   1699 			u_char	mesg_out = MSG_NOP;
   1700 			u_char	lastphase = AHC_INB(ahc, LASTPHASE);
   1701 
   1702 			sc_print_addr(xs->sc_link);
   1703 
   1704 			switch(lastphase) {
   1705 				case P_DATAOUT:
   1706 					phase = "Data-Out";
   1707 					break;
   1708 				case P_DATAIN:
   1709 					phase = "Data-In";
   1710 					mesg_out = MSG_INITIATOR_DET_ERROR;
   1711 					break;
   1712 				case P_COMMAND:
   1713 					phase = "Command";
   1714 					break;
   1715 				case P_MESGOUT:
   1716 					phase = "Message-Out";
   1717 					break;
   1718 				case P_STATUS:
   1719 					phase = "Status";
   1720 					mesg_out = MSG_INITIATOR_DET_ERROR;
   1721 					break;
   1722 				case P_MESGIN:
   1723 					phase = "Message-In";
   1724 					mesg_out = MSG_MSG_PARITY_ERROR;
   1725 					break;
   1726 				default:
   1727 					phase = "unknown";
   1728 					break;
   1729 			}
   1730                         printf("parity error during %s phase.\n", phase);
   1731 
   1732 			/*
   1733 			 * We've set the hardware to assert ATN if we
   1734 			 * get a parity error on "in" phases, so all we
   1735 			 * need to do is stuff the message buffer with
   1736 			 * the appropriate message.  In phases have set
   1737 			 * mesg_out to something other than MSG_NOP.
   1738 			 */
   1739 			if(mesg_out != MSG_NOP) {
   1740 				AHC_OUTB(ahc, MSG0, mesg_out);
   1741 				AHC_OUTB(ahc, MSG_LEN, 1);
   1742 			}
   1743 			else
   1744 				/*
   1745 				 * Should we allow the target to make
   1746 				 * this decision for us?
   1747 				 */
   1748 				xs->error = XS_DRIVER_STUFFUP;
   1749 		}
   1750 		else if (status & SELTO) {
   1751 			u_char waiting;
   1752 			u_char flags;
   1753                         xs->error = XS_SELTIMEOUT;
   1754 			/*
   1755 			 * Clear any pending messages for the timed out
   1756 			 * target, and mark the target as free
   1757 			 */
   1758 			flags = AHC_INB(ahc, FLAGS);
   1759 			AHC_OUTB(ahc, MSG_LEN, 0);
   1760 			ahc_unbusy_target(ahc, xs->sc_link->target,
   1761 #if defined(__FreeBSD__)
   1762 			 	((long)xs->sc_link->fordriver & SELBUSB)
   1763 #elif defined(__NetBSD__)
   1764 				IS_SCSIBUS_B(ahc, xs->sc_link)
   1765 #endif
   1766 				 	? 'B' : 'A');
   1767 
   1768 			AHC_OUTB(ahc, SCB_CONTROL, 0);
   1769 
   1770 			AHC_OUTB(ahc, CLRSINT1, CLRSELTIMEO);
   1771 
   1772 			AHC_OUTB(ahc, CLRINT, CLRSCSIINT);
   1773 
   1774 			/* Shift the waiting for selection queue forward */
   1775 			waiting = AHC_INB(ahc, WAITING_SCBH);
   1776 			AHC_OUTB(ahc, SCBPTR, waiting);
   1777 			waiting = AHC_INB(ahc, SCB_NEXT);
   1778 			AHC_OUTB(ahc, WAITING_SCBH, waiting);
   1779 
   1780 			RESTART_SEQUENCER(ahc);
   1781 		}
   1782 		else if (!(status & BUSFREE)) {
   1783 		      sc_print_addr(xs->sc_link);
   1784 		      printf("Unknown SCSIINT. Status = 0x%x\n", status);
   1785 		      AHC_OUTB(ahc, CLRSINT1, status);
   1786 		      UNPAUSE_SEQUENCER(ahc);
   1787 		      AHC_OUTB(ahc, CLRINT, CLRSCSIINT);
   1788 		      scb = NULL;
   1789 		}
   1790 		if(scb != NULL) {
   1791 		    /* We want to process the command */
   1792 		    untimeout(ahc_timeout, (caddr_t)scb);
   1793 		    ahc_done(ahc, scb);
   1794 		}
   1795 	}
   1796 	if (intstat & CMDCMPLT) {
   1797 		int   scb_index;
   1798 
   1799 		do {
   1800 			scb_index = AHC_INB(ahc, QOUTFIFO);
   1801 			scb = ahc->scbarray[scb_index];
   1802 			if (!scb || !(scb->flags & SCB_ACTIVE)) {
   1803 				printf("%s: WARNING "
   1804 				       "no command for scb %d (cmdcmplt)\n"
   1805 				       "QOUTCNT == %d\n",
   1806 					ahc_name(ahc), scb_index,
   1807 					AHC_INB(ahc, QOUTCNT));
   1808 				AHC_OUTB(ahc, CLRINT, CLRCMDINT);
   1809 				continue;
   1810 			}
   1811 			AHC_OUTB(ahc, CLRINT, CLRCMDINT);
   1812 			untimeout(ahc_timeout, (caddr_t)scb);
   1813 			ahc_done(ahc, scb);
   1814 
   1815 		} while (AHC_INB(ahc, QOUTCNT) & ahc->qcntmask);
   1816 
   1817 		ahc_run_waiting_queues(ahc);
   1818 	}
   1819 #if defined(__NetBSD__)
   1820 	return 1;
   1821 #endif
   1822 }
   1823 
   1824 /*
   1825  * We have a scb which has been processed by the
   1826  * adaptor, now we look to see how the operation
   1827  * went.
   1828  */
   1829 static void
   1830 ahc_done(ahc, scb)
   1831 	struct ahc_data *ahc;
   1832 	struct scb *scb;
   1833 {
   1834 	struct scsi_xfer *xs = scb->xs;
   1835 
   1836 	SC_DEBUG(xs->sc_link, SDEV_DB2, ("ahc_done\n"));
   1837 	/*
   1838 	 * Put the results of the operation
   1839 	 * into the xfer and call whoever started it
   1840 	 */
   1841 #if defined(__NetBSD__)
   1842 	if (xs->error != XS_NOERROR) {
   1843 		/* Don't override the error value. */
   1844 	} else if (scb->flags & SCB_ABORTED) {
   1845 		xs->error = XS_DRIVER_STUFFUP;
   1846 	} else
   1847 #endif
   1848 	if(scb->flags & SCB_SENSE)
   1849 		xs->error = XS_SENSE;
   1850 	if(scb->flags & SCB_SENTORDEREDTAG)
   1851 		ahc->in_timeout = FALSE;
   1852 #if defined(__FreeBSD__)
   1853 	if ((xs->flags & SCSI_ERR_OK) && !(xs->error == XS_SENSE)) {
   1854 		/* All went correctly  OR errors expected */
   1855 		xs->error = XS_NOERROR;
   1856 	}
   1857 #elif defined(__NetBSD__)
   1858 	/*
   1859 	 * Since NetBSD doesn't have error ignoring operation mode
   1860 	 * (SCSI_ERR_OK in FreeBSD), we don't have to care this case.
   1861 	 */
   1862 #endif
   1863 	xs->flags |= ITSDONE;
   1864 #ifdef AHC_TAGENABLE
   1865 	if(xs->cmd->opcode == INQUIRY && xs->error == XS_NOERROR)
   1866 	{
   1867 		struct scsi_inquiry_data *inq_data;
   1868 		u_short mask = 0x01 << (xs->sc_link->target |
   1869 				(scb->tcl & 0x08));
   1870 		/*
   1871 		 * Sneak a look at the results of the SCSI Inquiry
   1872 		 * command and see if we can do Tagged queing.  This
   1873 		 * should really be done by the higher level drivers.
   1874 		 */
   1875 		inq_data = (struct scsi_inquiry_data *)xs->data;
   1876 		if((inq_data->flags & SID_CmdQue) && !(ahc->tagenable & mask))
   1877 		{
   1878 		        printf("%s: target %d Tagged Queuing Device\n",
   1879 				ahc_name(ahc), xs->sc_link->target);
   1880 			ahc->tagenable |= mask;
   1881 			if(ahc->maxhscbs >= 16 || (ahc->flags & AHC_PAGESCBS)) {
   1882 				/* Default to 8 tags */
   1883 				xs->sc_link->opennings += 6;
   1884 			}
   1885 			else
   1886 			{
   1887 				/*
   1888 				 * Default to 4 tags on whimpy
   1889 				 * cards that don't have much SCB
   1890 				 * space and can't page.  This prevents
   1891 				 * a single device from hogging all
   1892 				 * slots.  We should really have a better
   1893 				 * way of providing fairness.
   1894 				 */
   1895 				xs->sc_link->opennings += 2;
   1896 			}
   1897 		}
   1898 	}
   1899 #endif
   1900 	ahc_free_scb(ahc, scb, xs->flags);
   1901 	scsi_done(xs);
   1902 }
   1903 
   1904 /*
   1905  * Start the board, ready for normal operation
   1906  */
   1907 int
   1908 ahc_init(ahc)
   1909 	struct  ahc_data *ahc;
   1910 {
   1911 	u_char	scsi_conf, sblkctl, i;
   1912 	int     max_targ = 15;
   1913 	/*
   1914 	 * Assume we have a board at this stage and it has been reset.
   1915 	 */
   1916 
   1917 	/* Handle the SCBPAGING option */
   1918 #ifndef AHC_SCBPAGING_ENABLE
   1919 	ahc->flags &= ~AHC_PAGESCBS;
   1920 #endif
   1921 
   1922 	/* Determine channel configuration and who we are on the scsi bus. */
   1923 	switch ( (sblkctl = AHC_INB(ahc, SBLKCTL) & 0x0a) ) {
   1924 	    case 0:
   1925 		ahc->our_id = (AHC_INB(ahc, SCSICONF) & HSCSIID);
   1926 		ahc->flags &= ~AHC_CHANNEL_B_PRIMARY;
   1927 		if(ahc->type == AHC_394)
   1928 			printf("Channel %c, SCSI Id=%d, ",
   1929 				ahc->flags & AHC_CHNLB ? 'B' : 'A',
   1930 				ahc->our_id);
   1931 		else
   1932 			printf("Single Channel, SCSI Id=%d, ", ahc->our_id);
   1933 		AHC_OUTB(ahc, FLAGS, SINGLE_BUS | (ahc->flags & AHC_PAGESCBS));
   1934 		break;
   1935 	    case 2:
   1936 		ahc->our_id = (AHC_INB(ahc, SCSICONF + 1) & HWSCSIID);
   1937 		ahc->flags &= ~AHC_CHANNEL_B_PRIMARY;
   1938 		if(ahc->type == AHC_394)
   1939 			printf("Wide Channel %c, SCSI Id=%d, ",
   1940 				ahc->flags & AHC_CHNLB ? 'B' : 'A',
   1941 				ahc->our_id);
   1942 		else
   1943 			printf("Wide Channel, SCSI Id=%d, ", ahc->our_id);
   1944 		ahc->type |= AHC_WIDE;
   1945 		AHC_OUTB(ahc, FLAGS, WIDE_BUS | (ahc->flags & AHC_PAGESCBS));
   1946 		break;
   1947 	    case 8:
   1948 		ahc->our_id = (AHC_INB(ahc, SCSICONF) & HSCSIID);
   1949 		ahc->our_id_b = (AHC_INB(ahc, SCSICONF + 1) & HSCSIID);
   1950 		printf("Twin Channel, A SCSI Id=%d, B SCSI Id=%d, ",
   1951 			ahc->our_id, ahc->our_id_b);
   1952 		ahc->type |= AHC_TWIN;
   1953 		AHC_OUTB(ahc, FLAGS, TWIN_BUS | (ahc->flags & AHC_PAGESCBS));
   1954 		break;
   1955 	    default:
   1956 		printf(" Unsupported adapter type.  Ignoring\n");
   1957 		return(-1);
   1958 	}
   1959 
   1960 	/* Determine the number of SCBs */
   1961 
   1962 	{
   1963 		AHC_OUTB(ahc, SCBPTR, 0);
   1964 		AHC_OUTB(ahc, SCB_CONTROL, 0);
   1965 		for(i = 1; i < AHC_SCB_MAX; i++) {
   1966 			AHC_OUTB(ahc, SCBPTR, i);
   1967 			AHC_OUTB(ahc, SCB_CONTROL, i);
   1968 			if(AHC_INB(ahc, SCB_CONTROL) != i)
   1969 				break;
   1970 			AHC_OUTB(ahc, SCBPTR, 0);
   1971 			if(AHC_INB(ahc, SCB_CONTROL) != 0)
   1972 				break;
   1973 			/* Clear the control byte. */
   1974 			AHC_OUTB(ahc, SCBPTR, i);
   1975 			AHC_OUTB(ahc, SCB_CONTROL, 0);
   1976 
   1977 			ahc->qcntmask |= i;     /* Update the count mask. */
   1978 		}
   1979 
   1980 		/* Ensure we clear the 0 SCB's control byte. */
   1981 		AHC_OUTB(ahc, SCBPTR, 0);
   1982 		AHC_OUTB(ahc, SCB_CONTROL, 0);
   1983 
   1984 		ahc->qcntmask |= i;
   1985 		ahc->maxhscbs = i;
   1986 	}
   1987 
   1988 	if((ahc->maxhscbs < AHC_SCB_MAX) && (ahc->flags & AHC_PAGESCBS))
   1989 		ahc->maxscbs = AHC_SCB_MAX;
   1990 	else {
   1991 		ahc->maxscbs = ahc->maxhscbs;
   1992 		ahc->flags &= ~AHC_PAGESCBS;
   1993 	}
   1994 
   1995 	printf("%d SCBs\n", ahc->maxhscbs);
   1996 
   1997 #ifdef AHC_DEBUG
   1998 	if(ahc_debug & AHC_SHOWMISC) {
   1999 		struct scb	test;
   2000 		printf("%s: hardware scb %ld bytes; kernel scb; "
   2001 		       "ahc_dma %d bytes\n",
   2002 			ahc_name(ahc),
   2003 		        (u_long)&(test.next) - (u_long)(&test),
   2004 			sizeof(test),
   2005 			sizeof(struct ahc_dma_seg));
   2006 	}
   2007 #endif /* AHC_DEBUG */
   2008 
   2009 	/* Set the SCSI Id, SXFRCTL0, SXFRCTL1, and SIMODE1, for both channels*/
   2010 	if(ahc->type & AHC_TWIN)
   2011 	{
   2012 		/*
   2013 		 * The device is gated to channel B after a chip reset,
   2014 		 * so set those values first
   2015 		 */
   2016 		AHC_OUTB(ahc, SCSIID, ahc->our_id_b);
   2017 		scsi_conf = AHC_INB(ahc, SCSICONF + 1);
   2018 		AHC_OUTB(ahc, SXFRCTL1, (scsi_conf & (ENSPCHK|STIMESEL))
   2019 					| ENSTIMER|ACTNEGEN|STPWEN);
   2020 		AHC_OUTB(ahc, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
   2021 		if(ahc->type & AHC_ULTRA)
   2022 			AHC_OUTB(ahc, SXFRCTL0, DFON|SPIOEN|ULTRAEN);
   2023 		else
   2024 			AHC_OUTB(ahc, SXFRCTL0, DFON|SPIOEN);
   2025 
   2026 		if(scsi_conf & RESET_SCSI) {
   2027 			/* Reset the bus */
   2028 			if(bootverbose)
   2029 				printf("%s: Reseting Channel B\n",
   2030 				       ahc_name(ahc));
   2031 			AHC_OUTB(ahc, SCSISEQ, SCSIRSTO);
   2032 			DELAY(1000);
   2033 			AHC_OUTB(ahc, SCSISEQ, 0);
   2034 
   2035 			/* Ensure we don't get a RSTI interrupt from this */
   2036 			AHC_OUTB(ahc, CLRSINT1, CLRSCSIRSTI);
   2037 			AHC_OUTB(ahc, CLRINT, CLRSCSIINT);
   2038 		}
   2039 
   2040 		/* Select Channel A */
   2041 		AHC_OUTB(ahc, SBLKCTL, 0);
   2042 	}
   2043 	AHC_OUTB(ahc, SCSIID, ahc->our_id);
   2044 	scsi_conf = AHC_INB(ahc, SCSICONF);
   2045 	AHC_OUTB(ahc, SXFRCTL1, (scsi_conf & (ENSPCHK|STIMESEL))
   2046 				| ENSTIMER|ACTNEGEN|STPWEN);
   2047 	AHC_OUTB(ahc, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
   2048 	if(ahc->type & AHC_ULTRA)
   2049 		AHC_OUTB(ahc, SXFRCTL0, DFON|SPIOEN|ULTRAEN);
   2050 	else
   2051 		AHC_OUTB(ahc, SXFRCTL0, DFON|SPIOEN);
   2052 
   2053 	if(scsi_conf & RESET_SCSI) {
   2054 		/* Reset the bus */
   2055 		if(bootverbose)
   2056 			printf("%s: Reseting Channel A\n", ahc_name(ahc));
   2057 
   2058 		AHC_OUTB(ahc, SCSISEQ, SCSIRSTO);
   2059 		DELAY(1000);
   2060 		AHC_OUTB(ahc, SCSISEQ, 0);
   2061 
   2062 		/* Ensure we don't get a RSTI interrupt from this */
   2063 		AHC_OUTB(ahc, CLRSINT1, CLRSCSIRSTI);
   2064 		AHC_OUTB(ahc, CLRINT, CLRSCSIINT);
   2065 	}
   2066 
   2067 	/*
   2068 	 * Look at the information that board initialization or
   2069 	 * the board bios has left us.  In the lower four bits of each
   2070 	 * target's scratch space any value other than 0 indicates
   2071 	 * that we should initiate syncronous transfers.  If it's zero,
   2072 	 * the user or the BIOS has decided to disable syncronous
   2073 	 * negotiation to that target so we don't activate the needsdtr
   2074 	 * flag.
   2075 	 */
   2076 	ahc->needsdtr_orig = 0;
   2077 	ahc->needwdtr_orig = 0;
   2078 
   2079 	/* Grab the disconnection disable table and invert it for our needs */
   2080 	if(ahc->flags & AHC_USEDEFAULTS) {
   2081 		printf("%s: Host Adapter Bios disabled.  Using default SCSI "
   2082 			"device parameters\n", ahc_name(ahc));
   2083 		ahc->discenable = 0xff;
   2084 	}
   2085 	else
   2086 		ahc->discenable = ~((AHC_INB(ahc, DISC_DSB + 1) << 8)
   2087 				   | AHC_INB(ahc, DISC_DSB));
   2088 
   2089 	if(!(ahc->type & (AHC_WIDE|AHC_TWIN)))
   2090 		max_targ = 7;
   2091 
   2092 	for(i = 0; i <= max_targ; i++){
   2093 		u_char target_settings;
   2094 		if (ahc->flags & AHC_USEDEFAULTS) {
   2095 			target_settings = 0; /* 10MHz */
   2096 			ahc->needsdtr_orig |= (0x01 << i);
   2097 			ahc->needwdtr_orig |= (0x01 << i);
   2098 		}
   2099 		else {
   2100 			/* Take the settings leftover in scratch RAM. */
   2101 			target_settings = AHC_INB(ahc, TARG_SCRATCH + i);
   2102 
   2103 			if(target_settings & 0x0f){
   2104 				ahc->needsdtr_orig |= (0x01 << i);
   2105 				/*Default to a asyncronous transfers(0 offset)*/
   2106 				target_settings &= 0xf0;
   2107 			}
   2108 			if(target_settings & 0x80){
   2109 				ahc->needwdtr_orig |= (0x01 << i);
   2110 				/*
   2111 				 * We'll set the Wide flag when we
   2112 				 * are successful with Wide negotiation.
   2113 				 * Turn it off for now so we aren't
   2114 				 * confused.
   2115 				 */
   2116 				target_settings &= 0x7f;
   2117 			}
   2118 		}
   2119 		AHC_OUTB(ahc, TARG_SCRATCH+i,target_settings);
   2120 	}
   2121 	/*
   2122 	 * If we are not a WIDE device, forget WDTR.  This
   2123 	 * makes the driver work on some cards that don't
   2124 	 * leave these fields cleared when the BIOS is not
   2125 	 * installed.
   2126 	 */
   2127 	if(!(ahc->type & AHC_WIDE))
   2128 		ahc->needwdtr_orig = 0;
   2129 	ahc->needsdtr = ahc->needsdtr_orig;
   2130 	ahc->needwdtr = ahc->needwdtr_orig;
   2131 	ahc->sdtrpending = 0;
   2132 	ahc->wdtrpending = 0;
   2133 	ahc->tagenable = 0;
   2134 	ahc->orderedtag = 0;
   2135 
   2136 #ifdef AHC_DEBUG
   2137 	/* How did we do? */
   2138 	if(ahc_debug & AHC_SHOWMISC)
   2139 		printf("NEEDSDTR == 0x%x\nNEEDWDTR == 0x%x\n"
   2140 			"DISCENABLE == 0x%x\n", ahc->needsdtr,
   2141 			ahc->needwdtr, ahc->discenable);
   2142 #endif
   2143 	/*
   2144 	 * Set the number of availible SCBs
   2145 	 */
   2146 	AHC_OUTB(ahc, SCBCOUNT, ahc->maxhscbs);
   2147 
   2148 	/*
   2149 	 * 2's compliment of maximum tag value
   2150 	 */
   2151 	i = ahc->maxscbs;
   2152 	AHC_OUTB(ahc, COMP_SCBCOUNT, -i & 0xff);
   2153 
   2154 	/*
   2155 	 * QCount mask to deal with broken aic7850s that
   2156 	 * sporatically get garbage in the upper bits of
   2157 	 * their QCount registers.
   2158 	 */
   2159 	AHC_OUTB(ahc, QCNTMASK, ahc->qcntmask);
   2160 
   2161 	/* We don't have any busy targets right now */
   2162 	AHC_OUTB(ahc, ACTIVE_A, 0);
   2163 	AHC_OUTB(ahc, ACTIVE_B, 0);
   2164 
   2165 	/* We don't have any waiting selections */
   2166 	AHC_OUTB(ahc, WAITING_SCBH, SCB_LIST_NULL);
   2167 
   2168 	/* Our disconnection list is empty too */
   2169 	AHC_OUTB(ahc, DISCONNECTED_SCBH, SCB_LIST_NULL);
   2170 
   2171 	/* Message out buffer starts empty */
   2172 	AHC_OUTB(ahc, MSG_LEN, 0x00);
   2173 
   2174 	/*
   2175 	 * Load the Sequencer program and Enable the adapter
   2176 	 * in "fast" mode.
   2177          */
   2178 	if(bootverbose)
   2179 		printf("%s: Downloading Sequencer Program...",
   2180 		       ahc_name(ahc));
   2181 
   2182 	ahc_loadseq(ahc);
   2183 
   2184 	if(bootverbose)
   2185 		printf("Done\n");
   2186 
   2187 	AHC_OUTB(ahc, SEQCTL, FASTMODE);
   2188 
   2189 	UNPAUSE_SEQUENCER(ahc);
   2190 
   2191 	/*
   2192 	 * Note that we are going and return (to probe)
   2193 	 */
   2194 	ahc->flags |= AHC_INIT;
   2195 	return (0);
   2196 }
   2197 
   2198 static void
   2199 ahcminphys(bp)
   2200         struct buf *bp;
   2201 {
   2202 /*
   2203  * Even though the card can transfer up to 16megs per command
   2204  * we are limited by the number of segments in the dma segment
   2205  * list that we can hold.  The worst case is that all pages are
   2206  * discontinuous physically, hense the "page per segment" limit
   2207  * enforced here.
   2208  */
   2209         if (bp->b_bcount > ((AHC_NSEG - 1) * PAGESIZ)) {
   2210                 bp->b_bcount = ((AHC_NSEG - 1) * PAGESIZ);
   2211         }
   2212 #if defined(__NetBSD__)
   2213 	minphys(bp);
   2214 #endif
   2215 }
   2216 
   2217 /*
   2218  * start a scsi operation given the command and
   2219  * the data address, target, and lun all of which
   2220  * are stored in the scsi_xfer struct
   2221  */
   2222 static int32_t
   2223 ahc_scsi_cmd(xs)
   2224         struct scsi_xfer *xs;
   2225 {
   2226         struct	scb *scb;
   2227         struct	ahc_dma_seg *sg;
   2228         int     seg;            /* scatter gather seg being worked on */
   2229         int     thiskv;
   2230         physaddr thisphys, nextphys;
   2231         int     bytes_this_seg, bytes_this_page, datalen, flags;
   2232         struct	ahc_data *ahc;
   2233 	u_short	mask;
   2234         int     s;
   2235 
   2236 	ahc = (struct ahc_data *)xs->sc_link->adapter_softc;
   2237 	mask  = (0x01 << (xs->sc_link->target
   2238 #if defined(__FreeBSD__)
   2239 				| ((u_long)xs->sc_link->fordriver & 0x08)));
   2240 #elif defined(__NetBSD__)
   2241 			| (IS_SCSIBUS_B(ahc, xs->sc_link) ? SELBUSB : 0) ));
   2242 #endif
   2243         SC_DEBUG(xs->sc_link, SDEV_DB2, ("ahc_scsi_cmd\n"));
   2244         /*
   2245          * get an scb to use. If the transfer
   2246          * is from a buf (possibly from interrupt time)
   2247          * then we can't allow it to sleep
   2248          */
   2249         flags = xs->flags;
   2250         if (flags & ITSDONE) {
   2251                 printf("%s: Already done?", ahc_name(ahc));
   2252                 xs->flags &= ~ITSDONE;
   2253         }
   2254         if (!(flags & INUSE)) {
   2255                 printf("%s: Not in use?", ahc_name(ahc));
   2256                 xs->flags |= INUSE;
   2257         }
   2258         if (!(scb = ahc_get_scb(ahc, flags))) {
   2259                 xs->error = XS_DRIVER_STUFFUP;
   2260                 return (TRY_AGAIN_LATER);
   2261         }
   2262         SC_DEBUG(xs->sc_link, SDEV_DB3, ("start scb(%p)\n", scb));
   2263         scb->xs = xs;
   2264         if (flags & SCSI_RESET)
   2265 		scb->flags |= SCB_DEVICE_RESET|SCB_IMMED;
   2266         /*
   2267          * Put all the arguments for the xfer in the scb
   2268          */
   2269 
   2270 	if(ahc->tagenable & mask) {
   2271 		scb->control |= TAG_ENB;
   2272 		if(ahc->orderedtag & mask) {
   2273 			printf("Ordered Tag sent\n");
   2274 			scb->control |= 0x02;
   2275 			ahc->orderedtag &= ~mask;
   2276 		}
   2277 	}
   2278 	if(ahc->discenable & mask)
   2279 		scb->control |= DISCENB;
   2280 	if((ahc->needwdtr & mask) && !(ahc->wdtrpending & mask))
   2281 	{
   2282 		scb->control |= NEEDWDTR;
   2283 		ahc->wdtrpending |= mask;
   2284 	}
   2285 	else if((ahc->needsdtr & mask) && !(ahc->sdtrpending & mask))
   2286 	{
   2287 		scb->control |= NEEDSDTR;
   2288 		ahc->sdtrpending |= mask;
   2289 	}
   2290 	scb->tcl = ((xs->sc_link->target << 4) & 0xF0) |
   2291 #if defined(__FreeBSD__)
   2292 				  ((u_long)xs->sc_link->fordriver & 0x08) |
   2293 #elif defined(__NetBSD__)
   2294 				  (IS_SCSIBUS_B(ahc,xs->sc_link)? SELBUSB : 0)|
   2295 #endif
   2296 				  (xs->sc_link->lun & 0x07);
   2297 	scb->cmdlen = xs->cmdlen;
   2298 	scb->cmdpointer = KVTOPHYS(xs->cmd);
   2299 	xs->resid = 0;
   2300 	xs->status = 0;
   2301 	if (xs->datalen) {      /* should use S/G only if not zero length */
   2302 		scb->SG_list_pointer = KVTOPHYS(scb->ahc_dma);
   2303 		sg = scb->ahc_dma;
   2304 		seg = 0;
   2305 		/*
   2306 		 * Set up the scatter gather block
   2307 		 */
   2308 		SC_DEBUG(xs->sc_link, SDEV_DB4,
   2309 			 ("%ld @%p:- ", xs->datalen, xs->data));
   2310 		datalen = xs->datalen;
   2311 		thiskv = (int) xs->data;
   2312 		thisphys = KVTOPHYS(thiskv);
   2313 
   2314 		while ((datalen) && (seg < AHC_NSEG)) {
   2315 			bytes_this_seg = 0;
   2316 
   2317 			/* put in the base address */
   2318 			sg->addr = thisphys;
   2319 
   2320 			SC_DEBUGN(xs->sc_link, SDEV_DB4, ("0x%lx", thisphys));
   2321 
   2322 			/* do it at least once */
   2323 			nextphys = thisphys;
   2324 			while ((datalen) && (thisphys == nextphys)) {
   2325 				/*
   2326 				 * This page is contiguous (physically)
   2327 				 * with the the last, just extend the
   2328 				 * length
   2329 				 */
   2330 				/* how far to the end of the page */
   2331 				nextphys = (thisphys & (~(PAGESIZ - 1)))
   2332 					   + PAGESIZ;
   2333 				bytes_this_page = nextphys - thisphys;
   2334 				/**** or the data ****/
   2335 				bytes_this_page = min(bytes_this_page ,datalen);
   2336 				bytes_this_seg += bytes_this_page;
   2337 				datalen -= bytes_this_page;
   2338 
   2339 				/* get more ready for the next page */
   2340 				thiskv = (thiskv & (~(PAGESIZ - 1)))
   2341 					 + PAGESIZ;
   2342 				if (datalen)
   2343 					thisphys = KVTOPHYS(thiskv);
   2344 			}
   2345 			/*
   2346 			 * next page isn't contiguous, finish the seg
   2347 			 */
   2348 			SC_DEBUGN(xs->sc_link, SDEV_DB4,
   2349 					("(0x%x)", bytes_this_seg));
   2350 			sg->len = bytes_this_seg;
   2351 			sg++;
   2352 			seg++;
   2353 		}
   2354 		scb->SG_segment_count = seg;
   2355 
   2356 		/* Copy the first SG into the data pointer area */
   2357 		scb->data = scb->ahc_dma->addr;
   2358 		scb->datalen = scb->ahc_dma->len;
   2359 		SC_DEBUGN(xs->sc_link, SDEV_DB4, ("\n"));
   2360 		if (datalen) {
   2361 			/* there's still data, must have run out of segs! */
   2362 			printf("%s: ahc_scsi_cmd: more than %d DMA segs\n",
   2363 				ahc_name(ahc), AHC_NSEG);
   2364 			xs->error = XS_DRIVER_STUFFUP;
   2365 			ahc_free_scb(ahc, scb, flags);
   2366 			return (COMPLETE);
   2367 		}
   2368 #ifdef AHC_BROKEN_CACHE
   2369 		if (ahc_broken_cache)
   2370 			INVALIDATE_CACHE();
   2371 #endif
   2372 	}
   2373 	else {
   2374 		/*
   2375 		 * No data xfer, use non S/G values
   2376 	 	 */
   2377 		scb->SG_segment_count = 0;
   2378 		scb->SG_list_pointer = 0;
   2379 		scb->data = 0;
   2380 		scb->datalen = 0;
   2381 	}
   2382 
   2383 #ifdef AHC_DEBUG
   2384 	if((ahc_debug & AHC_SHOWSCBS) && (xs->sc_link->target == DEBUGTARG))
   2385 		ahc_print_scb(scb);
   2386 #endif
   2387 	s = splbio();
   2388 
   2389 	if( scb->position != SCB_LIST_NULL )
   2390 	{
   2391 		/* We already have a valid slot */
   2392 		u_char curscb;
   2393 
   2394 		PAUSE_SEQUENCER(ahc);
   2395 		curscb = AHC_INB(ahc, SCBPTR);
   2396 		AHC_OUTB(ahc, SCBPTR, scb->position);
   2397 		ahc_send_scb(ahc, scb);
   2398 		AHC_OUTB(ahc, SCBPTR, curscb);
   2399 		AHC_OUTB(ahc, QINFIFO, scb->position);
   2400 		UNPAUSE_SEQUENCER(ahc);
   2401 		scb->flags = SCB_ACTIVE;
   2402 		if (!(flags & SCSI_NOMASK)) {
   2403 			timeout(ahc_timeout, (caddr_t)scb,
   2404 				(xs->timeout * hz) / 1000);
   2405 		}
   2406 		SC_DEBUG(xs->sc_link, SDEV_DB3, ("cmd_sent\n"));
   2407 	}
   2408 	else {
   2409 		scb->flags = SCB_WAITINGQ;
   2410 		SIMPLEQ_INSERT_TAIL(&ahc->waiting_scbs, scb, links);
   2411 		ahc_run_waiting_queues(ahc);
   2412 	}
   2413 	if (!(flags & SCSI_NOMASK)) {
   2414 		splx(s);
   2415 		return (SUCCESSFULLY_QUEUED);
   2416 	}
   2417 	/*
   2418 	 * If we can't use interrupts, poll for completion
   2419 	 */
   2420 	SC_DEBUG(xs->sc_link, SDEV_DB3, ("cmd_poll\n"));
   2421 	do {
   2422 		if (ahc_poll(ahc, xs->timeout)) {
   2423 			if (!(xs->flags & SCSI_SILENT))
   2424 				printf("cmd fail\n");
   2425 			ahc_timeout(scb);
   2426 			break;
   2427 		}
   2428 	} while (!(xs->flags & ITSDONE));  /* a non command complete intr */
   2429 	splx(s);
   2430 	return (COMPLETE);
   2431 }
   2432 
   2433 
   2434 /*
   2435  * A scb (and hence an scb entry on the board is put onto the
   2436  * free list.
   2437  */
   2438 static void
   2439 ahc_free_scb(ahc, scb, flags)
   2440         struct	ahc_data *ahc;
   2441         int     flags;
   2442         struct  scb *scb;
   2443 {
   2444 	struct scb *wscb;
   2445 	unsigned int opri;
   2446 
   2447 	opri = splbio();
   2448 
   2449 	scb->flags = SCB_FREE;
   2450 	if(scb->position == SCB_LIST_NULL) {
   2451 		SIMPLEQ_INSERT_HEAD(&ahc->page_scbs, scb, links);
   2452 		if(!scb->links.sqe_next && !ahc->free_scbs.sqh_first)
   2453 			/*
   2454 			 * If there were no SCBs availible, wake anybody waiting
   2455 			 * for one to come free.
   2456 			 */
   2457 			wakeup((caddr_t)&ahc->free_scbs);
   2458 	}
   2459 	/*
   2460 	 * If there are any SCBS on the waiting queue,
   2461 	 * assign the slot of this "freed" SCB to the first
   2462 	 * one.  We'll run the waiting queues after all command
   2463 	 * completes for a particular interrupt are completed
   2464 	 * or when we start another command.
   2465 	 */
   2466 	else if((wscb = ahc->waiting_scbs.sqh_first) != NULL) {
   2467 		SIMPLEQ_REMOVE_HEAD(&ahc->waiting_scbs, wscb, links);
   2468 		wscb->position = scb->position;
   2469 		SIMPLEQ_INSERT_HEAD(&ahc->assigned_scbs, wscb, links);
   2470 		wscb->flags = SCB_ASSIGNEDQ;
   2471 
   2472 		/*
   2473 		 * The "freed" SCB will need to be assigned a slot
   2474 		 * before being used, so put it in the page_scbs
   2475 		 * queue.
   2476 		 */
   2477 		scb->position = SCB_LIST_NULL;
   2478 		SIMPLEQ_INSERT_HEAD(&ahc->page_scbs, scb, links);
   2479 		if(!scb->links.sqe_next && !ahc->free_scbs.sqh_first)
   2480 			/*
   2481 			 * If there were no SCBs availible, wake anybody waiting
   2482 			 * for one to come free.
   2483 			 */
   2484 			wakeup((caddr_t)&ahc->free_scbs);
   2485 	}
   2486 	else {
   2487 		SIMPLEQ_INSERT_HEAD(&ahc->free_scbs, scb, links);
   2488 #ifdef AHC_DEBUG
   2489 		ahc->activescbs--;
   2490 #endif
   2491 		if(!scb->links.sqe_next && !ahc->page_scbs.sqh_first)
   2492 			/*
   2493 			 * If there were no SCBs availible, wake anybody waiting
   2494 			 * for one to come free.
   2495 			 */
   2496 			wakeup((caddr_t)&ahc->free_scbs);
   2497 	}
   2498 	splx(opri);
   2499 }
   2500 
   2501 /*
   2502  * Get a free scb, either one already assigned to a hardware slot
   2503  * on the adapter or one that will require an SCB to be paged out before
   2504  * use. If there are none, see if we can allocate a new SCB.  Otherwise
   2505  * either return an error or sleep.
   2506  */
   2507 static struct scb *
   2508 ahc_get_scb(ahc, flags)
   2509         struct	ahc_data *ahc;
   2510         int	flags;
   2511 {
   2512 	unsigned opri;
   2513 	struct scb *scbp;
   2514 
   2515 	opri = splbio();
   2516 	/*
   2517 	 * If we can and have to, sleep waiting for one to come free
   2518 	 * but only if we can't allocate a new one.
   2519 	 */
   2520 	while (1) {
   2521 		if((scbp = ahc->free_scbs.sqh_first)) {
   2522 			SIMPLEQ_REMOVE_HEAD(&ahc->free_scbs, scbp, links);
   2523 		}
   2524 		else if((scbp = ahc->page_scbs.sqh_first)) {
   2525 			SIMPLEQ_REMOVE_HEAD(&ahc->page_scbs, scbp, links);
   2526 		}
   2527 		else if (ahc->numscbs < ahc->maxscbs) {
   2528 			scbp = (struct scb *) malloc(sizeof(struct scb),
   2529 				M_TEMP, M_NOWAIT);
   2530 			if (scbp) {
   2531 				bzero(scbp, sizeof(struct scb));
   2532 				scbp->tag = ahc->numscbs;
   2533 				if( ahc->numscbs < ahc->maxhscbs )
   2534 					scbp->position = ahc->numscbs;
   2535 				else
   2536 					scbp->position = SCB_LIST_NULL;
   2537 				ahc->numscbs++;
   2538 				/*
   2539 				 * Place in the scbarray
   2540 				 * Never is removed.
   2541 				 */
   2542 				ahc->scbarray[scbp->tag] = scbp;
   2543 			}
   2544 			else {
   2545 				printf("%s: Can't malloc SCB\n",
   2546 				       ahc_name(ahc));
   2547 			}
   2548 		}
   2549 		else {
   2550 			if (!(flags & SCSI_NOSLEEP)) {
   2551 				tsleep((caddr_t)&ahc->free_scbs, PRIBIO,
   2552 					"ahcscb", 0);
   2553 				continue;
   2554 			}
   2555 		}
   2556 		break;
   2557 	}
   2558 
   2559 	if (scbp) {
   2560 		scbp->control = 0;
   2561 		scbp->status = 0;
   2562 		scbp->flags = 0;
   2563 #ifdef AHC_DEBUG
   2564 		ahc->activescbs++;
   2565 		if((ahc_debug & AHC_SHOWSCBCNT)
   2566 		  && (ahc->activescbs == ahc->maxhscbs))
   2567 			printf("%s: Max SCBs active\n", ahc_name(ahc));
   2568 #endif
   2569 	}
   2570 
   2571 	splx(opri);
   2572 
   2573 	return (scbp);
   2574 }
   2575 
   2576 static void ahc_loadseq(ahc)
   2577 	struct ahc_data *ahc;
   2578 {
   2579         static unsigned char seqprog[] = {
   2580 #               include "aic7xxx_seq.h"
   2581 	};
   2582 
   2583 	AHC_OUTB(ahc, SEQCTL, PERRORDIS|SEQRESET|LOADRAM);
   2584 
   2585 	AHC_OUTSB(ahc, SEQRAM, seqprog, sizeof(seqprog));
   2586 
   2587 	AHC_OUTB(ahc, SEQCTL, FASTMODE|SEQRESET);
   2588 	do {
   2589 		AHC_OUTB(ahc, SEQCTL, SEQRESET|FASTMODE);
   2590 
   2591 	} while (AHC_INB(ahc, SEQADDR0) != 0 &&
   2592 		 AHC_INB(ahc, SEQADDR1) != 0);
   2593 }
   2594 
   2595 /*
   2596  * Function to poll for command completion when
   2597  * interrupts are disabled (crash dumps)
   2598  */
   2599 static int
   2600 ahc_poll(ahc, wait)
   2601 	struct	ahc_data *ahc;
   2602 	int	wait; /* in msec */
   2603 {
   2604 	while (--wait) {
   2605 		DELAY(1000);
   2606 		if (AHC_INB(ahc, INTSTAT) & INT_PEND)
   2607 			break;
   2608 	} if (wait == 0) {
   2609 		printf("%s: board not responding\n", ahc_name(ahc));
   2610 		return (EIO);
   2611 	}
   2612 	ahc_intr((void *)ahc);
   2613 	return (0);
   2614 }
   2615 
   2616 static void
   2617 ahc_timeout(arg)
   2618 	void	*arg;
   2619 {
   2620 	struct	scb *scb = (struct scb *)arg;
   2621 	struct	ahc_data *ahc;
   2622 	int	s, h, found;
   2623 	u_char	bus_state;
   2624 	char	channel;
   2625 
   2626 	s = splbio();
   2627 
   2628 	h = splhigh();
   2629 
   2630 	if (!(scb->flags & SCB_ACTIVE)) {
   2631 		/* Previous timeout took care of me already */
   2632 		splx(h);
   2633 		splx(s);
   2634 		return;
   2635 	}
   2636 
   2637 	ahc = (struct ahc_data *)scb->xs->sc_link->adapter_softc;
   2638 
   2639 	if (ahc->in_timeout) {
   2640 		/*
   2641 		 * Some other SCB has started a recovery operation
   2642 		 * and is still working on cleaning things up.
   2643 		 */
   2644 		if (scb->flags & SCB_TIMEDOUT) {
   2645 			/*
   2646 			 * This SCB has been here before and is not the
   2647 			 * recovery SCB. Cut our losses and panic.  Its
   2648 			 * better to do this than trash a filesystem.
   2649 			 */
   2650 			panic("%s: Timed-out command times out "
   2651 				"again\n", ahc_name(ahc));
   2652 		}
   2653 		else if (!(scb->flags & SCB_ABORTED))
   2654 		{
   2655 			/*
   2656 			 * This is not the SCB that started this timeout
   2657 			 * processing.  Give this scb another lifetime so
   2658 			 * that it can continue once we deal with the
   2659 			 * timeout.
   2660 			 */
   2661 			scb->flags |= SCB_TIMEDOUT;
   2662 			timeout(ahc_timeout, (caddr_t)scb,
   2663 				(scb->xs->timeout * hz) / 1000);
   2664 			splx(h);
   2665 			splx(s);
   2666 			return;
   2667 		}
   2668 	}
   2669 	ahc->in_timeout = TRUE;
   2670 	splx(h);
   2671 
   2672 	/*
   2673 	 * Ensure that the card doesn't do anything
   2674 	 * behind our back.
   2675 	 */
   2676 	PAUSE_SEQUENCER(ahc);
   2677 
   2678 	sc_print_addr(scb->xs->sc_link);
   2679 	printf("timed out ");
   2680 	/*
   2681 	 * Take a snapshot of the bus state and print out
   2682 	 * some information so we can track down driver bugs.
   2683 	 */
   2684 	bus_state = AHC_INB(ahc, LASTPHASE);
   2685 
   2686 	switch(bus_state & PHASE_MASK)
   2687 	{
   2688 		case P_DATAOUT:
   2689 			printf("in dataout phase");
   2690 			break;
   2691 		case P_DATAIN:
   2692 			printf("in datain phase");
   2693 			break;
   2694 		case P_COMMAND:
   2695 			printf("in command phase");
   2696 			break;
   2697 		case P_MESGOUT:
   2698 			printf("in message out phase");
   2699 			break;
   2700 		case P_STATUS:
   2701 			printf("in status phase");
   2702 			break;
   2703 		case P_MESGIN:
   2704 			printf("in message in phase");
   2705 			break;
   2706 		default:
   2707 			printf("while idle, LASTPHASE == 0x%x",
   2708 				bus_state);
   2709 			/*
   2710 			 * We aren't in a valid phase, so assume we're
   2711 			 * idle.
   2712 			 */
   2713 			bus_state = 0;
   2714 			break;
   2715 	}
   2716 
   2717 	printf(", SCSISIGI == 0x%x\n", AHC_INB(ahc, SCSISIGI));
   2718 
   2719 	/* Decide our course of action */
   2720 
   2721 	if(scb->flags & SCB_ABORTED)
   2722 	{
   2723 		/*
   2724 		 * Been down this road before.
   2725 		 * Do a full bus reset.
   2726 		 */
   2727 		char channel = (scb->tcl & SELBUSB)
   2728 			   ? 'B': 'A';
   2729 		found = ahc_reset_channel(ahc, channel, scb->tag,
   2730 					  XS_TIMEOUT, /*Initiate Reset*/TRUE);
   2731 		printf("%s: Issued Channel %c Bus Reset #1. "
   2732 		       "%d SCBs aborted\n", ahc_name(ahc), channel, found);
   2733 		ahc->in_timeout = FALSE;
   2734 	}
   2735 	else if(scb->control & TAG_ENB) {
   2736 		/*
   2737 		 * We could be starving this command
   2738 		 * try sending an ordered tag command
   2739 		 * to the target we come from.
   2740 		 */
   2741 		scb->flags |= SCB_ABORTED|SCB_SENTORDEREDTAG;
   2742 		ahc->orderedtag |= 0xFF;
   2743 		timeout(ahc_timeout, (caddr_t)scb, (5 * hz));
   2744 		UNPAUSE_SEQUENCER(ahc);
   2745 		printf("Ordered Tag queued\n");
   2746 		goto done;
   2747 	}
   2748 	else {
   2749 		/*
   2750 		 * Send a Bus Device Reset Message:
   2751 		 * The target that is holding up the bus may not
   2752 		 * be the same as the one that triggered this timeout
   2753 		 * (different commands have different timeout lengths).
   2754 		 * It is also impossible to get a message to a target
   2755 		 * if we are in a "frozen" data transfer phase.  Our
   2756 		 * strategy here is to queue a bus device reset message
   2757 		 * to the timed out target if it is disconnected.
   2758 		 * Otherwise, if we have an active target we stuff the
   2759 		 * message buffer with a bus device reset message and
   2760 		 * assert ATN in the hopes that the target will let go
   2761 		 * of the bus and finally disconnect.  If this fails,
   2762 		 * we'll get another timeout 2 seconds later which will
   2763 		 * cause a bus reset.
   2764 		 *
   2765 		 * XXX If the SCB is paged out, we simply reset the
   2766 		 *     bus.  We should probably queue a new command
   2767 		 *     instead.
   2768 		 */
   2769 
   2770 		/* Test to see if scb is disconnected */
   2771 		if( !(scb->flags & SCB_PAGED_OUT ) ){
   2772 			u_char active_scb;
   2773 			struct scb *active_scbp;
   2774 
   2775 			active_scb = AHC_INB(ahc, SCBPTR);
   2776 			active_scbp = ahc->scbarray[AHC_INB(ahc, SCB_TAG)];
   2777 			AHC_OUTB(ahc, SCBPTR, scb->position);
   2778 
   2779 			if(AHC_INB(ahc, SCB_CONTROL) & DISCONNECTED) {
   2780 				if(ahc->flags & AHC_PAGESCBS) {
   2781 					/*
   2782 					 * Pull this SCB out of the
   2783 					 * disconnected list.
   2784 					 */
   2785 					u_char prev = AHC_INB(ahc, SCB_PREV);
   2786 					u_char next = AHC_INB(ahc, SCB_NEXT);
   2787 					if(prev == SCB_LIST_NULL) {
   2788 						/* At the head */
   2789 						AHC_OUTB(ahc, DISCONNECTED_SCBH,
   2790 						     next );
   2791 					}
   2792 					else {
   2793 						AHC_OUTB(ahc, SCBPTR, prev);
   2794 						AHC_OUTB(ahc, SCB_NEXT, next);
   2795 						if(next != SCB_LIST_NULL) {
   2796 							AHC_OUTB(ahc, SCBPTR,
   2797 							     next);
   2798 							AHC_OUTB(ahc, SCB_PREV,
   2799 							     prev);
   2800 						}
   2801 						AHC_OUTB(ahc, SCBPTR,
   2802 						     scb->position);
   2803 					}
   2804 				}
   2805 				scb->flags |= SCB_DEVICE_RESET|SCB_ABORTED;
   2806 				scb->control &= DISCENB;
   2807 				scb->cmdlen = 0;
   2808 				scb->SG_segment_count = 0;
   2809 				scb->SG_list_pointer = 0;
   2810 				scb->data = 0;
   2811 				scb->datalen = 0;
   2812 				ahc_send_scb(ahc, scb);
   2813 				ahc_add_waiting_scb(ahc, scb);
   2814 				timeout(ahc_timeout, (caddr_t)scb, (2 * hz));
   2815 				sc_print_addr(scb->xs->sc_link);
   2816 				printf("BUS DEVICE RESET message queued.\n");
   2817 				AHC_OUTB(ahc, SCBPTR, active_scb);
   2818 				UNPAUSE_SEQUENCER(ahc);
   2819 				goto done;
   2820 			}
   2821 			/* Is the active SCB really active? */
   2822 			else if((active_scbp->flags & SCB_ACTIVE) && bus_state){
   2823 				AHC_OUTB(ahc, MSG_LEN, 1);
   2824 				AHC_OUTB(ahc, MSG0, MSG_BUS_DEVICE_RESET);
   2825 				AHC_OUTB(ahc, SCSISIGO, bus_state|ATNO);
   2826 				sc_print_addr(active_scbp->xs->sc_link);
   2827 				printf("asserted ATN - device reset in "
   2828 				       "message buffer\n");
   2829 				active_scbp->flags |=   SCB_DEVICE_RESET
   2830 						      | SCB_ABORTED;
   2831 				if(active_scbp != scb) {
   2832 					untimeout(ahc_timeout,
   2833 						  (caddr_t)active_scbp);
   2834 					/* Give scb a new lease on life */
   2835 					timeout(ahc_timeout, (caddr_t)scb,
   2836 						(scb->xs->timeout * hz) / 1000);
   2837 				}
   2838 				timeout(ahc_timeout, (caddr_t)active_scbp,
   2839 					(2 * hz));
   2840 				AHC_OUTB(ahc, SCBPTR, active_scb);
   2841 				UNPAUSE_SEQUENCER(ahc);
   2842 				goto done;
   2843 			}
   2844 		}
   2845 		/*
   2846 		 * No active target or a paged out SCB.
   2847 		 * Try reseting the bus.
   2848 		 */
   2849 		channel = (scb->tcl & SELBUSB) ? 'B': 'A';
   2850 		found = ahc_reset_channel(ahc, channel, scb->tag,
   2851 					  XS_TIMEOUT,
   2852 					  /*Initiate Reset*/TRUE);
   2853 		printf("%s: Issued Channel %c Bus Reset #2. "
   2854 			"%d SCBs aborted\n", ahc_name(ahc), channel,
   2855 			found);
   2856 		ahc->in_timeout = FALSE;
   2857 	}
   2858 done:
   2859 	splx(s);
   2860 }
   2861 
   2862 
   2863 /*
   2864  * The device at the given target/channel has been reset.  Abort
   2865  * all active and queued scbs for that target/channel.
   2866  */
   2867 static int
   2868 ahc_reset_device(ahc, target, channel, timedout_scb, xs_error)
   2869 	struct ahc_data *ahc;
   2870 	int target;
   2871 	char channel;
   2872 	u_char timedout_scb;
   2873 	u_int32_t xs_error;
   2874 {
   2875         struct scb *scbp;
   2876 	u_char active_scb;
   2877 	int i = 0;
   2878 	int found = 0;
   2879 
   2880 	/* restore this when we're done */
   2881 	active_scb = AHC_INB(ahc, SCBPTR);
   2882 
   2883 	/*
   2884 	 * Search the QINFIFO.
   2885 	 */
   2886 	{
   2887 		int saved_queue[AHC_SCB_MAX];
   2888 		int queued = AHC_INB(ahc, QINCNT) & ahc->qcntmask;
   2889 
   2890 		for (i = 0; i < (queued - found); i++) {
   2891 			saved_queue[i] = AHC_INB(ahc, QINFIFO);
   2892 			AHC_OUTB(ahc, SCBPTR, saved_queue[i]);
   2893 			scbp = ahc->scbarray[AHC_INB(ahc, SCB_TAG)];
   2894 			if (ahc_match_scb (scbp, target, channel)){
   2895 				/*
   2896 				 * We found an scb that needs to be aborted.
   2897 				 */
   2898 				scbp->flags = SCB_ABORTED|SCB_QUEUED_FOR_DONE;
   2899 				scbp->xs->error |= xs_error;
   2900 				if(scbp->position != timedout_scb)
   2901 					untimeout(ahc_timeout, (caddr_t)scbp);
   2902 				AHC_OUTB(ahc, SCB_CONTROL, 0);
   2903 				i--;
   2904 				found++;
   2905 			}
   2906 		}
   2907 		/* Now put the saved scbs back. */
   2908 		for (queued = 0; queued < i; queued++) {
   2909 			AHC_OUTB(ahc, QINFIFO, saved_queue[queued]);
   2910 		}
   2911 	}
   2912 
   2913 	/*
   2914 	 * Search waiting for selection list.
   2915 	 */
   2916 	{
   2917 		u_char next, prev;
   2918 
   2919 		next = AHC_INB(ahc, WAITING_SCBH);  /* Start at head of list. */
   2920 		prev = SCB_LIST_NULL;
   2921 
   2922 		while (next != SCB_LIST_NULL) {
   2923 			AHC_OUTB(ahc, SCBPTR, next);
   2924 			scbp = ahc->scbarray[AHC_INB(ahc, SCB_TAG)];
   2925 			/*
   2926 			 * Select the SCB.
   2927 			 */
   2928 			if (ahc_match_scb(scbp, target, channel)) {
   2929 				next = ahc_abort_wscb(ahc, scbp, prev,
   2930 						timedout_scb, xs_error);
   2931 				found++;
   2932 			}
   2933 			else {
   2934 				prev = next;
   2935 				next = AHC_INB(ahc, SCB_NEXT);
   2936 			}
   2937 		}
   2938 	}
   2939 	/*
   2940 	 * Go through the entire SCB array now and look for
   2941 	 * commands for this target that are active.  These
   2942 	 * are other (most likely tagged) commands that
   2943 	 * were disconnected when the reset occured.
   2944 	 */
   2945 	for(i = 0; i < ahc->numscbs; i++) {
   2946 		scbp = ahc->scbarray[i];
   2947 		if((scbp->flags & SCB_ACTIVE)
   2948 		  && ahc_match_scb(scbp, target, channel)) {
   2949 			/* Ensure the target is "free" */
   2950 			ahc_unbusy_target(ahc, target, channel);
   2951 			if( !(scbp->flags & SCB_PAGED_OUT) )
   2952 			{
   2953 				AHC_OUTB(ahc, SCBPTR, scbp->position);
   2954 				AHC_OUTB(ahc, SCB_CONTROL, 0);
   2955 			}
   2956 			scbp->flags = SCB_ABORTED|SCB_QUEUED_FOR_DONE;
   2957 			scbp->xs->error |= xs_error;
   2958 			if(scbp->tag != timedout_scb)
   2959 				untimeout(ahc_timeout, (caddr_t)scbp);
   2960 			found++;
   2961 		}
   2962 	}
   2963 	AHC_OUTB(ahc, SCBPTR, active_scb);
   2964 	return found;
   2965 }
   2966 
   2967 /*
   2968  * Manipulate the waiting for selection list and return the
   2969  * scb that follows the one that we remove.
   2970  */
   2971 static u_char
   2972 ahc_abort_wscb (ahc, scbp, prev, timedout_scb, xs_error)
   2973 	struct ahc_data *ahc;
   2974         struct scb *scbp;
   2975 	u_char prev;
   2976 	u_char timedout_scb;
   2977 	u_int32_t xs_error;
   2978 {
   2979 	u_char curscbp, next;
   2980 	int target = ((scbp->tcl >> 4) & 0x0f);
   2981 	char channel = (scbp->tcl & SELBUSB) ? 'B' : 'A';
   2982 	/*
   2983 	 * Select the SCB we want to abort and
   2984 	 * pull the next pointer out of it.
   2985 	 */
   2986 	curscbp = AHC_INB(ahc, SCBPTR);
   2987 	AHC_OUTB(ahc, SCBPTR, scbp->position);
   2988 	next = AHC_INB(ahc, SCB_NEXT);
   2989 
   2990 	/* Clear the necessary fields */
   2991 	AHC_OUTB(ahc, SCB_CONTROL, 0);
   2992 	AHC_OUTB(ahc, SCB_NEXT, SCB_LIST_NULL);
   2993 	ahc_unbusy_target(ahc, target, channel);
   2994 
   2995 	/* update the waiting list */
   2996 	if( prev == SCB_LIST_NULL )
   2997 		/* First in the list */
   2998 		AHC_OUTB(ahc, WAITING_SCBH, next);
   2999 	else {
   3000 		/*
   3001 		 * Select the scb that pointed to us
   3002 		 * and update its next pointer.
   3003 		 */
   3004 		AHC_OUTB(ahc, SCBPTR, prev);
   3005 		AHC_OUTB(ahc, SCB_NEXT, next);
   3006 	}
   3007 	/*
   3008 	 * Point us back at the original scb position
   3009 	 * and inform the SCSI system that the command
   3010 	 * has been aborted.
   3011 	 */
   3012 	AHC_OUTB(ahc, SCBPTR, curscbp);
   3013 	scbp->flags = SCB_ABORTED|SCB_QUEUED_FOR_DONE;
   3014 	scbp->xs->error |= xs_error;
   3015 	if(scbp->tag != timedout_scb)
   3016 		untimeout(ahc_timeout, (caddr_t)scbp);
   3017 	return next;
   3018 }
   3019 
   3020 static void
   3021 ahc_busy_target(ahc, target, channel)
   3022 	struct ahc_data *ahc;
   3023 	u_char target;
   3024 	char   channel;
   3025 {
   3026 	u_char active;
   3027 	u_long active_port = ACTIVE_A;
   3028 
   3029 	if(target > 0x07 || channel == 'B') {
   3030 		/*
   3031 		 * targets on the Second channel or
   3032 		 * above id 7 store info in byte two
   3033 		 * of HA_ACTIVE
   3034 		 */
   3035 		active_port++;
   3036 	}
   3037 	active = AHC_INB(ahc, active_port);
   3038 	active |= (0x01 << (target & 0x07));
   3039 	AHC_OUTB(ahc, active_port, active);
   3040 }
   3041 
   3042 static void
   3043 ahc_unbusy_target(ahc, target, channel)
   3044 	struct ahc_data *ahc;
   3045 	u_char target;
   3046 	char   channel;
   3047 {
   3048 	u_char active;
   3049 	u_long active_port = ACTIVE_A;
   3050 
   3051 	if(target > 0x07 || channel == 'B') {
   3052 		/*
   3053 		 * targets on the Second channel or
   3054 		 * above id 7 store info in byte two
   3055 		 * of HA_ACTIVE
   3056 		 */
   3057 		active_port++;
   3058 	}
   3059 	active = AHC_INB(ahc, active_port);
   3060 	active &= ~(0x01 << (target & 0x07));
   3061 	AHC_OUTB(ahc, active_port, active);
   3062 }
   3063 
   3064 static void
   3065 ahc_reset_current_bus(ahc)
   3066 	struct ahc_data *ahc;
   3067 {
   3068 	AHC_OUTB(ahc, SCSISEQ, SCSIRSTO);
   3069 	DELAY(1000);
   3070 	AHC_OUTB(ahc, SCSISEQ, 0);
   3071 }
   3072 
   3073 static int
   3074 ahc_reset_channel(ahc, channel, timedout_scb, xs_error, initiate_reset)
   3075 	struct ahc_data *ahc;
   3076 	char   channel;
   3077 	u_char timedout_scb;
   3078 	u_int32_t xs_error;
   3079 	u_char initiate_reset;
   3080 {
   3081 	u_char sblkctl;
   3082 	char cur_channel;
   3083 	u_long offset, offset_max;
   3084 	int found;
   3085 
   3086 	/*
   3087 	 * Clean up all the state information for the
   3088 	 * pending transactions on this bus.
   3089 	 */
   3090 	found = ahc_reset_device(ahc, ALL_TARGETS, channel,
   3091 				 timedout_scb, xs_error);
   3092 	if(channel == 'B'){
   3093 		ahc->needsdtr |= (ahc->needsdtr_orig & 0xff00);
   3094 		ahc->sdtrpending &= 0x00ff;
   3095 		AHC_OUTB(ahc, ACTIVE_B, 0);
   3096 		offset = TARG_SCRATCH + 8;
   3097 		offset_max = TARG_SCRATCH + 16;
   3098 	}
   3099 	else if (ahc->type & AHC_WIDE){
   3100 		ahc->needsdtr = ahc->needsdtr_orig;
   3101 		ahc->needwdtr = ahc->needwdtr_orig;
   3102 		ahc->sdtrpending = 0;
   3103 		ahc->wdtrpending = 0;
   3104 		AHC_OUTB(ahc, ACTIVE_A, 0);
   3105 		AHC_OUTB(ahc, ACTIVE_B, 0);
   3106 		offset = TARG_SCRATCH;
   3107 		offset_max = TARG_SCRATCH + 16;
   3108 	}
   3109 	else{
   3110 		ahc->needsdtr |= (ahc->needsdtr_orig & 0x00ff);
   3111 		ahc->sdtrpending &= 0xff00;
   3112 		AHC_OUTB(ahc, ACTIVE_A, 0);
   3113 		offset = TARG_SCRATCH;
   3114 		offset_max = TARG_SCRATCH + 8;
   3115 	}
   3116 	for(;offset < offset_max;offset++) {
   3117 		/*
   3118 		 * Revert to async/narrow transfers
   3119 		 * until we renegotiate.
   3120 		 */
   3121 		u_char targ_scratch;
   3122 
   3123 		targ_scratch = AHC_INB(ahc, offset);
   3124 		targ_scratch &= SXFR;
   3125 		AHC_OUTB(ahc, offset, targ_scratch);
   3126 	}
   3127 
   3128 	/*
   3129 	 * Reset the bus if we are initiating this reset and
   3130 	 * restart/unpause the sequencer
   3131 	 */
   3132 	/* Case 1: Command for another bus is active */
   3133 	sblkctl = AHC_INB(ahc, SBLKCTL);
   3134 	cur_channel = (sblkctl & SELBUSB) ? 'B' : 'A';
   3135 	if(cur_channel != channel)
   3136 	{
   3137 		/*
   3138 		 * Stealthily reset the other bus
   3139 		 * without upsetting the current bus
   3140 		 */
   3141 		AHC_OUTB(ahc, SBLKCTL, sblkctl ^ SELBUSB);
   3142 		if( initiate_reset )
   3143 		{
   3144 			ahc_reset_current_bus(ahc);
   3145 		}
   3146 		AHC_OUTB(ahc, CLRSINT1, CLRSCSIRSTI|CLRSELTIMEO);
   3147 		AHC_OUTB(ahc, CLRINT, CLRSCSIINT);
   3148 		AHC_OUTB(ahc, SBLKCTL, sblkctl);
   3149 		UNPAUSE_SEQUENCER(ahc);
   3150 	}
   3151 	/* Case 2: A command from this bus is active or we're idle */
   3152 	else {
   3153 		if( initiate_reset )
   3154 		{
   3155 			ahc_reset_current_bus(ahc);
   3156 		}
   3157 		AHC_OUTB(ahc, CLRSINT1, CLRSCSIRSTI|CLRSELTIMEO);
   3158 		AHC_OUTB(ahc, CLRINT, CLRSCSIINT);
   3159 		RESTART_SEQUENCER(ahc);
   3160 	}
   3161 	ahc_run_done_queue(ahc);
   3162 	return found;
   3163 }
   3164 
   3165 void
   3166 ahc_run_done_queue(ahc)
   3167 	struct ahc_data *ahc;
   3168 {
   3169 	int i;
   3170 	struct scb *scbp;
   3171 
   3172 	for(i = 0; i < ahc->numscbs; i++) {
   3173 		scbp = ahc->scbarray[i];
   3174 		if(scbp->flags & SCB_QUEUED_FOR_DONE)
   3175 			ahc_done(ahc, scbp);
   3176 	}
   3177 }
   3178 
   3179 static int
   3180 ahc_match_scb (scb, target, channel)
   3181         struct scb *scb;
   3182         int target;
   3183 	char channel;
   3184 {
   3185 	int targ = (scb->tcl >> 4) & 0x0f;
   3186 	char chan = (scb->tcl & SELBUSB) ? 'B' : 'A';
   3187 
   3188 	if (target == ALL_TARGETS)
   3189 		return (chan == channel);
   3190 	else
   3191 		return ((chan == channel) && (targ == target));
   3192 }
   3193