Home | History | Annotate | Line # | Download | only in ic
ncr53c9x.c revision 1.150
      1 /*	$NetBSD: ncr53c9x.c,v 1.150 2019/02/03 03:19:27 mrg 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.150 2019/02/03 03:19:27 mrg 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);
    847 	splx(s);
    848 	if (ecb) {
    849 		memset(ecb, 0, sizeof(*ecb));
    850 		ecb->flags |= ECB_ALLOC;
    851 	}
    852 	return ecb;
    853 }
    854 
    855 /*
    856  * DRIVER FUNCTIONS CALLABLE FROM HIGHER LEVEL DRIVERS
    857  */
    858 
    859 /*
    860  * Start a SCSI-command
    861  * This function is called by the higher level SCSI-driver to queue/run
    862  * SCSI-commands.
    863  */
    864 
    865 void
    866 ncr53c9x_scsipi_request(struct scsipi_channel *chan, scsipi_adapter_req_t req,
    867     void *arg)
    868 {
    869 	struct scsipi_xfer *xs;
    870 	struct scsipi_periph *periph;
    871 	struct ncr53c9x_softc *sc;
    872 	struct ncr53c9x_ecb *ecb;
    873 	int flags;
    874 
    875 	NCR_TRACE(("[ncr53c9x_scsipi_request] "));
    876 
    877 	sc = device_private(chan->chan_adapter->adapt_dev);
    878 	mutex_enter(&sc->sc_lock);
    879 
    880 	switch (req) {
    881 	case ADAPTER_REQ_RUN_XFER:
    882 		xs = arg;
    883 		periph = xs->xs_periph;
    884 		flags = xs->xs_control;
    885 
    886 		NCR_CMDS(("[0x%x, %d]->%d ", (int)xs->cmd->opcode, xs->cmdlen,
    887 		    periph->periph_target));
    888 
    889 		/* Get an ECB to use. */
    890 		ecb = ncr53c9x_get_ecb(sc, xs->xs_control);
    891 		/*
    892 		 * This should never happen as we track resources
    893 		 * in the mid-layer, but for now it can as pool_get()
    894 		 * can fail.
    895 		 */
    896 		if (ecb == NULL) {
    897 			scsipi_printaddr(periph);
    898 			printf("%s: unable to allocate ecb\n",
    899 			    device_xname(sc->sc_dev));
    900 			xs->error = XS_RESOURCE_SHORTAGE;
    901 			mutex_exit(&sc->sc_lock);
    902 			scsipi_done(xs);
    903 			return;
    904 		}
    905 
    906 		/* Initialize ecb */
    907 		ecb->xs = xs;
    908 		ecb->timeout = xs->timeout;
    909 
    910 		if (flags & XS_CTL_RESET) {
    911 			ecb->flags |= ECB_RESET;
    912 			ecb->clen = 0;
    913 			ecb->dleft = 0;
    914 		} else {
    915 			memcpy(&ecb->cmd.cmd, xs->cmd, xs->cmdlen);
    916 			ecb->clen = xs->cmdlen;
    917 			ecb->daddr = xs->data;
    918 			ecb->dleft = xs->datalen;
    919 		}
    920 		ecb->stat = 0;
    921 
    922 		TAILQ_INSERT_TAIL(&sc->ready_list, ecb, chain);
    923 		ecb->flags |= ECB_READY;
    924 		if (sc->sc_state == NCR_IDLE)
    925 			ncr53c9x_sched(sc);
    926 
    927 		if ((flags & XS_CTL_POLL) == 0)
    928 			break;
    929 
    930 		/* Not allowed to use interrupts, use polling instead */
    931 		if (ncr53c9x_poll(sc, xs, ecb->timeout)) {
    932 			ncr53c9x_timeout(ecb);
    933 			if (ncr53c9x_poll(sc, xs, ecb->timeout))
    934 				ncr53c9x_timeout(ecb);
    935 		}
    936 		break;
    937 
    938 	case ADAPTER_REQ_GROW_RESOURCES:
    939 		/* XXX Not supported. */
    940 		break;
    941 
    942 	case ADAPTER_REQ_SET_XFER_MODE:
    943 	    {
    944 		struct ncr53c9x_tinfo *ti;
    945 		struct scsipi_xfer_mode *xm = arg;
    946 
    947 		ti = &sc->sc_tinfo[xm->xm_target];
    948 		ti->flags &= ~(T_NEGOTIATE|T_SYNCMODE);
    949 		ti->period = 0;
    950 		ti->offset = 0;
    951 
    952 		if ((sc->sc_cfflags & (1 << ((xm->xm_target & 7) + 16))) == 0 &&
    953 		    (xm->xm_mode & PERIPH_CAP_TQING)) {
    954 			NCR_MISC(("%s: target %d: tagged queuing\n",
    955 			    device_xname(sc->sc_dev), xm->xm_target));
    956 			ti->flags |= T_TAG;
    957 		} else
    958 			ti->flags &= ~T_TAG;
    959 
    960 		if ((xm->xm_mode & PERIPH_CAP_WIDE16) != 0) {
    961 			NCR_MISC(("%s: target %d: wide scsi negotiation\n",
    962 			    device_xname(sc->sc_dev), xm->xm_target));
    963 			if (sc->sc_rev == NCR_VARIANT_FAS366) {
    964 				ti->flags |= T_WIDE;
    965 				ti->width = 1;
    966 			}
    967 		}
    968 
    969 		if ((xm->xm_mode & PERIPH_CAP_SYNC) != 0 &&
    970 		    (ti->flags & T_SYNCHOFF) == 0 && sc->sc_minsync != 0) {
    971 			NCR_MISC(("%s: target %d: sync negotiation\n",
    972 			    device_xname(sc->sc_dev), xm->xm_target));
    973 			ti->flags |= T_NEGOTIATE;
    974 			ti->period = sc->sc_minsync;
    975 		}
    976 		/*
    977 		 * If we're not going to negotiate, send the notification
    978 		 * now, since it won't happen later.
    979 		 */
    980 		if ((ti->flags & T_NEGOTIATE) == 0)
    981 			ncr53c9x_update_xfer_mode(sc, xm->xm_target);
    982 	    }
    983 		break;
    984 	}
    985 
    986 	mutex_exit(&sc->sc_lock);
    987 }
    988 
    989 void
    990 ncr53c9x_update_xfer_mode(struct ncr53c9x_softc *sc, int target)
    991 {
    992 	struct scsipi_xfer_mode xm;
    993 	struct ncr53c9x_tinfo *ti = &sc->sc_tinfo[target];
    994 
    995 	xm.xm_target = target;
    996 	xm.xm_mode = 0;
    997 	xm.xm_period = 0;
    998 	xm.xm_offset = 0;
    999 
   1000 	if (ti->flags & T_SYNCMODE) {
   1001 		xm.xm_mode |= PERIPH_CAP_SYNC;
   1002 		xm.xm_period = ti->period;
   1003 		xm.xm_offset = ti->offset;
   1004 	}
   1005 	if (ti->width)
   1006 		xm.xm_mode |= PERIPH_CAP_WIDE16;
   1007 
   1008 	if ((ti->flags & (T_RSELECTOFF|T_TAG)) == T_TAG)
   1009 		xm.xm_mode |= PERIPH_CAP_TQING;
   1010 
   1011 	scsipi_async_event(&sc->sc_channel, ASYNC_EVENT_XFER_MODE, &xm);
   1012 }
   1013 
   1014 /*
   1015  * Used when interrupt driven I/O isn't allowed, e.g. during boot.
   1016  */
   1017 int
   1018 ncr53c9x_poll(struct ncr53c9x_softc *sc, struct scsipi_xfer *xs, int count)
   1019 {
   1020 
   1021 	NCR_TRACE(("[ncr53c9x_poll] "));
   1022 	while (count) {
   1023 		if (NCRDMA_ISINTR(sc)) {
   1024 			mutex_exit(&sc->sc_lock);
   1025 			ncr53c9x_intr(sc);
   1026 			mutex_enter(&sc->sc_lock);
   1027 		}
   1028 #if alternatively
   1029 		if (NCR_READ_REG(sc, NCR_STAT) & NCRSTAT_INT)
   1030 			ncr53c9x_intr(sc);
   1031 #endif
   1032 		if ((xs->xs_status & XS_STS_DONE) != 0)
   1033 			return 0;
   1034 		if (sc->sc_state == NCR_IDLE) {
   1035 			NCR_TRACE(("[ncr53c9x_poll: rescheduling] "));
   1036 			ncr53c9x_sched(sc);
   1037 		}
   1038 		DELAY(1000);
   1039 		count--;
   1040 	}
   1041 	return 1;
   1042 }
   1043 
   1044 int
   1045 ncr53c9x_ioctl(struct scsipi_channel *chan, u_long cmd, void *arg,
   1046     int flag, struct proc *p)
   1047 {
   1048 	struct ncr53c9x_softc *sc;
   1049 	int error = 0;
   1050 
   1051 	sc = device_private(chan->chan_adapter->adapt_dev);
   1052 	switch (cmd) {
   1053 	case SCBUSIORESET:
   1054 		mutex_enter(&sc->sc_lock);
   1055 		ncr53c9x_init(sc, 1);
   1056 		mutex_exit(&sc->sc_lock);
   1057 		break;
   1058 	default:
   1059 		error = ENOTTY;
   1060 		break;
   1061 	}
   1062 	return error;
   1063 }
   1064 
   1065 
   1066 /*
   1067  * LOW LEVEL SCSI UTILITIES
   1068  */
   1069 
   1070 /*
   1071  * Schedule a scsi operation.  This has now been pulled out of the interrupt
   1072  * handler so that we may call it from ncr53c9x_scsipi_request and
   1073  * ncr53c9x_done.  This may save us an unnecessary interrupt just to get
   1074  * things going.  Should only be called when state == NCR_IDLE and at bio pl.
   1075  */
   1076 void
   1077 ncr53c9x_sched(struct ncr53c9x_softc *sc)
   1078 {
   1079 	struct ncr53c9x_ecb *ecb;
   1080 	struct scsipi_periph *periph;
   1081 	struct ncr53c9x_tinfo *ti;
   1082 	struct ncr53c9x_linfo *li;
   1083 	int lun;
   1084 	int tag;
   1085 
   1086 	NCR_TRACE(("[ncr53c9x_sched] "));
   1087 	if (sc->sc_state != NCR_IDLE)
   1088 		panic("%s: not IDLE (state=%d)", __func__, sc->sc_state);
   1089 
   1090 	/*
   1091 	 * Find first ecb in ready queue that is for a target/lunit
   1092 	 * combinations that is not busy.
   1093 	 */
   1094 	for (ecb = TAILQ_FIRST(&sc->ready_list); ecb != NULL;
   1095 	    ecb = TAILQ_NEXT(ecb, chain)) {
   1096 		periph = ecb->xs->xs_periph;
   1097 		ti = &sc->sc_tinfo[periph->periph_target];
   1098 		lun = periph->periph_lun;
   1099 
   1100 		/* Select type of tag for this command */
   1101 		if ((ti->flags & T_RSELECTOFF) != 0)
   1102 			tag = 0;
   1103 		else if ((ti->flags & T_TAG) == 0)
   1104 			tag = 0;
   1105 		else if ((ecb->flags & ECB_SENSE) != 0)
   1106 			tag = 0;
   1107 		else
   1108 			tag = ecb->xs->xs_tag_type;
   1109 #if 0
   1110 		/* XXXX Use tags for polled commands? */
   1111 		if (ecb->xs->xs_control & XS_CTL_POLL)
   1112 			tag = 0;
   1113 #endif
   1114 
   1115 		li = TINFO_LUN(ti, lun);
   1116 		if (li == NULL) {
   1117 			/* Initialize LUN info and add to list. */
   1118 			li = malloc(sizeof(*li), M_DEVBUF, M_NOWAIT|M_ZERO);
   1119 			if (li == NULL) {
   1120 				continue;
   1121 			}
   1122 			li->lun = lun;
   1123 
   1124 			LIST_INSERT_HEAD(&ti->luns, li, link);
   1125 			if (lun < NCR_NLUN)
   1126 				ti->lun[lun] = li;
   1127 		}
   1128 		li->last_used = time_second;
   1129 		if (tag == 0) {
   1130 			/* Try to issue this as an un-tagged command */
   1131 			if (li->untagged == NULL)
   1132 				li->untagged = ecb;
   1133 		}
   1134 		if (li->untagged != NULL) {
   1135 			tag = 0;
   1136 			if ((li->busy != 1) && li->used == 0) {
   1137 				/* We need to issue this untagged command now */
   1138 				ecb = li->untagged;
   1139 				periph = ecb->xs->xs_periph;
   1140 			} else {
   1141 				/* Not ready yet */
   1142 				continue;
   1143 			}
   1144 		}
   1145 		ecb->tag[0] = tag;
   1146 		if (tag != 0) {
   1147 			li->queued[ecb->xs->xs_tag_id] = ecb;
   1148 			ecb->tag[1] = ecb->xs->xs_tag_id;
   1149 			li->used++;
   1150 		}
   1151 		if (li->untagged != NULL && (li->busy != 1)) {
   1152 			li->busy = 1;
   1153 			TAILQ_REMOVE(&sc->ready_list, ecb, chain);
   1154 			ecb->flags &= ~ECB_READY;
   1155 			sc->sc_nexus = ecb;
   1156 			ncr53c9x_select(sc, ecb);
   1157 			break;
   1158 		}
   1159 		if (li->untagged == NULL && tag != 0) {
   1160 			TAILQ_REMOVE(&sc->ready_list, ecb, chain);
   1161 			ecb->flags &= ~ECB_READY;
   1162 			sc->sc_nexus = ecb;
   1163 			ncr53c9x_select(sc, ecb);
   1164 			break;
   1165 		} else {
   1166 			NCR_TRACE(("%d:%d busy\n",
   1167 			    periph->periph_target,
   1168 			    periph->periph_lun));
   1169 		}
   1170 	}
   1171 }
   1172 
   1173 void
   1174 ncr53c9x_sense(struct ncr53c9x_softc *sc, struct ncr53c9x_ecb *ecb)
   1175 {
   1176 	struct scsipi_xfer *xs = ecb->xs;
   1177 	struct scsipi_periph *periph = xs->xs_periph;
   1178 	struct ncr53c9x_tinfo *ti = &sc->sc_tinfo[periph->periph_target];
   1179 	struct scsi_request_sense *ss = (void *)&ecb->cmd.cmd;
   1180 	struct ncr53c9x_linfo *li;
   1181 	int lun = periph->periph_lun;
   1182 
   1183 	NCR_TRACE(("requesting sense "));
   1184 	/* Next, setup a request sense command block */
   1185 	memset(ss, 0, sizeof(*ss));
   1186 	ss->opcode = SCSI_REQUEST_SENSE;
   1187 	ss->byte2 = periph->periph_lun << SCSI_CMD_LUN_SHIFT;
   1188 	ss->length = sizeof(struct scsi_sense_data);
   1189 	ecb->clen = sizeof(*ss);
   1190 	ecb->daddr = (uint8_t *)&xs->sense.scsi_sense;
   1191 	ecb->dleft = sizeof(struct scsi_sense_data);
   1192 	ecb->flags |= ECB_SENSE;
   1193 	ecb->timeout = NCR_SENSE_TIMEOUT;
   1194 	ti->senses++;
   1195 	li = TINFO_LUN(ti, lun);
   1196 	if (li->busy)
   1197 		li->busy = 0;
   1198 	ncr53c9x_dequeue(sc, ecb);
   1199 	li->untagged = ecb; /* must be executed first to fix C/A */
   1200 	li->busy = 2;
   1201 	if (ecb == sc->sc_nexus) {
   1202 		ncr53c9x_select(sc, ecb);
   1203 	} else {
   1204 		TAILQ_INSERT_HEAD(&sc->ready_list, ecb, chain);
   1205 		ecb->flags |= ECB_READY;
   1206 		if (sc->sc_state == NCR_IDLE)
   1207 			ncr53c9x_sched(sc);
   1208 	}
   1209 }
   1210 
   1211 /*
   1212  * POST PROCESSING OF SCSI_CMD (usually current)
   1213  */
   1214 void
   1215 ncr53c9x_done(struct ncr53c9x_softc *sc, struct ncr53c9x_ecb *ecb)
   1216 {
   1217 	struct scsipi_xfer *xs = ecb->xs;
   1218 	struct scsipi_periph *periph = xs->xs_periph;
   1219 	struct ncr53c9x_tinfo *ti = &sc->sc_tinfo[periph->periph_target];
   1220 	int lun = periph->periph_lun;
   1221 	struct ncr53c9x_linfo *li = TINFO_LUN(ti, lun);
   1222 
   1223 	NCR_TRACE(("[ncr53c9x_done(error:%x)] ", xs->error));
   1224 
   1225 	if ((xs->xs_control & XS_CTL_POLL) == 0)
   1226 		callout_stop(&xs->xs_callout);
   1227 
   1228 	/*
   1229 	 * Now, if we've come here with no error code, i.e. we've kept the
   1230 	 * initial XS_NOERROR, and the status code signals that we should
   1231 	 * check sense, we'll need to set up a request sense cmd block and
   1232 	 * push the command back into the ready queue *before* any other
   1233 	 * commands for this target/lunit, else we lose the sense info.
   1234 	 * We don't support chk sense conditions for the request sense cmd.
   1235 	 */
   1236 	if (xs->error == XS_NOERROR) {
   1237 		xs->status = ecb->stat;
   1238 		if ((ecb->flags & ECB_ABORT) != 0) {
   1239 			xs->error = XS_TIMEOUT;
   1240 		} else if ((ecb->flags & ECB_SENSE) != 0) {
   1241 			xs->error = XS_SENSE;
   1242 		} else if ((ecb->stat & ST_MASK) == SCSI_CHECK) {
   1243 			/* First, save the return values */
   1244 			xs->resid = ecb->dleft;
   1245 			ncr53c9x_sense(sc, ecb);
   1246 			return;
   1247 		} else {
   1248 			xs->resid = ecb->dleft;
   1249 		}
   1250 		if (xs->status == SCSI_QUEUE_FULL || xs->status == XS_BUSY)
   1251 			xs->error = XS_BUSY;
   1252 	}
   1253 
   1254 #ifdef NCR53C9X_DEBUG
   1255 	if (ncr53c9x_debug & NCR_SHOWTRAC) {
   1256 		if (xs->resid != 0)
   1257 			printf("resid=%d ", xs->resid);
   1258 		if (xs->error == XS_SENSE)
   1259 			printf("sense=0x%02x\n",
   1260 			    xs->sense.scsi_sense.response_code);
   1261 		else
   1262 			printf("error=%d\n", xs->error);
   1263 	}
   1264 #endif
   1265 
   1266 	/*
   1267 	 * Remove the ECB from whatever queue it's on.
   1268 	 */
   1269 	ncr53c9x_dequeue(sc, ecb);
   1270 	if (ecb == sc->sc_nexus) {
   1271 		sc->sc_nexus = NULL;
   1272 		if (sc->sc_state != NCR_CLEANING) {
   1273 			sc->sc_state = NCR_IDLE;
   1274 			ncr53c9x_sched(sc);
   1275 		}
   1276 	}
   1277 
   1278 	if (xs->error == XS_SELTIMEOUT) {
   1279 		/* Selection timeout -- discard this LUN if empty */
   1280 		if (li->untagged == NULL && li->used == 0) {
   1281 			if (lun < NCR_NLUN)
   1282 				ti->lun[lun] = NULL;
   1283 			LIST_REMOVE(li, link);
   1284 			free(li, M_DEVBUF);
   1285 		}
   1286 	}
   1287 
   1288 	ncr53c9x_free_ecb(sc, ecb);
   1289 	ti->cmds++;
   1290 	mutex_exit(&sc->sc_lock);
   1291 	scsipi_done(xs);
   1292 	mutex_enter(&sc->sc_lock);
   1293 }
   1294 
   1295 void
   1296 ncr53c9x_dequeue(struct ncr53c9x_softc *sc, struct ncr53c9x_ecb *ecb)
   1297 {
   1298 	struct ncr53c9x_tinfo *ti =
   1299 	    &sc->sc_tinfo[ecb->xs->xs_periph->periph_target];
   1300 	struct ncr53c9x_linfo *li;
   1301 	int64_t lun = ecb->xs->xs_periph->periph_lun;
   1302 
   1303 	li = TINFO_LUN(ti, lun);
   1304 #ifdef DIAGNOSTIC
   1305 	if (li == NULL || li->lun != lun)
   1306 		panic("%s: lun %" PRIx64 " for ecb %p does not exist",
   1307 		    __func__, lun, ecb);
   1308 #endif
   1309 	if (li->untagged == ecb) {
   1310 		li->busy = 0;
   1311 		li->untagged = NULL;
   1312 	}
   1313 	if (ecb->tag[0] && li->queued[ecb->tag[1]] != NULL) {
   1314 #ifdef DIAGNOSTIC
   1315 		if (li->queued[ecb->tag[1]] != NULL &&
   1316 		    (li->queued[ecb->tag[1]] != ecb))
   1317 			panic("%s: slot %d for lun %" PRIx64 " has %p "
   1318 			    "instead of ecb %p\n", __func__, ecb->tag[1],
   1319 			    lun,
   1320 			    li->queued[ecb->tag[1]], ecb);
   1321 #endif
   1322 		li->queued[ecb->tag[1]] = NULL;
   1323 		li->used--;
   1324 	}
   1325 
   1326 	if ((ecb->flags & ECB_READY) != 0) {
   1327 		ecb->flags &= ~ECB_READY;
   1328 		TAILQ_REMOVE(&sc->ready_list, ecb, chain);
   1329 	}
   1330 }
   1331 
   1332 /*
   1333  * INTERRUPT/PROTOCOL ENGINE
   1334  */
   1335 
   1336 /*
   1337  * Schedule an outgoing message by prioritizing it, and asserting
   1338  * attention on the bus. We can only do this when we are the initiator
   1339  * else there will be an illegal command interrupt.
   1340  */
   1341 #define ncr53c9x_sched_msgout(m) \
   1342 	do {							\
   1343 		NCR_MSGS(("ncr53c9x_sched_msgout %x %d", m, __LINE__));	\
   1344 		NCRCMD(sc, NCRCMD_SETATN);			\
   1345 		sc->sc_flags |= NCR_ATN;			\
   1346 		sc->sc_msgpriq |= (m);				\
   1347 	} while (/* CONSTCOND */0)
   1348 
   1349 static void
   1350 ncr53c9x_flushfifo(struct ncr53c9x_softc *sc)
   1351 {
   1352 
   1353 	NCR_TRACE(("[flushfifo] "));
   1354 
   1355 	NCRCMD(sc, NCRCMD_FLUSH);
   1356 
   1357 	if (sc->sc_phase == COMMAND_PHASE ||
   1358 	    sc->sc_phase == MESSAGE_OUT_PHASE)
   1359 		DELAY(2);
   1360 }
   1361 
   1362 static int
   1363 ncr53c9x_rdfifo(struct ncr53c9x_softc *sc, int how)
   1364 {
   1365 	int i, n;
   1366 	uint8_t *ibuf;
   1367 
   1368 	switch (how) {
   1369 	case NCR_RDFIFO_START:
   1370 		ibuf = sc->sc_imess;
   1371 		sc->sc_imlen = 0;
   1372 		break;
   1373 	case NCR_RDFIFO_CONTINUE:
   1374 		ibuf = sc->sc_imess + sc->sc_imlen;
   1375 		break;
   1376 	default:
   1377 		panic("%s: bad flag", __func__);
   1378 		break;
   1379 	}
   1380 
   1381 	/*
   1382 	 * XXX buffer (sc_imess) size for message
   1383 	 */
   1384 
   1385 	n = NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF;
   1386 
   1387 	if (sc->sc_rev == NCR_VARIANT_FAS366) {
   1388 		n *= 2;
   1389 
   1390 		for (i = 0; i < n; i++)
   1391 			ibuf[i] = NCR_READ_REG(sc, NCR_FIFO);
   1392 
   1393 		if (sc->sc_espstat2 & NCRFAS_STAT2_ISHUTTLE) {
   1394 
   1395 			NCR_WRITE_REG(sc, NCR_FIFO, 0);
   1396 			ibuf[i++] = NCR_READ_REG(sc, NCR_FIFO);
   1397 
   1398 			NCR_READ_REG(sc, NCR_FIFO);
   1399 
   1400 			ncr53c9x_flushfifo(sc);
   1401 		}
   1402 	} else {
   1403 		for (i = 0; i < n; i++)
   1404 			ibuf[i] = NCR_READ_REG(sc, NCR_FIFO);
   1405 	}
   1406 
   1407 	sc->sc_imlen += i;
   1408 
   1409 #if 0
   1410 #ifdef NCR53C9X_DEBUG
   1411 	{
   1412 		int j;
   1413 
   1414 		NCR_TRACE(("\n[rdfifo %s (%d):",
   1415 		    (how == NCR_RDFIFO_START) ? "start" : "cont",
   1416 		    (int)sc->sc_imlen));
   1417 		if (ncr53c9x_debug & NCR_SHOWTRAC) {
   1418 			for (j = 0; j < sc->sc_imlen; j++)
   1419 				printf(" %02x", sc->sc_imess[j]);
   1420 			printf("]\n");
   1421 		}
   1422 	}
   1423 #endif
   1424 #endif
   1425 	return sc->sc_imlen;
   1426 }
   1427 
   1428 static void
   1429 ncr53c9x_wrfifo(struct ncr53c9x_softc *sc, uint8_t *p, int len)
   1430 {
   1431 	int i;
   1432 
   1433 #ifdef NCR53C9X_DEBUG
   1434 	NCR_MSGS(("[wrfifo(%d):", len));
   1435 	if (ncr53c9x_debug & NCR_SHOWMSGS) {
   1436 		for (i = 0; i < len; i++)
   1437 			printf(" %02x", p[i]);
   1438 		printf("]\n");
   1439 	}
   1440 #endif
   1441 
   1442 	for (i = 0; i < len; i++) {
   1443 		NCR_WRITE_REG(sc, NCR_FIFO, p[i]);
   1444 
   1445 		if (sc->sc_rev == NCR_VARIANT_FAS366)
   1446 			NCR_WRITE_REG(sc, NCR_FIFO, 0);
   1447 	}
   1448 }
   1449 
   1450 int
   1451 ncr53c9x_reselect(struct ncr53c9x_softc *sc, int message, int tagtype,
   1452     int tagid)
   1453 {
   1454 	uint8_t selid, target, lun;
   1455 	struct ncr53c9x_ecb *ecb = NULL;
   1456 	struct ncr53c9x_tinfo *ti;
   1457 	struct ncr53c9x_linfo *li;
   1458 
   1459 	if (sc->sc_rev == NCR_VARIANT_FAS366) {
   1460 		target = sc->sc_selid;
   1461 	} else {
   1462 		/*
   1463 		 * The SCSI chip made a snapshot of the data bus
   1464 		 * while the reselection was being negotiated.
   1465 		 * This enables us to determine which target did
   1466 		 * the reselect.
   1467 		 */
   1468 		selid = sc->sc_selid & ~(1 << sc->sc_id);
   1469 		if (selid & (selid - 1)) {
   1470 			printf("%s: reselect with invalid selid %02x;"
   1471 			    " sending DEVICE RESET\n",
   1472 			    device_xname(sc->sc_dev), selid);
   1473 			goto reset;
   1474 		}
   1475 
   1476 		target = ffs(selid) - 1;
   1477 	}
   1478 	lun = message & 0x07;
   1479 
   1480 	/*
   1481 	 * Search wait queue for disconnected cmd
   1482 	 * The list should be short, so I haven't bothered with
   1483 	 * any more sophisticated structures than a simple
   1484 	 * singly linked list.
   1485 	 */
   1486 	ti = &sc->sc_tinfo[target];
   1487 	li = TINFO_LUN(ti, lun);
   1488 
   1489 	/*
   1490 	 * We can get as far as the LUN with the IDENTIFY
   1491 	 * message.  Check to see if we're running an
   1492 	 * un-tagged command.  Otherwise ack the IDENTIFY
   1493 	 * and wait for a tag message.
   1494 	 */
   1495 	if (li != NULL) {
   1496 		if (li->untagged != NULL && li->busy)
   1497 			ecb = li->untagged;
   1498 		else if (tagtype != MSG_SIMPLE_Q_TAG) {
   1499 			/* Wait for tag to come by */
   1500 			sc->sc_state = NCR_IDENTIFIED;
   1501 			return 0;
   1502 		} else if (tagtype)
   1503 			ecb = li->queued[tagid];
   1504 	}
   1505 	if (ecb == NULL) {
   1506 		printf("%s: reselect from target %d lun %d tag %x:%x "
   1507 		    "with no nexus; sending ABORT\n",
   1508 		    device_xname(sc->sc_dev), target, lun, tagtype, tagid);
   1509 		goto abort;
   1510 	}
   1511 
   1512 	/* Make this nexus active again. */
   1513 	sc->sc_state = NCR_CONNECTED;
   1514 	sc->sc_nexus = ecb;
   1515 	ncr53c9x_setsync(sc, ti);
   1516 
   1517 	if (ecb->flags & ECB_RESET)
   1518 		ncr53c9x_sched_msgout(SEND_DEV_RESET);
   1519 	else if (ecb->flags & ECB_ABORT)
   1520 		ncr53c9x_sched_msgout(SEND_ABORT);
   1521 
   1522 	/* Do an implicit RESTORE POINTERS. */
   1523 	sc->sc_dp = ecb->daddr;
   1524 	sc->sc_dleft = ecb->dleft;
   1525 
   1526 	return 0;
   1527 
   1528 reset:
   1529 	ncr53c9x_sched_msgout(SEND_DEV_RESET);
   1530 	return 1;
   1531 
   1532 abort:
   1533 	ncr53c9x_sched_msgout(SEND_ABORT);
   1534 	return 1;
   1535 }
   1536 
   1537 static inline int
   1538 __verify_msg_format(uint8_t *p, int len)
   1539 {
   1540 
   1541 	if (len == 1 && MSG_IS1BYTE(p[0]))
   1542 		return 1;
   1543 	if (len == 2 && MSG_IS2BYTE(p[0]))
   1544 		return 1;
   1545 	if (len >= 3 && MSG_ISEXTENDED(p[0]) &&
   1546 	    len == p[1] + 2)
   1547 		return 1;
   1548 
   1549 	return 0;
   1550 }
   1551 
   1552 /*
   1553  * Get an incoming message as initiator.
   1554  *
   1555  * The SCSI bus must already be in MESSAGE_IN_PHASE and there is a
   1556  * byte in the FIFO
   1557  */
   1558 void
   1559 ncr53c9x_msgin(struct ncr53c9x_softc *sc)
   1560 {
   1561 
   1562 	NCR_TRACE(("[ncr53c9x_msgin(curmsglen:%ld)] ", (long)sc->sc_imlen));
   1563 
   1564 	if (sc->sc_imlen == 0) {
   1565 		printf("%s: msgin: no msg byte available\n",
   1566 		    device_xname(sc->sc_dev));
   1567 		return;
   1568 	}
   1569 
   1570 	/*
   1571 	 * Prepare for a new message.  A message should (according
   1572 	 * to the SCSI standard) be transmitted in one single
   1573 	 * MESSAGE_IN_PHASE. If we have been in some other phase,
   1574 	 * then this is a new message.
   1575 	 */
   1576 	if (sc->sc_prevphase != MESSAGE_IN_PHASE &&
   1577 	    sc->sc_state != NCR_RESELECTED) {
   1578 		printf("%s: phase change, dropping message, "
   1579 		    "prev %d, state %d\n",
   1580 		    device_xname(sc->sc_dev), sc->sc_prevphase, sc->sc_state);
   1581 		sc->sc_flags &= ~NCR_DROP_MSGI;
   1582 		sc->sc_imlen = 0;
   1583 	}
   1584 
   1585 	/*
   1586 	 * If we're going to reject the message, don't bother storing
   1587 	 * the incoming bytes.  But still, we need to ACK them.
   1588 	 */
   1589 	if ((sc->sc_flags & NCR_DROP_MSGI) != 0) {
   1590 		NCRCMD(sc, NCRCMD_MSGOK);
   1591 		printf("<dropping msg byte %x>", sc->sc_imess[sc->sc_imlen]);
   1592 		return;
   1593 	}
   1594 
   1595 	if (sc->sc_imlen >= NCR_MAX_MSG_LEN) {
   1596 		ncr53c9x_sched_msgout(SEND_REJECT);
   1597 		sc->sc_flags |= NCR_DROP_MSGI;
   1598 	} else {
   1599 		uint8_t *pb;
   1600 		int plen;
   1601 
   1602 		switch (sc->sc_state) {
   1603 		/*
   1604 		 * if received message is the first of reselection
   1605 		 * then first byte is selid, and then message
   1606 		 */
   1607 		case NCR_RESELECTED:
   1608 			pb = sc->sc_imess + 1;
   1609 			plen = sc->sc_imlen - 1;
   1610 			break;
   1611 		default:
   1612 			pb = sc->sc_imess;
   1613 			plen = sc->sc_imlen;
   1614 			break;
   1615 		}
   1616 
   1617 		if (__verify_msg_format(pb, plen))
   1618 			goto gotit;
   1619 	}
   1620 
   1621 	/* Ack what we have so far */
   1622 	NCRCMD(sc, NCRCMD_MSGOK);
   1623 	return;
   1624 
   1625 gotit:
   1626 	NCR_MSGS(("gotmsg(%x) state %d", sc->sc_imess[0], sc->sc_state));
   1627 	/* we got complete message, flush the imess, */
   1628 	/* XXX nobody uses imlen below */
   1629 	sc->sc_imlen = 0;
   1630 	/*
   1631 	 * Now we should have a complete message (1 byte, 2 byte
   1632 	 * and moderately long extended messages).  We only handle
   1633 	 * extended messages which total length is shorter than
   1634 	 * NCR_MAX_MSG_LEN.  Longer messages will be amputated.
   1635 	 */
   1636 	switch (sc->sc_state) {
   1637 		struct ncr53c9x_ecb *ecb;
   1638 		struct ncr53c9x_tinfo *ti;
   1639 		struct ncr53c9x_linfo *li;
   1640 		int lun;
   1641 
   1642 	case NCR_CONNECTED:
   1643 		ecb = sc->sc_nexus;
   1644 		ti = &sc->sc_tinfo[ecb->xs->xs_periph->periph_target];
   1645 
   1646 		switch (sc->sc_imess[0]) {
   1647 		case MSG_CMDCOMPLETE:
   1648 			NCR_MSGS(("cmdcomplete "));
   1649 			if (sc->sc_dleft < 0) {
   1650 				scsipi_printaddr(ecb->xs->xs_periph);
   1651 				printf("%s: got %ld extra bytes\n",
   1652 				    device_xname(sc->sc_dev),
   1653 				    -(long)sc->sc_dleft);
   1654 				sc->sc_dleft = 0;
   1655 			}
   1656 			ecb->dleft = (ecb->flags & ECB_TENTATIVE_DONE) ?
   1657 			    0 : sc->sc_dleft;
   1658 			if ((ecb->flags & ECB_SENSE) == 0)
   1659 				ecb->xs->resid = ecb->dleft;
   1660 			sc->sc_state = NCR_CMDCOMPLETE;
   1661 			break;
   1662 
   1663 		case MSG_MESSAGE_REJECT:
   1664 			NCR_MSGS(("msg reject (msgout=%x) ", sc->sc_msgout));
   1665 			switch (sc->sc_msgout) {
   1666 			case SEND_TAG:
   1667 				/*
   1668 				 * Target does not like tagged queuing.
   1669 				 *  - Flush the command queue
   1670 				 *  - Disable tagged queuing for the target
   1671 				 *  - Dequeue ecb from the queued array.
   1672 				 */
   1673 				printf("%s: tagged queuing rejected: "
   1674 				    "target %d\n",
   1675 				    device_xname(sc->sc_dev),
   1676 				    ecb->xs->xs_periph->periph_target);
   1677 
   1678 				NCR_MSGS(("(rejected sent tag)"));
   1679 				NCRCMD(sc, NCRCMD_FLUSH);
   1680 				DELAY(1);
   1681 				ti->flags &= ~T_TAG;
   1682 				lun = ecb->xs->xs_periph->periph_lun;
   1683 				li = TINFO_LUN(ti, lun);
   1684 				if (ecb->tag[0] &&
   1685 				    li->queued[ecb->tag[1]] != NULL) {
   1686 					li->queued[ecb->tag[1]] = NULL;
   1687 					li->used--;
   1688 				}
   1689 				ecb->tag[0] = ecb->tag[1] = 0;
   1690 				li->untagged = ecb;
   1691 				li->busy = 1;
   1692 				break;
   1693 
   1694 			case SEND_SDTR:
   1695 				printf("%s: sync transfer rejected: "
   1696 				    "target %d\n",
   1697 				    device_xname(sc->sc_dev),
   1698 				    ecb->xs->xs_periph->periph_target);
   1699 
   1700 				sc->sc_flags &= ~NCR_SYNCHNEGO;
   1701 				ti->flags &= ~(T_NEGOTIATE | T_SYNCMODE);
   1702 				ncr53c9x_setsync(sc, ti);
   1703 				ncr53c9x_update_xfer_mode(sc,
   1704 				    ecb->xs->xs_periph->periph_target);
   1705 				break;
   1706 
   1707 			case SEND_WDTR:
   1708 				printf("%s: wide transfer rejected: "
   1709 				    "target %d\n",
   1710 				    device_xname(sc->sc_dev),
   1711 				    ecb->xs->xs_periph->periph_target);
   1712 				ti->flags &= ~(T_WIDE | T_WDTRSENT);
   1713 				ti->width = 0;
   1714 				break;
   1715 
   1716 			case SEND_INIT_DET_ERR:
   1717 				goto abort;
   1718 			}
   1719 			break;
   1720 
   1721 		case MSG_NOOP:
   1722 			NCR_MSGS(("noop "));
   1723 			break;
   1724 
   1725 		case MSG_HEAD_OF_Q_TAG:
   1726 		case MSG_SIMPLE_Q_TAG:
   1727 		case MSG_ORDERED_Q_TAG:
   1728 			NCR_MSGS(("TAG %x:%x",
   1729 			    sc->sc_imess[0], sc->sc_imess[1]));
   1730 			break;
   1731 
   1732 		case MSG_DISCONNECT:
   1733 			NCR_MSGS(("disconnect "));
   1734 			ti->dconns++;
   1735 			sc->sc_state = NCR_DISCONNECT;
   1736 
   1737 			/*
   1738 			 * Mark the fact that all bytes have moved. The
   1739 			 * target may not bother to do a SAVE POINTERS
   1740 			 * at this stage. This flag will set the residual
   1741 			 * count to zero on MSG COMPLETE.
   1742 			 */
   1743 			if (sc->sc_dleft == 0)
   1744 				ecb->flags |= ECB_TENTATIVE_DONE;
   1745 
   1746 			break;
   1747 
   1748 		case MSG_SAVEDATAPOINTER:
   1749 			NCR_MSGS(("save datapointer "));
   1750 			ecb->daddr = sc->sc_dp;
   1751 			ecb->dleft = sc->sc_dleft;
   1752 			break;
   1753 
   1754 		case MSG_RESTOREPOINTERS:
   1755 			NCR_MSGS(("restore datapointer "));
   1756 			sc->sc_dp = ecb->daddr;
   1757 			sc->sc_dleft = ecb->dleft;
   1758 			break;
   1759 
   1760 		case MSG_EXTENDED:
   1761 			NCR_MSGS(("extended(%x) ", sc->sc_imess[2]));
   1762 			switch (sc->sc_imess[2]) {
   1763 			case MSG_EXT_SDTR:
   1764 				NCR_MSGS(("SDTR period %d, offset %d ",
   1765 				    sc->sc_imess[3], sc->sc_imess[4]));
   1766 				if (sc->sc_imess[1] != 3)
   1767 					goto reject;
   1768 				ti->period = sc->sc_imess[3];
   1769 				ti->offset = sc->sc_imess[4];
   1770 				ti->flags &= ~T_NEGOTIATE;
   1771 				if (sc->sc_minsync == 0 ||
   1772 				    ti->offset == 0 ||
   1773 				    ti->period > 124) {
   1774 #if 0
   1775 #ifdef NCR53C9X_DEBUG
   1776 					scsipi_printaddr(ecb->xs->xs_periph);
   1777 					printf("async mode\n");
   1778 #endif
   1779 #endif
   1780 					ti->flags &= ~T_SYNCMODE;
   1781 					if ((sc->sc_flags&NCR_SYNCHNEGO) == 0) {
   1782 						/*
   1783 						 * target initiated negotiation
   1784 						 */
   1785 						ti->offset = 0;
   1786 						ncr53c9x_sched_msgout(
   1787 						    SEND_SDTR);
   1788 					}
   1789 				} else {
   1790 					int p;
   1791 
   1792 					p = ncr53c9x_stp2cpb(sc, ti->period);
   1793 					ti->period = ncr53c9x_cpb2stp(sc, p);
   1794 					if ((sc->sc_flags&NCR_SYNCHNEGO) == 0) {
   1795 						/*
   1796 						 * target initiated negotiation
   1797 						 */
   1798 						if (ti->period <
   1799 						    sc->sc_minsync)
   1800 							ti->period =
   1801 							    sc->sc_minsync;
   1802 						if (ti->offset > 15)
   1803 							ti->offset = 15;
   1804 						ti->flags &= ~T_SYNCMODE;
   1805 						ncr53c9x_sched_msgout(
   1806 						    SEND_SDTR);
   1807 					} else {
   1808 						/* we are sync */
   1809 						ti->flags |= T_SYNCMODE;
   1810 					}
   1811 				}
   1812 				ncr53c9x_update_xfer_mode(sc,
   1813 				    ecb->xs->xs_periph->periph_target);
   1814 				sc->sc_flags &= ~NCR_SYNCHNEGO;
   1815 				ncr53c9x_setsync(sc, ti);
   1816 				break;
   1817 
   1818 			case MSG_EXT_WDTR:
   1819 #ifdef NCR53C9X_DEBUG
   1820 				printf("%s: wide mode %d\n",
   1821 				    device_xname(sc->sc_dev), sc->sc_imess[3]);
   1822 #endif
   1823 				if (sc->sc_imess[3] == 1) {
   1824 					ti->cfg3 |= NCRFASCFG3_EWIDE;
   1825 					ncr53c9x_setsync(sc, ti);
   1826 				} else
   1827 					ti->width = 0;
   1828 				/*
   1829 				 * Device started width negotiation.
   1830 				 */
   1831 				if ((ti->flags & T_WDTRSENT) == 0)
   1832 					ncr53c9x_sched_msgout(SEND_WDTR);
   1833 				ti->flags &= ~(T_WIDE | T_WDTRSENT);
   1834 				break;
   1835 			default:
   1836 				scsipi_printaddr(ecb->xs->xs_periph);
   1837 				printf("%s: unrecognized MESSAGE EXTENDED;"
   1838 				    " sending REJECT\n",
   1839 				    device_xname(sc->sc_dev));
   1840 				goto reject;
   1841 			}
   1842 			break;
   1843 		case MSG_IGN_WIDE_RESIDUE:
   1844 			NCR_MSGS(("ignore wide residue "));
   1845 			break;
   1846 
   1847 		default:
   1848 			NCR_MSGS(("ident "));
   1849 			scsipi_printaddr(ecb->xs->xs_periph);
   1850 			printf("%s: unrecognized MESSAGE (%x); sending REJECT\n",
   1851 			    device_xname(sc->sc_dev), sc->sc_imess[0]);
   1852 		reject:
   1853 			ncr53c9x_sched_msgout(SEND_REJECT);
   1854 			break;
   1855 		}
   1856 		break;
   1857 
   1858 	case NCR_IDENTIFIED:
   1859 		/*
   1860 		 * IDENTIFY message was received and queue tag is expected now
   1861 		 */
   1862 		if ((sc->sc_imess[0] != MSG_SIMPLE_Q_TAG) ||
   1863 		    (sc->sc_msgify == 0)) {
   1864 			printf("%s: TAG reselect without IDENTIFY;"
   1865 			    " MSG %x;"
   1866 			    " sending DEVICE RESET\n",
   1867 			    device_xname(sc->sc_dev),
   1868 			    sc->sc_imess[0]);
   1869 			goto reset;
   1870 		}
   1871 		(void)ncr53c9x_reselect(sc, sc->sc_msgify,
   1872 		    sc->sc_imess[0], sc->sc_imess[1]);
   1873 		break;
   1874 
   1875 	case NCR_RESELECTED:
   1876 		if (MSG_ISIDENTIFY(sc->sc_imess[1])) {
   1877 			sc->sc_msgify = sc->sc_imess[1];
   1878 		} else {
   1879 			printf("%s: reselect without IDENTIFY;"
   1880 			    " MSG %x;"
   1881 			    " sending DEVICE RESET\n",
   1882 			    device_xname(sc->sc_dev),
   1883 			    sc->sc_imess[1]);
   1884 			goto reset;
   1885 		}
   1886 		(void)ncr53c9x_reselect(sc, sc->sc_msgify, 0, 0);
   1887 		break;
   1888 
   1889 	default:
   1890 		printf("%s: unexpected MESSAGE IN; sending DEVICE RESET\n",
   1891 		    device_xname(sc->sc_dev));
   1892 	reset:
   1893 		ncr53c9x_sched_msgout(SEND_DEV_RESET);
   1894 		break;
   1895 
   1896 	abort:
   1897 		ncr53c9x_sched_msgout(SEND_ABORT);
   1898 		break;
   1899 	}
   1900 
   1901 	/* if we have more messages to send set ATN */
   1902 	if (sc->sc_msgpriq)
   1903 		NCRCMD(sc, NCRCMD_SETATN);
   1904 
   1905 	/* Ack last message byte */
   1906 	NCRCMD(sc, NCRCMD_MSGOK);
   1907 
   1908 	/* Done, reset message pointer. */
   1909 	sc->sc_flags &= ~NCR_DROP_MSGI;
   1910 	sc->sc_imlen = 0;
   1911 }
   1912 
   1913 
   1914 /*
   1915  * Send the highest priority, scheduled message
   1916  */
   1917 void
   1918 ncr53c9x_msgout(struct ncr53c9x_softc *sc)
   1919 {
   1920 	struct ncr53c9x_tinfo *ti;
   1921 	struct ncr53c9x_ecb *ecb;
   1922 	size_t size;
   1923 
   1924 	NCR_TRACE(("[ncr53c9x_msgout(priq:%x, prevphase:%x)]",
   1925 	    sc->sc_msgpriq, sc->sc_prevphase));
   1926 
   1927 	/*
   1928 	 * XXX - the NCR_ATN flag is not in sync with the actual ATN
   1929 	 *	 condition on the SCSI bus. The 53c9x chip
   1930 	 *	 automatically turns off ATN before sending the
   1931 	 *	 message byte.  (see also the comment below in the
   1932 	 *	 default case when picking out a message to send)
   1933 	 */
   1934 	if (sc->sc_flags & NCR_ATN) {
   1935 		if (sc->sc_prevphase != MESSAGE_OUT_PHASE) {
   1936 		new:
   1937 			NCRCMD(sc, NCRCMD_FLUSH);
   1938 #if 0
   1939 			DELAY(1);
   1940 #endif
   1941 			sc->sc_msgoutq = 0;
   1942 			sc->sc_omlen = 0;
   1943 		}
   1944 	} else {
   1945 		if (sc->sc_prevphase == MESSAGE_OUT_PHASE) {
   1946 			ncr53c9x_sched_msgout(sc->sc_msgoutq);
   1947 			goto new;
   1948 		} else {
   1949 			printf("%s at line %d: unexpected MESSAGE OUT phase\n",
   1950 			    device_xname(sc->sc_dev), __LINE__);
   1951 		}
   1952 	}
   1953 
   1954 	if (sc->sc_omlen == 0) {
   1955 		/* Pick up highest priority message */
   1956 		sc->sc_msgout = sc->sc_msgpriq & -sc->sc_msgpriq;
   1957 		sc->sc_msgoutq |= sc->sc_msgout;
   1958 		sc->sc_msgpriq &= ~sc->sc_msgout;
   1959 		sc->sc_omlen = 1;		/* "Default" message len */
   1960 		switch (sc->sc_msgout) {
   1961 		case SEND_SDTR:
   1962 			ecb = sc->sc_nexus;
   1963 			ti = &sc->sc_tinfo[ecb->xs->xs_periph->periph_target];
   1964 			sc->sc_omess[0] = MSG_EXTENDED;
   1965 			sc->sc_omess[1] = MSG_EXT_SDTR_LEN;
   1966 			sc->sc_omess[2] = MSG_EXT_SDTR;
   1967 			sc->sc_omess[3] = ti->period;
   1968 			sc->sc_omess[4] = ti->offset;
   1969 			sc->sc_omlen = 5;
   1970 			if ((sc->sc_flags & NCR_SYNCHNEGO) == 0) {
   1971 				ti->flags |= T_SYNCMODE;
   1972 				ncr53c9x_setsync(sc, ti);
   1973 			}
   1974 			break;
   1975 		case SEND_WDTR:
   1976 			ecb = sc->sc_nexus;
   1977 			ti = &sc->sc_tinfo[ecb->xs->xs_periph->periph_target];
   1978 			sc->sc_omess[0] = MSG_EXTENDED;
   1979 			sc->sc_omess[1] = MSG_EXT_WDTR_LEN;
   1980 			sc->sc_omess[2] = MSG_EXT_WDTR;
   1981 			sc->sc_omess[3] = ti->width;
   1982 			sc->sc_omlen = 4;
   1983 			break;
   1984 		case SEND_IDENTIFY:
   1985 			if (sc->sc_state != NCR_CONNECTED) {
   1986 				printf("%s at line %d: no nexus\n",
   1987 				    device_xname(sc->sc_dev), __LINE__);
   1988 			}
   1989 			ecb = sc->sc_nexus;
   1990 			sc->sc_omess[0] =
   1991 			    MSG_IDENTIFY(ecb->xs->xs_periph->periph_lun, 0);
   1992 			break;
   1993 		case SEND_TAG:
   1994 			if (sc->sc_state != NCR_CONNECTED) {
   1995 				printf("%s at line %d: no nexus\n",
   1996 				    device_xname(sc->sc_dev), __LINE__);
   1997 			}
   1998 			ecb = sc->sc_nexus;
   1999 			sc->sc_omess[0] = ecb->tag[0];
   2000 			sc->sc_omess[1] = ecb->tag[1];
   2001 			sc->sc_omlen = 2;
   2002 			break;
   2003 		case SEND_DEV_RESET:
   2004 			sc->sc_flags |= NCR_ABORTING;
   2005 			sc->sc_omess[0] = MSG_BUS_DEV_RESET;
   2006 			ecb = sc->sc_nexus;
   2007 			ti = &sc->sc_tinfo[ecb->xs->xs_periph->periph_target];
   2008 			ti->flags &= ~T_SYNCMODE;
   2009 			ncr53c9x_update_xfer_mode(sc,
   2010 			    ecb->xs->xs_periph->periph_target);
   2011 			if ((ti->flags & T_SYNCHOFF) == 0)
   2012 				/* We can re-start sync negotiation */
   2013 				ti->flags |= T_NEGOTIATE;
   2014 			break;
   2015 		case SEND_PARITY_ERROR:
   2016 			sc->sc_omess[0] = MSG_PARITY_ERROR;
   2017 			break;
   2018 		case SEND_ABORT:
   2019 			sc->sc_flags |= NCR_ABORTING;
   2020 			sc->sc_omess[0] = MSG_ABORT;
   2021 			break;
   2022 		case SEND_INIT_DET_ERR:
   2023 			sc->sc_omess[0] = MSG_INITIATOR_DET_ERR;
   2024 			break;
   2025 		case SEND_REJECT:
   2026 			sc->sc_omess[0] = MSG_MESSAGE_REJECT;
   2027 			break;
   2028 		default:
   2029 			/*
   2030 			 * We normally do not get here, since the chip
   2031 			 * automatically turns off ATN before the last
   2032 			 * byte of a message is sent to the target.
   2033 			 * However, if the target rejects our (multi-byte)
   2034 			 * message early by switching to MSG IN phase
   2035 			 * ATN remains on, so the target may return to
   2036 			 * MSG OUT phase. If there are no scheduled messages
   2037 			 * left we send a NO-OP.
   2038 			 *
   2039 			 * XXX - Note that this leaves no useful purpose for
   2040 			 * the NCR_ATN flag.
   2041 			 */
   2042 			sc->sc_flags &= ~NCR_ATN;
   2043 			sc->sc_omess[0] = MSG_NOOP;
   2044 			break;
   2045 		}
   2046 		sc->sc_omp = sc->sc_omess;
   2047 	}
   2048 
   2049 #ifdef DEBUG
   2050 	if (ncr53c9x_debug & NCR_SHOWMSGS) {
   2051 		int i;
   2052 
   2053 		NCR_MSGS(("<msgout:"));
   2054 		for (i = 0; i < sc->sc_omlen; i++)
   2055 			NCR_MSGS((" %02x", sc->sc_omess[i]));
   2056 		NCR_MSGS(("> "));
   2057 	}
   2058 #endif
   2059 	if (sc->sc_rev == NCR_VARIANT_FAS366) {
   2060 		/*
   2061 		 * XXX fifo size
   2062 		 */
   2063 		ncr53c9x_flushfifo(sc);
   2064 		ncr53c9x_wrfifo(sc, sc->sc_omp, sc->sc_omlen);
   2065 		sc->sc_cmdlen = 0;
   2066 		NCRCMD(sc, NCRCMD_TRANS);
   2067 	} else {
   2068 		/* (re)send the message */
   2069 		size = uimin(sc->sc_omlen, sc->sc_maxxfer);
   2070 		NCRDMA_SETUP(sc, &sc->sc_omp, &sc->sc_omlen, 0, &size);
   2071 		/* Program the SCSI counter */
   2072 		NCR_SET_COUNT(sc, size);
   2073 
   2074 		/* Load the count in and start the message-out transfer */
   2075 		NCRCMD(sc, NCRCMD_NOP | NCRCMD_DMA);
   2076 		NCRCMD(sc, NCRCMD_TRANS | NCRCMD_DMA);
   2077 		NCRDMA_GO(sc);
   2078 	}
   2079 }
   2080 
   2081 /*
   2082  * This is the most critical part of the driver, and has to know
   2083  * how to deal with *all* error conditions and phases from the SCSI
   2084  * bus. If there are no errors and the DMA was active, then call the
   2085  * DMA pseudo-interrupt handler. If this returns 1, then that was it
   2086  * and we can return from here without further processing.
   2087  *
   2088  * Most of this needs verifying.
   2089  */
   2090 int
   2091 ncr53c9x_intr(void *arg)
   2092 {
   2093 	struct ncr53c9x_softc *sc = arg;
   2094 	struct ncr53c9x_ecb *ecb;
   2095 	struct scsipi_periph *periph;
   2096 	struct ncr53c9x_tinfo *ti;
   2097 	size_t size;
   2098 	int nfifo;
   2099 
   2100 	NCR_INTS(("[ncr53c9x_intr: state %d]", sc->sc_state));
   2101 
   2102 	if (!NCRDMA_ISINTR(sc))
   2103 		return 0;
   2104 
   2105 	mutex_enter(&sc->sc_lock);
   2106 again:
   2107 	/* and what do the registers say... */
   2108 	ncr53c9x_readregs(sc);
   2109 
   2110 	sc->sc_intrcnt.ev_count++;
   2111 
   2112 	/*
   2113 	 * At the moment, only a SCSI Bus Reset or Illegal
   2114 	 * Command are classed as errors. A disconnect is a
   2115 	 * valid condition, and we let the code check is the
   2116 	 * "NCR_BUSFREE_OK" flag was set before declaring it
   2117 	 * and error.
   2118 	 *
   2119 	 * Also, the status register tells us about "Gross
   2120 	 * Errors" and "Parity errors". Only the Gross Error
   2121 	 * is really bad, and the parity errors are dealt
   2122 	 * with later
   2123 	 *
   2124 	 * TODO
   2125 	 *	If there are too many parity error, go to slow
   2126 	 *	cable mode ?
   2127 	 */
   2128 
   2129 	/* SCSI Reset */
   2130 	if ((sc->sc_espintr & NCRINTR_SBR) != 0) {
   2131 		if ((NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF) != 0) {
   2132 			NCRCMD(sc, NCRCMD_FLUSH);
   2133 			DELAY(1);
   2134 		}
   2135 		if (sc->sc_state != NCR_SBR) {
   2136 			printf("%s: SCSI bus reset\n",
   2137 			    device_xname(sc->sc_dev));
   2138 			ncr53c9x_init(sc, 0); /* Restart everything */
   2139 			goto out;
   2140 		}
   2141 #if 0
   2142 /*XXX*/		printf("<expected bus reset: "
   2143 		    "[intr %x, stat %x, step %d]>\n",
   2144 		    sc->sc_espintr, sc->sc_espstat, sc->sc_espstep);
   2145 #endif
   2146 		if (sc->sc_nexus != NULL)
   2147 			panic("%s: nexus in reset state",
   2148 			    device_xname(sc->sc_dev));
   2149 		goto sched;
   2150 	}
   2151 
   2152 	ecb = sc->sc_nexus;
   2153 
   2154 #define NCRINTR_ERR (NCRINTR_SBR|NCRINTR_ILL)
   2155 	if (sc->sc_espintr & NCRINTR_ERR ||
   2156 	    sc->sc_espstat & NCRSTAT_GE) {
   2157 
   2158 		if ((sc->sc_espstat & NCRSTAT_GE) != 0) {
   2159 			/* Gross Error; no target ? */
   2160 			if (NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF) {
   2161 				NCRCMD(sc, NCRCMD_FLUSH);
   2162 				DELAY(1);
   2163 			}
   2164 			if (sc->sc_state == NCR_CONNECTED ||
   2165 			    sc->sc_state == NCR_SELECTING) {
   2166 				ecb->xs->error = XS_TIMEOUT;
   2167 				ncr53c9x_done(sc, ecb);
   2168 			}
   2169 			goto out;
   2170 		}
   2171 
   2172 		if ((sc->sc_espintr & NCRINTR_ILL) != 0) {
   2173 			if ((sc->sc_flags & NCR_EXPECT_ILLCMD) != 0) {
   2174 				/*
   2175 				 * Eat away "Illegal command" interrupt
   2176 				 * on a ESP100 caused by a re-selection
   2177 				 * while we were trying to select
   2178 				 * another target.
   2179 				 */
   2180 #ifdef NCR53C9X_DEBUG
   2181 				printf("%s: ESP100 work-around activated\n",
   2182 					device_xname(sc->sc_dev));
   2183 #endif
   2184 				sc->sc_flags &= ~NCR_EXPECT_ILLCMD;
   2185 				goto out;
   2186 			}
   2187 			/* illegal command, out of sync ? */
   2188 			printf("%s: illegal command: 0x%x "
   2189 			    "(state %d, phase %x, prevphase %x)\n",
   2190 			    device_xname(sc->sc_dev), sc->sc_lastcmd,
   2191 			    sc->sc_state, sc->sc_phase, sc->sc_prevphase);
   2192 			if (NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF) {
   2193 				NCRCMD(sc, NCRCMD_FLUSH);
   2194 				DELAY(1);
   2195 			}
   2196 			ncr53c9x_init(sc, 1); /* Restart everything */
   2197 			goto out;
   2198 		}
   2199 	}
   2200 	sc->sc_flags &= ~NCR_EXPECT_ILLCMD;
   2201 
   2202 	/*
   2203 	 * Call if DMA is active.
   2204 	 *
   2205 	 * If DMA_INTR returns true, then maybe go 'round the loop
   2206 	 * again in case there is no more DMA queued, but a phase
   2207 	 * change is expected.
   2208 	 */
   2209 	if (NCRDMA_ISACTIVE(sc)) {
   2210 		int r = NCRDMA_INTR(sc);
   2211 		if (r == -1) {
   2212 			printf("%s: DMA error; resetting\n",
   2213 			    device_xname(sc->sc_dev));
   2214 			ncr53c9x_init(sc, 1);
   2215 			goto out;
   2216 		}
   2217 		/* If DMA active here, then go back to work... */
   2218 		if (NCRDMA_ISACTIVE(sc))
   2219 			goto out;
   2220 
   2221 		if ((sc->sc_espstat & NCRSTAT_TC) == 0) {
   2222 			/*
   2223 			 * DMA not completed.  If we can not find a
   2224 			 * acceptable explanation, print a diagnostic.
   2225 			 */
   2226 			if (sc->sc_state == NCR_SELECTING)
   2227 				/*
   2228 				 * This can happen if we are reselected
   2229 				 * while using DMA to select a target.
   2230 				 */
   2231 				/*void*/;
   2232 			else if (sc->sc_prevphase == MESSAGE_OUT_PHASE) {
   2233 				/*
   2234 				 * Our (multi-byte) message (eg SDTR) was
   2235 				 * interrupted by the target to send
   2236 				 * a MSG REJECT.
   2237 				 * Print diagnostic if current phase
   2238 				 * is not MESSAGE IN.
   2239 				 */
   2240 				if (sc->sc_phase != MESSAGE_IN_PHASE)
   2241 					printf("%s: !TC on MSG OUT"
   2242 					    " [intr %x, stat %x, step %d]"
   2243 					    " prevphase %x, resid %lx\n",
   2244 					    device_xname(sc->sc_dev),
   2245 					    sc->sc_espintr,
   2246 					    sc->sc_espstat,
   2247 					    sc->sc_espstep,
   2248 					    sc->sc_prevphase,
   2249 					    (u_long)sc->sc_omlen);
   2250 			} else if (sc->sc_dleft == 0) {
   2251 				/*
   2252 				 * The DMA operation was started for
   2253 				 * a DATA transfer. Print a diagnostic
   2254 				 * if the DMA counter and TC bit
   2255 				 * appear to be out of sync.
   2256 				 */
   2257 				printf("%s: !TC on DATA XFER"
   2258 				    " [intr %x, stat %x, step %d]"
   2259 				    " prevphase %x, resid %x\n",
   2260 				    device_xname(sc->sc_dev),
   2261 				    sc->sc_espintr,
   2262 				    sc->sc_espstat,
   2263 				    sc->sc_espstep,
   2264 				    sc->sc_prevphase,
   2265 				    ecb ? ecb->dleft : -1);
   2266 			}
   2267 		}
   2268 	}
   2269 
   2270 	/*
   2271 	 * Check for less serious errors.
   2272 	 */
   2273 	if ((sc->sc_espstat & NCRSTAT_PE) != 0) {
   2274 		printf("%s: SCSI bus parity error\n", device_xname(sc->sc_dev));
   2275 		if (sc->sc_prevphase == MESSAGE_IN_PHASE)
   2276 			ncr53c9x_sched_msgout(SEND_PARITY_ERROR);
   2277 		else
   2278 			ncr53c9x_sched_msgout(SEND_INIT_DET_ERR);
   2279 	}
   2280 
   2281 	if ((sc->sc_espintr & NCRINTR_DIS) != 0) {
   2282 		sc->sc_msgify = 0;
   2283 		NCR_INTS(("<DISC [intr %x, stat %x, step %d]>",
   2284 		    sc->sc_espintr,sc->sc_espstat,sc->sc_espstep));
   2285 		if (NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF) {
   2286 			NCRCMD(sc, NCRCMD_FLUSH);
   2287 #if 0
   2288 			DELAY(1);
   2289 #endif
   2290 		}
   2291 		/*
   2292 		 * This command must (apparently) be issued within
   2293 		 * 250mS of a disconnect. So here you are...
   2294 		 */
   2295 		NCRCMD(sc, NCRCMD_ENSEL);
   2296 
   2297 		switch (sc->sc_state) {
   2298 		case NCR_RESELECTED:
   2299 			goto sched;
   2300 
   2301 		case NCR_SELECTING:
   2302 		{
   2303 			struct ncr53c9x_linfo *li;
   2304 
   2305 			ecb->xs->error = XS_SELTIMEOUT;
   2306 
   2307 			/* Selection timeout -- discard all LUNs if empty */
   2308 			periph = ecb->xs->xs_periph;
   2309 			ti = &sc->sc_tinfo[periph->periph_target];
   2310 			li = LIST_FIRST(&ti->luns);
   2311 			while (li != NULL) {
   2312 				if (li->untagged == NULL && li->used == 0) {
   2313 					if (li->lun < NCR_NLUN)
   2314 						ti->lun[li->lun] = NULL;
   2315 					LIST_REMOVE(li, link);
   2316 					free(li, M_DEVBUF);
   2317 					/*
   2318 					 * Restart the search at the beginning
   2319 					 */
   2320 					li = LIST_FIRST(&ti->luns);
   2321 					continue;
   2322 				}
   2323 				li = LIST_NEXT(li, link);
   2324 			}
   2325 			goto finish;
   2326 		}
   2327 		case NCR_CONNECTED:
   2328 			if ((sc->sc_flags & NCR_SYNCHNEGO) != 0) {
   2329 #ifdef NCR53C9X_DEBUG
   2330 				if (ecb != NULL)
   2331 					scsipi_printaddr(ecb->xs->xs_periph);
   2332 				printf("sync nego not completed!\n");
   2333 #endif
   2334 				ti = &sc->sc_tinfo[
   2335 				    ecb->xs->xs_periph->periph_target];
   2336 				sc->sc_flags &= ~NCR_SYNCHNEGO;
   2337 				ti->flags &= ~(T_NEGOTIATE | T_SYNCMODE);
   2338 			}
   2339 
   2340 			/* it may be OK to disconnect */
   2341 			if ((sc->sc_flags & NCR_ABORTING) == 0) {
   2342 				/*
   2343 				 * Section 5.1.1 of the SCSI 2 spec
   2344 				 * suggests issuing a REQUEST SENSE
   2345 				 * following an unexpected disconnect.
   2346 				 * Some devices go into a contingent
   2347 				 * allegiance condition when
   2348 				 * disconnecting, and this is necessary
   2349 				 * to clean up their state.
   2350 				 */
   2351 				printf("%s: unexpected disconnect "
   2352 			"[state %d, intr %x, stat %x, phase(c %x, p %x)]; ",
   2353 					device_xname(sc->sc_dev), sc->sc_state,
   2354 					sc->sc_espintr, sc->sc_espstat,
   2355 					sc->sc_phase, sc->sc_prevphase);
   2356 
   2357 				if ((ecb->flags & ECB_SENSE) != 0) {
   2358 					printf("resetting\n");
   2359 					goto reset;
   2360 				}
   2361 				printf("sending REQUEST SENSE\n");
   2362 				callout_stop(&ecb->xs->xs_callout);
   2363 				ncr53c9x_sense(sc, ecb);
   2364 				goto out;
   2365 			}
   2366 
   2367 			ecb->xs->error = XS_TIMEOUT;
   2368 			goto finish;
   2369 
   2370 		case NCR_DISCONNECT:
   2371 			sc->sc_nexus = NULL;
   2372 			goto sched;
   2373 
   2374 		case NCR_CMDCOMPLETE:
   2375 			goto finish;
   2376 		}
   2377 	}
   2378 
   2379 	switch (sc->sc_state) {
   2380 
   2381 	case NCR_SBR:
   2382 		printf("%s: waiting for SCSI Bus Reset to happen\n",
   2383 		    device_xname(sc->sc_dev));
   2384 		goto out;
   2385 
   2386 	case NCR_RESELECTED:
   2387 		/*
   2388 		 * we must be continuing a message ?
   2389 		 */
   2390 		printf("%s: unhandled reselect continuation, "
   2391 		    "state %d, intr %02x\n",
   2392 		    device_xname(sc->sc_dev), sc->sc_state, sc->sc_espintr);
   2393 		ncr53c9x_init(sc, 1);
   2394 		goto out;
   2395 
   2396 	case NCR_IDENTIFIED:
   2397 		ecb = sc->sc_nexus;
   2398 		if (sc->sc_phase != MESSAGE_IN_PHASE) {
   2399 			int i = (NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF);
   2400 			/*
   2401 			 * Things are seriously screwed up.
   2402 			 * Pull the brakes, i.e. reset
   2403 			 */
   2404 			printf("%s: target didn't send tag: %d bytes in fifo\n",
   2405 			    device_xname(sc->sc_dev), i);
   2406 			/* Drain and display fifo */
   2407 			while (i-- > 0)
   2408 				printf("[%d] ", NCR_READ_REG(sc, NCR_FIFO));
   2409 
   2410 			ncr53c9x_init(sc, 1);
   2411 			goto out;
   2412 		} else
   2413 			goto msgin;
   2414 
   2415 	case NCR_IDLE:
   2416 	case NCR_SELECTING:
   2417 		ecb = sc->sc_nexus;
   2418 		if (sc->sc_espintr & NCRINTR_RESEL) {
   2419 			sc->sc_msgpriq = sc->sc_msgout = sc->sc_msgoutq = 0;
   2420 			sc->sc_flags = 0;
   2421 			/*
   2422 			 * If we're trying to select a
   2423 			 * target ourselves, push our command
   2424 			 * back into the ready list.
   2425 			 */
   2426 			if (sc->sc_state == NCR_SELECTING) {
   2427 				NCR_INTS(("backoff selector "));
   2428 				callout_stop(&ecb->xs->xs_callout);
   2429 				ncr53c9x_dequeue(sc, ecb);
   2430 				TAILQ_INSERT_HEAD(&sc->ready_list, ecb, chain);
   2431 				ecb->flags |= ECB_READY;
   2432 				ecb = sc->sc_nexus = NULL;
   2433 			}
   2434 			sc->sc_state = NCR_RESELECTED;
   2435 			if (sc->sc_phase != MESSAGE_IN_PHASE) {
   2436 				/*
   2437 				 * Things are seriously screwed up.
   2438 				 * Pull the brakes, i.e. reset
   2439 				 */
   2440 				printf("%s: target didn't identify\n",
   2441 				    device_xname(sc->sc_dev));
   2442 				ncr53c9x_init(sc, 1);
   2443 				goto out;
   2444 			}
   2445 			/*
   2446 			 * The C90 only inhibits FIFO writes until reselection
   2447 			 * is complete, instead of waiting until the interrupt
   2448 			 * status register has been read.  So, if the reselect
   2449 			 * happens while we were entering command bytes (for
   2450 			 * another target) some of those bytes can appear in
   2451 			 * the FIFO here, after the interrupt is taken.
   2452 			 *
   2453 			 * To remedy this situation, pull the Selection ID
   2454 			 * and Identify message from the FIFO directly, and
   2455 			 * ignore any extraneous fifo contents. Also, set
   2456 			 * a flag that allows one Illegal Command Interrupt
   2457 			 * to occur which the chip also generates as a result
   2458 			 * of writing to the FIFO during a reselect.
   2459 			 */
   2460 			if (sc->sc_rev == NCR_VARIANT_ESP100) {
   2461 				nfifo = NCR_READ_REG(sc, NCR_FFLAG) &
   2462 				    NCRFIFO_FF;
   2463 				sc->sc_imess[0] = NCR_READ_REG(sc, NCR_FIFO);
   2464 				sc->sc_imess[1] = NCR_READ_REG(sc, NCR_FIFO);
   2465 				sc->sc_imlen = 2;
   2466 				if (nfifo != 2) {
   2467 					/* Flush the rest */
   2468 					NCRCMD(sc, NCRCMD_FLUSH);
   2469 				}
   2470 				sc->sc_flags |= NCR_EXPECT_ILLCMD;
   2471 				if (nfifo > 2)
   2472 					nfifo = 2; /* We fixed it.. */
   2473 			} else
   2474 				nfifo = ncr53c9x_rdfifo(sc, NCR_RDFIFO_START);
   2475 
   2476 			if (nfifo != 2) {
   2477 				printf("%s: RESELECT: %d bytes in FIFO! "
   2478 				    "[intr %x, stat %x, step %d, "
   2479 				    "prevphase %x]\n",
   2480 				    device_xname(sc->sc_dev),
   2481 				    nfifo,
   2482 				    sc->sc_espintr,
   2483 				    sc->sc_espstat,
   2484 				    sc->sc_espstep,
   2485 				    sc->sc_prevphase);
   2486 				ncr53c9x_init(sc, 1);
   2487 				goto out;
   2488 			}
   2489 			sc->sc_selid = sc->sc_imess[0];
   2490 			NCR_INTS(("selid=%02x ", sc->sc_selid));
   2491 
   2492 			/* Handle identify message */
   2493 			ncr53c9x_msgin(sc);
   2494 
   2495 			if (sc->sc_state != NCR_CONNECTED &&
   2496 			    sc->sc_state != NCR_IDENTIFIED) {
   2497 				/* IDENTIFY fail?! */
   2498 				printf("%s: identify failed, "
   2499 				    "state %d, intr %02x\n",
   2500 				    device_xname(sc->sc_dev),
   2501 				    sc->sc_state, sc->sc_espintr);
   2502 				ncr53c9x_init(sc, 1);
   2503 				goto out;
   2504 			}
   2505 			goto shortcut; /* ie. next phase expected soon */
   2506 		}
   2507 
   2508 #define	NCRINTR_DONE	(NCRINTR_FC | NCRINTR_BS)
   2509 		if ((sc->sc_espintr & NCRINTR_DONE) == NCRINTR_DONE) {
   2510 			/*
   2511 			 * Arbitration won; examine the `step' register
   2512 			 * to determine how far the selection could progress.
   2513 			 */
   2514 			ecb = sc->sc_nexus;
   2515 			if (ecb == NULL)
   2516 				panic("%s: no nexus", __func__);
   2517 
   2518 			periph = ecb->xs->xs_periph;
   2519 			ti = &sc->sc_tinfo[periph->periph_target];
   2520 
   2521 			switch (sc->sc_espstep) {
   2522 			case 0:
   2523 				/*
   2524 				 * The target did not respond with a
   2525 				 * message out phase - probably an old
   2526 				 * device that doesn't recognize ATN.
   2527 				 * Clear ATN and just continue, the
   2528 				 * target should be in the command
   2529 				 * phase.
   2530 				 * XXXX check for command phase?
   2531 				 */
   2532 				NCRCMD(sc, NCRCMD_RSTATN);
   2533 				break;
   2534 			case 1:
   2535 				if ((ti->flags & T_NEGOTIATE) == 0 &&
   2536 				    ecb->tag[0] == 0) {
   2537 					printf("%s: step 1 & !NEG\n",
   2538 					    device_xname(sc->sc_dev));
   2539 					goto reset;
   2540 				}
   2541 				if (sc->sc_phase != MESSAGE_OUT_PHASE) {
   2542 					printf("%s: !MSGOUT\n",
   2543 					    device_xname(sc->sc_dev));
   2544 					goto reset;
   2545 				}
   2546 				if (ti->flags & T_WIDE) {
   2547 					ti->flags |= T_WDTRSENT;
   2548 					ncr53c9x_sched_msgout(SEND_WDTR);
   2549 				}
   2550 				if (ti->flags & T_NEGOTIATE) {
   2551 					/* Start negotiating */
   2552 					ti->period = sc->sc_minsync;
   2553 					ti->offset = 15;
   2554 					sc->sc_flags |= NCR_SYNCHNEGO;
   2555 					if (ecb->tag[0])
   2556 						ncr53c9x_sched_msgout(
   2557 						    SEND_TAG | SEND_SDTR);
   2558 					else
   2559 						ncr53c9x_sched_msgout(
   2560 						    SEND_SDTR);
   2561 				} else {
   2562 					/* Could not do ATN3 so send TAG */
   2563 					ncr53c9x_sched_msgout(SEND_TAG);
   2564 				}
   2565 				sc->sc_prevphase = MESSAGE_OUT_PHASE; /* XXXX */
   2566 				break;
   2567 			case 3:
   2568 				/*
   2569 				 * Grr, this is supposed to mean
   2570 				 * "target left command phase  prematurely".
   2571 				 * It seems to happen regularly when
   2572 				 * sync mode is on.
   2573 				 * Look at FIFO to see if command went out.
   2574 				 * (Timing problems?)
   2575 				 */
   2576 				if (sc->sc_features & NCR_F_DMASELECT) {
   2577 					if (sc->sc_cmdlen == 0)
   2578 						/* Hope for the best.. */
   2579 						break;
   2580 				} else if ((NCR_READ_REG(sc, NCR_FFLAG)
   2581 				    & NCRFIFO_FF) == 0) {
   2582 					/* Hope for the best.. */
   2583 					break;
   2584 				}
   2585 				printf("(%s:%d:%d): selection failed;"
   2586 				    " %d left in FIFO "
   2587 				    "[intr %x, stat %x, step %d]\n",
   2588 				    device_xname(sc->sc_dev),
   2589 				    periph->periph_target,
   2590 				    periph->periph_lun,
   2591 				    NCR_READ_REG(sc, NCR_FFLAG)
   2592 				     & NCRFIFO_FF,
   2593 				    sc->sc_espintr, sc->sc_espstat,
   2594 				    sc->sc_espstep);
   2595 				NCRCMD(sc, NCRCMD_FLUSH);
   2596 				ncr53c9x_sched_msgout(SEND_ABORT);
   2597 				goto out;
   2598 			case 2:
   2599 				/* Select stuck at Command Phase */
   2600 				NCRCMD(sc, NCRCMD_FLUSH);
   2601 				break;
   2602 			case 4:
   2603 				if (sc->sc_features & NCR_F_DMASELECT &&
   2604 				    sc->sc_cmdlen != 0)
   2605 					printf("(%s:%d:%d): select; "
   2606 					    "%lu left in DMA buffer "
   2607 					    "[intr %x, stat %x, step %d]\n",
   2608 					    device_xname(sc->sc_dev),
   2609 					    periph->periph_target,
   2610 					    periph->periph_lun,
   2611 					    (u_long)sc->sc_cmdlen,
   2612 					    sc->sc_espintr,
   2613 					    sc->sc_espstat,
   2614 					    sc->sc_espstep);
   2615 				/* So far, everything went fine */
   2616 				break;
   2617 			}
   2618 
   2619 			sc->sc_prevphase = INVALID_PHASE; /* ?? */
   2620 			/* Do an implicit RESTORE POINTERS. */
   2621 			sc->sc_dp = ecb->daddr;
   2622 			sc->sc_dleft = ecb->dleft;
   2623 			sc->sc_state = NCR_CONNECTED;
   2624 			break;
   2625 
   2626 		} else {
   2627 
   2628 			printf("%s: unexpected status after select"
   2629 			    ": [intr %x, stat %x, step %x]\n",
   2630 			    device_xname(sc->sc_dev),
   2631 			    sc->sc_espintr, sc->sc_espstat, sc->sc_espstep);
   2632 			NCRCMD(sc, NCRCMD_FLUSH);
   2633 			DELAY(1);
   2634 			goto reset;
   2635 		}
   2636 		if (sc->sc_state == NCR_IDLE) {
   2637 			printf("%s: stray interrupt\n",
   2638 			    device_xname(sc->sc_dev));
   2639 			mutex_exit(&sc->sc_lock);
   2640 			return 0;
   2641 		}
   2642 		break;
   2643 
   2644 	case NCR_CONNECTED:
   2645 		if ((sc->sc_flags & NCR_ICCS) != 0) {
   2646 			/* "Initiate Command Complete Steps" in progress */
   2647 			uint8_t msg;
   2648 
   2649 			sc->sc_flags &= ~NCR_ICCS;
   2650 
   2651 			if ((sc->sc_espintr & NCRINTR_DONE) == 0) {
   2652 				printf("%s: ICCS: "
   2653 				    ": [intr %x, stat %x, step %x]\n",
   2654 				    device_xname(sc->sc_dev),
   2655 				    sc->sc_espintr, sc->sc_espstat,
   2656 				    sc->sc_espstep);
   2657 			}
   2658 			ncr53c9x_rdfifo(sc, NCR_RDFIFO_START);
   2659 			if (sc->sc_imlen < 2)
   2660 				printf("%s: can't get status, only %d bytes\n",
   2661 				    device_xname(sc->sc_dev),
   2662 				    (int)sc->sc_imlen);
   2663 			ecb->stat = sc->sc_imess[sc->sc_imlen - 2];
   2664 			msg = sc->sc_imess[sc->sc_imlen - 1];
   2665 			NCR_PHASE(("<stat:(%x,%x)>", ecb->stat, msg));
   2666 			if (msg == MSG_CMDCOMPLETE) {
   2667 				ecb->dleft = (ecb->flags & ECB_TENTATIVE_DONE)
   2668 				    ? 0 : sc->sc_dleft;
   2669 				if ((ecb->flags & ECB_SENSE) == 0)
   2670 					ecb->xs->resid = ecb->dleft;
   2671 				sc->sc_state = NCR_CMDCOMPLETE;
   2672 			} else
   2673 				printf("%s: STATUS_PHASE: msg %d\n",
   2674 				    device_xname(sc->sc_dev), msg);
   2675 			sc->sc_imlen = 0;
   2676 			NCRCMD(sc, NCRCMD_MSGOK);
   2677 			goto shortcut; /* ie. wait for disconnect */
   2678 		}
   2679 		break;
   2680 
   2681 	default:
   2682 		printf("%s: invalid state: %d [intr %x, phase(c %x, p %x)]\n",
   2683 			device_xname(sc->sc_dev), sc->sc_state,
   2684 			sc->sc_espintr, sc->sc_phase, sc->sc_prevphase);
   2685 		goto reset;
   2686 	}
   2687 
   2688 	/*
   2689 	 * Driver is now in state NCR_CONNECTED, i.e. we
   2690 	 * have a current command working the SCSI bus.
   2691 	 */
   2692 	if (sc->sc_state != NCR_CONNECTED || ecb == NULL) {
   2693 		panic("%s: no nexus", __func__);
   2694 	}
   2695 
   2696 	switch (sc->sc_phase) {
   2697 	case MESSAGE_OUT_PHASE:
   2698 		NCR_PHASE(("MESSAGE_OUT_PHASE "));
   2699 		ncr53c9x_msgout(sc);
   2700 		sc->sc_prevphase = MESSAGE_OUT_PHASE;
   2701 		break;
   2702 
   2703 	case MESSAGE_IN_PHASE:
   2704 msgin:
   2705 		NCR_PHASE(("MESSAGE_IN_PHASE "));
   2706 		if ((sc->sc_espintr & NCRINTR_BS) != 0) {
   2707 			if ((sc->sc_rev != NCR_VARIANT_FAS366) ||
   2708 			    (sc->sc_espstat2 & NCRFAS_STAT2_EMPTY) == 0) {
   2709 				NCRCMD(sc, NCRCMD_FLUSH);
   2710 			}
   2711 			sc->sc_flags |= NCR_WAITI;
   2712 			NCRCMD(sc, NCRCMD_TRANS);
   2713 		} else if ((sc->sc_espintr & NCRINTR_FC) != 0) {
   2714 			if ((sc->sc_flags & NCR_WAITI) == 0) {
   2715 				printf("%s: MSGIN: unexpected FC bit: "
   2716 				    "[intr %x, stat %x, step %x]\n",
   2717 				    device_xname(sc->sc_dev),
   2718 				    sc->sc_espintr, sc->sc_espstat,
   2719 				    sc->sc_espstep);
   2720 			}
   2721 			sc->sc_flags &= ~NCR_WAITI;
   2722 			ncr53c9x_rdfifo(sc,
   2723 			    (sc->sc_prevphase == sc->sc_phase) ?
   2724 			    NCR_RDFIFO_CONTINUE : NCR_RDFIFO_START);
   2725 			ncr53c9x_msgin(sc);
   2726 		} else {
   2727 			printf("%s: MSGIN: weird bits: "
   2728 			    "[intr %x, stat %x, step %x]\n",
   2729 			    device_xname(sc->sc_dev),
   2730 			    sc->sc_espintr, sc->sc_espstat, sc->sc_espstep);
   2731 		}
   2732 		sc->sc_prevphase = MESSAGE_IN_PHASE;
   2733 		goto shortcut;	/* i.e. expect data to be ready */
   2734 
   2735 	case COMMAND_PHASE:
   2736 		/*
   2737 		 * Send the command block. Normally we don't see this
   2738 		 * phase because the SEL_ATN command takes care of
   2739 		 * all this. However, we end up here if either the
   2740 		 * target or we wanted to exchange some more messages
   2741 		 * first (e.g. to start negotiations).
   2742 		 */
   2743 
   2744 		NCR_PHASE(("COMMAND_PHASE 0x%02x (%d) ",
   2745 		    ecb->cmd.cmd.opcode, ecb->clen));
   2746 		if (NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF) {
   2747 			NCRCMD(sc, NCRCMD_FLUSH);
   2748 #if 0
   2749 			DELAY(1);
   2750 #endif
   2751 		}
   2752 		if (sc->sc_features & NCR_F_DMASELECT) {
   2753 			/* setup DMA transfer for command */
   2754 			size = ecb->clen;
   2755 			sc->sc_cmdlen = size;
   2756 			sc->sc_cmdp = (void *)&ecb->cmd.cmd;
   2757 			NCRDMA_SETUP(sc, &sc->sc_cmdp, &sc->sc_cmdlen,
   2758 			    0, &size);
   2759 			/* Program the SCSI counter */
   2760 			NCR_SET_COUNT(sc, size);
   2761 
   2762 			/* load the count in */
   2763 			NCRCMD(sc, NCRCMD_NOP | NCRCMD_DMA);
   2764 
   2765 			/* start the command transfer */
   2766 			NCRCMD(sc, NCRCMD_TRANS | NCRCMD_DMA);
   2767 			NCRDMA_GO(sc);
   2768 		} else {
   2769 			ncr53c9x_wrfifo(sc, (uint8_t *)&ecb->cmd.cmd,
   2770 			    ecb->clen);
   2771 			sc->sc_cmdlen = 0;
   2772 			NCRCMD(sc, NCRCMD_TRANS);
   2773 		}
   2774 		sc->sc_prevphase = COMMAND_PHASE;
   2775 		break;
   2776 
   2777 	case DATA_OUT_PHASE:
   2778 		NCR_PHASE(("DATA_OUT_PHASE [%ld] ",(long)sc->sc_dleft));
   2779 		NCRCMD(sc, NCRCMD_FLUSH);
   2780 		size = uimin(sc->sc_dleft, sc->sc_maxxfer);
   2781 		NCRDMA_SETUP(sc, &sc->sc_dp, &sc->sc_dleft, 0, &size);
   2782 		sc->sc_prevphase = DATA_OUT_PHASE;
   2783 		goto setup_xfer;
   2784 
   2785 	case DATA_IN_PHASE:
   2786 		NCR_PHASE(("DATA_IN_PHASE "));
   2787 		if (sc->sc_rev == NCR_VARIANT_ESP100)
   2788 			NCRCMD(sc, NCRCMD_FLUSH);
   2789 		size = uimin(sc->sc_dleft, sc->sc_maxxfer);
   2790 		NCRDMA_SETUP(sc, &sc->sc_dp, &sc->sc_dleft, 1, &size);
   2791 		sc->sc_prevphase = DATA_IN_PHASE;
   2792 	setup_xfer:
   2793 		/* Target returned to data phase: wipe "done" memory */
   2794 		ecb->flags &= ~ECB_TENTATIVE_DONE;
   2795 
   2796 		/* Program the SCSI counter */
   2797 		NCR_SET_COUNT(sc, size);
   2798 
   2799 		/* load the count in */
   2800 		NCRCMD(sc, NCRCMD_NOP | NCRCMD_DMA);
   2801 
   2802 		/*
   2803 		 * Note that if `size' is 0, we've already transceived
   2804 		 * all the bytes we want but we're still in DATA PHASE.
   2805 		 * Apparently, the device needs padding. Also, a
   2806 		 * transfer size of 0 means "maximum" to the chip
   2807 		 * DMA logic.
   2808 		 */
   2809 		NCRCMD(sc,
   2810 		    (size == 0 ? NCRCMD_TRPAD : NCRCMD_TRANS) | NCRCMD_DMA);
   2811 		NCRDMA_GO(sc);
   2812 		goto out;
   2813 
   2814 	case STATUS_PHASE:
   2815 		NCR_PHASE(("STATUS_PHASE "));
   2816 		sc->sc_flags |= NCR_ICCS;
   2817 		NCRCMD(sc, NCRCMD_ICCS);
   2818 		sc->sc_prevphase = STATUS_PHASE;
   2819 		goto shortcut;	/* i.e. expect status results soon */
   2820 
   2821 	case INVALID_PHASE:
   2822 		break;
   2823 
   2824 	default:
   2825 		printf("%s: unexpected bus phase; resetting\n",
   2826 		    device_xname(sc->sc_dev));
   2827 		goto reset;
   2828 	}
   2829 
   2830 out:
   2831 	mutex_exit(&sc->sc_lock);
   2832 	return 1;
   2833 
   2834 reset:
   2835 	ncr53c9x_init(sc, 1);
   2836 	goto out;
   2837 
   2838 finish:
   2839 	ncr53c9x_done(sc, ecb);
   2840 	goto out;
   2841 
   2842 sched:
   2843 	sc->sc_state = NCR_IDLE;
   2844 	ncr53c9x_sched(sc);
   2845 	goto out;
   2846 
   2847 shortcut:
   2848 	/*
   2849 	 * The idea is that many of the SCSI operations take very little
   2850 	 * time, and going away and getting interrupted is too high an
   2851 	 * overhead to pay. For example, selecting, sending a message
   2852 	 * and command and then doing some work can be done in one "pass".
   2853 	 *
   2854 	 * The delay is a heuristic. It is 2 when at 20MHz, 2 at 25MHz and 1
   2855 	 * at 40MHz. This needs testing.
   2856 	 */
   2857 	{
   2858 		struct timeval wait, cur;
   2859 
   2860 		microtime(&wait);
   2861 		wait.tv_usec += 50 / sc->sc_freq;
   2862 		if (wait.tv_usec > 1000000) {
   2863 			wait.tv_sec++;
   2864 			wait.tv_usec -= 1000000;
   2865 		}
   2866 		do {
   2867 			if (NCRDMA_ISINTR(sc))
   2868 				goto again;
   2869 			microtime(&cur);
   2870 		} while (timercmp(&cur, &wait, <=));
   2871 	}
   2872 	goto out;
   2873 }
   2874 
   2875 void
   2876 ncr53c9x_abort(struct ncr53c9x_softc *sc, struct ncr53c9x_ecb *ecb)
   2877 {
   2878 
   2879 	/* 2 secs for the abort */
   2880 	ecb->timeout = NCR_ABORT_TIMEOUT;
   2881 	ecb->flags |= ECB_ABORT;
   2882 
   2883 	if (ecb == sc->sc_nexus) {
   2884 		/*
   2885 		 * If we're still selecting, the message will be scheduled
   2886 		 * after selection is complete.
   2887 		 */
   2888 		if (sc->sc_state == NCR_CONNECTED)
   2889 			ncr53c9x_sched_msgout(SEND_ABORT);
   2890 
   2891 		/*
   2892 		 * Reschedule timeout.
   2893 		 */
   2894 		callout_reset(&ecb->xs->xs_callout, mstohz(ecb->timeout),
   2895 		    ncr53c9x_timeout, ecb);
   2896 	} else {
   2897 		/*
   2898 		 * Just leave the command where it is.
   2899 		 * XXX - what choice do we have but to reset the SCSI
   2900 		 *	 eventually?
   2901 		 */
   2902 		if (sc->sc_state == NCR_IDLE)
   2903 			ncr53c9x_sched(sc);
   2904 	}
   2905 }
   2906 
   2907 void
   2908 ncr53c9x_timeout(void *arg)
   2909 {
   2910 	struct ncr53c9x_ecb *ecb = arg;
   2911 	struct scsipi_xfer *xs = ecb->xs;
   2912 	struct scsipi_periph *periph = xs->xs_periph;
   2913 	struct ncr53c9x_softc *sc;
   2914 	struct ncr53c9x_tinfo *ti;
   2915 
   2916 	sc = device_private(periph->periph_channel->chan_adapter->adapt_dev);
   2917 	ti = &sc->sc_tinfo[periph->periph_target];
   2918 
   2919 	scsipi_printaddr(periph);
   2920 	printf("%s: timed out [ecb %p (flags 0x%x, dleft %x, stat %x)], "
   2921 	    "<state %d, nexus %p, phase(l %x, c %x, p %x), resid %lx, "
   2922 	    "msg(q %x,o %x) %s>",
   2923 	    device_xname(sc->sc_dev),
   2924 	    ecb, ecb->flags, ecb->dleft, ecb->stat,
   2925 	    sc->sc_state, sc->sc_nexus,
   2926 	    NCR_READ_REG(sc, NCR_STAT),
   2927 	    sc->sc_phase, sc->sc_prevphase,
   2928 	    (long)sc->sc_dleft, sc->sc_msgpriq, sc->sc_msgout,
   2929 	    NCRDMA_ISACTIVE(sc) ? "DMA active" : "");
   2930 #if NCR53C9X_DEBUG > 1
   2931 	printf("TRACE: %s.", ecb->trace);
   2932 #endif
   2933 
   2934 	mutex_enter(&sc->sc_lock);
   2935 
   2936 	if (ecb->flags & ECB_ABORT) {
   2937 		/* abort timed out */
   2938 		printf(" AGAIN\n");
   2939 
   2940 		ncr53c9x_init(sc, 1);
   2941 	} else {
   2942 		/* abort the operation that has timed out */
   2943 		printf("\n");
   2944 		xs->error = XS_TIMEOUT;
   2945 		ncr53c9x_abort(sc, ecb);
   2946 
   2947 		/* Disable sync mode if stuck in a data phase */
   2948 		if (ecb == sc->sc_nexus &&
   2949 		    (ti->flags & T_SYNCMODE) != 0 &&
   2950 		    (sc->sc_phase & (MSGI | CDI)) == 0) {
   2951 			/* XXX ASYNC CALLBACK! */
   2952 			scsipi_printaddr(periph);
   2953 			printf("sync negotiation disabled\n");
   2954 			sc->sc_cfflags |=
   2955 			    (1 << ((periph->periph_target & 7) + 8));
   2956 			ncr53c9x_update_xfer_mode(sc, periph->periph_target);
   2957 		}
   2958 	}
   2959 
   2960 	mutex_exit(&sc->sc_lock);
   2961 }
   2962 
   2963 void
   2964 ncr53c9x_watch(void *arg)
   2965 {
   2966 	struct ncr53c9x_softc *sc = arg;
   2967 	struct ncr53c9x_tinfo *ti;
   2968 	struct ncr53c9x_linfo *li;
   2969 	int t;
   2970 	/* Delete any structures that have not been used in 10min. */
   2971 	time_t old = time_second - (10 * 60);
   2972 
   2973 	mutex_enter(&sc->sc_lock);
   2974 	for (t = 0; t < sc->sc_ntarg; t++) {
   2975 		ti = &sc->sc_tinfo[t];
   2976 		li = LIST_FIRST(&ti->luns);
   2977 		while (li) {
   2978 			if (li->last_used < old &&
   2979 			    li->untagged == NULL &&
   2980 			    li->used == 0) {
   2981 				if (li->lun < NCR_NLUN)
   2982 					ti->lun[li->lun] = NULL;
   2983 				LIST_REMOVE(li, link);
   2984 				free(li, M_DEVBUF);
   2985 				/* Restart the search at the beginning */
   2986 				li = LIST_FIRST(&ti->luns);
   2987 				continue;
   2988 			}
   2989 			li = LIST_NEXT(li, link);
   2990 		}
   2991 	}
   2992 	mutex_exit(&sc->sc_lock);
   2993 	callout_reset(&sc->sc_watchdog, 60 * hz, ncr53c9x_watch, sc);
   2994 }
   2995