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