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