Home | History | Annotate | Line # | Download | only in ic
ncr53c9x.c revision 1.74
      1 /*	$NetBSD: ncr53c9x.c,v 1.74 2001/04/21 07:28:22 tsutsui Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1998 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Charles M. Hannum.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*
     40  * Copyright (c) 1994 Peter Galbavy
     41  * Copyright (c) 1995 Paul Kranenburg
     42  * All rights reserved.
     43  *
     44  * Redistribution and use in source and binary forms, with or without
     45  * modification, are permitted provided that the following conditions
     46  * are met:
     47  * 1. Redistributions of source code must retain the above copyright
     48  *    notice, this list of conditions and the following disclaimer.
     49  * 2. Redistributions in binary form must reproduce the above copyright
     50  *    notice, this list of conditions and the following disclaimer in the
     51  *    documentation and/or other materials provided with the distribution.
     52  * 3. All advertising materials mentioning features or use of this software
     53  *    must display the following acknowledgement:
     54  *	This product includes software developed by Peter Galbavy
     55  * 4. The name of the author may not be used to endorse or promote products
     56  *    derived from this software without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     59  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     60  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     61  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
     62  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
     63  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
     64  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
     66  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
     67  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     68  * POSSIBILITY OF SUCH DAMAGE.
     69  */
     70 
     71 /*
     72  * Based on aic6360 by Jarle Greipsland
     73  *
     74  * Acknowledgements: Many of the algorithms used in this driver are
     75  * inspired by the work of Julian Elischer (julian (at) tfs.com) and
     76  * Charles Hannum (mycroft (at) duality.gnu.ai.mit.edu).  Thanks a million!
     77  */
     78 
     79 #include <sys/types.h>
     80 #include <sys/param.h>
     81 #include <sys/systm.h>
     82 #include <sys/callout.h>
     83 #include <sys/kernel.h>
     84 #include <sys/errno.h>
     85 #include <sys/ioctl.h>
     86 #include <sys/device.h>
     87 #include <sys/buf.h>
     88 #include <sys/malloc.h>
     89 #include <sys/proc.h>
     90 #include <sys/queue.h>
     91 #include <sys/pool.h>
     92 #include <sys/scsiio.h>
     93 
     94 #include <dev/scsipi/scsi_all.h>
     95 #include <dev/scsipi/scsipi_all.h>
     96 #include <dev/scsipi/scsiconf.h>
     97 #include <dev/scsipi/scsi_message.h>
     98 
     99 #include <dev/ic/ncr53c9xreg.h>
    100 #include <dev/ic/ncr53c9xvar.h>
    101 
    102 int ncr53c9x_debug = 0; /*NCR_SHOWPHASE|NCR_SHOWMISC|NCR_SHOWTRAC|NCR_SHOWCMDS;*/
    103 #ifdef DEBUG
    104 int ncr53c9x_notag = 0;
    105 #endif
    106 
    107 /*static*/ void	ncr53c9x_readregs(struct ncr53c9x_softc *);
    108 /*static*/ void	ncr53c9x_select(struct ncr53c9x_softc *, struct ncr53c9x_ecb *);
    109 /*static*/ int ncr53c9x_reselect(struct ncr53c9x_softc *, int, int, int);
    110 /*static*/ void	ncr53c9x_scsi_reset(struct ncr53c9x_softc *);
    111 /*static*/ int	ncr53c9x_poll(struct ncr53c9x_softc *,
    112 			      struct scsipi_xfer *, int);
    113 /*static*/ void	ncr53c9x_sched(struct ncr53c9x_softc *);
    114 /*static*/ void	ncr53c9x_done(struct ncr53c9x_softc *, struct ncr53c9x_ecb *);
    115 /*static*/ void	ncr53c9x_msgin(struct ncr53c9x_softc *);
    116 /*static*/ void	ncr53c9x_msgout(struct ncr53c9x_softc *);
    117 /*static*/ void	ncr53c9x_timeout(void *arg);
    118 /*static*/ void	ncr53c9x_watch(void *arg);
    119 /*static*/ void	ncr53c9x_abort(struct ncr53c9x_softc *, struct ncr53c9x_ecb *);
    120 /*static*/ void ncr53c9x_dequeue(struct ncr53c9x_softc *,
    121 				 struct ncr53c9x_ecb *);
    122 /*static*/ int	ncr53c9x_ioctl(struct scsipi_link *, u_long,
    123 			       caddr_t, int, struct proc *);
    124 
    125 void ncr53c9x_sense(struct ncr53c9x_softc *, struct ncr53c9x_ecb *);
    126 void ncr53c9x_free_ecb(struct ncr53c9x_softc *, struct ncr53c9x_ecb *, int);
    127 struct ncr53c9x_ecb *ncr53c9x_get_ecb(struct ncr53c9x_softc *, int);
    128 
    129 static inline int ncr53c9x_stp2cpb(struct ncr53c9x_softc *, int);
    130 static inline void ncr53c9x_setsync(struct ncr53c9x_softc *,
    131 				    struct ncr53c9x_tinfo *);
    132 static struct ncr53c9x_linfo *ncr53c9x_lunsearch(struct ncr53c9x_tinfo *,
    133 						 int64_t lun);
    134 
    135 static void ncr53c9x_wrfifo(struct ncr53c9x_softc *, u_char *, int);
    136 
    137 static int  ncr53c9x_rdfifo(struct ncr53c9x_softc *, int);
    138 #define NCR_RDFIFO_START   0
    139 #define NCR_RDFIFO_CONTINUE 1
    140 
    141 
    142 #define NCR_SET_COUNT(sc, size) do { \
    143 		NCR_WRITE_REG((sc), NCR_TCL, (size)); 			\
    144 		NCR_WRITE_REG((sc), NCR_TCM, (size) >> 8);		\
    145 		if ((sc->sc_cfg2 & NCRCFG2_FE) || 			\
    146 		    (sc->sc_rev == NCR_VARIANT_FAS366)) {		\
    147 			NCR_WRITE_REG((sc), NCR_TCH, (size) >> 16);	\
    148 		}							\
    149 		if (sc->sc_rev == NCR_VARIANT_FAS366) {			\
    150 			NCR_WRITE_REG(sc, NCR_RCH, 0);			\
    151 		}							\
    152 } while (0)
    153 
    154 static int ecb_pool_initialized = 0;
    155 static struct pool ecb_pool;
    156 
    157 /*
    158  * Names for the NCR53c9x variants, correspnding to the variant tags
    159  * in ncr53c9xvar.h.
    160  */
    161 static const char *ncr53c9x_variant_names[] = {
    162 	"ESP100",
    163 	"ESP100A",
    164 	"ESP200",
    165 	"NCR53C94",
    166 	"NCR53C96",
    167 	"ESP406",
    168 	"FAS408",
    169 	"FAS216",
    170 	"AM53C974",
    171 	"FAS366/HME",
    172 };
    173 
    174 static struct scsipi_adapter ncr53c9x_adapter = {
    175 	0,			/* adapter refcnt */
    176 	ncr53c9x_scsi_cmd,	/* cmd */
    177 	minphys,		/* minphys */
    178 	ncr53c9x_ioctl,		/* ioctl */
    179 	NULL,			/* enable */
    180 	NULL,			/* getgeom */
    181 };
    182 
    183 static struct scsipi_device ncr53c9x_device = {
    184 	NULL,			/* use default error handler */
    185 	NULL,			/* have a queue, served by this */
    186 	NULL,			/* have no async handler */
    187 	NULL,			/* use default 'done' routine */
    188 };
    189 
    190 /*
    191  * Search linked list for LUN info by LUN id.
    192  */
    193 static struct ncr53c9x_linfo *
    194 ncr53c9x_lunsearch(ti, lun)
    195 	struct ncr53c9x_tinfo *ti;
    196 	int64_t lun;
    197 {
    198 	struct ncr53c9x_linfo *li;
    199 	LIST_FOREACH(li, &ti->luns, link)
    200 		if (li->lun == lun)
    201 			return (li);
    202 	return (NULL);
    203 }
    204 
    205 /*
    206  * Attach this instance, and then all the sub-devices
    207  */
    208 void
    209 ncr53c9x_attach(sc, adapter, device)
    210 	struct ncr53c9x_softc *sc;
    211 	struct scsipi_adapter *adapter;
    212 	struct scsipi_device *device;
    213 {
    214 
    215 	callout_init(&sc->sc_watchdog);
    216 	/*
    217 	 * Allocate SCSI message buffers.
    218 	 * Front-ends can override allocation to avoid alignment
    219 	 * handling in the DMA engines. Note that that ncr53c9x_msgout()
    220 	 * can request a 1 byte DMA transfer.
    221 	 */
    222 	if (sc->sc_omess == NULL)
    223 		sc->sc_omess = malloc(NCR_MAX_MSG_LEN, M_DEVBUF, M_NOWAIT);
    224 
    225 	if (sc->sc_imess == NULL)
    226 		sc->sc_imess = malloc(NCR_MAX_MSG_LEN + 1, M_DEVBUF, M_NOWAIT);
    227 
    228 	if (sc->sc_omess == NULL || sc->sc_imess == NULL) {
    229 		printf("out of memory\n");
    230 		return;
    231 	}
    232 
    233 	/*
    234 	 * Note, the front-end has set us up to print the chip variation.
    235 	 */
    236 	if (sc->sc_rev >= NCR_VARIANT_MAX) {
    237 		printf("\n%s: unknown variant %d, devices not attached\n",
    238 		    sc->sc_dev.dv_xname, sc->sc_rev);
    239 		return;
    240 	}
    241 
    242 	printf(": %s, %dMHz, SCSI ID %d\n",
    243 	    ncr53c9x_variant_names[sc->sc_rev], sc->sc_freq, sc->sc_id);
    244 
    245 	sc->sc_ccf = FREQTOCCF(sc->sc_freq);
    246 
    247 	/* The value *must not* be == 1. Make it 2 */
    248 	if (sc->sc_ccf == 1)
    249 		sc->sc_ccf = 2;
    250 
    251 	/*
    252 	 * The recommended timeout is 250ms. This register is loaded
    253 	 * with a value calculated as follows, from the docs:
    254 	 *
    255 	 *		(timout period) x (CLK frequency)
    256 	 *	reg = -------------------------------------
    257 	 *		 8192 x (Clock Conversion Factor)
    258 	 *
    259 	 * Since CCF has a linear relation to CLK, this generally computes
    260 	 * to the constant of 153.
    261 	 */
    262 	sc->sc_timeout = ((250 * 1000) * sc->sc_freq) / (8192 * sc->sc_ccf);
    263 
    264 	/* CCF register only has 3 bits; 0 is actually 8 */
    265 	sc->sc_ccf &= 7;
    266 
    267 	/*
    268 	 * fill in the prototype scsipi_link.
    269 	 */
    270 	sc->sc_link.scsipi_scsi.channel = SCSI_CHANNEL_ONLY_ONE;
    271 	sc->sc_link.adapter_softc = sc;
    272 	sc->sc_link.scsipi_scsi.adapter_target = sc->sc_id;
    273 	sc->sc_link.adapter = (adapter) ? adapter : &ncr53c9x_adapter;
    274 	sc->sc_link.device = (device) ? device : &ncr53c9x_device;
    275 	sc->sc_link.openings = 2;
    276 	sc->sc_link.scsipi_scsi.max_target = 7;	/* XXX fas has 16(not supported) */
    277 	sc->sc_link.scsipi_scsi.max_lun = 7;
    278 	sc->sc_link.type = BUS_SCSI;
    279 
    280 	/*
    281 	 * Add reference to adapter so that we drop the reference after
    282 	 * config_found() to make sure the adatper is disabled.
    283 	 */
    284 	if (scsipi_adapter_addref(&sc->sc_link) != 0) {
    285 		printf("%s: unable to enable controller\n",
    286 		    sc->sc_dev.dv_xname);
    287 		return;
    288 	}
    289 
    290 	/* Reset state & bus */
    291 	sc->sc_cfflags = sc->sc_dev.dv_cfdata->cf_flags;
    292 	sc->sc_state = 0;
    293 	ncr53c9x_init(sc, 1);
    294 
    295 	/*
    296 	 * Now try to attach all the sub-devices
    297 	 */
    298 	sc->sc_child = config_found(&sc->sc_dev, &sc->sc_link, scsiprint);
    299 
    300 	scsipi_adapter_delref(&sc->sc_link);
    301 	callout_reset(&sc->sc_watchdog, 60*hz, ncr53c9x_watch, sc);
    302 }
    303 
    304 int
    305 ncr53c9x_detach(sc, flags)
    306 	struct ncr53c9x_softc *sc;
    307 	int flags;
    308 {
    309 	int error;
    310 
    311 	if (sc->sc_child) {
    312 		error = config_detach(sc->sc_child, flags);
    313 		if (error)
    314 			return (error);
    315 	}
    316 
    317 	free(sc->sc_imess, M_DEVBUF);
    318 	free(sc->sc_omess, M_DEVBUF);
    319 
    320 	return (0);
    321 }
    322 
    323 /*
    324  * This is the generic ncr53c9x reset function. It does not reset the SCSI bus,
    325  * only this controller, but kills any on-going commands, and also stops
    326  * and resets the DMA.
    327  *
    328  * After reset, registers are loaded with the defaults from the attach
    329  * routine above.
    330  */
    331 void
    332 ncr53c9x_reset(sc)
    333 	struct ncr53c9x_softc *sc;
    334 {
    335 
    336 	/* reset DMA first */
    337 	NCRDMA_RESET(sc);
    338 
    339 	/* reset SCSI chip */
    340 	NCRCMD(sc, NCRCMD_RSTCHIP);
    341 	NCRCMD(sc, NCRCMD_NOP);
    342 	DELAY(500);
    343 
    344 	/* do these backwards, and fall through */
    345 	switch (sc->sc_rev) {
    346 	case NCR_VARIANT_ESP406:
    347 	case NCR_VARIANT_FAS408:
    348 		NCR_WRITE_REG(sc, NCR_CFG5, sc->sc_cfg5 | NCRCFG5_SINT);
    349 		NCR_WRITE_REG(sc, NCR_CFG4, sc->sc_cfg4);
    350 	case NCR_VARIANT_AM53C974:
    351 	case NCR_VARIANT_FAS216:
    352 	case NCR_VARIANT_NCR53C94:
    353 	case NCR_VARIANT_NCR53C96:
    354 	case NCR_VARIANT_ESP200:
    355 		sc->sc_features |= NCR_F_HASCFG3;
    356 		NCR_WRITE_REG(sc, NCR_CFG3, sc->sc_cfg3);
    357 	case NCR_VARIANT_ESP100A:
    358 		sc->sc_features |= NCR_F_SELATN3;
    359 		NCR_WRITE_REG(sc, NCR_CFG2, sc->sc_cfg2);
    360 	case NCR_VARIANT_ESP100:
    361 		NCR_WRITE_REG(sc, NCR_CFG1, sc->sc_cfg1);
    362 		NCR_WRITE_REG(sc, NCR_CCF, sc->sc_ccf);
    363 		NCR_WRITE_REG(sc, NCR_SYNCOFF, 0);
    364 		NCR_WRITE_REG(sc, NCR_TIMEOUT, sc->sc_timeout);
    365 		break;
    366 
    367 	case NCR_VARIANT_FAS366:
    368 		sc->sc_features |=
    369 		    NCR_F_HASCFG3 | NCR_F_FASTSCSI | NCR_F_SELATN3;
    370 		sc->sc_cfg3 = NCRFASCFG3_FASTCLK | NCRFASCFG3_OBAUTO;
    371 		sc->sc_cfg3_fscsi = NCRFASCFG3_FASTSCSI;
    372 		NCR_WRITE_REG(sc, NCR_CFG3, sc->sc_cfg3);
    373 		sc->sc_cfg2 = 0; /* NCRCFG2_HMEFE| NCRCFG2_HME32 */
    374 		NCR_WRITE_REG(sc, NCR_CFG2, sc->sc_cfg2);
    375 		NCR_WRITE_REG(sc, NCR_CFG1, sc->sc_cfg1);
    376 		NCR_WRITE_REG(sc, NCR_CCF, sc->sc_ccf);
    377 		NCR_WRITE_REG(sc, NCR_SYNCOFF, 0);
    378 		NCR_WRITE_REG(sc, NCR_TIMEOUT, sc->sc_timeout);
    379 		break;
    380 
    381 	default:
    382 		printf("%s: unknown revision code, assuming ESP100\n",
    383 		    sc->sc_dev.dv_xname);
    384 		NCR_WRITE_REG(sc, NCR_CFG1, sc->sc_cfg1);
    385 		NCR_WRITE_REG(sc, NCR_CCF, sc->sc_ccf);
    386 		NCR_WRITE_REG(sc, NCR_SYNCOFF, 0);
    387 		NCR_WRITE_REG(sc, NCR_TIMEOUT, sc->sc_timeout);
    388 	}
    389 
    390 	if (sc->sc_rev == NCR_VARIANT_AM53C974)
    391 		NCR_WRITE_REG(sc, NCR_AMDCFG4, sc->sc_cfg4);
    392 
    393 #if 0
    394 	printf("%s: ncr53c9x_reset: revision %d\n",
    395 	       sc->sc_dev.dv_xname, sc->sc_rev);
    396 	printf("%s: ncr53c9x_reset: cfg1 0x%x, cfg2 0x%x, cfg3 0x%x, "
    397 	    "ccf 0x%x, timeout 0x%x\n",
    398 	    sc->sc_dev.dv_xname, sc->sc_cfg1, sc->sc_cfg2, sc->sc_cfg3,
    399 	    sc->sc_ccf, sc->sc_timeout);
    400 #endif
    401 }
    402 
    403 /*
    404  * Reset the SCSI bus, but not the chip
    405  */
    406 void
    407 ncr53c9x_scsi_reset(sc)
    408 	struct ncr53c9x_softc *sc;
    409 {
    410 
    411 	(*sc->sc_glue->gl_dma_stop)(sc);
    412 
    413 	printf("%s: resetting SCSI bus\n", sc->sc_dev.dv_xname);
    414 	NCRCMD(sc, NCRCMD_RSTSCSI);
    415 }
    416 
    417 /*
    418  * Initialize ncr53c9x state machine
    419  */
    420 void
    421 ncr53c9x_init(sc, doreset)
    422 	struct ncr53c9x_softc *sc;
    423 	int doreset;
    424 {
    425 	struct ncr53c9x_ecb *ecb;
    426 	struct ncr53c9x_linfo *li;
    427 	int i, r;
    428 
    429 	NCR_TRACE(("[NCR_INIT(%d) %d] ", doreset, sc->sc_state));
    430 
    431 	if (!ecb_pool_initialized) {
    432 		/* All instances share this pool */
    433 		pool_init(&ecb_pool, sizeof(struct ncr53c9x_ecb), 0, 0, 0,
    434 		    "ncr53c9x_ecb", 0, NULL, NULL, 0);
    435 		ecb_pool_initialized = 1;
    436 	}
    437 
    438 	if (sc->sc_state == 0) {
    439 		/* First time through; initialize. */
    440 
    441 		TAILQ_INIT(&sc->ready_list);
    442 		sc->sc_nexus = NULL;
    443 		bzero(sc->sc_tinfo, sizeof(sc->sc_tinfo));
    444 		for (r = 0; r < NCR_NTARG; r++) {
    445 			LIST_INIT(&sc->sc_tinfo[r].luns);
    446 		}
    447 	} else {
    448 		/* Cancel any active commands. */
    449 		sc->sc_state = NCR_CLEANING;
    450 		sc->sc_msgify = 0;
    451 		if ((ecb = sc->sc_nexus) != NULL) {
    452 			ecb->xs->error = XS_TIMEOUT;
    453 			ncr53c9x_done(sc, ecb);
    454 		}
    455 		/* Cancel outstanding disconnected commands on each LUN */
    456 		for (r = 0; r < 8; r++) {
    457 			LIST_FOREACH(li, &sc->sc_tinfo[r].luns, link) {
    458 				if ((ecb = li->untagged) != NULL) {
    459 					li->untagged = NULL;
    460 					/*
    461 					 * XXXXXXX
    462 					 *
    463 					 * Should we terminate a command
    464 					 * that never reached the disk?
    465 					 */
    466 					li->busy = 0;
    467 					ecb->xs->error = XS_TIMEOUT;
    468 					ncr53c9x_done(sc, ecb);
    469 				}
    470 				for (i = 0; i < 256; i++)
    471 					if ((ecb = li->queued[i])) {
    472 						li->queued[i] = NULL;
    473 						ecb->xs->error = XS_TIMEOUT;
    474 						ncr53c9x_done(sc, ecb);
    475 					}
    476 				li->used = 0;
    477 			}
    478 		}
    479 	}
    480 
    481 	/*
    482 	 * reset the chip to a known state
    483 	 */
    484 	ncr53c9x_reset(sc);
    485 
    486 	sc->sc_phase = sc->sc_prevphase = INVALID_PHASE;
    487 	for (r = 0; r < 8; r++) {
    488 		struct ncr53c9x_tinfo *ti = &sc->sc_tinfo[r];
    489 /* XXX - config flags per target: low bits: no reselect; high bits: no synch */
    490 
    491 		ti->flags = ((sc->sc_minsync && !(sc->sc_cfflags & (1<<(r+8))))
    492 		    ? 0 : T_SYNCHOFF) |
    493 		    ((sc->sc_cfflags & (1<<r)) ? T_RSELECTOFF : 0) |
    494 		    T_NEED_TO_RESET;
    495 #ifdef DEBUG
    496 		if (ncr53c9x_notag)
    497 			ti->flags &= ~T_TAG;
    498 #endif
    499 		ti->period = sc->sc_minsync;
    500 		ti->offset = 0;
    501 		ti->cfg3   = 0;
    502 	}
    503 
    504 	if (doreset) {
    505 		sc->sc_state = NCR_SBR;
    506 		NCRCMD(sc, NCRCMD_RSTSCSI);
    507 	} else {
    508 		sc->sc_state = NCR_IDLE;
    509 		ncr53c9x_sched(sc);
    510 	}
    511 }
    512 
    513 /*
    514  * Read the NCR registers, and save their contents for later use.
    515  * NCR_STAT, NCR_STEP & NCR_INTR are mostly zeroed out when reading
    516  * NCR_INTR - so make sure it is the last read.
    517  *
    518  * I think that (from reading the docs) most bits in these registers
    519  * only make sense when he DMA CSR has an interrupt showing. Call only
    520  * if an interrupt is pending.
    521  */
    522 __inline__ void
    523 ncr53c9x_readregs(sc)
    524 	struct ncr53c9x_softc *sc;
    525 {
    526 
    527 	sc->sc_espstat = NCR_READ_REG(sc, NCR_STAT);
    528 	/* Only the stepo bits are of interest */
    529 	sc->sc_espstep = NCR_READ_REG(sc, NCR_STEP) & NCRSTEP_MASK;
    530 
    531 	if (sc->sc_rev == NCR_VARIANT_FAS366)
    532 		sc->sc_espstat2 = NCR_READ_REG(sc, NCR_STAT2);
    533 
    534 	sc->sc_espintr = NCR_READ_REG(sc, NCR_INTR);
    535 
    536 	if (sc->sc_glue->gl_clear_latched_intr != NULL)
    537 		(*sc->sc_glue->gl_clear_latched_intr)(sc);
    538 
    539 	/*
    540 	 * Determine the SCSI bus phase, return either a real SCSI bus phase
    541 	 * or some pseudo phase we use to detect certain exceptions.
    542 	 */
    543 
    544 	sc->sc_phase = (sc->sc_espintr & NCRINTR_DIS) ?
    545 	    /* Disconnected */ BUSFREE_PHASE : sc->sc_espstat & NCRSTAT_PHASE;
    546 
    547 	NCR_MISC(("regs[intr=%02x,stat=%02x,step=%02x,stat2=%02x] ",
    548 	    sc->sc_espintr, sc->sc_espstat, sc->sc_espstep, sc->sc_espstat2));
    549 }
    550 
    551 /*
    552  * Convert Synchronous Transfer Period to chip register Clock Per Byte value.
    553  */
    554 static inline int
    555 ncr53c9x_stp2cpb(sc, period)
    556 	struct ncr53c9x_softc *sc;
    557 	int period;
    558 {
    559 	int v;
    560 	v = (sc->sc_freq * period) / 250;
    561 	if (ncr53c9x_cpb2stp(sc, v) < period)
    562 		/* Correct round-down error */
    563 		v++;
    564 	return (v);
    565 }
    566 
    567 static inline void
    568 ncr53c9x_setsync(sc, ti)
    569 	struct ncr53c9x_softc *sc;
    570 	struct ncr53c9x_tinfo *ti;
    571 {
    572 	u_char syncoff, synctp;
    573 	u_char cfg3 = sc->sc_cfg3 | ti->cfg3;
    574 
    575 	if (ti->flags & T_SYNCMODE) {
    576 		syncoff = ti->offset;
    577 		synctp = ncr53c9x_stp2cpb(sc, ti->period);
    578 		if (sc->sc_features & NCR_F_FASTSCSI) {
    579 			/*
    580 			 * If the period is 200ns or less (ti->period <= 50),
    581 			 * put the chip in Fast SCSI mode.
    582 			 */
    583 			if (ti->period <= 50)
    584 				/*
    585 				 * There are (at least) 4 variations of the
    586 				 * configuration 3 register.  The drive attach
    587 				 * routine sets the appropriate bit to put the
    588 				 * chip into Fast SCSI mode so that it doesn't
    589 				 * have to be figured out here each time.
    590 				 */
    591 				cfg3 |= sc->sc_cfg3_fscsi;
    592 		}
    593 
    594 		/*
    595 		 * Am53c974 requires different SYNCTP values when the
    596 		 * FSCSI bit is off.
    597 		 */
    598 		if (sc->sc_rev == NCR_VARIANT_AM53C974 &&
    599 		    (cfg3 & NCRAMDCFG3_FSCSI) == 0)
    600 			synctp--;
    601 	} else {
    602 		syncoff = 0;
    603 		synctp = 0;
    604 	}
    605 
    606 	if (sc->sc_features & NCR_F_HASCFG3)
    607 		NCR_WRITE_REG(sc, NCR_CFG3, cfg3);
    608 
    609 	NCR_WRITE_REG(sc, NCR_SYNCOFF, syncoff);
    610 	NCR_WRITE_REG(sc, NCR_SYNCTP, synctp);
    611 }
    612 
    613 /*
    614  * Send a command to a target, set the driver state to NCR_SELECTING
    615  * and let the caller take care of the rest.
    616  *
    617  * Keeping this as a function allows me to say that this may be done
    618  * by DMA instead of programmed I/O soon.
    619  */
    620 void
    621 ncr53c9x_select(sc, ecb)
    622 	struct ncr53c9x_softc *sc;
    623 	struct ncr53c9x_ecb *ecb;
    624 {
    625 	struct scsipi_link *sc_link = ecb->xs->sc_link;
    626 	int target = sc_link->scsipi_scsi.target;
    627 	int lun = sc_link->scsipi_scsi.lun;
    628 	struct ncr53c9x_tinfo *ti = &sc->sc_tinfo[target];
    629 	int tiflags = ti->flags;
    630 	u_char *cmd;
    631 	int clen;
    632 	int selatn3, selatns;
    633 	size_t dmasize;
    634 
    635 	NCR_TRACE(("[ncr53c9x_select(t%d,l%d,cmd:%x,tag:%x,%x)] ",
    636 	    target, lun, ecb->cmd.cmd.opcode, ecb->tag[0], ecb->tag[1]));
    637 
    638 	sc->sc_state = NCR_SELECTING;
    639 	/*
    640 	 * Schedule the timeout now, the first time we will go away
    641 	 * expecting to come back due to an interrupt, because it is
    642 	 * always possible that the interrupt may never happen.
    643 	 */
    644 	if ((ecb->xs->xs_control & XS_CTL_POLL) == 0) {
    645 		int timeout = ecb->timeout;
    646 
    647 		if (hz > 100 && timeout > 1000)
    648 			timeout = (timeout / 1000) * hz;
    649 		else
    650 			timeout = (timeout * hz) / 1000;
    651 
    652 		callout_reset(&ecb->xs->xs_callout, timeout,
    653 		    ncr53c9x_timeout, ecb);
    654 	}
    655 
    656 	/*
    657 	 * The docs say the target register is never reset, and I
    658 	 * can't think of a better place to set it
    659 	 */
    660 	if (sc->sc_rev == NCR_VARIANT_FAS366) {
    661 		NCRCMD(sc, NCRCMD_FLUSH);
    662 		NCR_WRITE_REG(sc, NCR_SELID, target | NCR_BUSID_HME);
    663 	} else {
    664 		NCR_WRITE_REG(sc, NCR_SELID, target);
    665 	}
    666 	ncr53c9x_setsync(sc, ti);
    667 
    668 	if ((ecb->flags & ECB_SENSE) != 0) {
    669 		/*
    670 		 * For REQUEST SENSE, we should not send an IDENTIFY or
    671 		 * otherwise mangle the target.  There should be no MESSAGE IN
    672 		 * phase.
    673 		 */
    674 		if (sc->sc_features & NCR_F_DMASELECT) {
    675 			/* setup DMA transfer for command */
    676 			dmasize = clen = ecb->clen;
    677 			sc->sc_cmdlen = clen;
    678 			sc->sc_cmdp = (caddr_t)&ecb->cmd.cmd;
    679 
    680 			/* Program the SCSI counter */
    681 			NCR_SET_COUNT(sc, dmasize);
    682 
    683 			if (sc->sc_rev != NCR_VARIANT_FAS366)
    684 				NCRCMD(sc, NCRCMD_NOP|NCRCMD_DMA);
    685 
    686 			/* And get the targets attention */
    687 			NCRCMD(sc, NCRCMD_SELNATN | NCRCMD_DMA);
    688 			NCRDMA_SETUP(sc, &sc->sc_cmdp, &sc->sc_cmdlen, 0,
    689 			    &dmasize);
    690 			NCRDMA_GO(sc);
    691 		} else {
    692 			ncr53c9x_wrfifo(sc, (u_char *)&ecb->cmd.cmd, ecb->clen);
    693 			NCRCMD(sc, NCRCMD_SELNATN);
    694 		}
    695 		return;
    696 	}
    697 
    698 	selatn3 = selatns = 0;
    699 	if (ecb->tag[0] != 0) {
    700 		if (sc->sc_features & NCR_F_SELATN3)
    701 			/* use SELATN3 to send tag messages */
    702 			selatn3 = 1;
    703 		else
    704 			/* We don't have SELATN3; use SELATNS to send tags */
    705 			selatns = 1;
    706 	}
    707 
    708 	if (ti->flags & T_NEGOTIATE) {
    709 		/* We have to use SELATNS to send sync/wide messages */
    710 		selatn3 = 0;
    711 		selatns = 1;
    712 	}
    713 
    714 	cmd = (u_char *)&ecb->cmd.cmd;
    715 
    716 	if (selatn3) {
    717 		/* We'll use tags with SELATN3 */
    718 		clen = ecb->clen + 3;
    719 		cmd -= 3;
    720 		cmd[0] = MSG_IDENTIFY(lun, 1);	/* msg[0] */
    721 		cmd[1] = ecb->tag[0];		/* msg[1] */
    722 		cmd[2] = ecb->tag[1];		/* msg[2] */
    723 	} else {
    724 		/* We don't have tags, or will send messages with SELATNS */
    725 		clen = ecb->clen + 1;
    726 		cmd -= 1;
    727 		cmd[0] = MSG_IDENTIFY(lun, (tiflags & T_RSELECTOFF) == 0);
    728 	}
    729 
    730 	if ((sc->sc_features & NCR_F_DMASELECT) && !selatns) {
    731 
    732 		/* setup DMA transfer for command */
    733 		dmasize = clen;
    734 		sc->sc_cmdlen = clen;
    735 		sc->sc_cmdp = cmd;
    736 
    737 		/* Program the SCSI counter */
    738 		NCR_SET_COUNT(sc, dmasize);
    739 
    740 		/* load the count in */
    741 		/* if (sc->sc_rev != NCR_VARIANT_FAS366) */
    742 			NCRCMD(sc, NCRCMD_NOP|NCRCMD_DMA);
    743 
    744 		/* And get the targets attention */
    745 		if (selatn3) {
    746 			sc->sc_msgout = SEND_TAG;
    747 			sc->sc_flags |= NCR_ATN;
    748 			NCRCMD(sc, NCRCMD_SELATN3 | NCRCMD_DMA);
    749 		} else
    750 			NCRCMD(sc, NCRCMD_SELATN | NCRCMD_DMA);
    751 		NCRDMA_SETUP(sc, &sc->sc_cmdp, &sc->sc_cmdlen, 0, &dmasize);
    752 		NCRDMA_GO(sc);
    753 		return;
    754 	}
    755 
    756 	/*
    757 	 * Who am I. This is where we tell the target that we are
    758 	 * happy for it to disconnect etc.
    759 	 */
    760 
    761 	/* Now get the command into the FIFO */
    762 	ncr53c9x_wrfifo(sc, cmd, clen);
    763 
    764 	/* And get the targets attention */
    765 	if (selatns) {
    766 		NCR_MISC(("SELATNS \n"));
    767 		/* Arbitrate, select and stop after IDENTIFY message */
    768 		NCRCMD(sc, NCRCMD_SELATNS);
    769 	} else if (selatn3) {
    770 		sc->sc_msgout = SEND_TAG;
    771 		sc->sc_flags |= NCR_ATN;
    772 		NCRCMD(sc, NCRCMD_SELATN3);
    773 	} else
    774 		NCRCMD(sc, NCRCMD_SELATN);
    775 }
    776 
    777 void
    778 ncr53c9x_free_ecb(sc, ecb, flags)
    779 	struct ncr53c9x_softc *sc;
    780 	struct ncr53c9x_ecb *ecb;
    781 	int flags;
    782 {
    783 	int s;
    784 
    785 	s = splbio();
    786 	ecb->flags = 0;
    787 	pool_put(&ecb_pool, (void *)ecb);
    788 	splx(s);
    789 	return;
    790 }
    791 
    792 struct ncr53c9x_ecb *
    793 ncr53c9x_get_ecb(sc, flags)
    794 	struct ncr53c9x_softc *sc;
    795 	int flags;
    796 {
    797 	struct ncr53c9x_ecb *ecb;
    798 	int s, wait = 0;
    799 
    800 	if ((curproc != NULL) && ((flags & XS_CTL_NOSLEEP) == 0))
    801 		wait = PR_WAITOK;
    802 
    803 	s = splbio();
    804 	ecb = (struct ncr53c9x_ecb *)pool_get(&ecb_pool, wait);
    805 	splx(s);
    806 	bzero(ecb, sizeof(*ecb));
    807 	if (ecb)
    808 		ecb->flags |= ECB_ALLOC;
    809 	return (ecb);
    810 }
    811 
    812 /*
    813  * DRIVER FUNCTIONS CALLABLE FROM HIGHER LEVEL DRIVERS
    814  */
    815 
    816 /*
    817  * Start a SCSI-command
    818  * This function is called by the higher level SCSI-driver to queue/run
    819  * SCSI-commands.
    820  */
    821 int
    822 ncr53c9x_scsi_cmd(xs)
    823 	struct scsipi_xfer *xs;
    824 {
    825 	struct scsipi_link *sc_link = xs->sc_link;
    826 	struct ncr53c9x_softc *sc = sc_link->adapter_softc;
    827 	struct ncr53c9x_ecb *ecb;
    828 	struct ncr53c9x_tinfo *ti;
    829 	struct ncr53c9x_linfo *li;
    830 	int64_t lun = sc_link->scsipi_scsi.lun;
    831 	int s, flags;
    832 
    833 	NCR_TRACE(("[ncr53c9x_scsi_cmd] "));
    834 	NCR_CMDS(("[0x%x, %d]->%d ", (int)xs->cmd->opcode, xs->cmdlen,
    835 	    sc_link->scsipi_scsi.target));
    836 
    837 	/*
    838 	 * Find the LUN info structure and allocate one if it does
    839 	 * not exist.
    840 	 */
    841 	flags = xs->xs_control;
    842 	ti = &sc->sc_tinfo[sc_link->scsipi_scsi.target];
    843 	li = TINFO_LUN(ti, lun);
    844 	if (li == NULL) {
    845 		int wait = M_NOWAIT;
    846 
    847 		/* Initialize LUN info and add to list. */
    848 		if ((curproc != NULL) && ((flags & XS_CTL_NOSLEEP) == 0))
    849 			wait = M_WAITOK;
    850 		if ((li = malloc(sizeof(*li), M_DEVBUF, M_NOWAIT)) == NULL)
    851 			return (TRY_AGAIN_LATER);
    852 
    853 		bzero(li, sizeof(*li));
    854 		li->last_used = time.tv_sec;
    855 		li->lun = lun;
    856 		s = splbio();
    857 		LIST_INSERT_HEAD(&ti->luns, li, link);
    858 		if (lun < NCR_NLUN)
    859 			ti->lun[lun] = li;
    860 		splx(s);
    861 	}
    862 
    863 	if ((ecb = ncr53c9x_get_ecb(sc, flags)) == NULL)
    864 		return (TRY_AGAIN_LATER);
    865 
    866 	/* Initialize ecb */
    867 	ecb->xs = xs;
    868 	ecb->timeout = xs->timeout;
    869 
    870 	if (flags & XS_CTL_RESET) {
    871 		ecb->flags |= ECB_RESET;
    872 		ecb->clen = 0;
    873 		ecb->dleft = 0;
    874 	} else {
    875 		bcopy(xs->cmd, &ecb->cmd.cmd, xs->cmdlen);
    876 		ecb->clen = xs->cmdlen;
    877 		ecb->daddr = xs->data;
    878 		ecb->dleft = xs->datalen;
    879 	}
    880 	ecb->stat = 0;
    881 
    882 	s = splbio();
    883 
    884 	TAILQ_INSERT_TAIL(&sc->ready_list, ecb, chain);
    885 	ecb->flags |= ECB_READY;
    886 	if (sc->sc_state == NCR_IDLE)
    887 		ncr53c9x_sched(sc);
    888 
    889 	splx(s);
    890 
    891 	if ((flags & XS_CTL_POLL) == 0)
    892 		return (SUCCESSFULLY_QUEUED);
    893 
    894 	/* Not allowed to use interrupts, use polling instead */
    895 	if (ncr53c9x_poll(sc, xs, ecb->timeout)) {
    896 		ncr53c9x_timeout(ecb);
    897 		if (ncr53c9x_poll(sc, xs, ecb->timeout))
    898 			ncr53c9x_timeout(ecb);
    899 	}
    900 	return (COMPLETE);
    901 }
    902 
    903 /*
    904  * Used when interrupt driven I/O isn't allowed, e.g. during boot.
    905  */
    906 int
    907 ncr53c9x_poll(sc, xs, count)
    908 	struct ncr53c9x_softc *sc;
    909 	struct scsipi_xfer *xs;
    910 	int count;
    911 {
    912 
    913 	NCR_TRACE(("[ncr53c9x_poll] "));
    914 	while (count) {
    915 		if (NCRDMA_ISINTR(sc)) {
    916 			ncr53c9x_intr(sc);
    917 		}
    918 #if alternatively
    919 		if (NCR_READ_REG(sc, NCR_STAT) & NCRSTAT_INT)
    920 			ncr53c9x_intr(sc);
    921 #endif
    922 		if ((xs->xs_status & XS_STS_DONE) != 0)
    923 			return (0);
    924 		if (sc->sc_state == NCR_IDLE) {
    925 			NCR_TRACE(("[ncr53c9x_poll: rescheduling] "));
    926 			ncr53c9x_sched(sc);
    927 		}
    928 		DELAY(1000);
    929 		count--;
    930 	}
    931 	return (1);
    932 }
    933 
    934 int
    935 ncr53c9x_ioctl(link, cmd, arg, flag, p)
    936 	struct scsipi_link *link;
    937 	u_long cmd;
    938 	caddr_t arg;
    939 	int flag;
    940 	struct proc *p;
    941 {
    942 	struct ncr53c9x_softc *sc = link->adapter_softc;
    943 	int s, error = 0;
    944 
    945 	s = splbio();
    946 
    947 	switch (cmd) {
    948 	case SCBUSACCEL: {
    949 		struct scbusaccel_args *sp = (struct scbusaccel_args *)arg;
    950 		struct ncr53c9x_tinfo *ti = &sc->sc_tinfo[sp->sa_target];
    951 
    952 		if (sp->sa_lun != 0)
    953 			break;
    954 
    955 		NCR_MISC(("%s: SCBUSACCEL flag 0x%x\n", sc->sc_dev.dv_xname,
    956 		    sp->sa_flags));
    957 
    958 		if ((sp->sa_flags & SC_ACCEL_WIDE) != 0) {
    959 			NCR_MISC(("%s: target %d: wide scsi negotiation\n",
    960 			    sc->sc_dev.dv_xname, sp->sa_target));
    961 
    962 			if (sc->sc_rev == NCR_VARIANT_FAS366) {
    963 				ti->flags |= T_WIDE;
    964 				ti->width = 1;
    965 			}
    966 		}
    967 
    968 		if ((sp->sa_flags & SC_ACCEL_SYNC) != 0) {
    969 			/*
    970 			 * Check if this adapter can do sync and
    971 			 * if the target is already clamped at
    972 			 * non-sync operation on user request.
    973 			 */
    974 			if (sc->sc_minsync != 0 &&
    975 			    (ti->flags & T_SYNCHOFF) == 0) {
    976 				NCR_MISC(("%s: target %d: sync negotiation\n",
    977 				    sc->sc_dev.dv_xname, sp->sa_target));
    978 				ti->flags |= T_NEGOTIATE;
    979 			}
    980 		}
    981 
    982 		if ((sp->sa_flags & SC_ACCEL_TAGS) != 0) {
    983 			if ((sc->sc_cfflags & (1<<((sp->sa_target)+16))) == 0) {
    984 				ti->flags |= T_TAG;
    985 				link->openings = 255;
    986 
    987 				printf("%s: target %d: tags\n",
    988 				    sc->sc_dev.dv_xname, sp->sa_target);
    989 			}
    990 		}
    991 		break;
    992 	}
    993 	default:
    994 		error = ENOTTY;
    995 		break;
    996 	}
    997 	splx(s);
    998 	return (error);
    999 }
   1000 
   1001 
   1002 /*
   1003  * LOW LEVEL SCSI UTILITIES
   1004  */
   1005 
   1006 /*
   1007  * Schedule a scsi operation.  This has now been pulled out of the interrupt
   1008  * handler so that we may call it from ncr53c9x_scsi_cmd and ncr53c9x_done.
   1009  * This may save us an unecessary interrupt just to get things going.
   1010  * Should only be called when state == NCR_IDLE and at bio pl.
   1011  */
   1012 void
   1013 ncr53c9x_sched(sc)
   1014 	struct ncr53c9x_softc *sc;
   1015 {
   1016 	struct ncr53c9x_ecb *ecb;
   1017 	struct scsipi_link *sc_link;
   1018 	struct ncr53c9x_tinfo *ti;
   1019 	int lun;
   1020 	struct ncr53c9x_linfo *li;
   1021 	int s, tag;
   1022 
   1023 	NCR_TRACE(("[ncr53c9x_sched] "));
   1024 	if (sc->sc_state != NCR_IDLE)
   1025 		panic("ncr53c9x_sched: not IDLE (state=%d)", sc->sc_state);
   1026 
   1027 	/*
   1028 	 * Find first ecb in ready queue that is for a target/lunit
   1029 	 * combinations that is not busy.
   1030 	 */
   1031 	for (ecb = TAILQ_FIRST(&sc->ready_list); ecb != NULL;
   1032 	     ecb = TAILQ_NEXT(ecb, chain)) {
   1033 		sc_link = ecb->xs->sc_link;
   1034 		ti = &sc->sc_tinfo[sc_link->scsipi_scsi.target];
   1035 		lun = sc_link->scsipi_scsi.lun;
   1036 
   1037 		/* Select type of tag for this command */
   1038 		if ((ti->flags & (T_RSELECTOFF)) != 0)
   1039 			tag = 0;
   1040 		else if ((ti->flags & (T_TAG)) == 0)
   1041 			tag = 0;
   1042 		else if ((ecb->flags & ECB_SENSE) != 0)
   1043 			tag = 0;
   1044 		else if (ecb->xs->xs_control & XS_CTL_URGENT)
   1045 			tag = MSG_HEAD_OF_Q_TAG;
   1046 		else
   1047 			tag = MSG_SIMPLE_Q_TAG;
   1048 #if 0
   1049 		/* XXXX Use tags for polled commands? */
   1050 		if (ecb->xs->xs_control & XS_CTL_POLL)
   1051 			tag = 0;
   1052 #endif
   1053 
   1054 		s = splbio();
   1055 		li = TINFO_LUN(ti, lun);
   1056 		if (li == NULL) {
   1057 			int wait = M_NOWAIT;
   1058 			int flags = ecb->xs->xs_control;
   1059 
   1060 			/* Initialize LUN info and add to list. */
   1061 			if ((curproc != NULL) &&
   1062 			    ((flags & XS_CTL_NOSLEEP) == 0))
   1063 				wait = M_WAITOK;
   1064 			if ((li = malloc(sizeof(*li), M_DEVBUF, M_NOWAIT))
   1065 			    == NULL) {
   1066 				splx(s);
   1067 				continue;
   1068 			}
   1069 			bzero(li, sizeof(*li));
   1070 			li->lun = lun;
   1071 
   1072 			LIST_INSERT_HEAD(&ti->luns, li, link);
   1073 			if (lun < NCR_NLUN)
   1074 				ti->lun[lun] = li;
   1075 		}
   1076 		li->last_used = time.tv_sec;
   1077 		if (tag == 0) {
   1078 			/* Try to issue this as an un-tagged command */
   1079 			if (li->untagged == NULL)
   1080 				li->untagged = ecb;
   1081 		}
   1082 		if (li->untagged != NULL) {
   1083 			tag = 0;
   1084 			if ((li->busy != 1) && li->used == 0) {
   1085 				/* We need to issue this untagged command now */
   1086 				ecb = li->untagged;
   1087 				sc_link = ecb->xs->sc_link;
   1088 			} else {
   1089 				/* Not ready yet */
   1090 				splx(s);
   1091 				continue;
   1092 			}
   1093 		}
   1094 		ecb->tag[0] = tag;
   1095 		if (tag != 0) {
   1096 			int i;
   1097 
   1098 			/* Allocate a tag */
   1099 			if (li->used == 255) {
   1100 				/* no free tags */
   1101 				splx(s);
   1102 				continue;
   1103 			}
   1104 			/* Start from the last used location */
   1105 			for (i = li->avail; i < 256; i++) {
   1106 				if (li->queued[i] == NULL)
   1107 					break;
   1108 			}
   1109 			/* Couldn't find one, start again from the beginning */
   1110 			if (i == 256) {
   1111 				for (i = 0; i < 256; i++) {
   1112 					if (li->queued[i] == NULL)
   1113 						break;
   1114 				}
   1115 			}
   1116 #ifdef DIAGNOSTIC
   1117 			/* There's supposed to be at least 1 tag avail */
   1118 			if (i == 256)
   1119 				panic("ncr53c9x_sched: tag alloc failure\n");
   1120 #endif
   1121 
   1122 			/* Save where to start next time. */
   1123 			li->avail = i + 1;
   1124 			li->used++;
   1125 
   1126 			li->queued[i] = ecb;
   1127 			ecb->tag[1] = i;
   1128 		}
   1129 		splx(s);
   1130 		if (li->untagged != NULL && (li->busy != 1)) {
   1131 			li->busy = 1;
   1132 			TAILQ_REMOVE(&sc->ready_list, ecb, chain);
   1133 			ecb->flags &= ~ECB_READY;
   1134 			sc->sc_nexus = ecb;
   1135 			ncr53c9x_select(sc, ecb);
   1136 			break;
   1137 		}
   1138 		if (li->untagged == NULL && tag != 0) {
   1139 			TAILQ_REMOVE(&sc->ready_list, ecb, chain);
   1140 			ecb->flags &= ~ECB_READY;
   1141 			sc->sc_nexus = ecb;
   1142 			ncr53c9x_select(sc, ecb);
   1143 			break;
   1144 		} else
   1145 			NCR_MISC(("%d:%d busy\n",
   1146 			    sc_link->scsipi_scsi.target,
   1147 			    sc_link->scsipi_scsi.lun));
   1148 	}
   1149 }
   1150 
   1151 void
   1152 ncr53c9x_sense(sc, ecb)
   1153 	struct ncr53c9x_softc *sc;
   1154 	struct ncr53c9x_ecb *ecb;
   1155 {
   1156 	struct scsipi_xfer *xs = ecb->xs;
   1157 	struct scsipi_link *sc_link = xs->sc_link;
   1158 	struct ncr53c9x_tinfo *ti = &sc->sc_tinfo[sc_link->scsipi_scsi.target];
   1159 	struct scsipi_sense *ss = (void *)&ecb->cmd.cmd;
   1160 	struct ncr53c9x_linfo *li;
   1161 	int lun = sc_link->scsipi_scsi.lun;
   1162 
   1163 	NCR_MISC(("requesting sense "));
   1164 	/* Next, setup a request sense command block */
   1165 	bzero(ss, sizeof(*ss));
   1166 	ss->opcode = REQUEST_SENSE;
   1167 	ss->byte2 = sc_link->scsipi_scsi.lun << SCSI_CMD_LUN_SHIFT;
   1168 	ss->length = sizeof(struct scsipi_sense_data);
   1169 	ecb->clen = sizeof(*ss);
   1170 	ecb->daddr = (char *)&xs->sense.scsi_sense;
   1171 	ecb->dleft = sizeof(struct scsipi_sense_data);
   1172 	ecb->flags |= ECB_SENSE;
   1173 	ecb->timeout = NCR_SENSE_TIMEOUT;
   1174 	ti->senses++;
   1175 	li = TINFO_LUN(ti, lun);
   1176 	if (li->busy)
   1177 		li->busy = 0;
   1178 	ncr53c9x_dequeue(sc, ecb);
   1179 	li->untagged = ecb; /* must be executed first to fix C/A */
   1180 	li->busy = 2;
   1181 	if (ecb == sc->sc_nexus) {
   1182 		ncr53c9x_select(sc, ecb);
   1183 	} else {
   1184 		TAILQ_INSERT_HEAD(&sc->ready_list, ecb, chain);
   1185 		ecb->flags |= ECB_READY;
   1186 		if (sc->sc_state == NCR_IDLE)
   1187 			ncr53c9x_sched(sc);
   1188 	}
   1189 }
   1190 
   1191 /*
   1192  * POST PROCESSING OF SCSI_CMD (usually current)
   1193  */
   1194 void
   1195 ncr53c9x_done(sc, ecb)
   1196 	struct ncr53c9x_softc *sc;
   1197 	struct ncr53c9x_ecb *ecb;
   1198 {
   1199 	struct scsipi_xfer *xs = ecb->xs;
   1200 	struct scsipi_link *sc_link = xs->sc_link;
   1201 	struct ncr53c9x_tinfo *ti = &sc->sc_tinfo[sc_link->scsipi_scsi.target];
   1202 	int lun = sc_link->scsipi_scsi.lun;
   1203 	struct ncr53c9x_linfo *li = TINFO_LUN(ti, lun);
   1204 
   1205 	NCR_TRACE(("[ncr53c9x_done(error:%x)] ", xs->error));
   1206 
   1207 	callout_stop(&ecb->xs->xs_callout);
   1208 
   1209 	if (ecb->stat == SCSI_QUEUE_FULL) {
   1210 		/*
   1211 		 * Set current throttle -- we should reset
   1212 		 * this periodically
   1213 		 */
   1214 		sc_link->openings = li->used - 1;
   1215 		printf("\n%s: QFULL -- throttling to %d commands\n",
   1216 		    sc->sc_dev.dv_xname, sc_link->openings);
   1217 
   1218 	}
   1219 
   1220 	/*
   1221 	 * Now, if we've come here with no error code, i.e. we've kept the
   1222 	 * initial XS_NOERROR, and the status code signals that we should
   1223 	 * check sense, we'll need to set up a request sense cmd block and
   1224 	 * push the command back into the ready queue *before* any other
   1225 	 * commands for this target/lunit, else we lose the sense info.
   1226 	 * We don't support chk sense conditions for the request sense cmd.
   1227 	 */
   1228 	if (xs->error == XS_NOERROR) {
   1229 		xs->status = ecb->stat;
   1230 		if ((ecb->flags & ECB_ABORT) != 0) {
   1231 			xs->error = XS_TIMEOUT;
   1232 		} else if ((ecb->flags & ECB_SENSE) != 0) {
   1233 			xs->error = XS_SENSE;
   1234 		} else if ((ecb->stat & ST_MASK) == SCSI_CHECK) {
   1235 			/* First, save the return values */
   1236 			xs->resid = ecb->dleft;
   1237 			ncr53c9x_sense(sc, ecb);
   1238 			return;
   1239 		} else {
   1240 			xs->resid = ecb->dleft;
   1241 		}
   1242 	}
   1243 
   1244 	xs->xs_status |= XS_STS_DONE;
   1245 
   1246 #ifdef NCR53C9X_DEBUG
   1247 	if (ncr53c9x_debug & NCR_SHOWMISC) {
   1248 		if (xs->resid != 0)
   1249 			printf("resid=%d ", xs->resid);
   1250 		if (xs->error == XS_SENSE)
   1251 			printf("sense=0x%02x\n",
   1252 			    xs->sense.scsi_sense.error_code);
   1253 		else
   1254 			printf("error=%d\n", xs->error);
   1255 	}
   1256 #endif
   1257 
   1258 	/*
   1259 	 * Remove the ECB from whatever queue it's on.
   1260 	 */
   1261 	ncr53c9x_dequeue(sc, ecb);
   1262 	if (ecb == sc->sc_nexus) {
   1263 		sc->sc_nexus = NULL;
   1264 		if (sc->sc_state != NCR_CLEANING) {
   1265 			sc->sc_state = NCR_IDLE;
   1266 			ncr53c9x_sched(sc);
   1267 		}
   1268 	}
   1269 
   1270 	if (xs->error == XS_SELTIMEOUT) {
   1271 		/* Selection timeout -- discard this LUN if empty */
   1272 		if (li->untagged == NULL && li->used == 0) {
   1273 			if (lun < NCR_NLUN)
   1274 				ti->lun[lun] = NULL;
   1275 			LIST_REMOVE(li, link);
   1276 			free(li, M_DEVBUF);
   1277 		}
   1278 	}
   1279 
   1280 	ncr53c9x_free_ecb(sc, ecb, xs->xs_control);
   1281 	ti->cmds++;
   1282 	scsipi_done(xs);
   1283 }
   1284 
   1285 void
   1286 ncr53c9x_dequeue(sc, ecb)
   1287 	struct ncr53c9x_softc *sc;
   1288 	struct ncr53c9x_ecb *ecb;
   1289 {
   1290 	struct ncr53c9x_tinfo *ti =
   1291 	    &sc->sc_tinfo[ecb->xs->sc_link->scsipi_scsi.target];
   1292 	struct ncr53c9x_linfo *li;
   1293 	int64_t lun = ecb->xs->sc_link->scsipi_scsi.lun;
   1294 
   1295 	li = TINFO_LUN(ti, lun);
   1296 #ifdef DIAGNOSTIC
   1297 	if (li == NULL || li->lun != lun)
   1298 		panic("ncr53c9x_dequeue: lun %qx for ecb %p does not exist\n",
   1299 		      (long long) lun, ecb);
   1300 #endif
   1301 	if (li->untagged == ecb) {
   1302 		li->busy = 0;
   1303 		li->untagged = NULL;
   1304 	}
   1305 	if (ecb->tag[0] && li->queued[ecb->tag[1]] != NULL) {
   1306 #ifdef DIAGNOSTIC
   1307 		if (li->queued[ecb->tag[1]] != NULL &&
   1308 		    (li->queued[ecb->tag[1]] != ecb))
   1309 			panic("ncr53c9x_dequeue: slot %d for lun %qx has %p "
   1310 			    "instead of ecb %p\n", ecb->tag[1],
   1311 			    (long long) lun,
   1312 			    li->queued[ecb->tag[1]], ecb);
   1313 #endif
   1314 		li->queued[ecb->tag[1]] = NULL;
   1315 		li->used--;
   1316 	}
   1317 
   1318 	if ((ecb->flags & ECB_READY) != 0) {
   1319 		ecb->flags &= ~ECB_READY;
   1320 		TAILQ_REMOVE(&sc->ready_list, ecb, chain);
   1321 	}
   1322 }
   1323 
   1324 /*
   1325  * INTERRUPT/PROTOCOL ENGINE
   1326  */
   1327 
   1328 /*
   1329  * Schedule an outgoing message by prioritizing it, and asserting
   1330  * attention on the bus. We can only do this when we are the initiator
   1331  * else there will be an illegal command interrupt.
   1332  */
   1333 #define ncr53c9x_sched_msgout(m) \
   1334 	do {							\
   1335 		NCR_MISC(("ncr53c9x_sched_msgout %x %d", m, __LINE__));	\
   1336 		NCRCMD(sc, NCRCMD_SETATN);			\
   1337 		sc->sc_flags |= NCR_ATN;			\
   1338 		sc->sc_msgpriq |= (m);				\
   1339 	} while (0)
   1340 
   1341 static void
   1342 ncr53c9x_flushfifo(struct ncr53c9x_softc *sc)
   1343 {
   1344 	NCR_MISC(("[flushfifo] "));
   1345 
   1346 	NCRCMD(sc, NCRCMD_FLUSH);
   1347 
   1348 	if (sc->sc_phase == COMMAND_PHASE ||
   1349 	    sc->sc_phase == MESSAGE_OUT_PHASE)
   1350 		DELAY(2);
   1351 }
   1352 
   1353 static int
   1354 ncr53c9x_rdfifo(struct ncr53c9x_softc *sc, int how)
   1355 {
   1356 	int i, n;
   1357 	u_char *buf;
   1358 
   1359 	switch(how) {
   1360 	case NCR_RDFIFO_START:
   1361 		buf = sc->sc_imess;
   1362 		sc->sc_imlen = 0;
   1363 		break;
   1364 	case NCR_RDFIFO_CONTINUE:
   1365 		buf = sc->sc_imess + sc->sc_imlen;
   1366 		break;
   1367 	default:
   1368 		panic("ncr53c9x_rdfifo: bad flag\n");
   1369 		break;
   1370 	}
   1371 
   1372 	/*
   1373 	 * XXX buffer (sc_imess) size for message
   1374 	 */
   1375 
   1376 	n = NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF;
   1377 
   1378 	if (sc->sc_rev == NCR_VARIANT_FAS366) {
   1379 		n *= 2;
   1380 
   1381 		for (i = 0; i < n; i++)
   1382 			buf[i] = NCR_READ_REG(sc, NCR_FIFO);
   1383 
   1384 		if (sc->sc_espstat2 & FAS_STAT2_ISHUTTLE) {
   1385 
   1386 			NCR_WRITE_REG(sc, NCR_FIFO, 0);
   1387 			buf[i++] = NCR_READ_REG(sc, NCR_FIFO);
   1388 
   1389 			NCR_READ_REG(sc, NCR_FIFO);
   1390 
   1391 			ncr53c9x_flushfifo(sc);
   1392 		}
   1393 	} else {
   1394 		for (i = 0; i < n; i++)
   1395 			buf[i] = NCR_READ_REG(sc, NCR_FIFO);
   1396 	}
   1397 
   1398 	sc->sc_imlen += i;
   1399 
   1400 #ifdef NCR53C9X_DEBUG
   1401  	{
   1402 		int j;
   1403 
   1404 		NCR_TRACE(("\n[rdfifo %s (%d):",
   1405 		    (how == NCR_RDFIFO_START) ? "start" : "cont",
   1406 		    (int)sc->sc_imlen));
   1407 		if (ncr53c9x_debug & NCR_SHOWTRAC) {
   1408 			for (j = 0; j < sc->sc_imlen; j++)
   1409 				printf(" %02x", sc->sc_imess[j]);
   1410 			printf("]\n");
   1411 		}
   1412 	}
   1413 #endif
   1414 	return sc->sc_imlen;
   1415 }
   1416 
   1417 static void
   1418 ncr53c9x_wrfifo(struct ncr53c9x_softc *sc, u_char *p, int len)
   1419 {
   1420 	int i;
   1421 
   1422 #ifdef NCR53C9X_DEBUG
   1423 	NCR_MISC(("[wrfifo(%d):", len));
   1424 	if (ncr53c9x_debug & NCR_SHOWTRAC) {
   1425 		for (i = 0; i < len; i++)
   1426 			printf(" %02x", p[i]);
   1427 		printf("]\n");
   1428 	}
   1429 #endif
   1430 
   1431 	for (i = 0; i < len; i++) {
   1432 		NCR_WRITE_REG(sc, NCR_FIFO, p[i]);
   1433 
   1434 		if (sc->sc_rev == NCR_VARIANT_FAS366)
   1435 			NCR_WRITE_REG(sc, NCR_FIFO, 0);
   1436 	}
   1437 }
   1438 
   1439 int
   1440 ncr53c9x_reselect(sc, message, tagtype, tagid)
   1441 	struct ncr53c9x_softc *sc;
   1442 	int message;
   1443 	int tagtype, tagid;
   1444 {
   1445 	u_char selid, target, lun;
   1446 	struct ncr53c9x_ecb *ecb = NULL;
   1447 	struct ncr53c9x_tinfo *ti;
   1448 	struct ncr53c9x_linfo *li;
   1449 
   1450 
   1451 	if (sc->sc_rev == NCR_VARIANT_FAS366) {
   1452 		target = sc->sc_selid;
   1453 	} else {
   1454 		/*
   1455 		 * The SCSI chip made a snapshot of the data bus
   1456 		 * while the reselection was being negotiated.
   1457 		 * This enables us to determine which target did
   1458 		 * the reselect.
   1459 		 */
   1460 		selid = sc->sc_selid & ~(1 << sc->sc_id);
   1461 		if (selid & (selid - 1)) {
   1462 			printf("%s: reselect with invalid selid %02x;"
   1463 			    " sending DEVICE RESET\n",
   1464 			    sc->sc_dev.dv_xname, selid);
   1465 			goto reset;
   1466 		}
   1467 
   1468 		target = ffs(selid) - 1;
   1469 	}
   1470 	lun = message & 0x07;
   1471 
   1472 	/*
   1473 	 * Search wait queue for disconnected cmd
   1474 	 * The list should be short, so I haven't bothered with
   1475 	 * any more sophisticated structures than a simple
   1476 	 * singly linked list.
   1477 	 */
   1478 	ti = &sc->sc_tinfo[target];
   1479 	li = TINFO_LUN(ti, lun);
   1480 
   1481 	/*
   1482 	 * We can get as far as the LUN with the IDENTIFY
   1483 	 * message.  Check to see if we're running an
   1484 	 * un-tagged command.  Otherwise ack the IDENTIFY
   1485 	 * and wait for a tag message.
   1486 	 */
   1487 	if (li != NULL) {
   1488 		if (li->untagged != NULL && li->busy)
   1489 			ecb = li->untagged;
   1490 		else if (tagtype != MSG_SIMPLE_Q_TAG) {
   1491 			/* Wait for tag to come by */
   1492 			sc->sc_state = NCR_IDENTIFIED;
   1493 			return (0);
   1494 		} else if (tagtype)
   1495 			ecb = li->queued[tagid];
   1496 	}
   1497 	if (ecb == NULL) {
   1498 		printf("%s: reselect from target %d lun %d tag %x:%x "
   1499 		    "with no nexus; sending ABORT\n",
   1500 		    sc->sc_dev.dv_xname, target, lun, tagtype, tagid);
   1501 		goto abort;
   1502 	}
   1503 
   1504 	/* Make this nexus active again. */
   1505 	sc->sc_state = NCR_CONNECTED;
   1506 	sc->sc_nexus = ecb;
   1507 	ncr53c9x_setsync(sc, ti);
   1508 
   1509 	if (ecb->flags & ECB_RESET)
   1510 		ncr53c9x_sched_msgout(SEND_DEV_RESET);
   1511 	else if (ecb->flags & ECB_ABORT)
   1512 		ncr53c9x_sched_msgout(SEND_ABORT);
   1513 
   1514 	/* Do an implicit RESTORE POINTERS. */
   1515 	sc->sc_dp = ecb->daddr;
   1516 	sc->sc_dleft = ecb->dleft;
   1517 
   1518 	return (0);
   1519 
   1520 reset:
   1521 	ncr53c9x_sched_msgout(SEND_DEV_RESET);
   1522 	return (1);
   1523 
   1524 abort:
   1525 	ncr53c9x_sched_msgout(SEND_ABORT);
   1526 	return (1);
   1527 }
   1528 
   1529 
   1530 /*
   1531  * XXX this might be common thing(check with scsipi)
   1532  */
   1533 #define IS1BYTEMSG(m) (((m) != 1 && (m) < 0x20) || (m) & 0x80)
   1534 #define IS2BYTEMSG(m) (((m) & 0xf0) == 0x20)
   1535 #define ISEXTMSG(m) ((m) == 1)
   1536 
   1537 static inline int
   1538 __verify_msg_format(u_char *p, int len)
   1539 {
   1540 
   1541 	if (len == 1 && IS1BYTEMSG(p[0]))
   1542 		return 1;
   1543 	if (len == 2 && IS2BYTEMSG(p[0]))
   1544 		return 1;
   1545 	if (len >= 3 && ISEXTMSG(p[0]) &&
   1546 	    len == p[1] + 2)
   1547 		return 1;
   1548 
   1549 	return 0;
   1550 }
   1551 
   1552 /*
   1553  * Get an incoming message as initiator.
   1554  *
   1555  * The SCSI bus must already be in MESSAGE_IN_PHASE and there is a
   1556  * byte in the FIFO
   1557  */
   1558 void
   1559 ncr53c9x_msgin(sc)
   1560 	struct ncr53c9x_softc *sc;
   1561 {
   1562 
   1563 	NCR_TRACE(("[ncr53c9x_msgin(curmsglen:%ld)] ", (long)sc->sc_imlen));
   1564 
   1565 	if (sc->sc_imlen == 0) {
   1566 		printf("%s: msgin: no msg byte available\n",
   1567 		    sc->sc_dev.dv_xname);
   1568 		return;
   1569 	}
   1570 
   1571 	/*
   1572 	 * Prepare for a new message.  A message should (according
   1573 	 * to the SCSI standard) be transmitted in one single
   1574 	 * MESSAGE_IN_PHASE. If we have been in some other phase,
   1575 	 * then this is a new message.
   1576 	 */
   1577 	if (sc->sc_prevphase != MESSAGE_IN_PHASE &&
   1578 	    sc->sc_state != NCR_RESELECTED) {
   1579 		printf("%s: phase change, dropping message, "
   1580 		    "prev %d, state %d\n",
   1581 		    sc->sc_dev.dv_xname, sc->sc_prevphase, sc->sc_state);
   1582 		sc->sc_flags &= ~NCR_DROP_MSGI;
   1583 		sc->sc_imlen = 0;
   1584 	}
   1585 
   1586 	NCR_TRACE(("<msgbyte:0x%02x>", sc->sc_imess[0]));
   1587 
   1588 	/*
   1589 	 * If we're going to reject the message, don't bother storing
   1590 	 * the incoming bytes.  But still, we need to ACK them.
   1591 	 */
   1592 	if ((sc->sc_flags & NCR_DROP_MSGI) != 0) {
   1593 		NCRCMD(sc, NCRCMD_MSGOK);
   1594 		printf("<dropping msg byte %x>", sc->sc_imess[sc->sc_imlen]);
   1595 		return;
   1596 	}
   1597 
   1598 	if (sc->sc_imlen >= NCR_MAX_MSG_LEN) {
   1599 		ncr53c9x_sched_msgout(SEND_REJECT);
   1600 		sc->sc_flags |= NCR_DROP_MSGI;
   1601 	} else {
   1602 		u_char *pb;
   1603 		int plen;
   1604 
   1605 		switch (sc->sc_state) {
   1606 		/*
   1607 		 * if received message is the first of reselection
   1608 		 * then first byte is selid, and then message
   1609 		 */
   1610 		case NCR_RESELECTED:
   1611 			pb = sc->sc_imess + 1;
   1612 			plen = sc->sc_imlen - 1;
   1613 			break;
   1614 		default:
   1615 			pb = sc->sc_imess;
   1616 			plen = sc->sc_imlen;
   1617 			break;
   1618 		}
   1619 
   1620 		if (__verify_msg_format(pb, plen))
   1621 			goto gotit;
   1622 	}
   1623 
   1624 	/* Ack what we have so far */
   1625 	NCRCMD(sc, NCRCMD_MSGOK);
   1626 	return;
   1627 
   1628 gotit:
   1629 	NCR_MSGS(("gotmsg(%x) state %d", sc->sc_imess[0], sc->sc_state));
   1630 	/* we got complete message, flush the imess, */
   1631 	/* XXX nobody uses imlen below */
   1632 	sc->sc_imlen = 0;
   1633 	/*
   1634 	 * Now we should have a complete message (1 byte, 2 byte
   1635 	 * and moderately long extended messages).  We only handle
   1636 	 * extended messages which total length is shorter than
   1637 	 * NCR_MAX_MSG_LEN.  Longer messages will be amputated.
   1638 	 */
   1639 	switch (sc->sc_state) {
   1640 		struct ncr53c9x_ecb *ecb;
   1641 		struct ncr53c9x_tinfo *ti;
   1642 		struct ncr53c9x_linfo *li;
   1643 		int lun;
   1644 
   1645 	case NCR_CONNECTED:
   1646 		ecb = sc->sc_nexus;
   1647 		ti = &sc->sc_tinfo[ecb->xs->sc_link->scsipi_scsi.target];
   1648 
   1649 		switch (sc->sc_imess[0]) {
   1650 		case MSG_CMDCOMPLETE:
   1651 			NCR_MSGS(("cmdcomplete "));
   1652 			if (sc->sc_dleft < 0) {
   1653 				scsi_print_addr(ecb->xs->sc_link);
   1654 				printf("got %ld extra bytes\n",
   1655 				    -(long)sc->sc_dleft);
   1656 				sc->sc_dleft = 0;
   1657 			}
   1658 			ecb->dleft = (ecb->flags & ECB_TENTATIVE_DONE) ?
   1659 			    0 : sc->sc_dleft;
   1660 			if ((ecb->flags & ECB_SENSE) == 0)
   1661 				ecb->xs->resid = ecb->dleft;
   1662 			sc->sc_state = NCR_CMDCOMPLETE;
   1663 			break;
   1664 
   1665 		case MSG_MESSAGE_REJECT:
   1666 			NCR_MSGS(("msg reject (msgout=%x) ", sc->sc_msgout));
   1667 			switch (sc->sc_msgout) {
   1668 			case SEND_TAG:
   1669 				/*
   1670 				 * Target does not like tagged queuing.
   1671 				 *  - Flush the command queue
   1672 				 *  - Disable tagged queuing for the target
   1673 				 *  - Dequeue ecb from the queued array.
   1674 				 */
   1675 				printf("%s: tagged queuing rejected: "
   1676 				    "target %d\n",
   1677 				    sc->sc_dev.dv_xname,
   1678 				    ecb->xs->sc_link->scsipi_scsi.target);
   1679 
   1680 				NCR_MSGS(("(rejected sent tag)"));
   1681 				NCRCMD(sc, NCRCMD_FLUSH);
   1682 				DELAY(1);
   1683 				ti->flags &= ~T_TAG;
   1684 				lun = ecb->xs->sc_link->scsipi_scsi.lun;
   1685 				li = TINFO_LUN(ti, lun);
   1686 				if (ecb->tag[0] &&
   1687 				    li->queued[ecb->tag[1]] != NULL) {
   1688 					li->queued[ecb->tag[1]] = NULL;
   1689 					li->used--;
   1690 				}
   1691 				ecb->tag[0] = ecb->tag[1] = 0;
   1692 				li->untagged = ecb;
   1693 				li->busy = 1;
   1694 				break;
   1695 
   1696 			case SEND_SDTR:
   1697 				printf("%s: sync transfer rejected: "
   1698 				    "target %d\n",
   1699 				    sc->sc_dev.dv_xname,
   1700 				    ecb->xs->sc_link->scsipi_scsi.target);
   1701 
   1702 				sc->sc_flags &= ~NCR_SYNCHNEGO;
   1703 				ti->flags &= ~(T_NEGOTIATE | T_SYNCMODE);
   1704 				ncr53c9x_setsync(sc, ti);
   1705 				break;
   1706 
   1707 			case SEND_WDTR:
   1708 				printf("%s: wide transfer rejected: "
   1709 				    "target %d\n",
   1710 				    sc->sc_dev.dv_xname,
   1711 				    ecb->xs->sc_link->scsipi_scsi.target);
   1712 				ti->flags &= ~T_WIDE;
   1713 				break;
   1714 
   1715 			case SEND_INIT_DET_ERR:
   1716 				goto abort;
   1717 			}
   1718 			break;
   1719 
   1720 		case MSG_NOOP:
   1721 			NCR_MSGS(("noop "));
   1722 			break;
   1723 
   1724 		case MSG_HEAD_OF_Q_TAG:
   1725 		case MSG_SIMPLE_Q_TAG:
   1726 		case MSG_ORDERED_Q_TAG:
   1727 			NCR_MSGS(("TAG %x:%x",
   1728 			    sc->sc_imess[0], sc->sc_imess[1]));
   1729 			break;
   1730 
   1731 		case MSG_DISCONNECT:
   1732 			NCR_MSGS(("disconnect "));
   1733 			ti->dconns++;
   1734 			sc->sc_state = NCR_DISCONNECT;
   1735 
   1736 			/*
   1737 			 * Mark the fact that all bytes have moved. The
   1738 			 * target may not bother to do a SAVE POINTERS
   1739 			 * at this stage. This flag will set the residual
   1740 			 * count to zero on MSG COMPLETE.
   1741 			 */
   1742 			if (sc->sc_dleft == 0)
   1743 				ecb->flags |= ECB_TENTATIVE_DONE;
   1744 
   1745 			break;
   1746 
   1747 		case MSG_SAVEDATAPOINTER:
   1748 			NCR_MSGS(("save datapointer "));
   1749 			ecb->daddr = sc->sc_dp;
   1750 			ecb->dleft = sc->sc_dleft;
   1751 			break;
   1752 
   1753 		case MSG_RESTOREPOINTERS:
   1754 			NCR_MSGS(("restore datapointer "));
   1755 			sc->sc_dp = ecb->daddr;
   1756 			sc->sc_dleft = ecb->dleft;
   1757 			break;
   1758 
   1759 		case MSG_EXTENDED:
   1760 			NCR_MSGS(("extended(%x) ", sc->sc_imess[2]));
   1761 			switch (sc->sc_imess[2]) {
   1762 			case MSG_EXT_SDTR:
   1763 				NCR_MSGS(("SDTR period %d, offset %d ",
   1764 				    sc->sc_imess[3], sc->sc_imess[4]));
   1765 				if (sc->sc_imess[1] != 3)
   1766 					goto reject;
   1767 				ti->period = sc->sc_imess[3];
   1768 				ti->offset = sc->sc_imess[4];
   1769 				ti->flags &= ~T_NEGOTIATE;
   1770 				if (sc->sc_minsync == 0 ||
   1771 				    ti->offset == 0 ||
   1772 				    ti->period > 124) {
   1773 #ifdef NCR53C9X_DEBUG
   1774 					scsi_print_addr(ecb->xs->sc_link);
   1775 					printf("async mode\n");
   1776 #endif
   1777 					if ((sc->sc_flags&NCR_SYNCHNEGO) == 0) {
   1778 						/*
   1779 						 * target initiated negotiation
   1780 						 */
   1781 						ti->offset = 0;
   1782 						ti->flags &= ~T_SYNCMODE;
   1783 						ncr53c9x_sched_msgout(
   1784 						    SEND_SDTR);
   1785 					} else {
   1786 						/* we are async */
   1787 						ti->flags &= ~T_SYNCMODE;
   1788 					}
   1789 				} else {
   1790 					int r = 250/ti->period;
   1791 					int s = (100*250)/ti->period - 100*r;
   1792 					int p;
   1793 
   1794 					p = ncr53c9x_stp2cpb(sc, ti->period);
   1795 					ti->period = ncr53c9x_cpb2stp(sc, p);
   1796 #ifdef NCR53C9X_DEBUG
   1797 					scsi_print_addr(ecb->xs->sc_link);
   1798 					printf("max sync rate %d.%02dMB/s\n",
   1799 					    r, s);
   1800 #endif
   1801 					if ((sc->sc_flags&NCR_SYNCHNEGO) == 0) {
   1802 						/*
   1803 						 * target initiated negotiation
   1804 						 */
   1805 						if (ti->period <
   1806 						    sc->sc_minsync)
   1807 							ti->period =
   1808 							    sc->sc_minsync;
   1809 						if (ti->offset > 15)
   1810 							ti->offset = 15;
   1811 						ti->flags &= ~T_SYNCMODE;
   1812 						ncr53c9x_sched_msgout(
   1813 						    SEND_SDTR);
   1814 					} else {
   1815 						/* we are sync */
   1816 						ti->flags |= T_SYNCMODE;
   1817 					}
   1818 				}
   1819 				sc->sc_flags &= ~NCR_SYNCHNEGO;
   1820 				ncr53c9x_setsync(sc, ti);
   1821 				break;
   1822 
   1823 			case MSG_EXT_WDTR:
   1824 				printf("%s: wide mode %d\n",
   1825 				       sc->sc_dev.dv_xname, sc->sc_imess[3]);
   1826 				if (sc->sc_imess[3] == 1) {
   1827 					ti->cfg3 |= NCRFASCFG3_EWIDE;
   1828 					ncr53c9x_setsync(sc, ti);
   1829 				}
   1830 				ti->flags &= ~T_WIDE;
   1831 				break;
   1832 			default:
   1833 				scsi_print_addr(ecb->xs->sc_link);
   1834 				printf("unrecognized MESSAGE EXTENDED;"
   1835 				    " sending REJECT\n");
   1836 				goto reject;
   1837 			}
   1838 			break;
   1839 
   1840 		default:
   1841 			NCR_MSGS(("ident "));
   1842 			scsi_print_addr(ecb->xs->sc_link);
   1843 			printf("unrecognized MESSAGE; sending REJECT\n");
   1844 		reject:
   1845 			ncr53c9x_sched_msgout(SEND_REJECT);
   1846 			break;
   1847 		}
   1848 		break;
   1849 
   1850 	case NCR_IDENTIFIED:
   1851 		/*
   1852 		 * IDENTIFY message was received and queue tag is expected now
   1853 		 */
   1854 		if ((sc->sc_imess[0] != MSG_SIMPLE_Q_TAG) ||
   1855 		    (sc->sc_msgify == 0)) {
   1856 			printf("%s: TAG reselect without IDENTIFY;"
   1857 			    " MSG %x;"
   1858 			    " sending DEVICE RESET\n",
   1859 			    sc->sc_dev.dv_xname,
   1860 			    sc->sc_imess[0]);
   1861 			goto reset;
   1862 		}
   1863 		(void) ncr53c9x_reselect(sc, sc->sc_msgify,
   1864 		    sc->sc_imess[0], sc->sc_imess[1]);
   1865 		break;
   1866 
   1867 	case NCR_RESELECTED:
   1868 		if (MSG_ISIDENTIFY(sc->sc_imess[1])) {
   1869 			sc->sc_msgify = sc->sc_imess[1];
   1870 		} else {
   1871 			printf("%s: reselect without IDENTIFY;"
   1872 			    " MSG %x;"
   1873 			    " sending DEVICE RESET\n",
   1874 			    sc->sc_dev.dv_xname,
   1875 			    sc->sc_imess[1]);
   1876 			goto reset;
   1877 		}
   1878 		(void) ncr53c9x_reselect(sc, sc->sc_msgify, 0, 0);
   1879 		break;
   1880 
   1881 	default:
   1882 		printf("%s: unexpected MESSAGE IN; sending DEVICE RESET\n",
   1883 		    sc->sc_dev.dv_xname);
   1884 	reset:
   1885 		ncr53c9x_sched_msgout(SEND_DEV_RESET);
   1886 		break;
   1887 
   1888 	abort:
   1889 		ncr53c9x_sched_msgout(SEND_ABORT);
   1890 		break;
   1891 	}
   1892 
   1893 	/* if we have more messages to send set ATN */
   1894 	if (sc->sc_msgpriq)
   1895 		NCRCMD(sc, NCRCMD_SETATN);
   1896 
   1897 	/* Ack last message byte */
   1898 	NCRCMD(sc, NCRCMD_MSGOK);
   1899 
   1900 	/* Done, reset message pointer. */
   1901 	sc->sc_flags &= ~NCR_DROP_MSGI;
   1902 	sc->sc_imlen = 0;
   1903 }
   1904 
   1905 
   1906 /*
   1907  * Send the highest priority, scheduled message
   1908  */
   1909 void
   1910 ncr53c9x_msgout(sc)
   1911 	struct ncr53c9x_softc *sc;
   1912 {
   1913 	struct ncr53c9x_tinfo *ti;
   1914 	struct ncr53c9x_ecb *ecb;
   1915 	size_t size;
   1916 
   1917 	NCR_TRACE(("[ncr53c9x_msgout(priq:%x, prevphase:%x)]",
   1918 	    sc->sc_msgpriq, sc->sc_prevphase));
   1919 
   1920 	/*
   1921 	 * XXX - the NCR_ATN flag is not in sync with the actual ATN
   1922 	 *	 condition on the SCSI bus. The 53c9x chip
   1923 	 *	 automatically turns off ATN before sending the
   1924 	 *	 message byte.  (see also the comment below in the
   1925 	 *	 default case when picking out a message to send)
   1926 	 */
   1927 	if (sc->sc_flags & NCR_ATN) {
   1928 		if (sc->sc_prevphase != MESSAGE_OUT_PHASE) {
   1929 		new:
   1930 			NCRCMD(sc, NCRCMD_FLUSH);
   1931 /*			DELAY(1); */
   1932 			sc->sc_msgoutq = 0;
   1933 			sc->sc_omlen = 0;
   1934 		}
   1935 	} else {
   1936 		if (sc->sc_prevphase == MESSAGE_OUT_PHASE) {
   1937 			ncr53c9x_sched_msgout(sc->sc_msgoutq);
   1938 			goto new;
   1939 		} else {
   1940 			printf("%s at line %d: unexpected MESSAGE OUT phase\n",
   1941 			    sc->sc_dev.dv_xname, __LINE__);
   1942 		}
   1943 	}
   1944 
   1945 	if (sc->sc_omlen == 0) {
   1946 		/* Pick up highest priority message */
   1947 		sc->sc_msgout = sc->sc_msgpriq & -sc->sc_msgpriq;
   1948 		sc->sc_msgoutq |= sc->sc_msgout;
   1949 		sc->sc_msgpriq &= ~sc->sc_msgout;
   1950 		sc->sc_omlen = 1;		/* "Default" message len */
   1951 		switch (sc->sc_msgout) {
   1952 		case SEND_SDTR:
   1953 			ecb = sc->sc_nexus;
   1954 			ti =
   1955 			    &sc->sc_tinfo[ecb->xs->sc_link->scsipi_scsi.target];
   1956 			sc->sc_omess[0] = MSG_EXTENDED;
   1957 			sc->sc_omess[1] = MSG_EXT_SDTR_LEN;
   1958 			sc->sc_omess[2] = MSG_EXT_SDTR;
   1959 			sc->sc_omess[3] = ti->period;
   1960 			sc->sc_omess[4] = ti->offset;
   1961 			sc->sc_omlen = 5;
   1962 			if ((sc->sc_flags & NCR_SYNCHNEGO) == 0) {
   1963 				ti->flags |= T_SYNCMODE;
   1964 				ncr53c9x_setsync(sc, ti);
   1965 			}
   1966 			break;
   1967 		case SEND_WDTR:
   1968 			ecb = sc->sc_nexus;
   1969 			ti =
   1970 			    &sc->sc_tinfo[ecb->xs->sc_link->scsipi_scsi.target];
   1971 			sc->sc_omess[0] = MSG_EXTENDED;
   1972 			sc->sc_omess[1] = MSG_EXT_WDTR_LEN;
   1973 			sc->sc_omess[2] = MSG_EXT_WDTR;
   1974 			sc->sc_omess[3] = ti->width;
   1975 			sc->sc_omlen = 4;
   1976 			break;
   1977                 case SEND_IDENTIFY:
   1978                         if (sc->sc_state != NCR_CONNECTED) {
   1979                                 printf("%s at line %d: no nexus\n",
   1980                                     sc->sc_dev.dv_xname, __LINE__);
   1981                         }
   1982                         ecb = sc->sc_nexus;
   1983                         sc->sc_omess[0] =
   1984                             MSG_IDENTIFY(ecb->xs->sc_link->scsipi_scsi.lun, 0);
   1985                         break;
   1986 		case SEND_TAG:
   1987 			if (sc->sc_state != NCR_CONNECTED) {
   1988 				printf("%s at line %d: no nexus\n",
   1989 				    sc->sc_dev.dv_xname, __LINE__);
   1990 			}
   1991 			ecb = sc->sc_nexus;
   1992 			sc->sc_omess[0] = ecb->tag[0];
   1993 			sc->sc_omess[1] = ecb->tag[1];
   1994 			sc->sc_omlen = 2;
   1995 			break;
   1996 		case SEND_DEV_RESET:
   1997 			sc->sc_flags |= NCR_ABORTING;
   1998 			sc->sc_omess[0] = MSG_BUS_DEV_RESET;
   1999 			ecb = sc->sc_nexus;
   2000 			ti =
   2001 			    &sc->sc_tinfo[ecb->xs->sc_link->scsipi_scsi.target];
   2002 			ti->flags &= ~T_SYNCMODE;
   2003 			if ((ti->flags & T_SYNCHOFF) == 0)
   2004 				/* We can re-start sync negotiation */
   2005 				ti->flags |= T_NEGOTIATE;
   2006 			break;
   2007 		case SEND_PARITY_ERROR:
   2008 			sc->sc_omess[0] = MSG_PARITY_ERROR;
   2009 			break;
   2010 		case SEND_ABORT:
   2011 			sc->sc_flags |= NCR_ABORTING;
   2012 			sc->sc_omess[0] = MSG_ABORT;
   2013 			break;
   2014 		case SEND_INIT_DET_ERR:
   2015 			sc->sc_omess[0] = MSG_INITIATOR_DET_ERR;
   2016 			break;
   2017 		case SEND_REJECT:
   2018 			sc->sc_omess[0] = MSG_MESSAGE_REJECT;
   2019 			break;
   2020 		default:
   2021 			/*
   2022 			 * We normally do not get here, since the chip
   2023 			 * automatically turns off ATN before the last
   2024 			 * byte of a message is sent to the target.
   2025 			 * However, if the target rejects our (multi-byte)
   2026 			 * message early by switching to MSG IN phase
   2027 			 * ATN remains on, so the target may return to
   2028 			 * MSG OUT phase. If there are no scheduled messages
   2029 			 * left we send a NO-OP.
   2030 			 *
   2031 			 * XXX - Note that this leaves no useful purpose for
   2032 			 * the NCR_ATN flag.
   2033 			 */
   2034 			sc->sc_flags &= ~NCR_ATN;
   2035 			sc->sc_omess[0] = MSG_NOOP;
   2036 			break;
   2037 		}
   2038 		sc->sc_omp = sc->sc_omess;
   2039 	}
   2040 
   2041 #ifdef DEBUG
   2042 	{
   2043 		int i;
   2044 
   2045 		NCR_MISC(("<msgout:"));
   2046 		for (i = 0; i < sc->sc_omlen; i++)
   2047 			NCR_MISC((" %02x", sc->sc_omess[i]));
   2048 		NCR_MISC(("> "));
   2049 	}
   2050 #endif
   2051 	if (sc->sc_rev == NCR_VARIANT_FAS366) {
   2052 		/*
   2053 		 * XXX fifo size
   2054 		 */
   2055 		ncr53c9x_flushfifo(sc);
   2056 		ncr53c9x_wrfifo(sc, sc->sc_omp, sc->sc_omlen);
   2057 		NCRCMD(sc, NCRCMD_TRANS);
   2058 	} else {
   2059 		/* (re)send the message */
   2060 		size = min(sc->sc_omlen, sc->sc_maxxfer);
   2061 		NCRDMA_SETUP(sc, &sc->sc_omp, &sc->sc_omlen, 0, &size);
   2062 		/* Program the SCSI counter */
   2063 		NCR_SET_COUNT(sc, size);
   2064 
   2065 		/* Load the count in and start the message-out transfer */
   2066 		NCRCMD(sc, NCRCMD_NOP|NCRCMD_DMA);
   2067 		NCRCMD(sc, NCRCMD_TRANS|NCRCMD_DMA);
   2068 		NCRDMA_GO(sc);
   2069 	}
   2070 }
   2071 
   2072 /*
   2073  * This is the most critical part of the driver, and has to know
   2074  * how to deal with *all* error conditions and phases from the SCSI
   2075  * bus. If there are no errors and the DMA was active, then call the
   2076  * DMA pseudo-interrupt handler. If this returns 1, then that was it
   2077  * and we can return from here without further processing.
   2078  *
   2079  * Most of this needs verifying.
   2080  */
   2081 int
   2082 ncr53c9x_intr(arg)
   2083 	void *arg;
   2084 {
   2085 	struct ncr53c9x_softc *sc = arg;
   2086 	struct ncr53c9x_ecb *ecb;
   2087 	struct scsipi_link *sc_link;
   2088 	struct ncr53c9x_tinfo *ti;
   2089 	size_t size;
   2090 	int nfifo;
   2091 
   2092 	NCR_MISC(("[ncr53c9x_intr: state %d]", sc->sc_state));
   2093 
   2094 	if (!NCRDMA_ISINTR(sc))
   2095 		return (0);
   2096 
   2097 again:
   2098 	/* and what do the registers say... */
   2099 	ncr53c9x_readregs(sc);
   2100 
   2101 	sc->sc_intrcnt.ev_count++;
   2102 
   2103 	/*
   2104 	 * At the moment, only a SCSI Bus Reset or Illegal
   2105 	 * Command are classed as errors. A disconnect is a
   2106 	 * valid condition, and we let the code check is the
   2107 	 * "NCR_BUSFREE_OK" flag was set before declaring it
   2108 	 * and error.
   2109 	 *
   2110 	 * Also, the status register tells us about "Gross
   2111 	 * Errors" and "Parity errors". Only the Gross Error
   2112 	 * is really bad, and the parity errors are dealt
   2113 	 * with later
   2114 	 *
   2115 	 * TODO
   2116 	 *	If there are too many parity error, go to slow
   2117 	 *	cable mode ?
   2118 	 */
   2119 
   2120 	/* SCSI Reset */
   2121 	if ((sc->sc_espintr & NCRINTR_SBR) != 0) {
   2122 		if ((NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF) != 0) {
   2123 			NCRCMD(sc, NCRCMD_FLUSH);
   2124 			DELAY(1);
   2125 		}
   2126 		if (sc->sc_state != NCR_SBR) {
   2127 			printf("%s: SCSI bus reset\n", sc->sc_dev.dv_xname);
   2128 			ncr53c9x_init(sc, 0); /* Restart everything */
   2129 			return (1);
   2130 		}
   2131 #if 0
   2132 /*XXX*/		printf("<expected bus reset: "
   2133 		    "[intr %x, stat %x, step %d]>\n",
   2134 		    sc->sc_espintr, sc->sc_espstat, sc->sc_espstep);
   2135 #endif
   2136 		if (sc->sc_nexus != NULL)
   2137 			panic("%s: nexus in reset state",
   2138 			    sc->sc_dev.dv_xname);
   2139 		goto sched;
   2140 	}
   2141 
   2142 	ecb = sc->sc_nexus;
   2143 
   2144 #define NCRINTR_ERR (NCRINTR_SBR|NCRINTR_ILL)
   2145 	if (sc->sc_espintr & NCRINTR_ERR ||
   2146 	    sc->sc_espstat & NCRSTAT_GE) {
   2147 
   2148 		if ((sc->sc_espstat & NCRSTAT_GE) != 0) {
   2149 			/* Gross Error; no target ? */
   2150 			if (NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF) {
   2151 				NCRCMD(sc, NCRCMD_FLUSH);
   2152 				DELAY(1);
   2153 			}
   2154 			if (sc->sc_state == NCR_CONNECTED ||
   2155 			    sc->sc_state == NCR_SELECTING) {
   2156 				ecb->xs->error = XS_TIMEOUT;
   2157 				ncr53c9x_done(sc, ecb);
   2158 			}
   2159 			return (1);
   2160 		}
   2161 
   2162 		if ((sc->sc_espintr & NCRINTR_ILL) != 0) {
   2163 			if ((sc->sc_flags & NCR_EXPECT_ILLCMD) != 0) {
   2164 				/*
   2165 				 * Eat away "Illegal command" interrupt
   2166 				 * on a ESP100 caused by a re-selection
   2167 				 * while we were trying to select
   2168 				 * another target.
   2169 				 */
   2170 #ifdef DEBUG
   2171 				printf("%s: ESP100 work-around activated\n",
   2172 					sc->sc_dev.dv_xname);
   2173 #endif
   2174 				sc->sc_flags &= ~NCR_EXPECT_ILLCMD;
   2175 				return (1);
   2176 			}
   2177 			/* illegal command, out of sync ? */
   2178 			printf("%s: illegal command: 0x%x "
   2179 			    "(state %d, phase %x, prevphase %x)\n",
   2180 			    sc->sc_dev.dv_xname, sc->sc_lastcmd,
   2181 			    sc->sc_state, sc->sc_phase, sc->sc_prevphase);
   2182 			if (NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF) {
   2183 				NCRCMD(sc, NCRCMD_FLUSH);
   2184 				DELAY(1);
   2185 			}
   2186 			ncr53c9x_init(sc, 1); /* Restart everything */
   2187 			return (1);
   2188 		}
   2189 	}
   2190 	sc->sc_flags &= ~NCR_EXPECT_ILLCMD;
   2191 
   2192 	/*
   2193 	 * Call if DMA is active.
   2194 	 *
   2195 	 * If DMA_INTR returns true, then maybe go 'round the loop
   2196 	 * again in case there is no more DMA queued, but a phase
   2197 	 * change is expected.
   2198 	 */
   2199 	if (NCRDMA_ISACTIVE(sc)) {
   2200 		int r = NCRDMA_INTR(sc);
   2201 		if (r == -1) {
   2202 			printf("%s: DMA error; resetting\n",
   2203 			    sc->sc_dev.dv_xname);
   2204 			ncr53c9x_init(sc, 1);
   2205 		}
   2206 		/* If DMA active here, then go back to work... */
   2207 		if (NCRDMA_ISACTIVE(sc))
   2208 			return (1);
   2209 
   2210 		if ((sc->sc_espstat & NCRSTAT_TC) == 0) {
   2211 			/*
   2212 			 * DMA not completed.  If we can not find a
   2213 			 * acceptable explanation, print a diagnostic.
   2214 			 */
   2215 			if (sc->sc_state == NCR_SELECTING)
   2216 				/*
   2217 				 * This can happen if we are reselected
   2218 				 * while using DMA to select a target.
   2219 				 */
   2220 				/*void*/;
   2221 			else if (sc->sc_prevphase == MESSAGE_OUT_PHASE) {
   2222 				/*
   2223 				 * Our (multi-byte) message (eg SDTR) was
   2224 				 * interrupted by the target to send
   2225 				 * a MSG REJECT.
   2226 				 * Print diagnostic if current phase
   2227 				 * is not MESSAGE IN.
   2228 				 */
   2229 				if (sc->sc_phase != MESSAGE_IN_PHASE)
   2230 					printf("%s: !TC on MSG OUT"
   2231 					    " [intr %x, stat %x, step %d]"
   2232 					    " prevphase %x, resid %lx\n",
   2233 					    sc->sc_dev.dv_xname,
   2234 					    sc->sc_espintr,
   2235 					    sc->sc_espstat,
   2236 					    sc->sc_espstep,
   2237 					    sc->sc_prevphase,
   2238 					    (u_long)sc->sc_omlen);
   2239 			} else if (sc->sc_dleft == 0) {
   2240 				/*
   2241 				 * The DMA operation was started for
   2242 				 * a DATA transfer. Print a diagnostic
   2243 				 * if the DMA counter and TC bit
   2244 				 * appear to be out of sync.
   2245 				 */
   2246 				printf("%s: !TC on DATA XFER"
   2247 				    " [intr %x, stat %x, step %d]"
   2248 				    " prevphase %x, resid %x\n",
   2249 				    sc->sc_dev.dv_xname,
   2250 				    sc->sc_espintr,
   2251 				    sc->sc_espstat,
   2252 				    sc->sc_espstep,
   2253 				    sc->sc_prevphase,
   2254 				    ecb ? ecb->dleft : -1);
   2255 			}
   2256 		}
   2257 	}
   2258 
   2259 	/*
   2260 	 * Check for less serious errors.
   2261 	 */
   2262 	if ((sc->sc_espstat & NCRSTAT_PE) != 0) {
   2263 		printf("%s: SCSI bus parity error\n", sc->sc_dev.dv_xname);
   2264 		if (sc->sc_prevphase == MESSAGE_IN_PHASE)
   2265 			ncr53c9x_sched_msgout(SEND_PARITY_ERROR);
   2266 		else
   2267 			ncr53c9x_sched_msgout(SEND_INIT_DET_ERR);
   2268 	}
   2269 
   2270 	if ((sc->sc_espintr & NCRINTR_DIS) != 0) {
   2271 		sc->sc_msgify = 0;
   2272 		NCR_MISC(("<DISC [intr %x, stat %x, step %d]>",
   2273 		    sc->sc_espintr,sc->sc_espstat,sc->sc_espstep));
   2274 		if (NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF) {
   2275 			NCRCMD(sc, NCRCMD_FLUSH);
   2276 /*			DELAY(1); */
   2277 		}
   2278 		/*
   2279 		 * This command must (apparently) be issued within
   2280 		 * 250mS of a disconnect. So here you are...
   2281 		 */
   2282 		NCRCMD(sc, NCRCMD_ENSEL);
   2283 
   2284 		switch (sc->sc_state) {
   2285 		case NCR_RESELECTED:
   2286 			goto sched;
   2287 
   2288 		case NCR_SELECTING:
   2289 		{
   2290 			struct ncr53c9x_linfo *li;
   2291 
   2292 			ecb->xs->error = XS_SELTIMEOUT;
   2293 
   2294 			/* Selection timeout -- discard all LUNs if empty */
   2295 			sc_link = ecb->xs->sc_link;
   2296 			ti = &sc->sc_tinfo[sc_link->scsipi_scsi.target];
   2297 			li = LIST_FIRST(&ti->luns);
   2298 			while (li != NULL) {
   2299 				if (li->untagged == NULL && li->used == 0) {
   2300 					if (li->lun < NCR_NLUN)
   2301 						ti->lun[li->lun] = NULL;
   2302 					LIST_REMOVE(li, link);
   2303 					free(li, M_DEVBUF);
   2304 					/*
   2305 					 * Restart the search at the beginning
   2306 					 */
   2307 					li = LIST_FIRST(&ti->luns);
   2308 					continue;
   2309 				}
   2310 				li = LIST_NEXT(li, link);
   2311 			}
   2312 			goto finish;
   2313 		}
   2314 		case NCR_CONNECTED:
   2315 			if ((sc->sc_flags & NCR_SYNCHNEGO) != 0) {
   2316 #ifdef NCR53C9X_DEBUG
   2317 				if (ecb != NULL)
   2318 					scsi_print_addr(ecb->xs->sc_link);
   2319 				printf("sync nego not completed!\n");
   2320 #endif
   2321 				ti = &sc->sc_tinfo[ecb->xs->sc_link->scsipi_scsi.target];
   2322 				sc->sc_flags &= ~NCR_SYNCHNEGO;
   2323 				ti->flags &= ~(T_NEGOTIATE | T_SYNCMODE);
   2324 			}
   2325 
   2326 			/* it may be OK to disconnect */
   2327 			if ((sc->sc_flags & NCR_ABORTING) == 0) {
   2328 				/*
   2329 				 * Section 5.1.1 of the SCSI 2 spec
   2330 				 * suggests issuing a REQUEST SENSE
   2331 				 * following an unexpected disconnect.
   2332 				 * Some devices go into a contingent
   2333 				 * allegiance condition when
   2334 				 * disconnecting, and this is necessary
   2335 				 * to clean up their state.
   2336 				 */
   2337 				printf("%s: unexpected disconnect; ",
   2338 				    sc->sc_dev.dv_xname);
   2339 				if ((ecb->flags & ECB_SENSE) != 0) {
   2340 					printf("resetting\n");
   2341 					goto reset;
   2342 				}
   2343 				printf("sending REQUEST SENSE\n");
   2344 				callout_stop(&ecb->xs->xs_callout);
   2345 				ncr53c9x_sense(sc, ecb);
   2346 				goto out;
   2347 			}
   2348 
   2349 			ecb->xs->error = XS_TIMEOUT;
   2350 			goto finish;
   2351 
   2352 		case NCR_DISCONNECT:
   2353 			sc->sc_nexus = NULL;
   2354 			goto sched;
   2355 
   2356 		case NCR_CMDCOMPLETE:
   2357 			goto finish;
   2358 		}
   2359 	}
   2360 
   2361 	switch (sc->sc_state) {
   2362 
   2363 	case NCR_SBR:
   2364 		printf("%s: waiting for SCSI Bus Reset to happen\n",
   2365 		    sc->sc_dev.dv_xname);
   2366 		return (1);
   2367 
   2368 	case NCR_RESELECTED:
   2369 		/*
   2370 		 * we must be continuing a message ?
   2371 		 */
   2372 		if (sc->sc_phase != MESSAGE_IN_PHASE) {
   2373 			printf("%s: target didn't identify\n",
   2374 			    sc->sc_dev.dv_xname);
   2375 			ncr53c9x_init(sc, 1);
   2376 			return (1);
   2377 		}
   2378 printf("<<RESELECT CONT'd>>");
   2379 #if XXXX
   2380 		ncr53c9x_msgin(sc);
   2381 		if (sc->sc_state != NCR_CONNECTED) {
   2382 			/* IDENTIFY fail?! */
   2383 			printf("%s: identify failed\n",
   2384 			    sc->sc_dev.dv_xname, sc->sc_state);
   2385 			ncr53c9x_init(sc, 1);
   2386 			return (1);
   2387 		}
   2388 #endif
   2389 		break;
   2390 
   2391 	case NCR_IDENTIFIED:
   2392 		ecb = sc->sc_nexus;
   2393 		if (sc->sc_phase != MESSAGE_IN_PHASE) {
   2394 			int i = (NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF);
   2395  			/*
   2396 			 * Things are seriously fucked up.
   2397 			 * Pull the brakes, i.e. reset
   2398 			 */
   2399 			printf("%s: target didn't send tag: %d bytes in fifo\n",
   2400 			    sc->sc_dev.dv_xname, i);
   2401 			/* Drain and display fifo */
   2402 			while (i-- > 0)
   2403 				printf("[%d] ", NCR_READ_REG(sc, NCR_FIFO));
   2404 
   2405 			ncr53c9x_init(sc, 1);
   2406 			return (1);
   2407 		} else
   2408 			goto msgin;
   2409 
   2410 		break;
   2411 
   2412 	case NCR_IDLE:
   2413 	case NCR_SELECTING:
   2414 		ecb = sc->sc_nexus;
   2415 		if (sc->sc_espintr & NCRINTR_RESEL) {
   2416 			sc->sc_msgpriq = sc->sc_msgout = sc->sc_msgoutq = 0;
   2417 			sc->sc_flags = 0;
   2418 			/*
   2419 			 * If we're trying to select a
   2420 			 * target ourselves, push our command
   2421 			 * back into the ready list.
   2422 			 */
   2423 			if (sc->sc_state == NCR_SELECTING) {
   2424 				NCR_MISC(("backoff selector "));
   2425 				callout_stop(&ecb->xs->xs_callout);
   2426 				ncr53c9x_dequeue(sc, ecb);
   2427 				TAILQ_INSERT_HEAD(&sc->ready_list, ecb, chain);
   2428 				ecb->flags |= ECB_READY;
   2429 				ecb = sc->sc_nexus = NULL;
   2430 			}
   2431 			sc->sc_state = NCR_RESELECTED;
   2432 			if (sc->sc_phase != MESSAGE_IN_PHASE) {
   2433 				/*
   2434 				 * Things are seriously fucked up.
   2435 				 * Pull the brakes, i.e. reset
   2436 				 */
   2437 				printf("%s: target didn't identify\n",
   2438 				    sc->sc_dev.dv_xname);
   2439 				ncr53c9x_init(sc, 1);
   2440 				return (1);
   2441 			}
   2442 			/*
   2443 			 * The C90 only inhibits FIFO writes until
   2444 			 * reselection is complete, instead of
   2445 			 * waiting until the interrupt status register
   2446 			 * has been read. So, if the reselect happens
   2447 			 * while we were entering a command bytes (for
   2448 			 * another target) some of those bytes can
   2449 			 * appear in the FIFO here, after the
   2450 			 * interrupt is taken.
   2451 			 */
   2452 			nfifo = ncr53c9x_rdfifo(sc, NCR_RDFIFO_START);
   2453 
   2454 			if (nfifo < 2 ||
   2455 			    (nfifo > 2 && sc->sc_rev != NCR_VARIANT_ESP100)) {
   2456 				printf("%s: RESELECT: %d bytes in FIFO! "
   2457 				    "[intr %x, stat %x, step %d, "
   2458 				    "prevphase %x]\n",
   2459 				    sc->sc_dev.dv_xname,
   2460 				    nfifo,
   2461 				    sc->sc_espintr,
   2462 				    sc->sc_espstat,
   2463 				    sc->sc_espstep,
   2464 				    sc->sc_prevphase);
   2465 				ncr53c9x_init(sc, 1);
   2466 				return (1);
   2467 			}
   2468 			sc->sc_selid = sc->sc_imess[0];
   2469 			NCR_MISC(("selid=%02x ", sc->sc_selid));
   2470 
   2471 			/* Handle identify message */
   2472 			ncr53c9x_msgin(sc);
   2473 			if (nfifo != 2) {
   2474 				/*
   2475 				 * Note: this should not happen
   2476 				 * with `dmaselect' on.
   2477 				 */
   2478 				sc->sc_flags |= NCR_EXPECT_ILLCMD;
   2479 				NCRCMD(sc, NCRCMD_FLUSH);
   2480 			} else if (sc->sc_features & NCR_F_DMASELECT &&
   2481 			    sc->sc_rev == NCR_VARIANT_ESP100) {
   2482 				sc->sc_flags |= NCR_EXPECT_ILLCMD;
   2483 			}
   2484 
   2485 			if (sc->sc_state != NCR_CONNECTED &&
   2486 			    sc->sc_state != NCR_IDENTIFIED) {
   2487 				/* IDENTIFY fail?! */
   2488 				printf("%s: identify failed, "
   2489 				    "state %d, intr %02x\n",
   2490 				    sc->sc_dev.dv_xname, sc->sc_state,
   2491 				    sc->sc_espintr);
   2492 				ncr53c9x_init(sc, 1);
   2493 				return (1);
   2494 			}
   2495 			goto shortcut; /* ie. next phase expected soon */
   2496 		}
   2497 
   2498 #define	NCRINTR_DONE	(NCRINTR_FC|NCRINTR_BS)
   2499 		if ((sc->sc_espintr & NCRINTR_DONE) == NCRINTR_DONE) {
   2500 			/*
   2501 			 * Arbitration won; examine the `step' register
   2502 			 * to determine how far the selection could progress.
   2503 			 */
   2504 			ecb = sc->sc_nexus;
   2505 			if (ecb == NULL)
   2506 				panic("ncr53c9x: no nexus");
   2507 
   2508 			sc_link = ecb->xs->sc_link;
   2509 			ti = &sc->sc_tinfo[sc_link->scsipi_scsi.target];
   2510 
   2511 			switch (sc->sc_espstep) {
   2512 			case 0:
   2513 				/*
   2514 				 * The target did not respond with a
   2515 				 * message out phase - probably an old
   2516 				 * device that doesn't recognize ATN.
   2517 				 * Clear ATN and just continue, the
   2518 				 * target should be in the command
   2519 				 * phase.
   2520 				 * XXXX check for command phase?
   2521 				 */
   2522 				NCRCMD(sc, NCRCMD_RSTATN);
   2523 				break;
   2524 			case 1:
   2525 				if ((ti->flags & T_NEGOTIATE) == 0 &&
   2526 				    ecb->tag[0] == 0) {
   2527 					printf("%s: step 1 & !NEG\n",
   2528 					    sc->sc_dev.dv_xname);
   2529 					goto reset;
   2530 				}
   2531 				if (sc->sc_phase != MESSAGE_OUT_PHASE) {
   2532 					printf("%s: !MSGOUT\n",
   2533 					    sc->sc_dev.dv_xname);
   2534 					goto reset;
   2535 				}
   2536 				if (ti->flags & T_WIDE) {
   2537 					ncr53c9x_sched_msgout(SEND_WDTR);
   2538 				}
   2539 				if (ti->flags & T_NEGOTIATE) {
   2540 					/* Start negotiating */
   2541 					ti->period = sc->sc_minsync;
   2542 					ti->offset = 15;
   2543 					sc->sc_flags |= NCR_SYNCHNEGO;
   2544 					if (ecb->tag[0])
   2545 						ncr53c9x_sched_msgout(
   2546 						    SEND_TAG|SEND_SDTR);
   2547 					else
   2548 						ncr53c9x_sched_msgout(
   2549 						    SEND_SDTR);
   2550 				} else {
   2551 					/* Could not do ATN3 so send TAG */
   2552 					ncr53c9x_sched_msgout(SEND_TAG);
   2553 				}
   2554 				sc->sc_prevphase = MESSAGE_OUT_PHASE; /* XXXX */
   2555 				break;
   2556 			case 3:
   2557 				/*
   2558 				 * Grr, this is supposed to mean
   2559 				 * "target left command phase  prematurely".
   2560 				 * It seems to happen regularly when
   2561 				 * sync mode is on.
   2562 				 * Look at FIFO to see if command went out.
   2563 				 * (Timing problems?)
   2564 				 */
   2565 				if (sc->sc_features & NCR_F_DMASELECT) {
   2566 					if (sc->sc_cmdlen == 0)
   2567 						/* Hope for the best.. */
   2568 						break;
   2569 				} else if ((NCR_READ_REG(sc, NCR_FFLAG)
   2570 				    & NCRFIFO_FF) == 0) {
   2571 					/* Hope for the best.. */
   2572 					break;
   2573 				}
   2574 				printf("(%s:%d:%d): selection failed;"
   2575 				    " %d left in FIFO "
   2576 				    "[intr %x, stat %x, step %d]\n",
   2577 				    sc->sc_dev.dv_xname,
   2578 				    sc_link->scsipi_scsi.target,
   2579 				    sc_link->scsipi_scsi.lun,
   2580 				    NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF,
   2581 				    sc->sc_espintr, sc->sc_espstat,
   2582 				    sc->sc_espstep);
   2583 				NCRCMD(sc, NCRCMD_FLUSH);
   2584 				ncr53c9x_sched_msgout(SEND_ABORT);
   2585 				return (1);
   2586 			case 2:
   2587 				/* Select stuck at Command Phase */
   2588 				NCRCMD(sc, NCRCMD_FLUSH);
   2589 				break;
   2590 			case 4:
   2591 				if (sc->sc_features & NCR_F_DMASELECT &&
   2592 				    sc->sc_cmdlen != 0)
   2593 					printf("(%s:%d:%d): select; "
   2594 					    "%lu left in DMA buffer "
   2595 					    "[intr %x, stat %x, step %d]\n",
   2596 					    sc->sc_dev.dv_xname,
   2597 					    sc_link->scsipi_scsi.target,
   2598 					    sc_link->scsipi_scsi.lun,
   2599 					    (u_long)sc->sc_cmdlen,
   2600 					    sc->sc_espintr,
   2601 					    sc->sc_espstat,
   2602 					    sc->sc_espstep);
   2603 				/* So far, everything went fine */
   2604 				break;
   2605 			}
   2606 
   2607 			sc->sc_prevphase = INVALID_PHASE; /* ?? */
   2608 			/* Do an implicit RESTORE POINTERS. */
   2609 			sc->sc_dp = ecb->daddr;
   2610 			sc->sc_dleft = ecb->dleft;
   2611 			sc->sc_state = NCR_CONNECTED;
   2612 			break;
   2613 
   2614 		} else {
   2615 
   2616 			printf("%s: unexpected status after select"
   2617 			    ": [intr %x, stat %x, step %x]\n",
   2618 			    sc->sc_dev.dv_xname,
   2619 			    sc->sc_espintr, sc->sc_espstat, sc->sc_espstep);
   2620 			NCRCMD(sc, NCRCMD_FLUSH);
   2621 			DELAY(1);
   2622 			goto reset;
   2623 		}
   2624 		if (sc->sc_state == NCR_IDLE) {
   2625 			printf("%s: stray interrupt\n", sc->sc_dev.dv_xname);
   2626 			return (0);
   2627 		}
   2628 		break;
   2629 
   2630 	case NCR_CONNECTED:
   2631 		if ((sc->sc_flags & NCR_ICCS) != 0) {
   2632 			/* "Initiate Command Complete Steps" in progress */
   2633 			u_char msg;
   2634 
   2635 			sc->sc_flags &= ~NCR_ICCS;
   2636 
   2637 			if (!(sc->sc_espintr & NCRINTR_DONE)) {
   2638 				printf("%s: ICCS: "
   2639 				    ": [intr %x, stat %x, step %x]\n",
   2640 				    sc->sc_dev.dv_xname,
   2641 				    sc->sc_espintr, sc->sc_espstat,
   2642 				    sc->sc_espstep);
   2643 			}
   2644 			ncr53c9x_rdfifo(sc, NCR_RDFIFO_START);
   2645 			if (sc->sc_imlen < 2)
   2646 				printf("%s: can't get status, only %d bytes\n",
   2647 				    sc->sc_dev.dv_xname, (int)sc->sc_imlen);
   2648 			ecb->stat = sc->sc_imess[sc->sc_imlen - 2];
   2649 			msg = sc->sc_imess[sc->sc_imlen - 1];
   2650 			NCR_PHASE(("<stat:(%x,%x)>", ecb->stat, msg));
   2651 			if (msg == MSG_CMDCOMPLETE) {
   2652 				ecb->dleft = (ecb->flags & ECB_TENTATIVE_DONE)
   2653 					? 0 : sc->sc_dleft;
   2654 				if ((ecb->flags & ECB_SENSE) == 0)
   2655 					ecb->xs->resid = ecb->dleft;
   2656 				sc->sc_state = NCR_CMDCOMPLETE;
   2657 			} else
   2658 				printf("%s: STATUS_PHASE: msg %d\n",
   2659 				    sc->sc_dev.dv_xname, msg);
   2660 			sc->sc_imlen = 0;
   2661 			NCRCMD(sc, NCRCMD_MSGOK);
   2662 			goto shortcut; /* ie. wait for disconnect */
   2663 		}
   2664 		break;
   2665 
   2666 	default:
   2667 		/* Don't panic: reset. */
   2668 		printf("%s: invalid state: %d",
   2669 		    sc->sc_dev.dv_xname, sc->sc_state);
   2670 		ncr53c9x_scsi_reset(sc);
   2671 		goto out;
   2672 #if 0
   2673 		panic("%s: invalid state: %d",
   2674 		    sc->sc_dev.dv_xname, sc->sc_state);
   2675 #endif
   2676 		break;
   2677 	}
   2678 
   2679 	/*
   2680 	 * Driver is now in state NCR_CONNECTED, i.e. we
   2681 	 * have a current command working the SCSI bus.
   2682 	 */
   2683 	if (sc->sc_state != NCR_CONNECTED || ecb == NULL) {
   2684 		panic("ncr53c9x: no nexus");
   2685 	}
   2686 
   2687 	switch (sc->sc_phase) {
   2688 	case MESSAGE_OUT_PHASE:
   2689 		NCR_PHASE(("MESSAGE_OUT_PHASE "));
   2690 		ncr53c9x_msgout(sc);
   2691 		sc->sc_prevphase = MESSAGE_OUT_PHASE;
   2692 		break;
   2693 
   2694 	case MESSAGE_IN_PHASE:
   2695 msgin:
   2696 		NCR_PHASE(("MESSAGE_IN_PHASE "));
   2697 		if ((sc->sc_espintr & NCRINTR_BS) != 0) {
   2698 			if ((sc->sc_rev != NCR_VARIANT_FAS366) ||
   2699 			    !(sc->sc_espstat2 & FAS_STAT2_EMPTY)) {
   2700 				NCRCMD(sc, NCRCMD_FLUSH);
   2701 			}
   2702 			sc->sc_flags |= NCR_WAITI;
   2703 			NCRCMD(sc, NCRCMD_TRANS);
   2704 		} else if ((sc->sc_espintr & NCRINTR_FC) != 0) {
   2705 			if ((sc->sc_flags & NCR_WAITI) == 0) {
   2706 				printf("%s: MSGIN: unexpected FC bit: "
   2707 				    "[intr %x, stat %x, step %x]\n",
   2708 				    sc->sc_dev.dv_xname,
   2709 				    sc->sc_espintr, sc->sc_espstat,
   2710 				    sc->sc_espstep);
   2711 			}
   2712 			sc->sc_flags &= ~NCR_WAITI;
   2713 			ncr53c9x_rdfifo(sc,
   2714 			    (sc->sc_prevphase == sc->sc_phase) ?
   2715 			    NCR_RDFIFO_CONTINUE : NCR_RDFIFO_START);
   2716 			ncr53c9x_msgin(sc);
   2717 		} else {
   2718 			printf("%s: MSGIN: weird bits: "
   2719 			    "[intr %x, stat %x, step %x]\n",
   2720 			    sc->sc_dev.dv_xname,
   2721 			    sc->sc_espintr, sc->sc_espstat, sc->sc_espstep);
   2722 		}
   2723 		sc->sc_prevphase = MESSAGE_IN_PHASE;
   2724 		goto shortcut;	/* i.e. expect data to be ready */
   2725 		break;
   2726 
   2727 	case COMMAND_PHASE:
   2728 		/*
   2729 		 * Send the command block. Normally we don't see this
   2730 		 * phase because the SEL_ATN command takes care of
   2731 		 * all this. However, we end up here if either the
   2732 		 * target or we wanted to exchange some more messages
   2733 		 * first (e.g. to start negotiations).
   2734 		 */
   2735 
   2736 		NCR_PHASE(("COMMAND_PHASE 0x%02x (%d) ",
   2737 		    ecb->cmd.cmd.opcode, ecb->clen));
   2738 		if (NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF) {
   2739 			NCRCMD(sc, NCRCMD_FLUSH);
   2740 /*			DELAY(1);*/
   2741 		}
   2742 		if (sc->sc_features & NCR_F_DMASELECT) {
   2743 			size_t size;
   2744 			/* setup DMA transfer for command */
   2745 			size = ecb->clen;
   2746 			sc->sc_cmdlen = size;
   2747 			sc->sc_cmdp = (caddr_t)&ecb->cmd.cmd;
   2748 			NCRDMA_SETUP(sc, &sc->sc_cmdp, &sc->sc_cmdlen,
   2749 			    0, &size);
   2750 			/* Program the SCSI counter */
   2751 			NCR_SET_COUNT(sc, size);
   2752 
   2753 			/* load the count in */
   2754 			NCRCMD(sc, NCRCMD_NOP|NCRCMD_DMA);
   2755 
   2756 			/* start the command transfer */
   2757 			NCRCMD(sc, NCRCMD_TRANS | NCRCMD_DMA);
   2758 			NCRDMA_GO(sc);
   2759 		} else {
   2760 			ncr53c9x_wrfifo(sc, (u_char *)&ecb->cmd.cmd, ecb->clen);
   2761 			NCRCMD(sc, NCRCMD_TRANS);
   2762 		}
   2763 		sc->sc_prevphase = COMMAND_PHASE;
   2764 		break;
   2765 
   2766 	case DATA_OUT_PHASE:
   2767 		NCR_PHASE(("DATA_OUT_PHASE [%ld] ",(long)sc->sc_dleft));
   2768 		NCRCMD(sc, NCRCMD_FLUSH);
   2769 		size = min(sc->sc_dleft, sc->sc_maxxfer);
   2770 		NCRDMA_SETUP(sc, &sc->sc_dp, &sc->sc_dleft, 0, &size);
   2771 		sc->sc_prevphase = DATA_OUT_PHASE;
   2772 		goto setup_xfer;
   2773 
   2774 	case DATA_IN_PHASE:
   2775 		NCR_PHASE(("DATA_IN_PHASE "));
   2776 		if (sc->sc_rev == NCR_VARIANT_ESP100)
   2777 			NCRCMD(sc, NCRCMD_FLUSH);
   2778 		size = min(sc->sc_dleft, sc->sc_maxxfer);
   2779 		NCRDMA_SETUP(sc, &sc->sc_dp, &sc->sc_dleft, 1, &size);
   2780 		sc->sc_prevphase = DATA_IN_PHASE;
   2781 	setup_xfer:
   2782 		/* Target returned to data phase: wipe "done" memory */
   2783 		ecb->flags &= ~ECB_TENTATIVE_DONE;
   2784 
   2785 		/* Program the SCSI counter */
   2786 		NCR_SET_COUNT(sc, size);
   2787 
   2788 		/* load the count in */
   2789 		NCRCMD(sc, NCRCMD_NOP|NCRCMD_DMA);
   2790 
   2791 		/*
   2792 		 * Note that if `size' is 0, we've already transceived
   2793 		 * all the bytes we want but we're still in DATA PHASE.
   2794 		 * Apparently, the device needs padding. Also, a
   2795 		 * transfer size of 0 means "maximum" to the chip
   2796 		 * DMA logic.
   2797 		 */
   2798 		NCRCMD(sc,
   2799 		    (size == 0 ? NCRCMD_TRPAD : NCRCMD_TRANS) | NCRCMD_DMA);
   2800 		NCRDMA_GO(sc);
   2801 		return (1);
   2802 
   2803 	case STATUS_PHASE:
   2804 		NCR_PHASE(("STATUS_PHASE "));
   2805 		sc->sc_flags |= NCR_ICCS;
   2806 		NCRCMD(sc, NCRCMD_ICCS);
   2807 		sc->sc_prevphase = STATUS_PHASE;
   2808 		goto shortcut;	/* i.e. expect status results soon */
   2809 		break;
   2810 
   2811 	case INVALID_PHASE:
   2812 		break;
   2813 
   2814 	default:
   2815 		printf("%s: unexpected bus phase; resetting\n",
   2816 		    sc->sc_dev.dv_xname);
   2817 		goto reset;
   2818 	}
   2819 
   2820 out:
   2821 	return (1);
   2822 
   2823 reset:
   2824 	ncr53c9x_init(sc, 1);
   2825 	goto out;
   2826 
   2827 finish:
   2828 	ncr53c9x_done(sc, ecb);
   2829 	goto out;
   2830 
   2831 sched:
   2832 	sc->sc_state = NCR_IDLE;
   2833 	ncr53c9x_sched(sc);
   2834 	goto out;
   2835 
   2836 shortcut:
   2837 	/*
   2838 	 * The idea is that many of the SCSI operations take very little
   2839 	 * time, and going away and getting interrupted is too high an
   2840 	 * overhead to pay. For example, selecting, sending a message
   2841 	 * and command and then doing some work can be done in one "pass".
   2842 	 *
   2843 	 * The delay is a heuristic. It is 2 when at 20MHz, 2 at 25MHz and 1
   2844 	 * at 40MHz. This needs testing.
   2845 	 */
   2846 	{
   2847 		struct timeval wait, cur;
   2848 
   2849 		microtime(&wait);
   2850 		wait.tv_usec += 50 / sc->sc_freq;
   2851 		if (wait.tv_usec > 1000000) {
   2852 			wait.tv_sec++;
   2853 			wait.tv_usec -= 1000000;
   2854 		}
   2855 		do {
   2856 			if (NCRDMA_ISINTR(sc))
   2857 				goto again;
   2858 			microtime(&cur);
   2859 		} while (cur.tv_sec <= wait.tv_sec &&
   2860 			 cur.tv_usec <= wait.tv_usec);
   2861 	}
   2862 	goto out;
   2863 }
   2864 
   2865 void
   2866 ncr53c9x_abort(sc, ecb)
   2867 	struct ncr53c9x_softc *sc;
   2868 	struct ncr53c9x_ecb *ecb;
   2869 {
   2870 
   2871 	/* 2 secs for the abort */
   2872 	ecb->timeout = NCR_ABORT_TIMEOUT;
   2873 	ecb->flags |= ECB_ABORT;
   2874 
   2875 	if (ecb == sc->sc_nexus) {
   2876 		int timeout;
   2877 
   2878 		/*
   2879 		 * If we're still selecting, the message will be scheduled
   2880 		 * after selection is complete.
   2881 		 */
   2882 		if (sc->sc_state == NCR_CONNECTED)
   2883 			ncr53c9x_sched_msgout(SEND_ABORT);
   2884 
   2885 		/*
   2886 		 * Reschedule timeout.
   2887 		 */
   2888 		timeout = ecb->timeout;
   2889 		if (hz > 100 && timeout > 1000)
   2890 			timeout = (timeout / 1000) * hz;
   2891 		else
   2892 			timeout = (timeout * hz) / 1000;
   2893 		callout_reset(&ecb->xs->xs_callout, timeout,
   2894 		    ncr53c9x_timeout, ecb);
   2895 	} else {
   2896 		/*
   2897 		 * Just leave the command where it is.
   2898 		 * XXX - what choice do we have but to reset the SCSI
   2899 		 *	 eventually?
   2900 		 */
   2901 		if (sc->sc_state == NCR_IDLE)
   2902 			ncr53c9x_sched(sc);
   2903 	}
   2904 }
   2905 
   2906 void
   2907 ncr53c9x_timeout(arg)
   2908 	void *arg;
   2909 {
   2910 	struct ncr53c9x_ecb *ecb = arg;
   2911 	struct scsipi_xfer *xs = ecb->xs;
   2912 	struct scsipi_link *sc_link = xs->sc_link;
   2913 	struct ncr53c9x_softc *sc = sc_link->adapter_softc;
   2914 	struct ncr53c9x_tinfo *ti = &sc->sc_tinfo[sc_link->scsipi_scsi.target];
   2915 	int s;
   2916 
   2917 	scsi_print_addr(sc_link);
   2918 	printf("%s: timed out [ecb %p (flags 0x%x, dleft %x, stat %x)], "
   2919 	    "<state %d, nexus %p, phase(l %x, c %x, p %x), resid %lx, "
   2920 	    "msg(q %x,o %x) %s>",
   2921 	    sc->sc_dev.dv_xname,
   2922 	    ecb, ecb->flags, ecb->dleft, ecb->stat,
   2923 	    sc->sc_state, sc->sc_nexus,
   2924 	    NCR_READ_REG(sc, NCR_STAT),
   2925 	    sc->sc_phase, sc->sc_prevphase,
   2926 	    (long)sc->sc_dleft, sc->sc_msgpriq, sc->sc_msgout,
   2927 	    NCRDMA_ISACTIVE(sc) ? "DMA active" : "");
   2928 #if NCR53C9X_DEBUG > 1
   2929 	printf("TRACE: %s.", ecb->trace);
   2930 #endif
   2931 
   2932 	s = splbio();
   2933 
   2934 	if (ecb->flags & ECB_ABORT) {
   2935 		/* abort timed out */
   2936 		printf(" AGAIN\n");
   2937 
   2938 		ncr53c9x_init(sc, 1);
   2939 	} else {
   2940 		/* abort the operation that has timed out */
   2941 		printf("\n");
   2942 		xs->error = XS_TIMEOUT;
   2943 		ncr53c9x_abort(sc, ecb);
   2944 
   2945 		/* Disable sync mode if stuck in a data phase */
   2946 		if (ecb == sc->sc_nexus &&
   2947 		    (ti->flags & T_SYNCMODE) != 0 &&
   2948 		    (sc->sc_phase & (MSGI|CDI)) == 0) {
   2949 			scsi_print_addr(sc_link);
   2950 			printf("sync negotiation disabled\n");
   2951 			sc->sc_cfflags |=
   2952 			    (1 << (sc_link->scsipi_scsi.target + 8));
   2953 		}
   2954 	}
   2955 
   2956 	splx(s);
   2957 }
   2958 
   2959 void
   2960 ncr53c9x_watch(arg)
   2961 	void *arg;
   2962 {
   2963 	struct ncr53c9x_softc *sc = (struct ncr53c9x_softc *)arg;
   2964 	struct ncr53c9x_tinfo *ti;
   2965 	struct ncr53c9x_linfo *li;
   2966 	int t, s;
   2967 	/* Delete any structures that have not been used in 10min. */
   2968 	time_t old = time.tv_sec - (10 * 60);
   2969 
   2970 	s = splbio();
   2971 	for (t = 0; t < NCR_NTARG; t++) {
   2972 		ti = &sc->sc_tinfo[t];
   2973 		li = LIST_FIRST(&ti->luns);
   2974 		while (li) {
   2975 			if (li->last_used < old &&
   2976 			    li->untagged == NULL &&
   2977 			    li->used == 0) {
   2978 				if (li->lun < NCR_NLUN)
   2979 					ti->lun[li->lun] = NULL;
   2980 				LIST_REMOVE(li, link);
   2981 				free(li, M_DEVBUF);
   2982 				/* Restart the search at the beginning */
   2983 				li = LIST_FIRST(&ti->luns);
   2984 				continue;
   2985 			}
   2986 			li = LIST_NEXT(li, link);
   2987 		}
   2988 	}
   2989 	splx(s);
   2990 	callout_reset(&sc->sc_watchdog, 60 * hz, ncr53c9x_watch, sc);
   2991 }
   2992 
   2993