]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - sys/dev/esp/ncr53c9x.c
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / sys / dev / esp / ncr53c9x.c
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.143 2011/07/31 18:39:00 jakllsch 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 *
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
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, %dMHz, 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          *              (timout 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
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
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
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
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
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
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
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
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
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                         sc->sc_cmdlen = 0;
895                         sc->sc_cmdp = NULL;
896                         goto cmd;
897                 }
898
899                 /* Program the SCSI counter. */
900                 NCR_SET_COUNT(sc, dmasize);
901
902                 /* Load the count in. */
903                 NCRCMD(sc, NCRCMD_NOP | NCRCMD_DMA);
904
905                 /* And get the target's attention. */
906                 if (selatn3) {
907                         sc->sc_msgout = SEND_TAG;
908                         sc->sc_flags |= NCR_ATN;
909                         NCRCMD(sc, NCRCMD_SELATN3 | NCRCMD_DMA);
910                 } else
911                         NCRCMD(sc, NCRCMD_SELATN | NCRCMD_DMA);
912                 NCRDMA_GO(sc);
913                 return;
914         }
915
916 cmd:
917         /*
918          * Who am I?  This is where we tell the target that we are
919          * happy for it to disconnect etc.
920          */
921
922         /* Now get the command into the FIFO. */
923         ncr53c9x_wrfifo(sc, cmd, clen);
924
925         /* And get the target's attention. */
926         if (selatns) {
927                 NCR_MSGS(("SELATNS \n"));
928                 /* Arbitrate, select and stop after IDENTIFY message. */
929                 NCRCMD(sc, NCRCMD_SELATNS);
930         } else if (selatn3) {
931                 sc->sc_msgout = SEND_TAG;
932                 sc->sc_flags |= NCR_ATN;
933                 NCRCMD(sc, NCRCMD_SELATN3);
934         } else
935                 NCRCMD(sc, NCRCMD_SELATN);
936 }
937
938 static void
939 ncr53c9x_free_ecb(struct ncr53c9x_softc *sc, struct ncr53c9x_ecb *ecb)
940 {
941
942         NCR_LOCK_ASSERT(sc, MA_OWNED);
943
944         ecb->flags = 0;
945         TAILQ_INSERT_TAIL(&sc->free_list, ecb, free_links);
946 }
947
948 static struct ncr53c9x_ecb *
949 ncr53c9x_get_ecb(struct ncr53c9x_softc *sc)
950 {
951         struct ncr53c9x_ecb *ecb;
952
953         NCR_LOCK_ASSERT(sc, MA_OWNED);
954
955         ecb = TAILQ_FIRST(&sc->free_list);
956         if (ecb) {
957                 if (ecb->flags != 0)
958                         panic("%s: ecb flags not cleared", __func__);
959                 TAILQ_REMOVE(&sc->free_list, ecb, free_links);
960                 ecb->flags = ECB_ALLOC;
961                 bzero(&ecb->ccb, sizeof(struct ncr53c9x_ecb) -
962                     offsetof(struct ncr53c9x_ecb, ccb));
963         }
964         return (ecb);
965 }
966
967 /*
968  * DRIVER FUNCTIONS CALLABLE FROM HIGHER LEVEL DRIVERS:
969  */
970
971 /*
972  * Start a SCSI-command.
973  * This function is called by the higher level SCSI-driver to queue/run
974  * SCSI-commands.
975  */
976
977 static void
978 ncr53c9x_action(struct cam_sim *sim, union ccb *ccb)
979 {
980         struct ccb_pathinq *cpi;
981         struct ccb_scsiio *csio;
982         struct ccb_trans_settings *cts;
983         struct ccb_trans_settings_scsi *scsi;
984         struct ccb_trans_settings_spi *spi;
985         struct ncr53c9x_ecb *ecb;
986         struct ncr53c9x_softc *sc;
987         struct ncr53c9x_tinfo *ti;
988         int target;
989
990         sc = cam_sim_softc(sim);
991
992         NCR_LOCK_ASSERT(sc, MA_OWNED);
993
994         NCR_TRACE(("[%s %d]", __func__, ccb->ccb_h.func_code));
995
996         switch (ccb->ccb_h.func_code) {
997         case XPT_RESET_BUS:
998                 ncr53c9x_init(sc, 1);
999                 ccb->ccb_h.status = CAM_REQ_CMP;
1000                 break;
1001
1002         case XPT_CALC_GEOMETRY:
1003                 cam_calc_geometry(&ccb->ccg, sc->sc_extended_geom);
1004                 break;
1005
1006         case XPT_PATH_INQ:
1007                 cpi = &ccb->cpi;
1008                 cpi->version_num = 1;
1009                 cpi->hba_inquiry = PI_SDTR_ABLE | PI_TAG_ABLE;
1010                 cpi->hba_inquiry |=
1011                     (sc->sc_rev == NCR_VARIANT_FAS366) ? PI_WIDE_16 : 0;
1012                 cpi->target_sprt = 0;
1013                 cpi->hba_misc = 0;
1014                 cpi->hba_eng_cnt = 0;
1015                 cpi->max_target = sc->sc_ntarg - 1;
1016                 cpi->max_lun = 7;
1017                 cpi->initiator_id = sc->sc_id;
1018                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
1019                 strncpy(cpi->hba_vid, "NCR", HBA_IDLEN);
1020                 strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
1021                 cpi->unit_number = cam_sim_unit(sim);
1022                 cpi->bus_id = 0;
1023                 cpi->base_transfer_speed = 3300;
1024                 cpi->protocol = PROTO_SCSI;
1025                 cpi->protocol_version = SCSI_REV_2;
1026                 cpi->transport = XPORT_SPI;
1027                 cpi->transport_version = 2;
1028                 cpi->maxio = sc->sc_maxxfer;
1029                 ccb->ccb_h.status = CAM_REQ_CMP;
1030                 break;
1031
1032         case XPT_GET_TRAN_SETTINGS:
1033                 cts = &ccb->cts;
1034                 ti = &sc->sc_tinfo[ccb->ccb_h.target_id];
1035                 scsi = &cts->proto_specific.scsi;
1036                 spi = &cts->xport_specific.spi;
1037
1038                 cts->protocol = PROTO_SCSI;
1039                 cts->protocol_version = SCSI_REV_2;
1040                 cts->transport = XPORT_SPI;
1041                 cts->transport_version = 2;
1042
1043                 if (cts->type == CTS_TYPE_CURRENT_SETTINGS) {
1044                         spi->sync_period = ti->curr.period;
1045                         spi->sync_offset = ti->curr.offset;
1046                         spi->bus_width = ti->curr.width;
1047                         if ((ti->flags & T_TAG) != 0) {
1048                                 spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
1049                                 scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
1050                         } else {
1051                                 spi->flags &= ~CTS_SPI_FLAGS_DISC_ENB;
1052                                 scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
1053                         }
1054                 } else {
1055                         if ((ti->flags & T_SYNCHOFF) != 0) {
1056                                 spi->sync_period = 0;
1057                                 spi->sync_offset = 0;
1058                         } else {
1059                                 spi->sync_period = sc->sc_minsync;
1060                                 spi->sync_offset = sc->sc_maxoffset;
1061                         }
1062                         spi->bus_width = sc->sc_maxwidth;
1063                         spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
1064                         scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
1065                 }
1066                 spi->valid =
1067                     CTS_SPI_VALID_BUS_WIDTH |
1068                     CTS_SPI_VALID_SYNC_RATE |
1069                     CTS_SPI_VALID_SYNC_OFFSET |
1070                     CTS_SPI_VALID_DISC;
1071                 scsi->valid = CTS_SCSI_VALID_TQ;
1072                 ccb->ccb_h.status = CAM_REQ_CMP;
1073                 break;
1074
1075         case XPT_ABORT:
1076                 device_printf(sc->sc_dev, "XPT_ABORT called\n");
1077                 ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
1078                 break;
1079
1080         case XPT_TERM_IO:
1081                 device_printf(sc->sc_dev, "XPT_TERM_IO called\n");
1082                 ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
1083                 break;
1084
1085         case XPT_RESET_DEV:
1086         case XPT_SCSI_IO:
1087                 if (ccb->ccb_h.target_id < 0 ||
1088                     ccb->ccb_h.target_id >= sc->sc_ntarg) {
1089                         ccb->ccb_h.status = CAM_PATH_INVALID;
1090                         goto done;
1091                 }
1092                 /* Get an ECB to use. */
1093                 ecb = ncr53c9x_get_ecb(sc);
1094                 /*
1095                  * This should never happen as we track resources
1096                  * in the mid-layer.
1097                  */
1098                 if (ecb == NULL) {
1099                         xpt_freeze_simq(sim, 1);
1100                         ccb->ccb_h.status = CAM_REQUEUE_REQ;
1101                         device_printf(sc->sc_dev, "unable to allocate ecb\n");
1102                         goto done;
1103                 }
1104
1105                 /* Initialize ecb. */
1106                 ecb->ccb = ccb;
1107                 ecb->timeout = ccb->ccb_h.timeout;
1108
1109                 if (ccb->ccb_h.func_code == XPT_RESET_DEV) {
1110                         ecb->flags |= ECB_RESET;
1111                         ecb->clen = 0;
1112                         ecb->dleft = 0;
1113                 } else {
1114                         csio = &ccb->csio;
1115                         if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0)
1116                                 bcopy(csio->cdb_io.cdb_ptr, &ecb->cmd.cmd,
1117                                     csio->cdb_len);
1118                         else
1119                                 bcopy(csio->cdb_io.cdb_bytes, &ecb->cmd.cmd,
1120                                     csio->cdb_len);
1121                         ecb->clen = csio->cdb_len;
1122                         ecb->daddr = csio->data_ptr;
1123                         ecb->dleft = csio->dxfer_len;
1124                 }
1125                 ecb->stat = 0;
1126
1127                 TAILQ_INSERT_TAIL(&sc->ready_list, ecb, chain);
1128                 ecb->flags |= ECB_READY;
1129                 if (sc->sc_state == NCR_IDLE)
1130                         ncr53c9x_sched(sc);
1131                 return;
1132
1133         case XPT_SET_TRAN_SETTINGS:
1134                 cts = &ccb->cts;
1135                 target = ccb->ccb_h.target_id;
1136                 ti = &sc->sc_tinfo[target];
1137                 scsi = &cts->proto_specific.scsi;
1138                 spi = &cts->xport_specific.spi;
1139
1140                 if ((scsi->valid & CTS_SCSI_VALID_TQ) != 0) {
1141                         if ((sc->sc_cfflags & (1<<((target & 7) + 16))) == 0 &&
1142                             (scsi->flags & CTS_SCSI_FLAGS_TAG_ENB)) {
1143                                 NCR_MISC(("%s: target %d: tagged queuing\n",
1144                                     device_get_nameunit(sc->sc_dev), target));
1145                                 ti->flags |= T_TAG;
1146                         } else
1147                                 ti->flags &= ~T_TAG;
1148                 }
1149
1150                 if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0) {
1151                         NCR_MISC(("%s: target %d: wide negotiation\n",
1152                             device_get_nameunit(sc->sc_dev), target));
1153                         ti->goal.width = spi->bus_width;
1154                 }
1155
1156                 if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) != 0) {
1157                         NCR_MISC(("%s: target %d: sync period negotiation\n",
1158                             device_get_nameunit(sc->sc_dev), target));
1159                         ti->goal.period = spi->sync_period;
1160                 }
1161
1162                 if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) != 0) {
1163                         NCR_MISC(("%s: target %d: sync offset negotiation\n",
1164                             device_get_nameunit(sc->sc_dev), target));
1165                         ti->goal.offset = spi->sync_offset;
1166                 }
1167
1168                 ccb->ccb_h.status = CAM_REQ_CMP;
1169                 break;
1170
1171         default:
1172                 device_printf(sc->sc_dev, "Unhandled function code %d\n",
1173                     ccb->ccb_h.func_code);
1174                 ccb->ccb_h.status = CAM_PROVIDE_FAIL;
1175         }
1176
1177 done:
1178         xpt_done(ccb);
1179 }
1180
1181 /*
1182  * Used when interrupt driven I/O is not allowed, e.g. during boot.
1183  */
1184 static void
1185 ncr53c9x_poll(struct cam_sim *sim)
1186 {
1187         struct ncr53c9x_softc *sc;
1188
1189         sc = cam_sim_softc(sim);
1190
1191         NCR_LOCK_ASSERT(sc, MA_OWNED);
1192
1193         NCR_TRACE(("[%s] ", __func__));
1194
1195         if (NCRDMA_ISINTR(sc))
1196                 ncr53c9x_intr1(sc);
1197 }
1198
1199 /*
1200  *  Asynchronous notification handler
1201  */
1202 static void
1203 ncr53c9x_async(void *cbarg, uint32_t code, struct cam_path *path, void *arg)
1204 {
1205         struct ncr53c9x_softc *sc;
1206         struct ncr53c9x_tinfo *ti;
1207         int target;
1208
1209         sc = cam_sim_softc(cbarg);
1210
1211         NCR_LOCK_ASSERT(sc, MA_OWNED);
1212
1213         switch (code) {
1214         case AC_LOST_DEVICE:
1215                 target = xpt_path_target_id(path);
1216                 if (target < 0 || target >= sc->sc_ntarg)
1217                         break;
1218
1219                 /* Cancel outstanding disconnected commands. */
1220                 ncr53c9x_clear_target(sc, target, CAM_REQ_ABORTED);
1221
1222                 /* Set the default parameters for the target. */
1223                 ti = &sc->sc_tinfo[target];
1224 /* XXX - config flags per target: low bits: no reselect; high bits: no synch */
1225                 ti->flags = ((sc->sc_minsync != 0 &&
1226                     (sc->sc_cfflags & (1 << ((target & 7) + 8))) == 0) ?
1227                     0 : T_SYNCHOFF) |
1228                     ((sc->sc_cfflags & (1 << (target & 7))) == 0 ?
1229                     0 : T_RSELECTOFF);
1230                 ti->curr.period = ti->goal.period = 0;
1231                 ti->curr.offset = ti->goal.offset = 0;
1232                 ti->curr.width = ti->goal.width = MSG_EXT_WDTR_BUS_8_BIT;
1233                 break;
1234         }
1235 }
1236
1237 /*
1238  * LOW LEVEL SCSI UTILITIES
1239  */
1240
1241 /*
1242  * Schedule a SCSI operation.  This has now been pulled out of the interrupt
1243  * handler so that we may call it from ncr53c9x_action and ncr53c9x_done.
1244  * This may save us an unnecessary interrupt just to get things going.
1245  * Should only be called when state == NCR_IDLE and with sc_lock held.
1246  */
1247 static void
1248 ncr53c9x_sched(struct ncr53c9x_softc *sc)
1249 {
1250         struct ncr53c9x_ecb *ecb;
1251         struct ncr53c9x_linfo *li;
1252         struct ncr53c9x_tinfo *ti;
1253         int lun, tag;
1254
1255         NCR_LOCK_ASSERT(sc, MA_OWNED);
1256
1257         NCR_TRACE(("[%s] ", __func__));
1258
1259         if (sc->sc_state != NCR_IDLE)
1260                 panic("%s: not IDLE (state=%d)", __func__, sc->sc_state);
1261
1262         /*
1263          * Find first ecb in ready queue that is for a target/lunit
1264          * combinations that is not busy.
1265          */
1266         TAILQ_FOREACH(ecb, &sc->ready_list, chain) {
1267                 ti = &sc->sc_tinfo[ecb->ccb->ccb_h.target_id];
1268                 lun = ecb->ccb->ccb_h.target_lun;
1269
1270                 /* Select type of tag for this command */
1271                 if ((ti->flags & (T_RSELECTOFF | T_TAG)) != T_TAG)
1272                         tag = 0;
1273                 else if ((ecb->flags & ECB_SENSE) != 0)
1274                         tag = 0;
1275                 else if ((ecb->ccb->ccb_h.flags & CAM_TAG_ACTION_VALID) == 0)
1276                         tag = 0;
1277                 else if (ecb->ccb->csio.tag_action == CAM_TAG_ACTION_NONE)
1278                         tag = 0;
1279                 else
1280                         tag = ecb->ccb->csio.tag_action;
1281
1282                 li = TINFO_LUN(ti, lun);
1283                 if (li == NULL) {
1284                         /* Initialize LUN info and add to list. */
1285                         li = malloc(sizeof(*li), M_DEVBUF, M_NOWAIT | M_ZERO);
1286                         if (li == NULL)
1287                                 continue;
1288                         li->lun = lun;
1289
1290                         LIST_INSERT_HEAD(&ti->luns, li, link);
1291                         if (lun < NCR_NLUN)
1292                                 ti->lun[lun] = li;
1293                 }
1294                 li->last_used = time_second;
1295                 if (tag == 0) {
1296                         /* Try to issue this as an untagged command. */
1297                         if (li->untagged == NULL)
1298                                 li->untagged = ecb;
1299                 }
1300                 if (li->untagged != NULL) {
1301                         tag = 0;
1302                         if ((li->busy != 1) && li->used == 0) {
1303                                 /*
1304                                  * We need to issue this untagged command
1305                                  * now.
1306                                  */
1307                                 ecb = li->untagged;
1308                         } else {
1309                                 /* not ready, yet */
1310                                 continue;
1311                         }
1312                 }
1313                 ecb->tag[0] = tag;
1314                 if (tag != 0) {
1315                         li->queued[ecb->tag_id] = ecb;
1316                         ecb->tag[1] = ecb->tag_id;
1317                         li->used++;
1318                 }
1319                 if (li->untagged != NULL && (li->busy != 1)) {
1320                         li->busy = 1;
1321                         TAILQ_REMOVE(&sc->ready_list, ecb, chain);
1322                         ecb->flags &= ~ECB_READY;
1323                         sc->sc_nexus = ecb;
1324                         ncr53c9x_select(sc, ecb);
1325                         break;
1326                 }
1327                 if (li->untagged == NULL && tag != 0) {
1328                         TAILQ_REMOVE(&sc->ready_list, ecb, chain);
1329                         ecb->flags &= ~ECB_READY;
1330                         sc->sc_nexus = ecb;
1331                         ncr53c9x_select(sc, ecb);
1332                         break;
1333                 } else
1334                         NCR_TRACE(("[%s %d:%d busy] \n", __func__,
1335                             ecb->ccb->ccb_h.target_id,
1336                             ecb->ccb->ccb_h.target_lun));
1337         }
1338 }
1339
1340 static void
1341 ncr53c9x_sense(struct ncr53c9x_softc *sc, struct ncr53c9x_ecb *ecb)
1342 {
1343         union ccb *ccb = ecb->ccb;
1344         struct ncr53c9x_linfo *li;
1345         struct ncr53c9x_tinfo *ti;
1346         struct scsi_request_sense *ss = (void *)&ecb->cmd.cmd;
1347         int lun;
1348
1349         NCR_LOCK_ASSERT(sc, MA_OWNED);
1350
1351         NCR_TRACE(("[%s] ", __func__));
1352
1353         lun = ccb->ccb_h.target_lun;
1354         ti = &sc->sc_tinfo[ccb->ccb_h.target_id];
1355
1356         /* Next, setup a REQUEST SENSE command block. */
1357         memset(ss, 0, sizeof(*ss));
1358         ss->opcode = REQUEST_SENSE;
1359         ss->byte2 = ccb->ccb_h.target_lun << SCSI_CMD_LUN_SHIFT;
1360         ss->length = sizeof(struct scsi_sense_data);
1361         ecb->clen = sizeof(*ss);
1362         memset(&ccb->csio.sense_data, 0, sizeof(ccb->csio.sense_data));
1363         ecb->daddr = (uint8_t *)&ccb->csio.sense_data;
1364         ecb->dleft = sizeof(struct scsi_sense_data);
1365         ecb->flags |= ECB_SENSE;
1366         ecb->timeout = NCR_SENSE_TIMEOUT;
1367         ti->senses++;
1368         li = TINFO_LUN(ti, lun);
1369         if (li->busy)
1370                 li->busy = 0;
1371         ncr53c9x_dequeue(sc, ecb);
1372         li->untagged = ecb;     /* Must be executed first to fix C/A. */
1373         li->busy = 2;
1374         if (ecb == sc->sc_nexus)
1375                 ncr53c9x_select(sc, ecb);
1376         else {
1377                 TAILQ_INSERT_HEAD(&sc->ready_list, ecb, chain);
1378                 ecb->flags |= ECB_READY;
1379                 if (sc->sc_state == NCR_IDLE)
1380                         ncr53c9x_sched(sc);
1381         }
1382 }
1383
1384 /*
1385  * POST PROCESSING OF SCSI_CMD (usually current)
1386  */
1387 static void
1388 ncr53c9x_done(struct ncr53c9x_softc *sc, struct ncr53c9x_ecb *ecb)
1389 {
1390         union ccb *ccb = ecb->ccb;
1391         struct ncr53c9x_linfo *li;
1392         struct ncr53c9x_tinfo *ti;
1393         int lun, sense_returned;
1394
1395         NCR_LOCK_ASSERT(sc, MA_OWNED);
1396
1397         NCR_TRACE(("[%s(status:%x)] ", __func__, ccb->ccb_h.status));
1398
1399         ti = &sc->sc_tinfo[ccb->ccb_h.target_id];
1400         lun = ccb->ccb_h.target_lun;
1401         li = TINFO_LUN(ti, lun);
1402
1403         callout_stop(&ecb->ch);
1404
1405         /*
1406          * Now, if we've come here with no error code, i.e. we've kept the
1407          * initial CAM_REQ_CMP, and the status code signals that we should
1408          * check sense, we'll need to set up a request sense cmd block and
1409          * push the command back into the ready queue *before* any other
1410          * commands for this target/lunit, else we lose the sense info.
1411          * We don't support chk sense conditions for the request sense cmd.
1412          */
1413         if (ccb->ccb_h.status == CAM_REQ_CMP) {
1414                 ccb->csio.scsi_status = ecb->stat;
1415                 if ((ecb->flags & ECB_ABORT) != 0)
1416                         ccb->ccb_h.status = CAM_CMD_TIMEOUT;
1417                 else if ((ecb->flags & ECB_SENSE) != 0 &&
1418                    (ecb->stat != SCSI_STATUS_CHECK_COND)) {
1419                         ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1420                         ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR |
1421                             CAM_AUTOSNS_VALID;
1422                         sense_returned = sizeof(ccb->csio.sense_data) -
1423                             ecb->dleft;
1424                         if (sense_returned < ccb->csio.sense_len)
1425                                 ccb->csio.sense_resid = ccb->csio.sense_len -
1426                                     sense_returned;
1427                         else
1428                                 ccb->csio.sense_resid = 0;
1429                 } else if (ecb->stat == SCSI_STATUS_CHECK_COND) {
1430                         if ((ecb->flags & ECB_SENSE) != 0)
1431                                 ccb->ccb_h.status = CAM_AUTOSENSE_FAIL;
1432                         else {
1433                                 /* First, save the return values. */
1434                                 ccb->csio.resid = ecb->dleft;
1435                                 if ((ccb->ccb_h.flags & CAM_DIS_AUTOSENSE) ==
1436                                     0) {
1437                                         ncr53c9x_sense(sc, ecb);
1438                                         return;
1439                                 }
1440                                 ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR;
1441                         }
1442                 } else
1443                         ccb->csio.resid = ecb->dleft;
1444                 if (ecb->stat == SCSI_STATUS_QUEUE_FULL)
1445                         ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR;
1446                 else if (ecb->stat == SCSI_STATUS_BUSY)
1447                         ccb->ccb_h.status = CAM_SCSI_BUSY;
1448         } else if ((ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
1449                 ccb->ccb_h.status |= CAM_DEV_QFRZN;
1450                 xpt_freeze_devq(ccb->ccb_h.path, 1);
1451         }
1452
1453 #ifdef NCR53C9X_DEBUG
1454         if ((ncr53c9x_debug & NCR_SHOWTRAC) != 0) {
1455                 if (ccb->csio.resid != 0)
1456                         printf("resid=%d ", ccb->csio.resid);
1457                 if ((ccb->ccb_h.status & CAM_AUTOSNS_VALID) != 0)
1458                         printf("sense=0x%02x\n",
1459                             ccb->csio.sense_data.error_code);
1460                 else
1461                         printf("status SCSI=0x%x CAM=0x%x\n",
1462                             ccb->csio.scsi_status, ccb->ccb_h.status);
1463         }
1464 #endif
1465
1466         /*
1467          * Remove the ECB from whatever queue it's on.
1468          */
1469         ncr53c9x_dequeue(sc, ecb);
1470         if (ecb == sc->sc_nexus) {
1471                 sc->sc_nexus = NULL;
1472                 if (sc->sc_state != NCR_CLEANING) {
1473                         sc->sc_state = NCR_IDLE;
1474                         ncr53c9x_sched(sc);
1475                 }
1476         }
1477
1478         if ((ccb->ccb_h.status & CAM_SEL_TIMEOUT) != 0) {
1479                 /* Selection timeout -- discard this LUN if empty. */
1480                 if (li->untagged == NULL && li->used == 0) {
1481                         if (lun < NCR_NLUN)
1482                                 ti->lun[lun] = NULL;
1483                         LIST_REMOVE(li, link);
1484                         free(li, M_DEVBUF);
1485                 }
1486         }
1487
1488         ncr53c9x_free_ecb(sc, ecb);
1489         ti->cmds++;
1490         xpt_done(ccb);
1491 }
1492
1493 static void
1494 ncr53c9x_dequeue(struct ncr53c9x_softc *sc, struct ncr53c9x_ecb *ecb)
1495 {
1496         struct ncr53c9x_linfo *li;
1497         struct ncr53c9x_tinfo *ti;
1498         int64_t lun;
1499
1500         NCR_LOCK_ASSERT(sc, MA_OWNED);
1501
1502         ti = &sc->sc_tinfo[ecb->ccb->ccb_h.target_id];
1503         lun = ecb->ccb->ccb_h.target_lun;
1504         li = TINFO_LUN(ti, lun);
1505 #ifdef DIAGNOSTIC
1506         if (li == NULL || li->lun != lun)
1507                 panic("%s: lun %qx for ecb %p does not exist", __func__,
1508                     (long long)lun, ecb);
1509 #endif
1510         if (li->untagged == ecb) {
1511                 li->busy = 0;
1512                 li->untagged = NULL;
1513         }
1514         if (ecb->tag[0] && li->queued[ecb->tag[1]] != NULL) {
1515 #ifdef DIAGNOSTIC
1516                 if (li->queued[ecb->tag[1]] != NULL &&
1517                     (li->queued[ecb->tag[1]] != ecb))
1518                         panic("%s: slot %d for lun %qx has %p instead of ecb "
1519                             "%p", __func__, ecb->tag[1], (long long)lun,
1520                             li->queued[ecb->tag[1]], ecb);
1521 #endif
1522                 li->queued[ecb->tag[1]] = NULL;
1523                 li->used--;
1524         }
1525         ecb->tag[0] = ecb->tag[1] = 0;
1526
1527         if ((ecb->flags & ECB_READY) != 0) {
1528                 ecb->flags &= ~ECB_READY;
1529                 TAILQ_REMOVE(&sc->ready_list, ecb, chain);
1530         }
1531 }
1532
1533 /*
1534  * INTERRUPT/PROTOCOL ENGINE
1535  */
1536
1537 /*
1538  * Schedule an outgoing message by prioritizing it, and asserting
1539  * attention on the bus.  We can only do this when we are the initiator
1540  * else there will be an illegal command interrupt.
1541  */
1542 #define ncr53c9x_sched_msgout(m) do {                                   \
1543         NCR_MSGS(("ncr53c9x_sched_msgout %x %d", m, __LINE__));         \
1544         NCRCMD(sc, NCRCMD_SETATN);                                      \
1545         sc->sc_flags |= NCR_ATN;                                        \
1546         sc->sc_msgpriq |= (m);                                          \
1547 } while (/* CONSTCOND */0)
1548
1549 static void
1550 ncr53c9x_flushfifo(struct ncr53c9x_softc *sc)
1551 {
1552
1553         NCR_LOCK_ASSERT(sc, MA_OWNED);
1554
1555         NCR_TRACE(("[%s] ", __func__));
1556
1557         NCRCMD(sc, NCRCMD_FLUSH);
1558
1559         if (sc->sc_phase == COMMAND_PHASE ||
1560             sc->sc_phase == MESSAGE_OUT_PHASE)
1561                 DELAY(2);
1562 }
1563
1564 static int
1565 ncr53c9x_rdfifo(struct ncr53c9x_softc *sc, int how)
1566 {
1567         int i, n;
1568         uint8_t *ibuf;
1569
1570         NCR_LOCK_ASSERT(sc, MA_OWNED);
1571
1572         switch (how) {
1573         case NCR_RDFIFO_START:
1574                 ibuf = sc->sc_imess;
1575                 sc->sc_imlen = 0;
1576                 break;
1577
1578         case NCR_RDFIFO_CONTINUE:
1579                 ibuf = sc->sc_imess + sc->sc_imlen;
1580                 break;
1581
1582         default:
1583                 panic("%s: bad flag", __func__);
1584                 /* NOTREACHED */
1585         }
1586
1587         /*
1588          * XXX buffer (sc_imess) size for message
1589          */
1590
1591         n = NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF;
1592
1593         if (sc->sc_rev == NCR_VARIANT_FAS366) {
1594                 n *= 2;
1595
1596                 for (i = 0; i < n; i++)
1597                         ibuf[i] = NCR_READ_REG(sc, NCR_FIFO);
1598
1599                 if (sc->sc_espstat2 & NCRFAS_STAT2_ISHUTTLE) {
1600
1601                         NCR_WRITE_REG(sc, NCR_FIFO, 0);
1602                         ibuf[i++] = NCR_READ_REG(sc, NCR_FIFO);
1603
1604                         NCR_READ_REG(sc, NCR_FIFO);
1605
1606                         ncr53c9x_flushfifo(sc);
1607                 }
1608         } else
1609                 for (i = 0; i < n; i++)
1610                         ibuf[i] = NCR_READ_REG(sc, NCR_FIFO);
1611
1612         sc->sc_imlen += i;
1613
1614 #if 0
1615 #ifdef NCR53C9X_DEBUG
1616         NCR_TRACE(("\n[rdfifo %s (%d):",
1617             (how == NCR_RDFIFO_START) ? "start" : "cont", (int)sc->sc_imlen));
1618         if ((ncr53c9x_debug & NCR_SHOWTRAC) != 0) {
1619                 for (i = 0; i < sc->sc_imlen; i++)
1620                         printf(" %02x", sc->sc_imess[i]);
1621                 printf("]\n");
1622         }
1623 #endif
1624 #endif
1625         return (sc->sc_imlen);
1626 }
1627
1628 static void
1629 ncr53c9x_wrfifo(struct ncr53c9x_softc *sc, uint8_t *p, int len)
1630 {
1631         int i;
1632
1633         NCR_LOCK_ASSERT(sc, MA_OWNED);
1634
1635 #ifdef NCR53C9X_DEBUG
1636         NCR_MSGS(("[wrfifo(%d):", len));
1637         if ((ncr53c9x_debug & NCR_SHOWMSGS) != 0) {
1638                 for (i = 0; i < len; i++)
1639                         printf(" %02x", p[i]);
1640                 printf("]\n");
1641         }
1642 #endif
1643
1644         for (i = 0; i < len; i++) {
1645                 NCR_WRITE_REG(sc, NCR_FIFO, p[i]);
1646
1647                 if (sc->sc_rev == NCR_VARIANT_FAS366)
1648                         NCR_WRITE_REG(sc, NCR_FIFO, 0);
1649         }
1650 }
1651
1652 static int
1653 ncr53c9x_reselect(struct ncr53c9x_softc *sc, int message, int tagtype,
1654     int tagid)
1655 {
1656         struct ncr53c9x_ecb *ecb = NULL;
1657         struct ncr53c9x_linfo *li;
1658         struct ncr53c9x_tinfo *ti;
1659         uint8_t lun, selid, target;
1660
1661         NCR_LOCK_ASSERT(sc, MA_OWNED);
1662
1663         if (sc->sc_rev == NCR_VARIANT_FAS366)
1664                 target = sc->sc_selid;
1665         else {
1666                 /*
1667                  * The SCSI chip made a snapshot of the data bus
1668                  * while the reselection was being negotiated.
1669                  * This enables us to determine which target did
1670                  * the reselect.
1671                  */
1672                 selid = sc->sc_selid & ~(1 << sc->sc_id);
1673                 if (selid & (selid - 1)) {
1674                         device_printf(sc->sc_dev, "reselect with invalid "
1675                             "selid %02x; sending DEVICE RESET\n", selid);
1676                         goto reset;
1677                 }
1678
1679                 target = ffs(selid) - 1;
1680         }
1681         lun = message & 0x07;
1682
1683         /*
1684          * Search wait queue for disconnected command.
1685          * The list should be short, so I haven't bothered with
1686          * any more sophisticated structures than a simple
1687          * singly linked list.
1688          */
1689         ti = &sc->sc_tinfo[target];
1690         li = TINFO_LUN(ti, lun);
1691
1692         /*
1693          * We can get as far as the LUN with the IDENTIFY
1694          * message.  Check to see if we're running an
1695          * untagged command.  Otherwise ack the IDENTIFY
1696          * and wait for a tag message.
1697          */
1698         if (li != NULL) {
1699                 if (li->untagged != NULL && li->busy)
1700                         ecb = li->untagged;
1701                 else if (tagtype != MSG_SIMPLE_Q_TAG) {
1702                         /* Wait for tag to come by. */
1703                         sc->sc_state = NCR_IDENTIFIED;
1704                         return (0);
1705                 } else if (tagtype)
1706                         ecb = li->queued[tagid];
1707         }
1708         if (ecb == NULL) {
1709                 device_printf(sc->sc_dev, "reselect from target %d lun %d "
1710                     "tag %x:%x with no nexus; sending ABORT\n",
1711                     target, lun, tagtype, tagid);
1712                 goto abort;
1713         }
1714
1715         /* Make this nexus active again. */
1716         sc->sc_state = NCR_CONNECTED;
1717         sc->sc_nexus = ecb;
1718         ncr53c9x_setsync(sc, ti);
1719
1720         if (ecb->flags & ECB_RESET)
1721                 ncr53c9x_sched_msgout(SEND_DEV_RESET);
1722         else if (ecb->flags & ECB_ABORT)
1723                 ncr53c9x_sched_msgout(SEND_ABORT);
1724
1725         /* Do an implicit RESTORE POINTERS. */
1726         sc->sc_dp = ecb->daddr;
1727         sc->sc_dleft = ecb->dleft;
1728
1729         return (0);
1730
1731 reset:
1732         ncr53c9x_sched_msgout(SEND_DEV_RESET);
1733         return (1);
1734
1735 abort:
1736         ncr53c9x_sched_msgout(SEND_ABORT);
1737         return (1);
1738 }
1739
1740 /* From NetBSD; these should go into CAM at some point. */
1741 #define MSG_ISEXTENDED(m)       ((m) == MSG_EXTENDED)
1742 #define MSG_IS1BYTE(m) \
1743         ((!MSG_ISEXTENDED(m) && (m) < 0x20) || MSG_ISIDENTIFY(m))
1744 #define MSG_IS2BYTE(m)          (((m) & 0xf0) == 0x20)
1745
1746 static inline int
1747 __verify_msg_format(uint8_t *p, int len)
1748 {
1749
1750         if (len == 1 && MSG_IS1BYTE(p[0]))
1751                 return (1);
1752         if (len == 2 && MSG_IS2BYTE(p[0]))
1753                 return (1);
1754         if (len >= 3 && MSG_ISEXTENDED(p[0]) &&
1755             len == p[1] + 2)
1756                 return (1);
1757
1758         return (0);
1759 }
1760
1761 /*
1762  * Get an incoming message as initiator.
1763  *
1764  * The SCSI bus must already be in MESSAGE_IN_PHASE and there is a
1765  * byte in the FIFO.
1766  */
1767 static void
1768 ncr53c9x_msgin(struct ncr53c9x_softc *sc)
1769 {
1770         struct ncr53c9x_ecb *ecb;
1771         struct ncr53c9x_linfo *li;
1772         struct ncr53c9x_tinfo *ti;
1773         uint8_t *pb;
1774         int lun, plen;
1775
1776         NCR_LOCK_ASSERT(sc, MA_OWNED);
1777
1778         NCR_TRACE(("[%s(curmsglen:%ld)] ", __func__, (long)sc->sc_imlen));
1779
1780         if (sc->sc_imlen == 0) {
1781                 device_printf(sc->sc_dev, "msgin: no msg byte available\n");
1782                 return;
1783         }
1784
1785         /*
1786          * Prepare for a new message.  A message should (according
1787          * to the SCSI standard) be transmitted in one single
1788          * MESSAGE_IN_PHASE.  If we have been in some other phase,
1789          * then this is a new message.
1790          */
1791         if (sc->sc_prevphase != MESSAGE_IN_PHASE &&
1792             sc->sc_state != NCR_RESELECTED) {
1793                 device_printf(sc->sc_dev, "phase change, dropping message, "
1794                     "prev %d, state %d\n", sc->sc_prevphase, sc->sc_state);
1795                 sc->sc_flags &= ~NCR_DROP_MSGI;
1796                 sc->sc_imlen = 0;
1797         }
1798
1799         /*
1800          * If we're going to reject the message, don't bother storing
1801          * the incoming bytes.  But still, we need to ACK them.
1802          */
1803         if ((sc->sc_flags & NCR_DROP_MSGI) != 0) {
1804                 NCRCMD(sc, NCRCMD_MSGOK);
1805                 device_printf(sc->sc_dev, "<dropping msg byte %x>",
1806                     sc->sc_imess[sc->sc_imlen]);
1807                 return;
1808         }
1809
1810         if (sc->sc_imlen >= NCR_MAX_MSG_LEN) {
1811                 ncr53c9x_sched_msgout(SEND_REJECT);
1812                 sc->sc_flags |= NCR_DROP_MSGI;
1813         } else {
1814                 switch (sc->sc_state) {
1815                 /*
1816                  * if received message is the first of reselection
1817                  * then first byte is selid, and then message
1818                  */
1819                 case NCR_RESELECTED:
1820                         pb = sc->sc_imess + 1;
1821                         plen = sc->sc_imlen - 1;
1822                         break;
1823
1824                 default:
1825                         pb = sc->sc_imess;
1826                         plen = sc->sc_imlen;
1827                 }
1828
1829                 if (__verify_msg_format(pb, plen))
1830                         goto gotit;
1831         }
1832
1833         /* Acknowledge what we have so far. */
1834         NCRCMD(sc, NCRCMD_MSGOK);
1835         return;
1836
1837 gotit:
1838         NCR_MSGS(("gotmsg(%x) state %d", sc->sc_imess[0], sc->sc_state));
1839         /*
1840          * We got a complete message, flush the imess.
1841          * XXX nobody uses imlen below.
1842          */
1843         sc->sc_imlen = 0;
1844         /*
1845          * Now we should have a complete message (1 byte, 2 byte
1846          * and moderately long extended messages).  We only handle
1847          * extended messages which total length is shorter than
1848          * NCR_MAX_MSG_LEN.  Longer messages will be amputated.
1849          */
1850         switch (sc->sc_state) {
1851         case NCR_CONNECTED:
1852                 ecb = sc->sc_nexus;
1853                 ti = &sc->sc_tinfo[ecb->ccb->ccb_h.target_id];
1854
1855                 switch (sc->sc_imess[0]) {
1856                 case MSG_CMDCOMPLETE:
1857                         NCR_MSGS(("cmdcomplete "));
1858                         if (sc->sc_dleft < 0) {
1859                                 xpt_print_path(ecb->ccb->ccb_h.path);
1860                                 printf("got %ld extra bytes\n",
1861                                     -(long)sc->sc_dleft);
1862                                 sc->sc_dleft = 0;
1863                         }
1864                         ecb->dleft = (ecb->flags & ECB_TENTATIVE_DONE) ?
1865                             0 : sc->sc_dleft;
1866                         if ((ecb->flags & ECB_SENSE) == 0)
1867                                 ecb->ccb->csio.resid = ecb->dleft;
1868                         sc->sc_state = NCR_CMDCOMPLETE;
1869                         break;
1870
1871                 case MSG_MESSAGE_REJECT:
1872                         NCR_MSGS(("msg reject (msgout=%x) ", sc->sc_msgout));
1873                         switch (sc->sc_msgout) {
1874                         case SEND_TAG:
1875                                 /*
1876                                  * Target does not like tagged queuing.
1877                                  *  - Flush the command queue
1878                                  *  - Disable tagged queuing for the target
1879                                  *  - Dequeue ecb from the queued array.
1880                                  */
1881                                 device_printf(sc->sc_dev, "tagged queuing "
1882                                     "rejected: target %d\n",
1883                                     ecb->ccb->ccb_h.target_id);
1884
1885                                 NCR_MSGS(("(rejected sent tag)"));
1886                                 NCRCMD(sc, NCRCMD_FLUSH);
1887                                 DELAY(1);
1888                                 ti->flags &= ~T_TAG;
1889                                 lun = ecb->ccb->ccb_h.target_lun;
1890                                 li = TINFO_LUN(ti, lun);
1891                                 if (ecb->tag[0] &&
1892                                     li->queued[ecb->tag[1]] != NULL) {
1893                                         li->queued[ecb->tag[1]] = NULL;
1894                                         li->used--;
1895                                 }
1896                                 ecb->tag[0] = ecb->tag[1] = 0;
1897                                 li->untagged = ecb;
1898                                 li->busy = 1;
1899                                 break;
1900
1901                         case SEND_SDTR:
1902                                 device_printf(sc->sc_dev, "sync transfer "
1903                                     "rejected: target %d\n",
1904                                     ecb->ccb->ccb_h.target_id);
1905
1906                                 ti->flags &= ~T_SDTRSENT;
1907                                 ti->curr.period = ti->goal.period = 0;
1908                                 ti->curr.offset = ti->goal.offset = 0;
1909                                 ncr53c9x_setsync(sc, ti);
1910                                 break;
1911
1912                         case SEND_WDTR:
1913                                 device_printf(sc->sc_dev, "wide transfer "
1914                                     "rejected: target %d\n",
1915                                     ecb->ccb->ccb_h.target_id);
1916
1917                                 ti->flags &= ~T_WDTRSENT;
1918                                 ti->curr.width = ti->goal.width =
1919                                     MSG_EXT_WDTR_BUS_8_BIT;
1920                                 ncr53c9x_setsync(sc, ti);
1921                                 break;
1922
1923                         case SEND_INIT_DET_ERR:
1924                                 goto abort;
1925                         }
1926                         break;
1927
1928                 case MSG_NOOP:
1929                         NCR_MSGS(("noop "));
1930                         break;
1931
1932                 case MSG_HEAD_OF_Q_TAG:
1933                 case MSG_SIMPLE_Q_TAG:
1934                 case MSG_ORDERED_Q_TAG:
1935                         NCR_MSGS(("TAG %x:%x",
1936                             sc->sc_imess[0], sc->sc_imess[1]));
1937                         break;
1938
1939                 case MSG_DISCONNECT:
1940                         NCR_MSGS(("disconnect "));
1941                         ti->dconns++;
1942                         sc->sc_state = NCR_DISCONNECT;
1943
1944                         /*
1945                          * Mark the fact that all bytes have moved.  The
1946                          * target may not bother to do a SAVE POINTERS
1947                          * at this stage.  This flag will set the residual
1948                          * count to zero on MSG COMPLETE.
1949                          */
1950                         if (sc->sc_dleft == 0)
1951                                 ecb->flags |= ECB_TENTATIVE_DONE;
1952                         break;
1953
1954                 case MSG_SAVEDATAPOINTER:
1955                         NCR_MSGS(("save datapointer "));
1956                         ecb->daddr = sc->sc_dp;
1957                         ecb->dleft = sc->sc_dleft;
1958                         break;
1959
1960                 case MSG_RESTOREPOINTERS:
1961                         NCR_MSGS(("restore datapointer "));
1962                         sc->sc_dp = ecb->daddr;
1963                         sc->sc_dleft = ecb->dleft;
1964                         break;
1965
1966                 case MSG_EXTENDED:
1967                         NCR_MSGS(("extended(%x) ", sc->sc_imess[2]));
1968                         switch (sc->sc_imess[2]) {
1969                         case MSG_EXT_SDTR:
1970                                 NCR_MSGS(("SDTR period %d, offset %d ",
1971                                     sc->sc_imess[3], sc->sc_imess[4]));
1972                                 if (sc->sc_imess[1] != 3)
1973                                         goto reject;
1974                                 ti->curr.period = sc->sc_imess[3];
1975                                 ti->curr.offset = sc->sc_imess[4];
1976                                 if (sc->sc_minsync == 0 ||
1977                                     ti->curr.offset == 0 ||
1978                                     ti->curr.period > 124) {
1979 #if 0
1980 #ifdef NCR53C9X_DEBUG
1981                                         xpt_print_path(ecb->ccb->ccb_h.path);
1982                                         printf("async mode\n");
1983 #endif
1984 #endif
1985                                         if ((ti->flags & T_SDTRSENT) == 0) {
1986                                                 /*
1987                                                  * target initiated negotiation
1988                                                  */
1989                                                 ti->curr.offset = 0;
1990                                                 ncr53c9x_sched_msgout(
1991                                                     SEND_SDTR);
1992                                         }
1993                                 } else {
1994                                         ti->curr.period =
1995                                             ncr53c9x_cpb2stp(sc,
1996                                             ncr53c9x_stp2cpb(sc,
1997                                             ti->curr.period));
1998                                         if ((ti->flags & T_SDTRSENT) == 0) {
1999                                                 /*
2000                                                  * target initiated negotiation
2001                                                  */
2002                                                 if (ti->curr.period <
2003                                                     sc->sc_minsync)
2004                                                         ti->curr.period =
2005                                                             sc->sc_minsync;
2006                                                 if (ti->curr.offset >
2007                                                     sc->sc_maxoffset)
2008                                                         ti->curr.offset =
2009                                                             sc->sc_maxoffset;
2010                                                 ncr53c9x_sched_msgout(
2011                                                     SEND_SDTR);
2012                                         }
2013                                 }
2014                                 ti->flags &= ~T_SDTRSENT;
2015                                 ti->goal.period = ti->curr.period;
2016                                 ti->goal.offset = ti->curr.offset;
2017                                 ncr53c9x_setsync(sc, ti);
2018                                 break;
2019
2020                         case MSG_EXT_WDTR:
2021                                 NCR_MSGS(("wide mode %d ", sc->sc_imess[3]));
2022                                 ti->curr.width = sc->sc_imess[3];
2023                                 if (!(ti->flags & T_WDTRSENT))
2024                                         /*
2025                                          * target initiated negotiation
2026                                          */
2027                                         ncr53c9x_sched_msgout(SEND_WDTR);
2028                                 ti->flags &= ~T_WDTRSENT;
2029                                 ti->goal.width = ti->curr.width;
2030                                 ncr53c9x_setsync(sc, ti);
2031                                 break;
2032
2033                         default:
2034                                 xpt_print_path(ecb->ccb->ccb_h.path);
2035                                 printf("unrecognized MESSAGE EXTENDED 0x%x;"
2036                                     " sending REJECT\n", sc->sc_imess[2]);
2037                                 goto reject;
2038                         }
2039                         break;
2040
2041                 default:
2042                         NCR_MSGS(("ident "));
2043                         xpt_print_path(ecb->ccb->ccb_h.path);
2044                         printf("unrecognized MESSAGE 0x%x; sending REJECT\n",
2045                             sc->sc_imess[0]);
2046                         /* FALLTHROUGH */
2047                 reject:
2048                         ncr53c9x_sched_msgout(SEND_REJECT);
2049                         break;
2050                 }
2051                 break;
2052
2053         case NCR_IDENTIFIED:
2054                 /*
2055                  * IDENTIFY message was received and queue tag is expected
2056                  * now.
2057                  */
2058                 if ((sc->sc_imess[0] != MSG_SIMPLE_Q_TAG) ||
2059                     (sc->sc_msgify == 0)) {
2060                         device_printf(sc->sc_dev, "TAG reselect without "
2061                             "IDENTIFY; MSG %x; sending DEVICE RESET\n",
2062                             sc->sc_imess[0]);
2063                         goto reset;
2064                 }
2065                 (void)ncr53c9x_reselect(sc, sc->sc_msgify,
2066                     sc->sc_imess[0], sc->sc_imess[1]);
2067                 break;
2068
2069         case NCR_RESELECTED:
2070                 if (MSG_ISIDENTIFY(sc->sc_imess[1]))
2071                         sc->sc_msgify = sc->sc_imess[1];
2072                 else {
2073                         device_printf(sc->sc_dev, "reselect without IDENTIFY;"
2074                             " MSG %x; sending DEVICE RESET\n", sc->sc_imess[1]);
2075                         goto reset;
2076                 }
2077                 (void)ncr53c9x_reselect(sc, sc->sc_msgify, 0, 0);
2078                 break;
2079
2080         default:
2081                 device_printf(sc->sc_dev, "unexpected MESSAGE IN; "
2082                     "sending DEVICE RESET\n");
2083                 /* FALLTHROUGH */
2084         reset:
2085                 ncr53c9x_sched_msgout(SEND_DEV_RESET);
2086                 break;
2087
2088         abort:
2089                 ncr53c9x_sched_msgout(SEND_ABORT);
2090         }
2091
2092         /* If we have more messages to send set ATN. */
2093         if (sc->sc_msgpriq) {
2094                 NCRCMD(sc, NCRCMD_SETATN);
2095                 sc->sc_flags |= NCR_ATN;
2096         }
2097
2098         /* Acknowledge last message byte. */
2099         NCRCMD(sc, NCRCMD_MSGOK);
2100
2101         /* Done, reset message pointer. */
2102         sc->sc_flags &= ~NCR_DROP_MSGI;
2103         sc->sc_imlen = 0;
2104 }
2105
2106 /*
2107  * Send the highest priority, scheduled message.
2108  */
2109 static void
2110 ncr53c9x_msgout(struct ncr53c9x_softc *sc)
2111 {
2112         struct ncr53c9x_tinfo *ti;
2113         struct ncr53c9x_ecb *ecb;
2114         size_t size;
2115         int error;
2116 #ifdef NCR53C9X_DEBUG
2117         int i;
2118 #endif
2119
2120         NCR_LOCK_ASSERT(sc, MA_OWNED);
2121
2122         NCR_TRACE(("[%s(priq:%x, prevphase:%x)]", __func__, sc->sc_msgpriq,
2123             sc->sc_prevphase));
2124
2125         /*
2126          * XXX - the NCR_ATN flag is not in sync with the actual ATN
2127          *       condition on the SCSI bus.  The 53c9x chip
2128          *       automatically turns off ATN before sending the
2129          *       message byte.  (See also the comment below in the
2130          *       default case when picking out a message to send.)
2131          */
2132         if (sc->sc_flags & NCR_ATN) {
2133                 if (sc->sc_prevphase != MESSAGE_OUT_PHASE) {
2134                 new:
2135                         NCRCMD(sc, NCRCMD_FLUSH);
2136 #if 0
2137                         DELAY(1);
2138 #endif
2139                         sc->sc_msgoutq = 0;
2140                         sc->sc_omlen = 0;
2141                 }
2142         } else {
2143                 if (sc->sc_prevphase == MESSAGE_OUT_PHASE) {
2144                         ncr53c9x_sched_msgout(sc->sc_msgoutq);
2145                         goto new;
2146                 } else
2147                         device_printf(sc->sc_dev, "at line %d: unexpected "
2148                             "MESSAGE OUT phase\n", __LINE__);
2149         }
2150
2151         if (sc->sc_omlen == 0) {
2152                 /* Pick up highest priority message. */
2153                 sc->sc_msgout = sc->sc_msgpriq & -sc->sc_msgpriq;
2154                 sc->sc_msgoutq |= sc->sc_msgout;
2155                 sc->sc_msgpriq &= ~sc->sc_msgout;
2156                 sc->sc_omlen = 1;               /* "Default" message len */
2157                 switch (sc->sc_msgout) {
2158                 case SEND_SDTR:
2159                         ecb = sc->sc_nexus;
2160                         ti = &sc->sc_tinfo[ecb->ccb->ccb_h.target_id];
2161                         sc->sc_omess[0] = MSG_EXTENDED;
2162                         sc->sc_omess[1] = MSG_EXT_SDTR_LEN;
2163                         sc->sc_omess[2] = MSG_EXT_SDTR;
2164                         sc->sc_omess[3] = ti->goal.period;
2165                         sc->sc_omess[4] = ti->goal.offset;
2166                         sc->sc_omlen = 5;
2167                         break;
2168
2169                 case SEND_WDTR:
2170                         ecb = sc->sc_nexus;
2171                         ti = &sc->sc_tinfo[ecb->ccb->ccb_h.target_id];
2172                         sc->sc_omess[0] = MSG_EXTENDED;
2173                         sc->sc_omess[1] = MSG_EXT_WDTR_LEN;
2174                         sc->sc_omess[2] = MSG_EXT_WDTR;
2175                         sc->sc_omess[3] = ti->goal.width;
2176                         sc->sc_omlen = 4;
2177                         break;
2178
2179                 case SEND_IDENTIFY:
2180                         if (sc->sc_state != NCR_CONNECTED)
2181                                 device_printf(sc->sc_dev, "at line %d: no "
2182                                     "nexus\n", __LINE__);
2183                         ecb = sc->sc_nexus;
2184                         sc->sc_omess[0] =
2185                             MSG_IDENTIFY(ecb->ccb->ccb_h.target_lun, 0);
2186                         break;
2187
2188                 case SEND_TAG:
2189                         if (sc->sc_state != NCR_CONNECTED)
2190                                 device_printf(sc->sc_dev, "at line %d: no "
2191                                     "nexus\n", __LINE__);
2192                         ecb = sc->sc_nexus;
2193                         sc->sc_omess[0] = ecb->tag[0];
2194                         sc->sc_omess[1] = ecb->tag[1];
2195                         sc->sc_omlen = 2;
2196                         break;
2197
2198                 case SEND_DEV_RESET:
2199                         sc->sc_flags |= NCR_ABORTING;
2200                         sc->sc_omess[0] = MSG_BUS_DEV_RESET;
2201                         ecb = sc->sc_nexus;
2202                         ti = &sc->sc_tinfo[ecb->ccb->ccb_h.target_id];
2203                         ti->curr.period = 0;
2204                         ti->curr.offset = 0;
2205                         ti->curr.width = MSG_EXT_WDTR_BUS_8_BIT;
2206                         break;
2207
2208                 case SEND_PARITY_ERROR:
2209                         sc->sc_omess[0] = MSG_PARITY_ERROR;
2210                         break;
2211
2212                 case SEND_ABORT:
2213                         sc->sc_flags |= NCR_ABORTING;
2214                         sc->sc_omess[0] = MSG_ABORT;
2215                         break;
2216
2217                 case SEND_INIT_DET_ERR:
2218                         sc->sc_omess[0] = MSG_INITIATOR_DET_ERR;
2219                         break;
2220
2221                 case SEND_REJECT:
2222                         sc->sc_omess[0] = MSG_MESSAGE_REJECT;
2223                         break;
2224
2225                 default:
2226                         /*
2227                          * We normally do not get here, since the chip
2228                          * automatically turns off ATN before the last
2229                          * byte of a message is sent to the target.
2230                          * However, if the target rejects our (multi-byte)
2231                          * message early by switching to MSG IN phase
2232                          * ATN remains on, so the target may return to
2233                          * MSG OUT phase.  If there are no scheduled messages
2234                          * left we send a NO-OP.
2235                          *
2236                          * XXX - Note that this leaves no useful purpose for
2237                          * the NCR_ATN flag.
2238                          */
2239                         sc->sc_flags &= ~NCR_ATN;
2240                         sc->sc_omess[0] = MSG_NOOP;
2241                 }
2242                 sc->sc_omp = sc->sc_omess;
2243         }
2244
2245 #ifdef NCR53C9X_DEBUG
2246         if ((ncr53c9x_debug & NCR_SHOWMSGS) != 0) {
2247                 NCR_MSGS(("<msgout:"));
2248                 for (i = 0; i < sc->sc_omlen; i++)
2249                         NCR_MSGS((" %02x", sc->sc_omess[i]));
2250                 NCR_MSGS(("> "));
2251         }
2252 #endif
2253
2254         if (sc->sc_rev != NCR_VARIANT_FAS366) {
2255                 /* (Re)send the message. */
2256                 size = ulmin(sc->sc_omlen, sc->sc_maxxfer);
2257                 error = NCRDMA_SETUP(sc, &sc->sc_omp, &sc->sc_omlen, 0, &size);
2258                 if (error != 0)
2259                         goto cmd;
2260
2261                 /* Program the SCSI counter. */
2262                 NCR_SET_COUNT(sc, size);
2263
2264                 /* Load the count in and start the message-out transfer. */
2265                 NCRCMD(sc, NCRCMD_NOP | NCRCMD_DMA);
2266                 NCRCMD(sc, NCRCMD_TRANS | NCRCMD_DMA);
2267                 NCRDMA_GO(sc);
2268                 return;
2269         }
2270
2271 cmd:
2272         /*
2273          * XXX FIFO size
2274          */
2275         ncr53c9x_flushfifo(sc);
2276         ncr53c9x_wrfifo(sc, sc->sc_omp, sc->sc_omlen);
2277         NCRCMD(sc, NCRCMD_TRANS);
2278 }
2279
2280 void
2281 ncr53c9x_intr(void *arg)
2282 {
2283         struct ncr53c9x_softc *sc = arg;
2284
2285         if (!NCRDMA_ISINTR(sc))
2286                 return;
2287
2288         NCR_LOCK(sc);
2289
2290         ncr53c9x_intr1(sc);
2291
2292         NCR_UNLOCK(sc);
2293 }
2294
2295 /*
2296  * This is the most critical part of the driver, and has to know
2297  * how to deal with *all* error conditions and phases from the SCSI
2298  * bus.  If there are no errors and the DMA was active, then call the
2299  * DMA pseudo-interrupt handler.  If this returns 1, then that was it
2300  * and we can return from here without further processing.
2301  *
2302  * Most of this needs verifying.
2303  */
2304 static void
2305 ncr53c9x_intr1(struct ncr53c9x_softc *sc)
2306 {
2307         struct ncr53c9x_ecb *ecb;
2308         struct ncr53c9x_linfo *li;
2309         struct ncr53c9x_tinfo *ti;
2310         struct timeval cur, wait;
2311         size_t size;
2312         int error, i, nfifo;
2313         uint8_t msg;
2314
2315         NCR_LOCK_ASSERT(sc, MA_OWNED);
2316
2317         NCR_INTS(("[ncr53c9x_intr: state %d]", sc->sc_state));
2318
2319 again:
2320         /* and what do the registers say... */
2321         ncr53c9x_readregs(sc);
2322
2323         /*
2324          * At the moment, only a SCSI Bus Reset or Illegal
2325          * Command are classed as errors.  A disconnect is a
2326          * valid condition, and we let the code check is the
2327          * "NCR_BUSFREE_OK" flag was set before declaring it
2328          * and error.
2329          *
2330          * Also, the status register tells us about "Gross
2331          * Errors" and "Parity errors".  Only the Gross Error
2332          * is really bad, and the parity errors are dealt
2333          * with later.
2334          *
2335          * TODO
2336          *      If there are too many parity error, go to slow
2337          *      cable mode?
2338          */
2339
2340         if ((sc->sc_espintr & NCRINTR_SBR) != 0) {
2341                 if ((NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF) != 0) {
2342                         NCRCMD(sc, NCRCMD_FLUSH);
2343                         DELAY(1);
2344                 }
2345                 if (sc->sc_state != NCR_SBR) {
2346                         device_printf(sc->sc_dev, "SCSI bus reset\n");
2347                         ncr53c9x_init(sc, 0);   /* Restart everything. */
2348                         return;
2349                 }
2350 #if 0
2351 /*XXX*/         device_printf(sc->sc_dev, "<expected bus reset: "
2352                     "[intr %x, stat %x, step %d]>\n",
2353                     sc->sc_espintr, sc->sc_espstat, sc->sc_espstep);
2354 #endif
2355                 if (sc->sc_nexus != NULL)
2356                         panic("%s: nexus in reset state",
2357                             device_get_nameunit(sc->sc_dev));
2358                 goto sched;
2359         }
2360
2361         ecb = sc->sc_nexus;
2362
2363 #define NCRINTR_ERR (NCRINTR_SBR | NCRINTR_ILL)
2364         if (sc->sc_espintr & NCRINTR_ERR ||
2365             sc->sc_espstat & NCRSTAT_GE) {
2366                 if ((sc->sc_espstat & NCRSTAT_GE) != 0) {
2367                         /* Gross Error; no target? */
2368                         if (NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF) {
2369                                 NCRCMD(sc, NCRCMD_FLUSH);
2370                                 DELAY(1);
2371                         }
2372                         if (sc->sc_state == NCR_CONNECTED ||
2373                             sc->sc_state == NCR_SELECTING) {
2374                                 ecb->ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2375                                 ncr53c9x_done(sc, ecb);
2376                         }
2377                         return;
2378                 }
2379
2380                 if ((sc->sc_espintr & NCRINTR_ILL) != 0) {
2381                         if ((sc->sc_flags & NCR_EXPECT_ILLCMD) != 0) {
2382                                 /*
2383                                  * Eat away "Illegal command" interrupt
2384                                  * on a ESP100 caused by a re-selection
2385                                  * while we were trying to select
2386                                  * another target.
2387                                  */
2388 #ifdef NCR53C9X_DEBUG
2389                                 device_printf(sc->sc_dev, "ESP100 work-around "
2390                                     "activated\n");
2391 #endif
2392                                 sc->sc_flags &= ~NCR_EXPECT_ILLCMD;
2393                                 return;
2394                         }
2395                         /* Illegal command, out of sync? */
2396                         device_printf(sc->sc_dev, "illegal command: 0x%x "
2397                             "(state %d, phase %x, prevphase %x)\n",
2398                             sc->sc_lastcmd,
2399                             sc->sc_state, sc->sc_phase, sc->sc_prevphase);
2400                         if (NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF) {
2401                                 NCRCMD(sc, NCRCMD_FLUSH);
2402                                 DELAY(1);
2403                         }
2404                         goto reset;
2405                 }
2406         }
2407         sc->sc_flags &= ~NCR_EXPECT_ILLCMD;
2408
2409         /*
2410          * Call if DMA is active.
2411          *
2412          * If DMA_INTR returns true, then maybe go 'round the loop
2413          * again in case there is no more DMA queued, but a phase
2414          * change is expected.
2415          */
2416         if (NCRDMA_ISACTIVE(sc)) {
2417                 if (NCRDMA_INTR(sc) == -1) {
2418                         device_printf(sc->sc_dev, "DMA error; resetting\n");
2419                         goto reset;
2420                 }
2421                 /* If DMA active here, then go back to work... */
2422                 if (NCRDMA_ISACTIVE(sc))
2423                         return;
2424
2425                 if ((sc->sc_espstat & NCRSTAT_TC) == 0) {
2426                         /*
2427                          * DMA not completed.  If we can not find a
2428                          * acceptable explanation, print a diagnostic.
2429                          */
2430                         if (sc->sc_state == NCR_SELECTING)
2431                                 /*
2432                                  * This can happen if we are reselected
2433                                  * while using DMA to select a target.
2434                                  */
2435                                 /*void*/;
2436                         else if (sc->sc_prevphase == MESSAGE_OUT_PHASE) {
2437                                 /*
2438                                  * Our (multi-byte) message (eg SDTR) was
2439                                  * interrupted by the target to send
2440                                  * a MSG REJECT.
2441                                  * Print diagnostic if current phase
2442                                  * is not MESSAGE IN.
2443                                  */
2444                                 if (sc->sc_phase != MESSAGE_IN_PHASE)
2445                                         device_printf(sc->sc_dev,"!TC on MSGOUT"
2446                                             " [intr %x, stat %x, step %d]"
2447                                             " prevphase %x, resid %lx\n",
2448                                             sc->sc_espintr,
2449                                             sc->sc_espstat,
2450                                             sc->sc_espstep,
2451                                             sc->sc_prevphase,
2452                                             (u_long)sc->sc_omlen);
2453                         } else if (sc->sc_dleft == 0) {
2454                                 /*
2455                                  * The DMA operation was started for
2456                                  * a DATA transfer.  Print a diagnostic
2457                                  * if the DMA counter and TC bit
2458                                  * appear to be out of sync.
2459                                  *
2460                                  * XXX This is fatal and usually means that
2461                                  *     the DMA engine is hopelessly out of
2462                                  *     sync with reality.  A disk is likely
2463                                  *     getting spammed at this point.
2464                                  */
2465                                 device_printf(sc->sc_dev, "!TC on DATA XFER"
2466                                     " [intr %x, stat %x, step %d]"
2467                                     " prevphase %x, resid %x\n",
2468                                     sc->sc_espintr,
2469                                     sc->sc_espstat,
2470                                     sc->sc_espstep,
2471                                     sc->sc_prevphase,
2472                                     ecb ? ecb->dleft : -1);
2473                                 goto reset;
2474                         }
2475                 }
2476         }
2477
2478         /*
2479          * Check for less serious errors.
2480          */
2481         if ((sc->sc_espstat & NCRSTAT_PE) != 0) {
2482                 device_printf(sc->sc_dev, "SCSI bus parity error\n");
2483                 if (sc->sc_prevphase == MESSAGE_IN_PHASE)
2484                         ncr53c9x_sched_msgout(SEND_PARITY_ERROR);
2485                 else
2486                         ncr53c9x_sched_msgout(SEND_INIT_DET_ERR);
2487         }
2488
2489         if ((sc->sc_espintr & NCRINTR_DIS) != 0) {
2490                 sc->sc_msgify = 0;
2491                 NCR_INTS(("<DISC [intr %x, stat %x, step %d]>",
2492                     sc->sc_espintr,sc->sc_espstat,sc->sc_espstep));
2493                 if (NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF) {
2494                         NCRCMD(sc, NCRCMD_FLUSH);
2495 #if 0
2496                         DELAY(1);
2497 #endif
2498                 }
2499                 /*
2500                  * This command must (apparently) be issued within
2501                  * 250mS of a disconnect.  So here you are...
2502                  */
2503                 NCRCMD(sc, NCRCMD_ENSEL);
2504
2505                 switch (sc->sc_state) {
2506                 case NCR_RESELECTED:
2507                         goto sched;
2508
2509                 case NCR_SELECTING:
2510                         ecb->ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2511
2512                         /* Selection timeout -- discard all LUNs if empty. */
2513                         ti = &sc->sc_tinfo[ecb->ccb->ccb_h.target_id];
2514                         li = LIST_FIRST(&ti->luns);
2515                         while (li != NULL) {
2516                                 if (li->untagged == NULL && li->used == 0) {
2517                                         if (li->lun < NCR_NLUN)
2518                                                 ti->lun[li->lun] = NULL;
2519                                         LIST_REMOVE(li, link);
2520                                         free(li, M_DEVBUF);
2521                                         /*
2522                                          * Restart the search at the beginning.
2523                                          */
2524                                         li = LIST_FIRST(&ti->luns);
2525                                         continue;
2526                                 }
2527                                 li = LIST_NEXT(li, link);
2528                         }
2529                         goto finish;
2530
2531                 case NCR_CONNECTED:
2532                         if (ecb != NULL) {
2533                                 ti = &sc->sc_tinfo[ecb->ccb->ccb_h.target_id];
2534                                 if ((ti->flags & T_SDTRSENT) != 0) {
2535                                         xpt_print_path(ecb->ccb->ccb_h.path);
2536                                         printf("sync nego not completed!\n");
2537                                         ti->flags &= ~T_SDTRSENT;
2538                                         ti->curr.period = ti->goal.period = 0;
2539                                         ti->curr.offset = ti->goal.offset = 0;
2540                                         ncr53c9x_setsync(sc, ti);
2541                                 }
2542                                 if ((ti->flags & T_WDTRSENT) != 0) {
2543                                         xpt_print_path(ecb->ccb->ccb_h.path);
2544                                         printf("wide nego not completed!\n");
2545                                         ti->flags &= ~T_WDTRSENT;
2546                                         ti->curr.width = ti->goal.width =
2547                                             MSG_EXT_WDTR_BUS_8_BIT;
2548                                         ncr53c9x_setsync(sc, ti);
2549                                 }
2550                         }
2551
2552                         /* It may be OK to disconnect. */
2553                         if ((sc->sc_flags & NCR_ABORTING) == 0) {
2554                                 /*
2555                                  * Section 5.1.1 of the SCSI 2 spec
2556                                  * suggests issuing a REQUEST SENSE
2557                                  * following an unexpected disconnect.
2558                                  * Some devices go into a contingent
2559                                  * allegiance condition when
2560                                  * disconnecting, and this is necessary
2561                                  * to clean up their state.
2562                                  */
2563                                 device_printf(sc->sc_dev, "unexpected "
2564                                     "disconnect [state %d, intr %x, stat %x, "
2565                                     "phase(c %x, p %x)]; ", sc->sc_state,
2566                                     sc->sc_espintr, sc->sc_espstat,
2567                                     sc->sc_phase, sc->sc_prevphase);
2568
2569                                 /*
2570                                  * XXX This will cause a chip reset and will
2571                                  *     prevent us from finding out the real
2572                                  *     problem with the device.  However, it's
2573                                  *     necessary until a way can be found to
2574                                  *     safely cancel the DMA that is in
2575                                  *     progress.
2576                                  */
2577                                 if (1 || (ecb->flags & ECB_SENSE) != 0) {
2578                                         printf("resetting\n");
2579                                         goto reset;
2580                                 }
2581                                 printf("sending REQUEST SENSE\n");
2582                                 callout_stop(&ecb->ch);
2583                                 ncr53c9x_sense(sc, ecb);
2584                                 return;
2585                         } else if (ecb != NULL &&
2586                             (ecb->flags & ECB_RESET) != 0) {
2587                                 ecb->ccb->ccb_h.status = CAM_REQ_CMP;
2588                                 goto finish;
2589                         }
2590
2591                         ecb->ccb->ccb_h.status = CAM_CMD_TIMEOUT;
2592                         goto finish;
2593
2594                 case NCR_DISCONNECT:
2595                         sc->sc_nexus = NULL;
2596                         goto sched;
2597
2598                 case NCR_CMDCOMPLETE:
2599                         ecb->ccb->ccb_h.status = CAM_REQ_CMP;
2600                         goto finish;
2601                 }
2602         }
2603
2604         switch (sc->sc_state) {
2605         case NCR_SBR:
2606                 device_printf(sc->sc_dev, "waiting for Bus Reset to happen\n");
2607                 return;
2608
2609         case NCR_RESELECTED:
2610                 /*
2611                  * We must be continuing a message?
2612                  */
2613                 device_printf(sc->sc_dev, "unhandled reselect continuation, "
2614                     "state %d, intr %02x\n", sc->sc_state, sc->sc_espintr);
2615                 goto reset;
2616                 break;
2617
2618         case NCR_IDENTIFIED:
2619                 ecb = sc->sc_nexus;
2620                 if (sc->sc_phase != MESSAGE_IN_PHASE) {
2621                         i = NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF;
2622                         /*
2623                          * Things are seriously screwed up.
2624                          * Pull the brakes, i.e. reset.
2625                          */
2626                         device_printf(sc->sc_dev, "target didn't send tag: %d "
2627                             "bytes in FIFO\n", i);
2628                         /* Drain and display FIFO. */
2629                         while (i-- > 0)
2630                                 printf("[%d] ", NCR_READ_REG(sc, NCR_FIFO));
2631
2632                         goto reset;
2633                 } else
2634                         goto msgin;
2635
2636         case NCR_IDLE:
2637         case NCR_SELECTING:
2638                 ecb = sc->sc_nexus;
2639                 if (sc->sc_espintr & NCRINTR_RESEL) {
2640                         sc->sc_msgpriq = sc->sc_msgout = sc->sc_msgoutq = 0;
2641                         sc->sc_flags = 0;
2642                         /*
2643                          * If we're trying to select a
2644                          * target ourselves, push our command
2645                          * back into the ready list.
2646                          */
2647                         if (sc->sc_state == NCR_SELECTING) {
2648                                 NCR_INTS(("backoff selector "));
2649                                 callout_stop(&ecb->ch);
2650                                 ncr53c9x_dequeue(sc, ecb);
2651                                 TAILQ_INSERT_HEAD(&sc->ready_list, ecb, chain);
2652                                 ecb->flags |= ECB_READY;
2653                                 ecb = sc->sc_nexus = NULL;
2654                         }
2655                         sc->sc_state = NCR_RESELECTED;
2656                         if (sc->sc_phase != MESSAGE_IN_PHASE) {
2657                                 /*
2658                                  * Things are seriously screwed up.
2659                                  * Pull the brakes, i.e. reset
2660                                  */
2661                                 device_printf(sc->sc_dev, "target didn't "
2662                                     "identify\n");
2663                                 goto reset;
2664                         }
2665                         /*
2666                          * The C90 only inhibits FIFO writes until reselection
2667                          * is complete instead of waiting until the interrupt
2668                          * status register has been read.  So, if the reselect
2669                          * happens while we were entering command bytes (for
2670                          * another target) some of those bytes can appear in
2671                          * the FIFO here, after the interrupt is taken.
2672                          *
2673                          * To remedy this situation, pull the Selection ID
2674                          * and Identify message from the FIFO directly, and
2675                          * ignore any extraneous FIFO contents.  Also, set
2676                          * a flag that allows one Illegal Command Interrupt
2677                          * to occur which the chip also generates as a result
2678                          * of writing to the FIFO during a reselect.
2679                          */
2680                         if (sc->sc_rev == NCR_VARIANT_ESP100) {
2681                                 nfifo =
2682                                     NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF;
2683                                 sc->sc_imess[0] = NCR_READ_REG(sc, NCR_FIFO);
2684                                 sc->sc_imess[1] = NCR_READ_REG(sc, NCR_FIFO);
2685                                 sc->sc_imlen = 2;
2686                                 if (nfifo != 2) {
2687                                         /* Flush the rest. */
2688                                         NCRCMD(sc, NCRCMD_FLUSH);
2689                                 }
2690                                 sc->sc_flags |= NCR_EXPECT_ILLCMD;
2691                                 if (nfifo > 2)
2692                                         nfifo = 2;      /* We fixed it... */
2693                         } else
2694                                 nfifo = ncr53c9x_rdfifo(sc, NCR_RDFIFO_START);
2695
2696                         if (nfifo != 2) {
2697                                 device_printf(sc->sc_dev, "RESELECT: %d bytes "
2698                                     "in FIFO! [intr %x, stat %x, step %d, "
2699                                     "prevphase %x]\n",
2700                                     nfifo,
2701                                     sc->sc_espintr,
2702                                     sc->sc_espstat,
2703                                     sc->sc_espstep,
2704                                     sc->sc_prevphase);
2705                                 goto reset;
2706                         }
2707                         sc->sc_selid = sc->sc_imess[0];
2708                         NCR_INTS(("selid=%02x ", sc->sc_selid));
2709
2710                         /* Handle IDENTIFY message. */
2711                         ncr53c9x_msgin(sc);
2712
2713                         if (sc->sc_state != NCR_CONNECTED &&
2714                             sc->sc_state != NCR_IDENTIFIED) {
2715                                 /* IDENTIFY fail?! */
2716                                 device_printf(sc->sc_dev, "identify failed, "
2717                                     "state %d, intr %02x\n", sc->sc_state,
2718                                     sc->sc_espintr);
2719                                 goto reset;
2720                         }
2721                         goto shortcut;  /* i.e. next phase expected soon */
2722                 }
2723
2724 #define NCRINTR_DONE    (NCRINTR_FC | NCRINTR_BS)
2725                 if ((sc->sc_espintr & NCRINTR_DONE) == NCRINTR_DONE) {
2726                         /*
2727                          * Arbitration won; examine the `step' register
2728                          * to determine how far the selection could progress.
2729                          */
2730                         if (ecb == NULL) {
2731                                 /*
2732                                  * When doing path inquiry during boot
2733                                  * FAS100A trigger a stray interrupt which
2734                                  * we just ignore instead of panicing.
2735                                  */
2736                                 if (sc->sc_state == NCR_IDLE &&
2737                                     sc->sc_espstep == 0)
2738                                         return;
2739                                 panic("%s: no nexus", __func__);
2740                         }
2741
2742                         ti = &sc->sc_tinfo[ecb->ccb->ccb_h.target_id];
2743
2744                         switch (sc->sc_espstep) {
2745                         case 0:
2746                                 /*
2747                                  * The target did not respond with a
2748                                  * message out phase - probably an old
2749                                  * device that doesn't recognize ATN.
2750                                  * Clear ATN and just continue, the
2751                                  * target should be in the command
2752                                  * phase.
2753                                  * XXX check for command phase?
2754                                  */
2755                                 NCRCMD(sc, NCRCMD_RSTATN);
2756                                 break;
2757
2758                         case 1:
2759                                 if (ti->curr.period == ti->goal.period &&
2760                                     ti->curr.offset == ti->goal.offset &&
2761                                     ti->curr.width == ti->goal.width &&
2762                                     ecb->tag[0] == 0) {
2763                                         device_printf(sc->sc_dev, "step 1 "
2764                                             "and no negotiation to perform "
2765                                             "or tag to send\n");
2766                                         goto reset;
2767                                 }
2768                                 if (sc->sc_phase != MESSAGE_OUT_PHASE) {
2769                                         device_printf(sc->sc_dev, "step 1 "
2770                                             "but not in MESSAGE_OUT_PHASE\n");
2771                                         goto reset;
2772                                 }
2773                                 sc->sc_prevphase = MESSAGE_OUT_PHASE; /* XXX */
2774                                 if (ecb->flags & ECB_RESET) {
2775                                         /*
2776                                          * A DEVICE RESET was scheduled and
2777                                          * ATNS used.  As SEND_DEV_RESET has
2778                                          * the highest priority, the target
2779                                          * will reset and disconnect and we
2780                                          * will end up in ncr53c9x_done w/o
2781                                          * negotiating or sending a TAG.  So
2782                                          * we just break here in order to
2783                                          * avoid warnings about negotiation
2784                                          * not having completed.
2785                                          */
2786                                         ncr53c9x_sched_msgout(SEND_DEV_RESET);
2787                                         break;
2788                                 }
2789                                 if (ti->curr.width != ti->goal.width) {
2790                                         ti->flags |= T_WDTRSENT | T_SDTRSENT;
2791                                         ncr53c9x_sched_msgout(SEND_WDTR |
2792                                             SEND_SDTR);
2793                                 }
2794                                 if (ti->curr.period != ti->goal.period ||
2795                                     ti->curr.offset != ti->goal.offset) {
2796                                         ti->flags |= T_SDTRSENT;
2797                                         ncr53c9x_sched_msgout(SEND_SDTR);
2798                                 }
2799                                 if (ecb->tag[0] != 0)
2800                                         /* Could not do ATN3 so send TAG. */
2801                                         ncr53c9x_sched_msgout(SEND_TAG);
2802                                 break;
2803
2804                         case 3:
2805                                 /*
2806                                  * Grr, this is supposed to mean
2807                                  * "target left command phase prematurely".
2808                                  * It seems to happen regularly when
2809                                  * sync mode is on.
2810                                  * Look at FIFO to see if command went out.
2811                                  * (Timing problems?)
2812                                  */
2813                                 if (sc->sc_features & NCR_F_DMASELECT) {
2814                                         if (sc->sc_cmdlen == 0)
2815                                                 /* Hope for the best... */
2816                                                 break;
2817                                 } else if ((NCR_READ_REG(sc, NCR_FFLAG) &
2818                                     NCRFIFO_FF) == 0) {
2819                                         /* Hope for the best... */
2820                                         break;
2821                                 }
2822                                 xpt_print_path(ecb->ccb->ccb_h.path);
2823                                 printf("selection failed; %d left in FIFO "
2824                                     "[intr %x, stat %x, step %d]\n",
2825                                     NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF,
2826                                     sc->sc_espintr, sc->sc_espstat,
2827                                     sc->sc_espstep);
2828                                 NCRCMD(sc, NCRCMD_FLUSH);
2829                                 ncr53c9x_sched_msgout(SEND_ABORT);
2830                                 return;
2831
2832                         case 2:
2833                                 /* Select stuck at Command Phase. */
2834                                 NCRCMD(sc, NCRCMD_FLUSH);
2835                                 break;
2836
2837                         case 4:
2838                                 if (sc->sc_features & NCR_F_DMASELECT &&
2839                                     sc->sc_cmdlen != 0) {
2840                                         xpt_print_path(ecb->ccb->ccb_h.path);
2841                                         printf("select; %lu left in DMA buffer "
2842                                             "[intr %x, stat %x, step %d]\n",
2843                                             (u_long)sc->sc_cmdlen,
2844                                             sc->sc_espintr,
2845                                             sc->sc_espstat,
2846                                             sc->sc_espstep);
2847                                 }
2848                                 /* So far, everything went fine. */
2849                                 break;
2850                         }
2851
2852                         sc->sc_prevphase = INVALID_PHASE;       /* ??? */
2853                         /* Do an implicit RESTORE POINTERS. */
2854                         sc->sc_dp = ecb->daddr;
2855                         sc->sc_dleft = ecb->dleft;
2856                         sc->sc_state = NCR_CONNECTED;
2857                         break;
2858                 } else {
2859                         device_printf(sc->sc_dev, "unexpected status after "
2860                             "select: [intr %x, stat %x, step %x]\n",
2861                             sc->sc_espintr, sc->sc_espstat, sc->sc_espstep);
2862                         NCRCMD(sc, NCRCMD_FLUSH);
2863                         DELAY(1);
2864                         goto reset;
2865                 }
2866                 if (sc->sc_state == NCR_IDLE) {
2867                         device_printf(sc->sc_dev, "stray interrupt\n");
2868                         return;
2869                 }
2870                 break;
2871
2872         case NCR_CONNECTED:
2873                 if ((sc->sc_flags & NCR_ICCS) != 0) {
2874                         /* "Initiate Command Complete Steps" in progress */
2875                         sc->sc_flags &= ~NCR_ICCS;
2876
2877                         if ((sc->sc_espintr & NCRINTR_DONE) == 0) {
2878                                 device_printf(sc->sc_dev, "ICCS: "
2879                                     ": [intr %x, stat %x, step %x]\n",
2880                                     sc->sc_espintr, sc->sc_espstat,
2881                                     sc->sc_espstep);
2882                         }
2883                         ncr53c9x_rdfifo(sc, NCR_RDFIFO_START);
2884                         if (sc->sc_imlen < 2)
2885                                 device_printf(sc->sc_dev, "can't get status, "
2886                                     "only %d bytes\n", (int)sc->sc_imlen);
2887                         ecb->stat = sc->sc_imess[sc->sc_imlen - 2];
2888                         msg = sc->sc_imess[sc->sc_imlen - 1];
2889                         NCR_PHASE(("<stat:(%x,%x)>", ecb->stat, msg));
2890                         if (msg == MSG_CMDCOMPLETE) {
2891                                 ecb->dleft =
2892                                     (ecb->flags & ECB_TENTATIVE_DONE) ?
2893                                     0 : sc->sc_dleft;
2894                                 if ((ecb->flags & ECB_SENSE) == 0)
2895                                         ecb->ccb->csio.resid = ecb->dleft;
2896                                 sc->sc_state = NCR_CMDCOMPLETE;
2897                         } else
2898                                 device_printf(sc->sc_dev, "STATUS_PHASE: "
2899                                     "msg %d\n", msg);
2900                         sc->sc_imlen = 0;
2901                         NCRCMD(sc, NCRCMD_MSGOK);
2902                         goto shortcut;  /* i.e. wait for disconnect */
2903                 }
2904                 break;
2905
2906         default:
2907                 device_printf(sc->sc_dev, "invalid state: %d [intr %x, "
2908                     "phase(c %x, p %x)]\n", sc->sc_state,
2909                     sc->sc_espintr, sc->sc_phase, sc->sc_prevphase);
2910                 goto reset;
2911         }
2912
2913         /*
2914          * Driver is now in state NCR_CONNECTED, i.e. we
2915          * have a current command working the SCSI bus.
2916          */
2917         if (sc->sc_state != NCR_CONNECTED || ecb == NULL)
2918                 panic("%s: no nexus", __func__);
2919
2920         switch (sc->sc_phase) {
2921         case MESSAGE_OUT_PHASE:
2922                 NCR_PHASE(("MESSAGE_OUT_PHASE "));
2923                 ncr53c9x_msgout(sc);
2924                 sc->sc_prevphase = MESSAGE_OUT_PHASE;
2925                 break;
2926
2927         case MESSAGE_IN_PHASE:
2928 msgin:
2929                 NCR_PHASE(("MESSAGE_IN_PHASE "));
2930                 if ((sc->sc_espintr & NCRINTR_BS) != 0) {
2931                         if ((sc->sc_rev != NCR_VARIANT_FAS366) ||
2932                             (sc->sc_espstat2 & NCRFAS_STAT2_EMPTY) == 0) {
2933                                 NCRCMD(sc, NCRCMD_FLUSH);
2934                         }
2935                         sc->sc_flags |= NCR_WAITI;
2936                         NCRCMD(sc, NCRCMD_TRANS);
2937                 } else if ((sc->sc_espintr & NCRINTR_FC) != 0) {
2938                         if ((sc->sc_flags & NCR_WAITI) == 0) {
2939                                 device_printf(sc->sc_dev, "MSGIN: unexpected "
2940                                     "FC bit: [intr %x, stat %x, step %x]\n",
2941                                     sc->sc_espintr, sc->sc_espstat,
2942                                     sc->sc_espstep);
2943                         }
2944                         sc->sc_flags &= ~NCR_WAITI;
2945                         ncr53c9x_rdfifo(sc,
2946                             (sc->sc_prevphase == sc->sc_phase) ?
2947                             NCR_RDFIFO_CONTINUE : NCR_RDFIFO_START);
2948                         ncr53c9x_msgin(sc);
2949                 } else
2950                         device_printf(sc->sc_dev, "MSGIN: weird bits: "
2951                             "[intr %x, stat %x, step %x]\n",
2952                             sc->sc_espintr, sc->sc_espstat, sc->sc_espstep);
2953                 sc->sc_prevphase = MESSAGE_IN_PHASE;
2954                 goto shortcut;  /* i.e. expect data to be ready */
2955
2956         case COMMAND_PHASE:
2957                 /*
2958                  * Send the command block.  Normally we don't see this
2959                  * phase because the SEL_ATN command takes care of
2960                  * all this.  However, we end up here if either the
2961                  * target or we wanted to exchange some more messages
2962                  * first (e.g. to start negotiations).
2963                  */
2964
2965                 NCR_PHASE(("COMMAND_PHASE 0x%02x (%d) ",
2966                     ecb->cmd.cmd.opcode, ecb->clen));
2967                 if (NCR_READ_REG(sc, NCR_FFLAG) & NCRFIFO_FF) {
2968                         NCRCMD(sc, NCRCMD_FLUSH);
2969 #if 0
2970                         DELAY(1);
2971 #endif
2972                 }
2973                 /*
2974                  * If we have more messages to send, e.g. WDTR or SDTR
2975                  * after we've sent a TAG, set ATN so we'll go back to
2976                  * MESSAGE_OUT_PHASE.
2977                  */
2978                 if (sc->sc_msgpriq) {
2979                         NCRCMD(sc, NCRCMD_SETATN);
2980                         sc->sc_flags |= NCR_ATN;
2981                 }
2982                 if (sc->sc_features & NCR_F_DMASELECT) {
2983                         /* Setup DMA transfer for command. */
2984                         size = ecb->clen;
2985                         sc->sc_cmdlen = size;
2986                         sc->sc_cmdp = (void *)&ecb->cmd.cmd;
2987                         error = NCRDMA_SETUP(sc, &sc->sc_cmdp, &sc->sc_cmdlen,
2988                             0, &size);
2989                         if (error != 0) {
2990                                 sc->sc_cmdlen = 0;
2991                                 sc->sc_cmdp = NULL;
2992                                 goto cmd;
2993                         }
2994
2995                         /* Program the SCSI counter. */
2996                         NCR_SET_COUNT(sc, size);
2997
2998                         /* Load the count in. */
2999                         NCRCMD(sc, NCRCMD_NOP | NCRCMD_DMA);
3000
3001                         /* Start the command transfer. */
3002                         NCRCMD(sc, NCRCMD_TRANS | NCRCMD_DMA);
3003                         NCRDMA_GO(sc);
3004                         sc->sc_prevphase = COMMAND_PHASE;
3005                         break;
3006                 }
3007 cmd:
3008                 ncr53c9x_wrfifo(sc, (uint8_t *)&ecb->cmd.cmd, ecb->clen);
3009                 NCRCMD(sc, NCRCMD_TRANS);
3010                 sc->sc_prevphase = COMMAND_PHASE;
3011                 break;
3012
3013         case DATA_OUT_PHASE:
3014                 NCR_PHASE(("DATA_OUT_PHASE [%ld] ", (long)sc->sc_dleft));
3015                 sc->sc_prevphase = DATA_OUT_PHASE;
3016                 NCRCMD(sc, NCRCMD_FLUSH);
3017                 size = ulmin(sc->sc_dleft, sc->sc_maxxfer);
3018                 error = NCRDMA_SETUP(sc, &sc->sc_dp, &sc->sc_dleft, 0, &size);
3019                 goto setup_xfer;
3020
3021         case DATA_IN_PHASE:
3022                 NCR_PHASE(("DATA_IN_PHASE "));
3023                 sc->sc_prevphase = DATA_IN_PHASE;
3024                 if (sc->sc_rev == NCR_VARIANT_ESP100)
3025                         NCRCMD(sc, NCRCMD_FLUSH);
3026                 size = ulmin(sc->sc_dleft, sc->sc_maxxfer);
3027                 error = NCRDMA_SETUP(sc, &sc->sc_dp, &sc->sc_dleft, 1, &size);
3028 setup_xfer:
3029                 if (error != 0) {
3030                         switch (error) {
3031                         case EFBIG:
3032                                 ecb->ccb->ccb_h.status |= CAM_REQ_TOO_BIG;
3033                                 break;
3034                         case EINPROGRESS:
3035                                 panic("%s: cannot deal with deferred DMA",
3036                                     __func__);
3037                         case EINVAL:
3038                                 ecb->ccb->ccb_h.status |= CAM_REQ_INVALID;
3039                                 break;
3040                         case ENOMEM:
3041                                 ecb->ccb->ccb_h.status |= CAM_REQUEUE_REQ;
3042                                 break;
3043                         default:
3044                                 ecb->ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
3045                         }
3046                         goto finish;
3047                 }
3048
3049                 /* Target returned to data phase: wipe "done" memory */
3050                 ecb->flags &= ~ECB_TENTATIVE_DONE;
3051
3052                 /* Program the SCSI counter. */
3053                 NCR_SET_COUNT(sc, size);
3054
3055                 /* Load the count in. */
3056                 NCRCMD(sc, NCRCMD_NOP | NCRCMD_DMA);
3057
3058                 /*
3059                  * Note that if `size' is 0, we've already transceived
3060                  * all the bytes we want but we're still in DATA PHASE.
3061                  * Apparently, the device needs padding.  Also, a
3062                  * transfer size of 0 means "maximum" to the chip
3063                  * DMA logic.
3064                  */
3065                 NCRCMD(sc,
3066                     (size == 0 ? NCRCMD_TRPAD : NCRCMD_TRANS) | NCRCMD_DMA);
3067                 NCRDMA_GO(sc);
3068                 return;
3069
3070         case STATUS_PHASE:
3071                 NCR_PHASE(("STATUS_PHASE "));
3072                 sc->sc_flags |= NCR_ICCS;
3073                 NCRCMD(sc, NCRCMD_ICCS);
3074                 sc->sc_prevphase = STATUS_PHASE;
3075                 goto shortcut;  /* i.e. expect status results soon */
3076
3077         case INVALID_PHASE:
3078                 break;
3079
3080         default:
3081                 device_printf(sc->sc_dev,
3082                     "unexpected bus phase; resetting\n");
3083                 goto reset;
3084         }
3085
3086         return;
3087
3088 reset:
3089         ncr53c9x_init(sc, 1);
3090         return;
3091
3092 finish:
3093         ncr53c9x_done(sc, ecb);
3094         return;
3095
3096 sched:
3097         sc->sc_state = NCR_IDLE;
3098         ncr53c9x_sched(sc);
3099         return;
3100
3101 shortcut:
3102         /*
3103          * The idea is that many of the SCSI operations take very little
3104          * time, and going away and getting interrupted is too high an
3105          * overhead to pay.  For example, selecting, sending a message
3106          * and command and then doing some work can be done in one "pass".
3107          *
3108          * The delay is a heuristic.  It is 2 when at 20MHz, 2 at 25MHz and 1
3109          * at 40MHz. This needs testing.
3110          */
3111         microtime(&wait);
3112         wait.tv_usec += 50 / sc->sc_freq;
3113         if (wait.tv_usec > 1000000) {
3114                 wait.tv_sec++;
3115                 wait.tv_usec -= 1000000;
3116         }
3117         do {
3118                 if (NCRDMA_ISINTR(sc))
3119                         goto again;
3120                 microtime(&cur);
3121         } while (cur.tv_sec <= wait.tv_sec && cur.tv_usec <= wait.tv_usec);
3122 }
3123
3124 static void
3125 ncr53c9x_abort(struct ncr53c9x_softc *sc, struct ncr53c9x_ecb *ecb)
3126 {
3127
3128         NCR_LOCK_ASSERT(sc, MA_OWNED);
3129
3130         /* 2 secs for the abort */
3131         ecb->timeout = NCR_ABORT_TIMEOUT;
3132         ecb->flags |= ECB_ABORT;
3133
3134         if (ecb == sc->sc_nexus) {
3135                 /*
3136                  * If we're still selecting, the message will be scheduled
3137                  * after selection is complete.
3138                  */
3139                 if (sc->sc_state == NCR_CONNECTED)
3140                         ncr53c9x_sched_msgout(SEND_ABORT);
3141
3142                 /*
3143                  * Reschedule callout.
3144                  */
3145                 callout_reset(&ecb->ch, mstohz(ecb->timeout),
3146                     ncr53c9x_callout, ecb);
3147         } else {
3148                 /*
3149                  * Just leave the command where it is.
3150                  * XXX - what choice do we have but to reset the SCSI
3151                  *       eventually?
3152                  */
3153                 if (sc->sc_state == NCR_IDLE)
3154                         ncr53c9x_sched(sc);
3155         }
3156 }
3157
3158 static void
3159 ncr53c9x_callout(void *arg)
3160 {
3161         struct ncr53c9x_ecb *ecb = arg;
3162         union ccb *ccb = ecb->ccb;
3163         struct ncr53c9x_softc *sc = ecb->sc;
3164         struct ncr53c9x_tinfo *ti;
3165
3166         NCR_LOCK_ASSERT(sc, MA_OWNED);
3167
3168         ti = &sc->sc_tinfo[ccb->ccb_h.target_id];
3169         xpt_print_path(ccb->ccb_h.path);
3170         device_printf(sc->sc_dev, "timed out [ecb %p (flags 0x%x, dleft %x, "
3171             "stat %x)], <state %d, nexus %p, phase(l %x, c %x, p %x), "
3172             "resid %lx, msg(q %x,o %x) %s>",
3173             ecb, ecb->flags, ecb->dleft, ecb->stat,
3174             sc->sc_state, sc->sc_nexus,
3175             NCR_READ_REG(sc, NCR_STAT),
3176             sc->sc_phase, sc->sc_prevphase,
3177             (long)sc->sc_dleft, sc->sc_msgpriq, sc->sc_msgout,
3178             NCRDMA_ISACTIVE(sc) ? "DMA active" : "");
3179 #if defined(NCR53C9X_DEBUG) && NCR53C9X_DEBUG > 1
3180         printf("TRACE: %s.", ecb->trace);
3181 #endif
3182
3183         if (ecb->flags & ECB_ABORT) {
3184                 /* Abort timed out. */
3185                 printf(" AGAIN\n");
3186                 ncr53c9x_init(sc, 1);
3187         } else {
3188                 /* Abort the operation that has timed out. */
3189                 printf("\n");
3190                 ccb->ccb_h.status = CAM_CMD_TIMEOUT;
3191                 ncr53c9x_abort(sc, ecb);
3192
3193                 /* Disable sync mode if stuck in a data phase. */
3194                 if (ecb == sc->sc_nexus &&
3195                     ti->curr.offset != 0 &&
3196                     (sc->sc_phase & (MSGI | CDI)) == 0) {
3197                         /* XXX ASYNC CALLBACK! */
3198                         ti->goal.offset = 0;
3199                         xpt_print_path(ccb->ccb_h.path);
3200                         printf("sync negotiation disabled\n");
3201                 }
3202         }
3203 }
3204
3205 static void
3206 ncr53c9x_watch(void *arg)
3207 {
3208         struct ncr53c9x_softc *sc = arg;
3209         struct ncr53c9x_linfo *li;
3210         struct ncr53c9x_tinfo *ti;
3211         time_t old;
3212         int t;
3213
3214         NCR_LOCK_ASSERT(sc, MA_OWNED);
3215
3216         /* Delete any structures that have not been used in 10min. */
3217         old = time_second - (10 * 60);
3218
3219         for (t = 0; t < sc->sc_ntarg; t++) {
3220                 ti = &sc->sc_tinfo[t];
3221                 li = LIST_FIRST(&ti->luns);
3222                 while (li) {
3223                         if (li->last_used < old &&
3224                             li->untagged == NULL &&
3225                             li->used == 0) {
3226                                 if (li->lun < NCR_NLUN)
3227                                         ti->lun[li->lun] = NULL;
3228                                 LIST_REMOVE(li, link);
3229                                 free(li, M_DEVBUF);
3230                                 /* Restart the search at the beginning. */
3231                                 li = LIST_FIRST(&ti->luns);
3232                                 continue;
3233                         }
3234                         li = LIST_NEXT(li, link);
3235                 }
3236         }
3237         callout_reset(&sc->sc_watchdog, 60 * hz, ncr53c9x_watch, sc);
3238 }