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