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