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