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