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