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