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