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