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