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