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