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