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