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