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