]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - sys/dev/sym/sym_hipd.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / sys / dev / sym / sym_hipd.c
1 /*-
2  *  Device driver optimized for the Symbios/LSI 53C896/53C895A/53C1010
3  *  PCI-SCSI controllers.
4  *
5  *  Copyright (C) 1999-2001  Gerard Roudier <groudier@free.fr>
6  *
7  *  This driver also supports the following Symbios/LSI PCI-SCSI chips:
8  *      53C810A, 53C825A, 53C860, 53C875, 53C876, 53C885, 53C895,
9  *      53C810,  53C815,  53C825 and the 53C1510D is 53C8XX mode.
10  *
11  *
12  *  This driver for FreeBSD-CAM is derived from the Linux sym53c8xx driver.
13  *  Copyright (C) 1998-1999  Gerard Roudier
14  *
15  *  The sym53c8xx driver is derived from the ncr53c8xx driver that had been
16  *  a port of the FreeBSD ncr driver to Linux-1.2.13.
17  *
18  *  The original ncr driver has been written for 386bsd and FreeBSD by
19  *          Wolfgang Stanglmeier        <wolf@cologne.de>
20  *          Stefan Esser                <se@mi.Uni-Koeln.de>
21  *  Copyright (C) 1994  Wolfgang Stanglmeier
22  *
23  *  The initialisation code, and part of the code that addresses
24  *  FreeBSD-CAM services is based on the aic7xxx driver for FreeBSD-CAM
25  *  written by Justin T. Gibbs.
26  *
27  *  Other major contributions:
28  *
29  *  NVRAM detection and reading.
30  *  Copyright (C) 1997 Richard Waltham <dormouse@farsrobt.demon.co.uk>
31  *
32  *-----------------------------------------------------------------------------
33  *
34  * Redistribution and use in source and binary forms, with or without
35  * modification, are permitted provided that the following conditions
36  * are met:
37  * 1. Redistributions of source code must retain the above copyright
38  *    notice, this list of conditions and the following disclaimer.
39  * 2. Redistributions in binary form must reproduce the above copyright
40  *    notice, this list of conditions and the following disclaimer in the
41  *    documentation and/or other materials provided with the distribution.
42  * 3. The name of the author may not be used to endorse or promote products
43  *    derived from this software without specific prior written permission.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
49  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  */
57
58 #include <sys/cdefs.h>
59 __FBSDID("$FreeBSD$");
60
61 #define SYM_DRIVER_NAME "sym-1.6.5-20000902"
62
63 /* #define SYM_DEBUG_GENERIC_SUPPORT */
64
65 #include <sys/param.h>
66
67 /*
68  *  Driver configuration options.
69  */
70 #include "opt_sym.h"
71 #include <dev/sym/sym_conf.h>
72
73 #include <sys/systm.h>
74 #include <sys/malloc.h>
75 #include <sys/endian.h>
76 #include <sys/kernel.h>
77 #include <sys/lock.h>
78 #include <sys/mutex.h>
79 #include <sys/module.h>
80 #include <sys/bus.h>
81
82 #include <sys/proc.h>
83
84 #include <dev/pci/pcireg.h>
85 #include <dev/pci/pcivar.h>
86
87 #include <machine/bus.h>
88 #include <machine/resource.h>
89
90 #ifdef __sparc64__
91 #include <dev/ofw/openfirm.h>
92 #include <machine/ofw_machdep.h>
93 #endif
94
95 #include <sys/rman.h>
96
97 #include <cam/cam.h>
98 #include <cam/cam_ccb.h>
99 #include <cam/cam_sim.h>
100 #include <cam/cam_xpt_sim.h>
101 #include <cam/cam_debug.h>
102
103 #include <cam/scsi/scsi_all.h>
104 #include <cam/scsi/scsi_message.h>
105
106 /* Short and quite clear integer types */
107 typedef int8_t    s8;
108 typedef int16_t   s16;
109 typedef int32_t   s32;
110 typedef u_int8_t  u8;
111 typedef u_int16_t u16;
112 typedef u_int32_t u32;
113
114 /*
115  *  Driver definitions.
116  */
117 #include <dev/sym/sym_defs.h>
118 #include <dev/sym/sym_fw.h>
119
120 /*
121  *  IA32 architecture does not reorder STORES and prevents
122  *  LOADS from passing STORES. It is called `program order'
123  *  by Intel and allows device drivers to deal with memory
124  *  ordering by only ensuring that the code is not reordered
125  *  by the compiler when ordering is required.
126  *  Other architectures implement a weaker ordering that
127  *  requires memory barriers (and also IO barriers when they
128  *  make sense) to be used.
129  */
130 #if     defined __i386__ || defined __amd64__
131 #define MEMORY_BARRIER()        do { ; } while(0)
132 #elif   defined __powerpc__
133 #define MEMORY_BARRIER()        __asm__ volatile("eieio; sync" : : : "memory")
134 #elif   defined __ia64__
135 #define MEMORY_BARRIER()        __asm__ volatile("mf.a; mf" : : : "memory")
136 #elif   defined __sparc64__
137 #define MEMORY_BARRIER()        __asm__ volatile("membar #Sync" : : : "memory")
138 #else
139 #error  "Not supported platform"
140 #endif
141
142 /*
143  *  A la VMS/CAM-3 queue management.
144  */
145 typedef struct sym_quehead {
146         struct sym_quehead *flink;      /* Forward  pointer */
147         struct sym_quehead *blink;      /* Backward pointer */
148 } SYM_QUEHEAD;
149
150 #define sym_que_init(ptr) do { \
151         (ptr)->flink = (ptr); (ptr)->blink = (ptr); \
152 } while (0)
153
154 static __inline struct sym_quehead *sym_que_first(struct sym_quehead *head)
155 {
156         return (head->flink == head) ? NULL : head->flink;
157 }
158
159 static __inline struct sym_quehead *sym_que_last(struct sym_quehead *head)
160 {
161         return (head->blink == head) ? NULL : head->blink;
162 }
163
164 static __inline void __sym_que_add(struct sym_quehead * new,
165         struct sym_quehead * blink,
166         struct sym_quehead * flink)
167 {
168         flink->blink    = new;
169         new->flink      = flink;
170         new->blink      = blink;
171         blink->flink    = new;
172 }
173
174 static __inline void __sym_que_del(struct sym_quehead * blink,
175         struct sym_quehead * flink)
176 {
177         flink->blink = blink;
178         blink->flink = flink;
179 }
180
181 static __inline int sym_que_empty(struct sym_quehead *head)
182 {
183         return head->flink == head;
184 }
185
186 static __inline void sym_que_splice(struct sym_quehead *list,
187         struct sym_quehead *head)
188 {
189         struct sym_quehead *first = list->flink;
190
191         if (first != list) {
192                 struct sym_quehead *last = list->blink;
193                 struct sym_quehead *at   = head->flink;
194
195                 first->blink = head;
196                 head->flink  = first;
197
198                 last->flink = at;
199                 at->blink   = last;
200         }
201 }
202
203 #define sym_que_entry(ptr, type, member) \
204         ((type *)((char *)(ptr)-(size_t)(&((type *)0)->member)))
205
206 #define sym_insque(new, pos)            __sym_que_add(new, pos, (pos)->flink)
207
208 #define sym_remque(el)                  __sym_que_del((el)->blink, (el)->flink)
209
210 #define sym_insque_head(new, head)      __sym_que_add(new, head, (head)->flink)
211
212 static __inline struct sym_quehead *sym_remque_head(struct sym_quehead *head)
213 {
214         struct sym_quehead *elem = head->flink;
215
216         if (elem != head)
217                 __sym_que_del(head, elem->flink);
218         else
219                 elem = NULL;
220         return elem;
221 }
222
223 #define sym_insque_tail(new, head)      __sym_que_add(new, (head)->blink, head)
224
225 static __inline struct sym_quehead *sym_remque_tail(struct sym_quehead *head)
226 {
227         struct sym_quehead *elem = head->blink;
228
229         if (elem != head)
230                 __sym_que_del(elem->blink, head);
231         else
232                 elem = NULL;
233         return elem;
234 }
235
236 /*
237  *  This one may be useful.
238  */
239 #define FOR_EACH_QUEUED_ELEMENT(head, qp) \
240         for (qp = (head)->flink; qp != (head); qp = qp->flink)
241 /*
242  *  FreeBSD does not offer our kind of queue in the CAM CCB.
243  *  So, we have to cast.
244  */
245 #define sym_qptr(p)     ((struct sym_quehead *) (p))
246
247 /*
248  *  Simple bitmap operations.
249  */
250 #define sym_set_bit(p, n)       (((u32 *)(p))[(n)>>5] |=  (1<<((n)&0x1f)))
251 #define sym_clr_bit(p, n)       (((u32 *)(p))[(n)>>5] &= ~(1<<((n)&0x1f)))
252 #define sym_is_bit(p, n)        (((u32 *)(p))[(n)>>5] &   (1<<((n)&0x1f)))
253
254 /*
255  *  Number of tasks per device we want to handle.
256  */
257 #if     SYM_CONF_MAX_TAG_ORDER > 8
258 #error  "more than 256 tags per logical unit not allowed."
259 #endif
260 #define SYM_CONF_MAX_TASK       (1<<SYM_CONF_MAX_TAG_ORDER)
261
262 /*
263  *  Donnot use more tasks that we can handle.
264  */
265 #ifndef SYM_CONF_MAX_TAG
266 #define SYM_CONF_MAX_TAG        SYM_CONF_MAX_TASK
267 #endif
268 #if     SYM_CONF_MAX_TAG > SYM_CONF_MAX_TASK
269 #undef  SYM_CONF_MAX_TAG
270 #define SYM_CONF_MAX_TAG        SYM_CONF_MAX_TASK
271 #endif
272
273 /*
274  *    This one means 'NO TAG for this job'
275  */
276 #define NO_TAG  (256)
277
278 /*
279  *  Number of SCSI targets.
280  */
281 #if     SYM_CONF_MAX_TARGET > 16
282 #error  "more than 16 targets not allowed."
283 #endif
284
285 /*
286  *  Number of logical units per target.
287  */
288 #if     SYM_CONF_MAX_LUN > 64
289 #error  "more than 64 logical units per target not allowed."
290 #endif
291
292 /*
293  *    Asynchronous pre-scaler (ns). Shall be 40 for
294  *    the SCSI timings to be compliant.
295  */
296 #define SYM_CONF_MIN_ASYNC (40)
297
298 /*
299  *  Number of entries in the START and DONE queues.
300  *
301  *  We limit to 1 PAGE in order to succeed allocation of
302  *  these queues. Each entry is 8 bytes long (2 DWORDS).
303  */
304 #ifdef  SYM_CONF_MAX_START
305 #define SYM_CONF_MAX_QUEUE (SYM_CONF_MAX_START+2)
306 #else
307 #define SYM_CONF_MAX_QUEUE (7*SYM_CONF_MAX_TASK+2)
308 #define SYM_CONF_MAX_START (SYM_CONF_MAX_QUEUE-2)
309 #endif
310
311 #if     SYM_CONF_MAX_QUEUE > PAGE_SIZE/8
312 #undef  SYM_CONF_MAX_QUEUE
313 #define SYM_CONF_MAX_QUEUE   PAGE_SIZE/8
314 #undef  SYM_CONF_MAX_START
315 #define SYM_CONF_MAX_START (SYM_CONF_MAX_QUEUE-2)
316 #endif
317
318 /*
319  *  For this one, we want a short name :-)
320  */
321 #define MAX_QUEUE       SYM_CONF_MAX_QUEUE
322
323 /*
324  *  Active debugging tags and verbosity.
325  */
326 #define DEBUG_ALLOC     (0x0001)
327 #define DEBUG_PHASE     (0x0002)
328 #define DEBUG_POLL      (0x0004)
329 #define DEBUG_QUEUE     (0x0008)
330 #define DEBUG_RESULT    (0x0010)
331 #define DEBUG_SCATTER   (0x0020)
332 #define DEBUG_SCRIPT    (0x0040)
333 #define DEBUG_TINY      (0x0080)
334 #define DEBUG_TIMING    (0x0100)
335 #define DEBUG_NEGO      (0x0200)
336 #define DEBUG_TAGS      (0x0400)
337 #define DEBUG_POINTER   (0x0800)
338
339 #if 0
340 static int sym_debug = 0;
341         #define DEBUG_FLAGS sym_debug
342 #else
343 /*      #define DEBUG_FLAGS (0x0631) */
344         #define DEBUG_FLAGS (0x0000)
345
346 #endif
347 #define sym_verbose     (np->verbose)
348
349 /*
350  *  Insert a delay in micro-seconds and milli-seconds.
351  */
352 static void UDELAY(int us) { DELAY(us); }
353 static void MDELAY(int ms) { while (ms--) UDELAY(1000); }
354
355 /*
356  *  Simple power of two buddy-like allocator.
357  *
358  *  This simple code is not intended to be fast, but to
359  *  provide power of 2 aligned memory allocations.
360  *  Since the SCRIPTS processor only supplies 8 bit arithmetic,
361  *  this allocator allows simple and fast address calculations
362  *  from the SCRIPTS code. In addition, cache line alignment
363  *  is guaranteed for power of 2 cache line size.
364  *
365  *  This allocator has been developed for the Linux sym53c8xx
366  *  driver, since this O/S does not provide naturally aligned
367  *  allocations.
368  *  It has the advantage of allowing the driver to use private
369  *  pages of memory that will be useful if we ever need to deal
370  *  with IO MMUs for PCI.
371  */
372 #define MEMO_SHIFT      4       /* 16 bytes minimum memory chunk */
373 #define MEMO_PAGE_ORDER 0       /* 1 PAGE  maximum */
374 #if 0
375 #define MEMO_FREE_UNUSED        /* Free unused pages immediately */
376 #endif
377 #define MEMO_WARN       1
378 #define MEMO_CLUSTER_SHIFT      (PAGE_SHIFT+MEMO_PAGE_ORDER)
379 #define MEMO_CLUSTER_SIZE       (1UL << MEMO_CLUSTER_SHIFT)
380 #define MEMO_CLUSTER_MASK       (MEMO_CLUSTER_SIZE-1)
381
382 #define get_pages()             malloc(MEMO_CLUSTER_SIZE, M_DEVBUF, M_NOWAIT)
383 #define free_pages(p)           free((p), M_DEVBUF)
384
385 typedef u_long m_addr_t;        /* Enough bits to bit-hack addresses */
386
387 typedef struct m_link {         /* Link between free memory chunks */
388         struct m_link *next;
389 } m_link_s;
390
391 typedef struct m_vtob {         /* Virtual to Bus address translation */
392         struct m_vtob   *next;
393         bus_dmamap_t    dmamap; /* Map for this chunk */
394         m_addr_t        vaddr;  /* Virtual address */
395         m_addr_t        baddr;  /* Bus physical address */
396 } m_vtob_s;
397 /* Hash this stuff a bit to speed up translations */
398 #define VTOB_HASH_SHIFT         5
399 #define VTOB_HASH_SIZE          (1UL << VTOB_HASH_SHIFT)
400 #define VTOB_HASH_MASK          (VTOB_HASH_SIZE-1)
401 #define VTOB_HASH_CODE(m)       \
402         ((((m_addr_t) (m)) >> MEMO_CLUSTER_SHIFT) & VTOB_HASH_MASK)
403
404 typedef struct m_pool {         /* Memory pool of a given kind */
405         bus_dma_tag_t    dev_dmat;      /* Identifies the pool */
406         bus_dma_tag_t    dmat;          /* Tag for our fixed allocations */
407         m_addr_t (*getp)(struct m_pool *);
408 #ifdef  MEMO_FREE_UNUSED
409         void (*freep)(struct m_pool *, m_addr_t);
410 #endif
411 #define M_GETP()                mp->getp(mp)
412 #define M_FREEP(p)              mp->freep(mp, p)
413         int nump;
414         m_vtob_s *(vtob[VTOB_HASH_SIZE]);
415         struct m_pool *next;
416         struct m_link h[MEMO_CLUSTER_SHIFT - MEMO_SHIFT + 1];
417 } m_pool_s;
418
419 static void *___sym_malloc(m_pool_s *mp, int size)
420 {
421         int i = 0;
422         int s = (1 << MEMO_SHIFT);
423         int j;
424         m_addr_t a;
425         m_link_s *h = mp->h;
426
427         if (size > MEMO_CLUSTER_SIZE)
428                 return NULL;
429
430         while (size > s) {
431                 s <<= 1;
432                 ++i;
433         }
434
435         j = i;
436         while (!h[j].next) {
437                 if (s == MEMO_CLUSTER_SIZE) {
438                         h[j].next = (m_link_s *) M_GETP();
439                         if (h[j].next)
440                                 h[j].next->next = NULL;
441                         break;
442                 }
443                 ++j;
444                 s <<= 1;
445         }
446         a = (m_addr_t) h[j].next;
447         if (a) {
448                 h[j].next = h[j].next->next;
449                 while (j > i) {
450                         j -= 1;
451                         s >>= 1;
452                         h[j].next = (m_link_s *) (a+s);
453                         h[j].next->next = NULL;
454                 }
455         }
456 #ifdef DEBUG
457         printf("___sym_malloc(%d) = %p\n", size, (void *) a);
458 #endif
459         return (void *) a;
460 }
461
462 static void ___sym_mfree(m_pool_s *mp, void *ptr, int size)
463 {
464         int i = 0;
465         int s = (1 << MEMO_SHIFT);
466         m_link_s *q;
467         m_addr_t a, b;
468         m_link_s *h = mp->h;
469
470 #ifdef DEBUG
471         printf("___sym_mfree(%p, %d)\n", ptr, size);
472 #endif
473
474         if (size > MEMO_CLUSTER_SIZE)
475                 return;
476
477         while (size > s) {
478                 s <<= 1;
479                 ++i;
480         }
481
482         a = (m_addr_t) ptr;
483
484         while (1) {
485 #ifdef MEMO_FREE_UNUSED
486                 if (s == MEMO_CLUSTER_SIZE) {
487                         M_FREEP(a);
488                         break;
489                 }
490 #endif
491                 b = a ^ s;
492                 q = &h[i];
493                 while (q->next && q->next != (m_link_s *) b) {
494                         q = q->next;
495                 }
496                 if (!q->next) {
497                         ((m_link_s *) a)->next = h[i].next;
498                         h[i].next = (m_link_s *) a;
499                         break;
500                 }
501                 q->next = q->next->next;
502                 a = a & b;
503                 s <<= 1;
504                 ++i;
505         }
506 }
507
508 static void *__sym_calloc2(m_pool_s *mp, int size, char *name, int uflags)
509 {
510         void *p;
511
512         p = ___sym_malloc(mp, size);
513
514         if (DEBUG_FLAGS & DEBUG_ALLOC)
515                 printf ("new %-10s[%4d] @%p.\n", name, size, p);
516
517         if (p)
518                 bzero(p, size);
519         else if (uflags & MEMO_WARN)
520                 printf ("__sym_calloc2: failed to allocate %s[%d]\n", name, size);
521
522         return p;
523 }
524
525 #define __sym_calloc(mp, s, n)  __sym_calloc2(mp, s, n, MEMO_WARN)
526
527 static void __sym_mfree(m_pool_s *mp, void *ptr, int size, char *name)
528 {
529         if (DEBUG_FLAGS & DEBUG_ALLOC)
530                 printf ("freeing %-10s[%4d] @%p.\n", name, size, ptr);
531
532         ___sym_mfree(mp, ptr, size);
533
534 }
535
536 /*
537  * Default memory pool we donnot need to involve in DMA.
538  */
539 /*
540  * With the `bus dma abstraction', we use a separate pool for
541  * memory we donnot need to involve in DMA.
542  */
543 static m_addr_t ___mp0_getp(m_pool_s *mp)
544 {
545         m_addr_t m = (m_addr_t) get_pages();
546         if (m)
547                 ++mp->nump;
548         return m;
549 }
550
551 #ifdef  MEMO_FREE_UNUSED
552 static void ___mp0_freep(m_pool_s *mp, m_addr_t m)
553 {
554         free_pages(m);
555         --mp->nump;
556 }
557 #endif
558
559 #ifdef  MEMO_FREE_UNUSED
560 static m_pool_s mp0 = {0, 0, ___mp0_getp, ___mp0_freep};
561 #else
562 static m_pool_s mp0 = {0, 0, ___mp0_getp};
563 #endif
564
565 /*
566  * Actual memory allocation routine for non-DMAed memory.
567  */
568 static void *sym_calloc(int size, char *name)
569 {
570         void *m;
571         /* Lock */
572         m = __sym_calloc(&mp0, size, name);
573         /* Unlock */
574         return m;
575 }
576
577 /*
578  * Actual memory allocation routine for non-DMAed memory.
579  */
580 static void sym_mfree(void *ptr, int size, char *name)
581 {
582         /* Lock */
583         __sym_mfree(&mp0, ptr, size, name);
584         /* Unlock */
585 }
586
587 /*
588  * DMAable pools.
589  */
590 /*
591  * With `bus dma abstraction', we use a separate pool per parent
592  * BUS handle. A reverse table (hashed) is maintained for virtual
593  * to BUS address translation.
594  */
595 static void getbaddrcb(void *arg, bus_dma_segment_t *segs, int nseg __unused,
596     int error)
597 {
598         bus_addr_t *baddr;
599
600         KASSERT(nseg == 1, ("%s: too many DMA segments (%d)", __func__, nseg));
601
602         baddr = (bus_addr_t *)arg;
603         if (error)
604                 *baddr = 0;
605         else
606                 *baddr = segs->ds_addr;
607 }
608
609 static m_addr_t ___dma_getp(m_pool_s *mp)
610 {
611         m_vtob_s *vbp;
612         void *vaddr = NULL;
613         bus_addr_t baddr = 0;
614
615         vbp = __sym_calloc(&mp0, sizeof(*vbp), "VTOB");
616         if (!vbp)
617                 goto out_err;
618
619         if (bus_dmamem_alloc(mp->dmat, &vaddr,
620                         BUS_DMA_COHERENT | BUS_DMA_WAITOK, &vbp->dmamap))
621                 goto out_err;
622         bus_dmamap_load(mp->dmat, vbp->dmamap, vaddr,
623                         MEMO_CLUSTER_SIZE, getbaddrcb, &baddr, BUS_DMA_NOWAIT);
624         if (baddr) {
625                 int hc = VTOB_HASH_CODE(vaddr);
626                 vbp->vaddr = (m_addr_t) vaddr;
627                 vbp->baddr = (m_addr_t) baddr;
628                 vbp->next = mp->vtob[hc];
629                 mp->vtob[hc] = vbp;
630                 ++mp->nump;
631                 return (m_addr_t) vaddr;
632         }
633 out_err:
634         if (baddr)
635                 bus_dmamap_unload(mp->dmat, vbp->dmamap);
636         if (vaddr)
637                 bus_dmamem_free(mp->dmat, vaddr, vbp->dmamap);
638         if (vbp) {
639                 if (vbp->dmamap)
640                         bus_dmamap_destroy(mp->dmat, vbp->dmamap);
641                 __sym_mfree(&mp0, vbp, sizeof(*vbp), "VTOB");
642         }
643         return 0;
644 }
645
646 #ifdef  MEMO_FREE_UNUSED
647 static void ___dma_freep(m_pool_s *mp, m_addr_t m)
648 {
649         m_vtob_s **vbpp, *vbp;
650         int hc = VTOB_HASH_CODE(m);
651
652         vbpp = &mp->vtob[hc];
653         while (*vbpp && (*vbpp)->vaddr != m)
654                 vbpp = &(*vbpp)->next;
655         if (*vbpp) {
656                 vbp = *vbpp;
657                 *vbpp = (*vbpp)->next;
658                 bus_dmamap_unload(mp->dmat, vbp->dmamap);
659                 bus_dmamem_free(mp->dmat, (void *) vbp->vaddr, vbp->dmamap);
660                 bus_dmamap_destroy(mp->dmat, vbp->dmamap);
661                 __sym_mfree(&mp0, vbp, sizeof(*vbp), "VTOB");
662                 --mp->nump;
663         }
664 }
665 #endif
666
667 static __inline m_pool_s *___get_dma_pool(bus_dma_tag_t dev_dmat)
668 {
669         m_pool_s *mp;
670         for (mp = mp0.next; mp && mp->dev_dmat != dev_dmat; mp = mp->next);
671         return mp;
672 }
673
674 static m_pool_s *___cre_dma_pool(bus_dma_tag_t dev_dmat)
675 {
676         m_pool_s *mp = NULL;
677
678         mp = __sym_calloc(&mp0, sizeof(*mp), "MPOOL");
679         if (mp) {
680                 mp->dev_dmat = dev_dmat;
681                 if (!bus_dma_tag_create(dev_dmat, 1, MEMO_CLUSTER_SIZE,
682                                BUS_SPACE_MAXADDR_32BIT,
683                                BUS_SPACE_MAXADDR,
684                                NULL, NULL, MEMO_CLUSTER_SIZE, 1,
685                                MEMO_CLUSTER_SIZE, 0,
686                                NULL, NULL, &mp->dmat)) {
687                         mp->getp = ___dma_getp;
688 #ifdef  MEMO_FREE_UNUSED
689                         mp->freep = ___dma_freep;
690 #endif
691                         mp->next = mp0.next;
692                         mp0.next = mp;
693                         return mp;
694                 }
695         }
696         if (mp)
697                 __sym_mfree(&mp0, mp, sizeof(*mp), "MPOOL");
698         return NULL;
699 }
700
701 #ifdef  MEMO_FREE_UNUSED
702 static void ___del_dma_pool(m_pool_s *p)
703 {
704         struct m_pool **pp = &mp0.next;
705
706         while (*pp && *pp != p)
707                 pp = &(*pp)->next;
708         if (*pp) {
709                 *pp = (*pp)->next;
710                 bus_dma_tag_destroy(p->dmat);
711                 __sym_mfree(&mp0, p, sizeof(*p), "MPOOL");
712         }
713 }
714 #endif
715
716 static void *__sym_calloc_dma(bus_dma_tag_t dev_dmat, int size, char *name)
717 {
718         struct m_pool *mp;
719         void *m = NULL;
720
721         /* Lock */
722         mp = ___get_dma_pool(dev_dmat);
723         if (!mp)
724                 mp = ___cre_dma_pool(dev_dmat);
725         if (mp)
726                 m = __sym_calloc(mp, size, name);
727 #ifdef  MEMO_FREE_UNUSED
728         if (mp && !mp->nump)
729                 ___del_dma_pool(mp);
730 #endif
731         /* Unlock */
732
733         return m;
734 }
735
736 static void
737 __sym_mfree_dma(bus_dma_tag_t dev_dmat, void *m, int size, char *name)
738 {
739         struct m_pool *mp;
740
741         /* Lock */
742         mp = ___get_dma_pool(dev_dmat);
743         if (mp)
744                 __sym_mfree(mp, m, size, name);
745 #ifdef  MEMO_FREE_UNUSED
746         if (mp && !mp->nump)
747                 ___del_dma_pool(mp);
748 #endif
749         /* Unlock */
750 }
751
752 static m_addr_t __vtobus(bus_dma_tag_t dev_dmat, void *m)
753 {
754         m_pool_s *mp;
755         int hc = VTOB_HASH_CODE(m);
756         m_vtob_s *vp = NULL;
757         m_addr_t a = ((m_addr_t) m) & ~MEMO_CLUSTER_MASK;
758
759         /* Lock */
760         mp = ___get_dma_pool(dev_dmat);
761         if (mp) {
762                 vp = mp->vtob[hc];
763                 while (vp && (m_addr_t) vp->vaddr != a)
764                         vp = vp->next;
765         }
766         /* Unlock */
767         if (!vp)
768                 panic("sym: VTOBUS FAILED!\n");
769         return vp ? vp->baddr + (((m_addr_t) m) - a) : 0;
770 }
771
772 /*
773  * Verbs for DMAable memory handling.
774  * The _uvptv_ macro avoids a nasty warning about pointer to volatile
775  * being discarded.
776  */
777 #define _uvptv_(p) ((void *)((vm_offset_t)(p)))
778 #define _sym_calloc_dma(np, s, n)       __sym_calloc_dma(np->bus_dmat, s, n)
779 #define _sym_mfree_dma(np, p, s, n)     \
780                                 __sym_mfree_dma(np->bus_dmat, _uvptv_(p), s, n)
781 #define sym_calloc_dma(s, n)            _sym_calloc_dma(np, s, n)
782 #define sym_mfree_dma(p, s, n)          _sym_mfree_dma(np, p, s, n)
783 #define _vtobus(np, p)                  __vtobus(np->bus_dmat, _uvptv_(p))
784 #define vtobus(p)                       _vtobus(np, p)
785
786 /*
787  *  Print a buffer in hexadecimal format.
788  */
789 static void sym_printb_hex (u_char *p, int n)
790 {
791         while (n-- > 0)
792                 printf (" %x", *p++);
793 }
794
795 /*
796  *  Same with a label at beginning and .\n at end.
797  */
798 static void sym_printl_hex (char *label, u_char *p, int n)
799 {
800         printf ("%s", label);
801         sym_printb_hex (p, n);
802         printf (".\n");
803 }
804
805 /*
806  *  Return a string for SCSI BUS mode.
807  */
808 static const char *sym_scsi_bus_mode(int mode)
809 {
810         switch(mode) {
811         case SMODE_HVD: return "HVD";
812         case SMODE_SE:  return "SE";
813         case SMODE_LVD: return "LVD";
814         }
815         return "??";
816 }
817
818 /*
819  *  Some poor and bogus sync table that refers to Tekram NVRAM layout.
820  */
821 #ifdef SYM_CONF_NVRAM_SUPPORT
822 static const u_char Tekram_sync[16] =
823         {25,31,37,43, 50,62,75,125, 12,15,18,21, 6,7,9,10};
824 #endif
825
826 /*
827  *  Union of supported NVRAM formats.
828  */
829 struct sym_nvram {
830         int type;
831 #define SYM_SYMBIOS_NVRAM       (1)
832 #define SYM_TEKRAM_NVRAM        (2)
833 #ifdef  SYM_CONF_NVRAM_SUPPORT
834         union {
835                 Symbios_nvram Symbios;
836                 Tekram_nvram Tekram;
837         } data;
838 #endif
839 };
840
841 /*
842  *  This one is hopefully useless, but actually useful. :-)
843  */
844 #ifndef assert
845 #define assert(expression) { \
846         if (!(expression)) { \
847                 (void)panic( \
848                         "assertion \"%s\" failed: file \"%s\", line %d\n", \
849                         #expression, \
850                         __FILE__, __LINE__); \
851         } \
852 }
853 #endif
854
855 /*
856  *  Some provision for a possible big endian mode supported by
857  *  Symbios chips (never seen, by the way).
858  *  For now, this stuff does not deserve any comments. :)
859  */
860 #define sym_offb(o)     (o)
861 #define sym_offw(o)     (o)
862
863 /*
864  *  Some provision for support for BIG ENDIAN CPU.
865  */
866 #define cpu_to_scr(dw)  htole32(dw)
867 #define scr_to_cpu(dw)  le32toh(dw)
868
869 /*
870  *  Access to the chip IO registers and on-chip RAM.
871  *  We use the `bus space' interface under FreeBSD-4 and
872  *  later kernel versions.
873  */
874 #if defined(SYM_CONF_IOMAPPED)
875
876 #define INB_OFF(o)      bus_read_1(np->io_res, (o))
877 #define INW_OFF(o)      bus_read_2(np->io_res, (o))
878 #define INL_OFF(o)      bus_read_4(np->io_res, (o))
879
880 #define OUTB_OFF(o, v)  bus_write_1(np->io_res, (o), (v))
881 #define OUTW_OFF(o, v)  bus_write_2(np->io_res, (o), (v))
882 #define OUTL_OFF(o, v)  bus_write_4(np->io_res, (o), (v))
883
884 #else   /* Memory mapped IO */
885
886 #define INB_OFF(o)      bus_read_1(np->mmio_res, (o))
887 #define INW_OFF(o)      bus_read_2(np->mmio_res, (o))
888 #define INL_OFF(o)      bus_read_4(np->mmio_res, (o))
889
890 #define OUTB_OFF(o, v)  bus_write_1(np->mmio_res, (o), (v))
891 #define OUTW_OFF(o, v)  bus_write_2(np->mmio_res, (o), (v))
892 #define OUTL_OFF(o, v)  bus_write_4(np->mmio_res, (o), (v))
893
894 #endif  /* SYM_CONF_IOMAPPED */
895
896 #define OUTRAM_OFF(o, a, l)     \
897         bus_write_region_1(np->ram_res, (o), (a), (l))
898
899 /*
900  *  Common definitions for both bus space and legacy IO methods.
901  */
902 #define INB(r)          INB_OFF(offsetof(struct sym_reg,r))
903 #define INW(r)          INW_OFF(offsetof(struct sym_reg,r))
904 #define INL(r)          INL_OFF(offsetof(struct sym_reg,r))
905
906 #define OUTB(r, v)      OUTB_OFF(offsetof(struct sym_reg,r), (v))
907 #define OUTW(r, v)      OUTW_OFF(offsetof(struct sym_reg,r), (v))
908 #define OUTL(r, v)      OUTL_OFF(offsetof(struct sym_reg,r), (v))
909
910 #define OUTONB(r, m)    OUTB(r, INB(r) | (m))
911 #define OUTOFFB(r, m)   OUTB(r, INB(r) & ~(m))
912 #define OUTONW(r, m)    OUTW(r, INW(r) | (m))
913 #define OUTOFFW(r, m)   OUTW(r, INW(r) & ~(m))
914 #define OUTONL(r, m)    OUTL(r, INL(r) | (m))
915 #define OUTOFFL(r, m)   OUTL(r, INL(r) & ~(m))
916
917 /*
918  *  We normally want the chip to have a consistent view
919  *  of driver internal data structures when we restart it.
920  *  Thus these macros.
921  */
922 #define OUTL_DSP(v)                             \
923         do {                                    \
924                 MEMORY_BARRIER();               \
925                 OUTL (nc_dsp, (v));             \
926         } while (0)
927
928 #define OUTONB_STD()                            \
929         do {                                    \
930                 MEMORY_BARRIER();               \
931                 OUTONB (nc_dcntl, (STD|NOCOM)); \
932         } while (0)
933
934 /*
935  *  Command control block states.
936  */
937 #define HS_IDLE         (0)
938 #define HS_BUSY         (1)
939 #define HS_NEGOTIATE    (2)     /* sync/wide data transfer*/
940 #define HS_DISCONNECT   (3)     /* Disconnected by target */
941 #define HS_WAIT         (4)     /* waiting for resource   */
942
943 #define HS_DONEMASK     (0x80)
944 #define HS_COMPLETE     (4|HS_DONEMASK)
945 #define HS_SEL_TIMEOUT  (5|HS_DONEMASK) /* Selection timeout      */
946 #define HS_UNEXPECTED   (6|HS_DONEMASK) /* Unexpected disconnect  */
947 #define HS_COMP_ERR     (7|HS_DONEMASK) /* Completed with error   */
948
949 /*
950  *  Software Interrupt Codes
951  */
952 #define SIR_BAD_SCSI_STATUS     (1)
953 #define SIR_SEL_ATN_NO_MSG_OUT  (2)
954 #define SIR_MSG_RECEIVED        (3)
955 #define SIR_MSG_WEIRD           (4)
956 #define SIR_NEGO_FAILED         (5)
957 #define SIR_NEGO_PROTO          (6)
958 #define SIR_SCRIPT_STOPPED      (7)
959 #define SIR_REJECT_TO_SEND      (8)
960 #define SIR_SWIDE_OVERRUN       (9)
961 #define SIR_SODL_UNDERRUN       (10)
962 #define SIR_RESEL_NO_MSG_IN     (11)
963 #define SIR_RESEL_NO_IDENTIFY   (12)
964 #define SIR_RESEL_BAD_LUN       (13)
965 #define SIR_TARGET_SELECTED     (14)
966 #define SIR_RESEL_BAD_I_T_L     (15)
967 #define SIR_RESEL_BAD_I_T_L_Q   (16)
968 #define SIR_ABORT_SENT          (17)
969 #define SIR_RESEL_ABORTED       (18)
970 #define SIR_MSG_OUT_DONE        (19)
971 #define SIR_COMPLETE_ERROR      (20)
972 #define SIR_DATA_OVERRUN        (21)
973 #define SIR_BAD_PHASE           (22)
974 #define SIR_MAX                 (22)
975
976 /*
977  *  Extended error bit codes.
978  *  xerr_status field of struct sym_ccb.
979  */
980 #define XE_EXTRA_DATA   (1)     /* unexpected data phase         */
981 #define XE_BAD_PHASE    (1<<1)  /* illegal phase (4/5)           */
982 #define XE_PARITY_ERR   (1<<2)  /* unrecovered SCSI parity error */
983 #define XE_SODL_UNRUN   (1<<3)  /* ODD transfer in DATA OUT phase */
984 #define XE_SWIDE_OVRUN  (1<<4)  /* ODD transfer in DATA IN phase */
985
986 /*
987  *  Negotiation status.
988  *  nego_status field of struct sym_ccb.
989  */
990 #define NS_SYNC         (1)
991 #define NS_WIDE         (2)
992 #define NS_PPR          (3)
993
994 /*
995  *  A CCB hashed table is used to retrieve CCB address
996  *  from DSA value.
997  */
998 #define CCB_HASH_SHIFT          8
999 #define CCB_HASH_SIZE           (1UL << CCB_HASH_SHIFT)
1000 #define CCB_HASH_MASK           (CCB_HASH_SIZE-1)
1001 #define CCB_HASH_CODE(dsa)      (((dsa) >> 9) & CCB_HASH_MASK)
1002
1003 /*
1004  *  Device flags.
1005  */
1006 #define SYM_DISC_ENABLED        (1)
1007 #define SYM_TAGS_ENABLED        (1<<1)
1008 #define SYM_SCAN_BOOT_DISABLED  (1<<2)
1009 #define SYM_SCAN_LUNS_DISABLED  (1<<3)
1010
1011 /*
1012  *  Host adapter miscellaneous flags.
1013  */
1014 #define SYM_AVOID_BUS_RESET     (1)
1015 #define SYM_SCAN_TARGETS_HILO   (1<<1)
1016
1017 /*
1018  *  Device quirks.
1019  *  Some devices, for example the CHEETAH 2 LVD, disconnects without
1020  *  saving the DATA POINTER then reselects and terminates the IO.
1021  *  On reselection, the automatic RESTORE DATA POINTER makes the
1022  *  CURRENT DATA POINTER not point at the end of the IO.
1023  *  This behaviour just breaks our calculation of the residual.
1024  *  For now, we just force an AUTO SAVE on disconnection and will
1025  *  fix that in a further driver version.
1026  */
1027 #define SYM_QUIRK_AUTOSAVE 1
1028
1029 /*
1030  *  Misc.
1031  */
1032 #define SYM_LOCK()              mtx_lock(&np->mtx)
1033 #define SYM_LOCK_ASSERT(_what)  mtx_assert(&np->mtx, (_what))
1034 #define SYM_LOCK_DESTROY()      mtx_destroy(&np->mtx)
1035 #define SYM_LOCK_INIT()         mtx_init(&np->mtx, "sym_lock", NULL, MTX_DEF)
1036 #define SYM_LOCK_INITIALIZED()  mtx_initialized(&np->mtx)
1037 #define SYM_UNLOCK()            mtx_unlock(&np->mtx)
1038
1039 #define SYM_SNOOP_TIMEOUT (10000000)
1040 #define SYM_PCI_IO      PCIR_BAR(0)
1041 #define SYM_PCI_MMIO    PCIR_BAR(1)
1042 #define SYM_PCI_RAM     PCIR_BAR(2)
1043 #define SYM_PCI_RAM64   PCIR_BAR(3)
1044
1045 /*
1046  *  Back-pointer from the CAM CCB to our data structures.
1047  */
1048 #define sym_hcb_ptr     spriv_ptr0
1049 /* #define sym_ccb_ptr  spriv_ptr1 */
1050
1051 /*
1052  *  We mostly have to deal with pointers.
1053  *  Thus these typedef's.
1054  */
1055 typedef struct sym_tcb *tcb_p;
1056 typedef struct sym_lcb *lcb_p;
1057 typedef struct sym_ccb *ccb_p;
1058 typedef struct sym_hcb *hcb_p;
1059
1060 /*
1061  *  Gather negotiable parameters value
1062  */
1063 struct sym_trans {
1064         u8 scsi_version;
1065         u8 spi_version;
1066         u8 period;
1067         u8 offset;
1068         u8 width;
1069         u8 options;     /* PPR options */
1070 };
1071
1072 struct sym_tinfo {
1073         struct sym_trans current;
1074         struct sym_trans goal;
1075         struct sym_trans user;
1076 };
1077
1078 #define BUS_8_BIT       MSG_EXT_WDTR_BUS_8_BIT
1079 #define BUS_16_BIT      MSG_EXT_WDTR_BUS_16_BIT
1080
1081 /*
1082  *  Global TCB HEADER.
1083  *
1084  *  Due to lack of indirect addressing on earlier NCR chips,
1085  *  this substructure is copied from the TCB to a global
1086  *  address after selection.
1087  *  For SYMBIOS chips that support LOAD/STORE this copy is
1088  *  not needed and thus not performed.
1089  */
1090 struct sym_tcbh {
1091         /*
1092          *  Scripts bus addresses of LUN table accessed from scripts.
1093          *  LUN #0 is a special case, since multi-lun devices are rare,
1094          *  and we we want to speed-up the general case and not waste
1095          *  resources.
1096          */
1097         u32     luntbl_sa;      /* bus address of this table    */
1098         u32     lun0_sa;        /* bus address of LCB #0        */
1099         /*
1100          *  Actual SYNC/WIDE IO registers value for this target.
1101          *  'sval', 'wval' and 'uval' are read from SCRIPTS and
1102          *  so have alignment constraints.
1103          */
1104 /*0*/   u_char  uval;           /* -> SCNTL4 register           */
1105 /*1*/   u_char  sval;           /* -> SXFER  io register        */
1106 /*2*/   u_char  filler1;
1107 /*3*/   u_char  wval;           /* -> SCNTL3 io register        */
1108 };
1109
1110 /*
1111  *  Target Control Block
1112  */
1113 struct sym_tcb {
1114         /*
1115          *  TCB header.
1116          *  Assumed at offset 0.
1117          */
1118 /*0*/   struct sym_tcbh head;
1119
1120         /*
1121          *  LUN table used by the SCRIPTS processor.
1122          *  An array of bus addresses is used on reselection.
1123          */
1124         u32     *luntbl;        /* LCBs bus address table       */
1125
1126         /*
1127          *  LUN table used by the C code.
1128          */
1129         lcb_p   lun0p;          /* LCB of LUN #0 (usual case)   */
1130 #if SYM_CONF_MAX_LUN > 1
1131         lcb_p   *lunmp;         /* Other LCBs [1..MAX_LUN]      */
1132 #endif
1133
1134         /*
1135          *  Bitmap that tells about LUNs that succeeded at least
1136          *  1 IO and therefore assumed to be a real device.
1137          *  Avoid useless allocation of the LCB structure.
1138          */
1139         u32     lun_map[(SYM_CONF_MAX_LUN+31)/32];
1140
1141         /*
1142          *  Bitmap that tells about LUNs that haven't yet an LCB
1143          *  allocated (not discovered or LCB allocation failed).
1144          */
1145         u32     busy0_map[(SYM_CONF_MAX_LUN+31)/32];
1146
1147         /*
1148          *  Transfer capabilities (SIP)
1149          */
1150         struct sym_tinfo tinfo;
1151
1152         /*
1153          * Keep track of the CCB used for the negotiation in order
1154          * to ensure that only 1 negotiation is queued at a time.
1155          */
1156         ccb_p   nego_cp;        /* CCB used for the nego                */
1157
1158         /*
1159          *  Set when we want to reset the device.
1160          */
1161         u_char  to_reset;
1162
1163         /*
1164          *  Other user settable limits and options.
1165          *  These limits are read from the NVRAM if present.
1166          */
1167         u_char  usrflags;
1168         u_short usrtags;
1169 };
1170
1171 /*
1172  *  Assert some alignments required by the chip.
1173  */
1174 CTASSERT(((offsetof(struct sym_reg, nc_sxfer) ^
1175     offsetof(struct sym_tcb, head.sval)) &3) == 0);
1176 CTASSERT(((offsetof(struct sym_reg, nc_scntl3) ^
1177     offsetof(struct sym_tcb, head.wval)) &3) == 0);
1178
1179 /*
1180  *  Global LCB HEADER.
1181  *
1182  *  Due to lack of indirect addressing on earlier NCR chips,
1183  *  this substructure is copied from the LCB to a global
1184  *  address after selection.
1185  *  For SYMBIOS chips that support LOAD/STORE this copy is
1186  *  not needed and thus not performed.
1187  */
1188 struct sym_lcbh {
1189         /*
1190          *  SCRIPTS address jumped by SCRIPTS on reselection.
1191          *  For not probed logical units, this address points to
1192          *  SCRIPTS that deal with bad LU handling (must be at
1193          *  offset zero of the LCB for that reason).
1194          */
1195 /*0*/   u32     resel_sa;
1196
1197         /*
1198          *  Task (bus address of a CCB) read from SCRIPTS that points
1199          *  to the unique ITL nexus allowed to be disconnected.
1200          */
1201         u32     itl_task_sa;
1202
1203         /*
1204          *  Task table bus address (read from SCRIPTS).
1205          */
1206         u32     itlq_tbl_sa;
1207 };
1208
1209 /*
1210  *  Logical Unit Control Block
1211  */
1212 struct sym_lcb {
1213         /*
1214          *  TCB header.
1215          *  Assumed at offset 0.
1216          */
1217 /*0*/   struct sym_lcbh head;
1218
1219         /*
1220          *  Task table read from SCRIPTS that contains pointers to
1221          *  ITLQ nexuses. The bus address read from SCRIPTS is
1222          *  inside the header.
1223          */
1224         u32     *itlq_tbl;      /* Kernel virtual address       */
1225
1226         /*
1227          *  Busy CCBs management.
1228          */
1229         u_short busy_itlq;      /* Number of busy tagged CCBs   */
1230         u_short busy_itl;       /* Number of busy untagged CCBs */
1231
1232         /*
1233          *  Circular tag allocation buffer.
1234          */
1235         u_short ia_tag;         /* Tag allocation index         */
1236         u_short if_tag;         /* Tag release index            */
1237         u_char  *cb_tags;       /* Circular tags buffer         */
1238
1239         /*
1240          *  Set when we want to clear all tasks.
1241          */
1242         u_char to_clear;
1243
1244         /*
1245          *  Capabilities.
1246          */
1247         u_char  user_flags;
1248         u_char  current_flags;
1249 };
1250
1251 /*
1252  *  Action from SCRIPTS on a task.
1253  *  Is part of the CCB, but is also used separately to plug
1254  *  error handling action to perform from SCRIPTS.
1255  */
1256 struct sym_actscr {
1257         u32     start;          /* Jumped by SCRIPTS after selection    */
1258         u32     restart;        /* Jumped by SCRIPTS on relection       */
1259 };
1260
1261 /*
1262  *  Phase mismatch context.
1263  *
1264  *  It is part of the CCB and is used as parameters for the
1265  *  DATA pointer. We need two contexts to handle correctly the
1266  *  SAVED DATA POINTER.
1267  */
1268 struct sym_pmc {
1269         struct  sym_tblmove sg; /* Updated interrupted SG block */
1270         u32     ret;            /* SCRIPT return address        */
1271 };
1272
1273 /*
1274  *  LUN control block lookup.
1275  *  We use a direct pointer for LUN #0, and a table of
1276  *  pointers which is only allocated for devices that support
1277  *  LUN(s) > 0.
1278  */
1279 #if SYM_CONF_MAX_LUN <= 1
1280 #define sym_lp(tp, lun) (!lun) ? (tp)->lun0p : 0
1281 #else
1282 #define sym_lp(tp, lun) \
1283         (!lun) ? (tp)->lun0p : (tp)->lunmp ? (tp)->lunmp[(lun)] : 0
1284 #endif
1285
1286 /*
1287  *  Status are used by the host and the script processor.
1288  *
1289  *  The last four bytes (status[4]) are copied to the
1290  *  scratchb register (declared as scr0..scr3) just after the
1291  *  select/reselect, and copied back just after disconnecting.
1292  *  Inside the script the XX_REG are used.
1293  */
1294
1295 /*
1296  *  Last four bytes (script)
1297  */
1298 #define  QU_REG scr0
1299 #define  HS_REG scr1
1300 #define  HS_PRT nc_scr1
1301 #define  SS_REG scr2
1302 #define  SS_PRT nc_scr2
1303 #define  HF_REG scr3
1304 #define  HF_PRT nc_scr3
1305
1306 /*
1307  *  Last four bytes (host)
1308  */
1309 #define  actualquirks  phys.head.status[0]
1310 #define  host_status   phys.head.status[1]
1311 #define  ssss_status   phys.head.status[2]
1312 #define  host_flags    phys.head.status[3]
1313
1314 /*
1315  *  Host flags
1316  */
1317 #define HF_IN_PM0       1u
1318 #define HF_IN_PM1       (1u<<1)
1319 #define HF_ACT_PM       (1u<<2)
1320 #define HF_DP_SAVED     (1u<<3)
1321 #define HF_SENSE        (1u<<4)
1322 #define HF_EXT_ERR      (1u<<5)
1323 #define HF_DATA_IN      (1u<<6)
1324 #ifdef SYM_CONF_IARB_SUPPORT
1325 #define HF_HINT_IARB    (1u<<7)
1326 #endif
1327
1328 /*
1329  *  Global CCB HEADER.
1330  *
1331  *  Due to lack of indirect addressing on earlier NCR chips,
1332  *  this substructure is copied from the ccb to a global
1333  *  address after selection (or reselection) and copied back
1334  *  before disconnect.
1335  *  For SYMBIOS chips that support LOAD/STORE this copy is
1336  *  not needed and thus not performed.
1337  */
1338 struct sym_ccbh {
1339         /*
1340          *  Start and restart SCRIPTS addresses (must be at 0).
1341          */
1342 /*0*/   struct sym_actscr go;
1343
1344         /*
1345          *  SCRIPTS jump address that deal with data pointers.
1346          *  'savep' points to the position in the script responsible
1347          *  for the actual transfer of data.
1348          *  It's written on reception of a SAVE_DATA_POINTER message.
1349          */
1350         u32     savep;          /* Jump address to saved data pointer   */
1351         u32     lastp;          /* SCRIPTS address at end of data       */
1352         u32     goalp;          /* Not accessed for now from SCRIPTS    */
1353
1354         /*
1355          *  Status fields.
1356          */
1357         u8      status[4];
1358 };
1359
1360 /*
1361  *  Data Structure Block
1362  *
1363  *  During execution of a ccb by the script processor, the
1364  *  DSA (data structure address) register points to this
1365  *  substructure of the ccb.
1366  */
1367 struct sym_dsb {
1368         /*
1369          *  CCB header.
1370          *  Also assumed at offset 0 of the sym_ccb structure.
1371          */
1372 /*0*/   struct sym_ccbh head;
1373
1374         /*
1375          *  Phase mismatch contexts.
1376          *  We need two to handle correctly the SAVED DATA POINTER.
1377          *  MUST BOTH BE AT OFFSET < 256, due to using 8 bit arithmetic
1378          *  for address calculation from SCRIPTS.
1379          */
1380         struct sym_pmc pm0;
1381         struct sym_pmc pm1;
1382
1383         /*
1384          *  Table data for Script
1385          */
1386         struct sym_tblsel  select;
1387         struct sym_tblmove smsg;
1388         struct sym_tblmove smsg_ext;
1389         struct sym_tblmove cmd;
1390         struct sym_tblmove sense;
1391         struct sym_tblmove wresid;
1392         struct sym_tblmove data [SYM_CONF_MAX_SG];
1393 };
1394
1395 /*
1396  *  Our Command Control Block
1397  */
1398 struct sym_ccb {
1399         /*
1400          *  This is the data structure which is pointed by the DSA
1401          *  register when it is executed by the script processor.
1402          *  It must be the first entry.
1403          */
1404         struct sym_dsb phys;
1405
1406         /*
1407          *  Pointer to CAM ccb and related stuff.
1408          */
1409         struct callout ch;      /* callout handle               */
1410         union ccb *cam_ccb;     /* CAM scsiio ccb               */
1411         u8      cdb_buf[16];    /* Copy of CDB                  */
1412         u8      *sns_bbuf;      /* Bounce buffer for sense data */
1413 #define SYM_SNS_BBUF_LEN        sizeof(struct scsi_sense_data)
1414         int     data_len;       /* Total data length            */
1415         int     segments;       /* Number of SG segments        */
1416
1417         /*
1418          *  Miscellaneous status'.
1419          */
1420         u_char  nego_status;    /* Negotiation status           */
1421         u_char  xerr_status;    /* Extended error flags         */
1422         u32     extra_bytes;    /* Extraneous bytes transferred */
1423
1424         /*
1425          *  Message areas.
1426          *  We prepare a message to be sent after selection.
1427          *  We may use a second one if the command is rescheduled
1428          *  due to CHECK_CONDITION or COMMAND TERMINATED.
1429          *  Contents are IDENTIFY and SIMPLE_TAG.
1430          *  While negotiating sync or wide transfer,
1431          *  a SDTR or WDTR message is appended.
1432          */
1433         u_char  scsi_smsg [12];
1434         u_char  scsi_smsg2[12];
1435
1436         /*
1437          *  Auto request sense related fields.
1438          */
1439         u_char  sensecmd[6];    /* Request Sense command        */
1440         u_char  sv_scsi_status; /* Saved SCSI status            */
1441         u_char  sv_xerr_status; /* Saved extended status        */
1442         int     sv_resid;       /* Saved residual               */
1443
1444         /*
1445          *  Map for the DMA of user data.
1446          */
1447         void            *arg;   /* Argument for some callback   */
1448         bus_dmamap_t    dmamap; /* DMA map for user data        */
1449         u_char          dmamapped;
1450 #define SYM_DMA_NONE    0
1451 #define SYM_DMA_READ    1
1452 #define SYM_DMA_WRITE   2
1453         /*
1454          *  Other fields.
1455          */
1456         u32     ccb_ba;         /* BUS address of this CCB      */
1457         u_short tag;            /* Tag for this transfer        */
1458                                 /*  NO_TAG means no tag         */
1459         u_char  target;
1460         u_char  lun;
1461         ccb_p   link_ccbh;      /* Host adapter CCB hash chain  */
1462         SYM_QUEHEAD
1463                 link_ccbq;      /* Link to free/busy CCB queue  */
1464         u32     startp;         /* Initial data pointer         */
1465         int     ext_sg;         /* Extreme data pointer, used   */
1466         int     ext_ofs;        /*  to calculate the residual.  */
1467         u_char  to_abort;       /* Want this IO to be aborted   */
1468 };
1469
1470 #define CCB_BA(cp,lbl)  (cp->ccb_ba + offsetof(struct sym_ccb, lbl))
1471
1472 /*
1473  *  Host Control Block
1474  */
1475 struct sym_hcb {
1476         struct mtx      mtx;
1477
1478         /*
1479          *  Global headers.
1480          *  Due to poorness of addressing capabilities, earlier
1481          *  chips (810, 815, 825) copy part of the data structures
1482          *  (CCB, TCB and LCB) in fixed areas.
1483          */
1484 #ifdef  SYM_CONF_GENERIC_SUPPORT
1485         struct sym_ccbh ccb_head;
1486         struct sym_tcbh tcb_head;
1487         struct sym_lcbh lcb_head;
1488 #endif
1489         /*
1490          *  Idle task and invalid task actions and
1491          *  their bus addresses.
1492          */
1493         struct sym_actscr idletask, notask, bad_itl, bad_itlq;
1494         vm_offset_t idletask_ba, notask_ba, bad_itl_ba, bad_itlq_ba;
1495
1496         /*
1497          *  Dummy lun table to protect us against target
1498          *  returning bad lun number on reselection.
1499          */
1500         u32     *badluntbl;     /* Table physical address       */
1501         u32     badlun_sa;      /* SCRIPT handler BUS address   */
1502
1503         /*
1504          *  Bus address of this host control block.
1505          */
1506         u32     hcb_ba;
1507
1508         /*
1509          *  Bit 32-63 of the on-chip RAM bus address in LE format.
1510          *  The START_RAM64 script loads the MMRS and MMWS from this
1511          *  field.
1512          */
1513         u32     scr_ram_seg;
1514
1515         /*
1516          *  Chip and controller indentification.
1517          */
1518         device_t device;
1519
1520         /*
1521          *  Initial value of some IO register bits.
1522          *  These values are assumed to have been set by BIOS, and may
1523          *  be used to probe adapter implementation differences.
1524          */
1525         u_char  sv_scntl0, sv_scntl3, sv_dmode, sv_dcntl, sv_ctest3, sv_ctest4,
1526                 sv_ctest5, sv_gpcntl, sv_stest2, sv_stest4, sv_scntl4,
1527                 sv_stest1;
1528
1529         /*
1530          *  Actual initial value of IO register bits used by the
1531          *  driver. They are loaded at initialisation according to
1532          *  features that are to be enabled/disabled.
1533          */
1534         u_char  rv_scntl0, rv_scntl3, rv_dmode, rv_dcntl, rv_ctest3, rv_ctest4,
1535                 rv_ctest5, rv_stest2, rv_ccntl0, rv_ccntl1, rv_scntl4;
1536
1537         /*
1538          *  Target data.
1539          */
1540 #ifdef __amd64__
1541         struct sym_tcb  *target;
1542 #else
1543         struct sym_tcb  target[SYM_CONF_MAX_TARGET];
1544 #endif
1545
1546         /*
1547          *  Target control block bus address array used by the SCRIPT
1548          *  on reselection.
1549          */
1550         u32             *targtbl;
1551         u32             targtbl_ba;
1552
1553         /*
1554          *  CAM SIM information for this instance.
1555          */
1556         struct          cam_sim  *sim;
1557         struct          cam_path *path;
1558
1559         /*
1560          *  Allocated hardware resources.
1561          */
1562         struct resource *irq_res;
1563         struct resource *io_res;
1564         struct resource *mmio_res;
1565         struct resource *ram_res;
1566         int             ram_id;
1567         void *intr;
1568
1569         /*
1570          *  Bus stuff.
1571          *
1572          *  My understanding of PCI is that all agents must share the
1573          *  same addressing range and model.
1574          *  But some hardware architecture guys provide complex and
1575          *  brain-deaded stuff that makes shit.
1576          *  This driver only support PCI compliant implementations and
1577          *  deals with part of the BUS stuff complexity only to fit O/S
1578          *  requirements.
1579          */
1580
1581         /*
1582          *  DMA stuff.
1583          */
1584         bus_dma_tag_t   bus_dmat;       /* DMA tag from parent BUS      */
1585         bus_dma_tag_t   data_dmat;      /* DMA tag for user data        */
1586         /*
1587          *  BUS addresses of the chip
1588          */
1589         vm_offset_t     mmio_ba;        /* MMIO BUS address             */
1590         int             mmio_ws;        /* MMIO Window size             */
1591
1592         vm_offset_t     ram_ba;         /* RAM BUS address              */
1593         int             ram_ws;         /* RAM window size              */
1594
1595         /*
1596          *  SCRIPTS virtual and physical bus addresses.
1597          *  'script'  is loaded in the on-chip RAM if present.
1598          *  'scripth' stays in main memory for all chips except the
1599          *  53C895A, 53C896 and 53C1010 that provide 8K on-chip RAM.
1600          */
1601         u_char          *scripta0;      /* Copies of script and scripth */
1602         u_char          *scriptb0;      /* Copies of script and scripth */
1603         vm_offset_t     scripta_ba;     /* Actual script and scripth    */
1604         vm_offset_t     scriptb_ba;     /*  bus addresses.              */
1605         vm_offset_t     scriptb0_ba;
1606         u_short         scripta_sz;     /* Actual size of script A      */
1607         u_short         scriptb_sz;     /* Actual size of script B      */
1608
1609         /*
1610          *  Bus addresses, setup and patch methods for
1611          *  the selected firmware.
1612          */
1613         struct sym_fwa_ba fwa_bas;      /* Useful SCRIPTA bus addresses */
1614         struct sym_fwb_ba fwb_bas;      /* Useful SCRIPTB bus addresses */
1615         void            (*fw_setup)(hcb_p np, const struct sym_fw *fw);
1616         void            (*fw_patch)(hcb_p np);
1617         const char      *fw_name;
1618
1619         /*
1620          *  General controller parameters and configuration.
1621          */
1622         u_short device_id;      /* PCI device id                */
1623         u_char  revision_id;    /* PCI device revision id       */
1624         u_int   features;       /* Chip features map            */
1625         u_char  myaddr;         /* SCSI id of the adapter       */
1626         u_char  maxburst;       /* log base 2 of dwords burst   */
1627         u_char  maxwide;        /* Maximum transfer width       */
1628         u_char  minsync;        /* Min sync period factor (ST)  */
1629         u_char  maxsync;        /* Max sync period factor (ST)  */
1630         u_char  maxoffs;        /* Max scsi offset        (ST)  */
1631         u_char  minsync_dt;     /* Min sync period factor (DT)  */
1632         u_char  maxsync_dt;     /* Max sync period factor (DT)  */
1633         u_char  maxoffs_dt;     /* Max scsi offset        (DT)  */
1634         u_char  multiplier;     /* Clock multiplier (1,2,4)     */
1635         u_char  clock_divn;     /* Number of clock divisors     */
1636         u32     clock_khz;      /* SCSI clock frequency in KHz  */
1637         u32     pciclk_khz;     /* Estimated PCI clock  in KHz  */
1638         /*
1639          *  Start queue management.
1640          *  It is filled up by the host processor and accessed by the
1641          *  SCRIPTS processor in order to start SCSI commands.
1642          */
1643         volatile                /* Prevent code optimizations   */
1644         u32     *squeue;        /* Start queue virtual address  */
1645         u32     squeue_ba;      /* Start queue BUS address      */
1646         u_short squeueput;      /* Next free slot of the queue  */
1647         u_short actccbs;        /* Number of allocated CCBs     */
1648
1649         /*
1650          *  Command completion queue.
1651          *  It is the same size as the start queue to avoid overflow.
1652          */
1653         u_short dqueueget;      /* Next position to scan        */
1654         volatile                /* Prevent code optimizations   */
1655         u32     *dqueue;        /* Completion (done) queue      */
1656         u32     dqueue_ba;      /* Done queue BUS address       */
1657
1658         /*
1659          *  Miscellaneous buffers accessed by the scripts-processor.
1660          *  They shall be DWORD aligned, because they may be read or
1661          *  written with a script command.
1662          */
1663         u_char          msgout[8];      /* Buffer for MESSAGE OUT       */
1664         u_char          msgin [8];      /* Buffer for MESSAGE IN        */
1665         u32             lastmsg;        /* Last SCSI message sent       */
1666         u_char          scratch;        /* Scratch for SCSI receive     */
1667
1668         /*
1669          *  Miscellaneous configuration and status parameters.
1670          */
1671         u_char          usrflags;       /* Miscellaneous user flags     */
1672         u_char          scsi_mode;      /* Current SCSI BUS mode        */
1673         u_char          verbose;        /* Verbosity for this controller*/
1674         u32             cache;          /* Used for cache test at init. */
1675
1676         /*
1677          *  CCB lists and queue.
1678          */
1679         ccb_p ccbh[CCB_HASH_SIZE];      /* CCB hashed by DSA value      */
1680         SYM_QUEHEAD     free_ccbq;      /* Queue of available CCBs      */
1681         SYM_QUEHEAD     busy_ccbq;      /* Queue of busy CCBs           */
1682
1683         /*
1684          *  During error handling and/or recovery,
1685          *  active CCBs that are to be completed with
1686          *  error or requeued are moved from the busy_ccbq
1687          *  to the comp_ccbq prior to completion.
1688          */
1689         SYM_QUEHEAD     comp_ccbq;
1690
1691         /*
1692          *  CAM CCB pending queue.
1693          */
1694         SYM_QUEHEAD     cam_ccbq;
1695
1696         /*
1697          *  IMMEDIATE ARBITRATION (IARB) control.
1698          *
1699          *  We keep track in 'last_cp' of the last CCB that has been
1700          *  queued to the SCRIPTS processor and clear 'last_cp' when
1701          *  this CCB completes. If last_cp is not zero at the moment
1702          *  we queue a new CCB, we set a flag in 'last_cp' that is
1703          *  used by the SCRIPTS as a hint for setting IARB.
1704          *  We donnot set more than 'iarb_max' consecutive hints for
1705          *  IARB in order to leave devices a chance to reselect.
1706          *  By the way, any non zero value of 'iarb_max' is unfair. :)
1707          */
1708 #ifdef SYM_CONF_IARB_SUPPORT
1709         u_short         iarb_max;       /* Max. # consecutive IARB hints*/
1710         u_short         iarb_count;     /* Actual # of these hints      */
1711         ccb_p           last_cp;
1712 #endif
1713
1714         /*
1715          *  Command abort handling.
1716          *  We need to synchronize tightly with the SCRIPTS
1717          *  processor in order to handle things correctly.
1718          */
1719         u_char          abrt_msg[4];    /* Message to send buffer       */
1720         struct sym_tblmove abrt_tbl;    /* Table for the MOV of it      */
1721         struct sym_tblsel  abrt_sel;    /* Sync params for selection    */
1722         u_char          istat_sem;      /* Tells the chip to stop (SEM) */
1723 };
1724
1725 #define HCB_BA(np, lbl)     (np->hcb_ba      + offsetof(struct sym_hcb, lbl))
1726
1727 /*
1728  *  Return the name of the controller.
1729  */
1730 static __inline const char *sym_name(hcb_p np)
1731 {
1732         return device_get_nameunit(np->device);
1733 }
1734
1735 /*--------------------------------------------------------------------------*/
1736 /*------------------------------ FIRMWARES ---------------------------------*/
1737 /*--------------------------------------------------------------------------*/
1738
1739 /*
1740  *  This stuff will be moved to a separate source file when
1741  *  the driver will be broken into several source modules.
1742  */
1743
1744 /*
1745  *  Macros used for all firmwares.
1746  */
1747 #define SYM_GEN_A(s, label)     ((short) offsetof(s, label)),
1748 #define SYM_GEN_B(s, label)     ((short) offsetof(s, label)),
1749 #define PADDR_A(label)          SYM_GEN_PADDR_A(struct SYM_FWA_SCR, label)
1750 #define PADDR_B(label)          SYM_GEN_PADDR_B(struct SYM_FWB_SCR, label)
1751
1752 #ifdef  SYM_CONF_GENERIC_SUPPORT
1753 /*
1754  *  Allocate firmware #1 script area.
1755  */
1756 #define SYM_FWA_SCR             sym_fw1a_scr
1757 #define SYM_FWB_SCR             sym_fw1b_scr
1758 #include <dev/sym/sym_fw1.h>
1759 static const struct sym_fwa_ofs sym_fw1a_ofs = {
1760         SYM_GEN_FW_A(struct SYM_FWA_SCR)
1761 };
1762 static const struct sym_fwb_ofs sym_fw1b_ofs = {
1763         SYM_GEN_FW_B(struct SYM_FWB_SCR)
1764 };
1765 #undef  SYM_FWA_SCR
1766 #undef  SYM_FWB_SCR
1767 #endif  /* SYM_CONF_GENERIC_SUPPORT */
1768
1769 /*
1770  *  Allocate firmware #2 script area.
1771  */
1772 #define SYM_FWA_SCR             sym_fw2a_scr
1773 #define SYM_FWB_SCR             sym_fw2b_scr
1774 #include <dev/sym/sym_fw2.h>
1775 static const struct sym_fwa_ofs sym_fw2a_ofs = {
1776         SYM_GEN_FW_A(struct SYM_FWA_SCR)
1777 };
1778 static const struct sym_fwb_ofs sym_fw2b_ofs = {
1779         SYM_GEN_FW_B(struct SYM_FWB_SCR)
1780         SYM_GEN_B(struct SYM_FWB_SCR, start64)
1781         SYM_GEN_B(struct SYM_FWB_SCR, pm_handle)
1782 };
1783 #undef  SYM_FWA_SCR
1784 #undef  SYM_FWB_SCR
1785
1786 #undef  SYM_GEN_A
1787 #undef  SYM_GEN_B
1788 #undef  PADDR_A
1789 #undef  PADDR_B
1790
1791 #ifdef  SYM_CONF_GENERIC_SUPPORT
1792 /*
1793  *  Patch routine for firmware #1.
1794  */
1795 static void
1796 sym_fw1_patch(hcb_p np)
1797 {
1798         struct sym_fw1a_scr *scripta0;
1799         struct sym_fw1b_scr *scriptb0;
1800
1801         scripta0 = (struct sym_fw1a_scr *) np->scripta0;
1802         scriptb0 = (struct sym_fw1b_scr *) np->scriptb0;
1803
1804         /*
1805          *  Remove LED support if not needed.
1806          */
1807         if (!(np->features & FE_LED0)) {
1808                 scripta0->idle[0]       = cpu_to_scr(SCR_NO_OP);
1809                 scripta0->reselected[0] = cpu_to_scr(SCR_NO_OP);
1810                 scripta0->start[0]      = cpu_to_scr(SCR_NO_OP);
1811         }
1812
1813 #ifdef SYM_CONF_IARB_SUPPORT
1814         /*
1815          *    If user does not want to use IMMEDIATE ARBITRATION
1816          *    when we are reselected while attempting to arbitrate,
1817          *    patch the SCRIPTS accordingly with a SCRIPT NO_OP.
1818          */
1819         if (!SYM_CONF_SET_IARB_ON_ARB_LOST)
1820                 scripta0->ungetjob[0] = cpu_to_scr(SCR_NO_OP);
1821 #endif
1822         /*
1823          *  Patch some data in SCRIPTS.
1824          *  - start and done queue initial bus address.
1825          *  - target bus address table bus address.
1826          */
1827         scriptb0->startpos[0]   = cpu_to_scr(np->squeue_ba);
1828         scriptb0->done_pos[0]   = cpu_to_scr(np->dqueue_ba);
1829         scriptb0->targtbl[0]    = cpu_to_scr(np->targtbl_ba);
1830 }
1831 #endif  /* SYM_CONF_GENERIC_SUPPORT */
1832
1833 /*
1834  *  Patch routine for firmware #2.
1835  */
1836 static void
1837 sym_fw2_patch(hcb_p np)
1838 {
1839         struct sym_fw2a_scr *scripta0;
1840         struct sym_fw2b_scr *scriptb0;
1841
1842         scripta0 = (struct sym_fw2a_scr *) np->scripta0;
1843         scriptb0 = (struct sym_fw2b_scr *) np->scriptb0;
1844
1845         /*
1846          *  Remove LED support if not needed.
1847          */
1848         if (!(np->features & FE_LED0)) {
1849                 scripta0->idle[0]       = cpu_to_scr(SCR_NO_OP);
1850                 scripta0->reselected[0] = cpu_to_scr(SCR_NO_OP);
1851                 scripta0->start[0]      = cpu_to_scr(SCR_NO_OP);
1852         }
1853
1854 #ifdef SYM_CONF_IARB_SUPPORT
1855         /*
1856          *    If user does not want to use IMMEDIATE ARBITRATION
1857          *    when we are reselected while attempting to arbitrate,
1858          *    patch the SCRIPTS accordingly with a SCRIPT NO_OP.
1859          */
1860         if (!SYM_CONF_SET_IARB_ON_ARB_LOST)
1861                 scripta0->ungetjob[0] = cpu_to_scr(SCR_NO_OP);
1862 #endif
1863         /*
1864          *  Patch some variable in SCRIPTS.
1865          *  - start and done queue initial bus address.
1866          *  - target bus address table bus address.
1867          */
1868         scriptb0->startpos[0]   = cpu_to_scr(np->squeue_ba);
1869         scriptb0->done_pos[0]   = cpu_to_scr(np->dqueue_ba);
1870         scriptb0->targtbl[0]    = cpu_to_scr(np->targtbl_ba);
1871
1872         /*
1873          *  Remove the load of SCNTL4 on reselection if not a C10.
1874          */
1875         if (!(np->features & FE_C10)) {
1876                 scripta0->resel_scntl4[0] = cpu_to_scr(SCR_NO_OP);
1877                 scripta0->resel_scntl4[1] = cpu_to_scr(0);
1878         }
1879
1880         /*
1881          *  Remove a couple of work-arounds specific to C1010 if
1882          *  they are not desirable. See `sym_fw2.h' for more details.
1883          */
1884         if (!(np->device_id == PCI_ID_LSI53C1010_2 &&
1885               np->revision_id < 0x1 &&
1886               np->pciclk_khz < 60000)) {
1887                 scripta0->datao_phase[0] = cpu_to_scr(SCR_NO_OP);
1888                 scripta0->datao_phase[1] = cpu_to_scr(0);
1889         }
1890         if (!(np->device_id == PCI_ID_LSI53C1010 &&
1891               /* np->revision_id < 0xff */ 1)) {
1892                 scripta0->sel_done[0] = cpu_to_scr(SCR_NO_OP);
1893                 scripta0->sel_done[1] = cpu_to_scr(0);
1894         }
1895
1896         /*
1897          *  Patch some other variables in SCRIPTS.
1898          *  These ones are loaded by the SCRIPTS processor.
1899          */
1900         scriptb0->pm0_data_addr[0] =
1901                 cpu_to_scr(np->scripta_ba +
1902                            offsetof(struct sym_fw2a_scr, pm0_data));
1903         scriptb0->pm1_data_addr[0] =
1904                 cpu_to_scr(np->scripta_ba +
1905                            offsetof(struct sym_fw2a_scr, pm1_data));
1906 }
1907
1908 /*
1909  *  Fill the data area in scripts.
1910  *  To be done for all firmwares.
1911  */
1912 static void
1913 sym_fw_fill_data (u32 *in, u32 *out)
1914 {
1915         int     i;
1916
1917         for (i = 0; i < SYM_CONF_MAX_SG; i++) {
1918                 *in++  = SCR_CHMOV_TBL ^ SCR_DATA_IN;
1919                 *in++  = offsetof (struct sym_dsb, data[i]);
1920                 *out++ = SCR_CHMOV_TBL ^ SCR_DATA_OUT;
1921                 *out++ = offsetof (struct sym_dsb, data[i]);
1922         }
1923 }
1924
1925 /*
1926  *  Setup useful script bus addresses.
1927  *  To be done for all firmwares.
1928  */
1929 static void
1930 sym_fw_setup_bus_addresses(hcb_p np, const struct sym_fw *fw)
1931 {
1932         u32 *pa;
1933         const u_short *po;
1934         int i;
1935
1936         /*
1937          *  Build the bus address table for script A
1938          *  from the script A offset table.
1939          */
1940         po = (const u_short *) fw->a_ofs;
1941         pa = (u32 *) &np->fwa_bas;
1942         for (i = 0 ; i < sizeof(np->fwa_bas)/sizeof(u32) ; i++)
1943                 pa[i] = np->scripta_ba + po[i];
1944
1945         /*
1946          *  Same for script B.
1947          */
1948         po = (const u_short *) fw->b_ofs;
1949         pa = (u32 *) &np->fwb_bas;
1950         for (i = 0 ; i < sizeof(np->fwb_bas)/sizeof(u32) ; i++)
1951                 pa[i] = np->scriptb_ba + po[i];
1952 }
1953
1954 #ifdef  SYM_CONF_GENERIC_SUPPORT
1955 /*
1956  *  Setup routine for firmware #1.
1957  */
1958 static void
1959 sym_fw1_setup(hcb_p np, const struct sym_fw *fw)
1960 {
1961         struct sym_fw1a_scr *scripta0;
1962
1963         scripta0 = (struct sym_fw1a_scr *) np->scripta0;
1964
1965         /*
1966          *  Fill variable parts in scripts.
1967          */
1968         sym_fw_fill_data(scripta0->data_in, scripta0->data_out);
1969
1970         /*
1971          *  Setup bus addresses used from the C code..
1972          */
1973         sym_fw_setup_bus_addresses(np, fw);
1974 }
1975 #endif  /* SYM_CONF_GENERIC_SUPPORT */
1976
1977 /*
1978  *  Setup routine for firmware #2.
1979  */
1980 static void
1981 sym_fw2_setup(hcb_p np, const struct sym_fw *fw)
1982 {
1983         struct sym_fw2a_scr *scripta0;
1984
1985         scripta0 = (struct sym_fw2a_scr *) np->scripta0;
1986
1987         /*
1988          *  Fill variable parts in scripts.
1989          */
1990         sym_fw_fill_data(scripta0->data_in, scripta0->data_out);
1991
1992         /*
1993          *  Setup bus addresses used from the C code..
1994          */
1995         sym_fw_setup_bus_addresses(np, fw);
1996 }
1997
1998 /*
1999  *  Allocate firmware descriptors.
2000  */
2001 #ifdef  SYM_CONF_GENERIC_SUPPORT
2002 static const struct sym_fw sym_fw1 = SYM_FW_ENTRY(sym_fw1, "NCR-generic");
2003 #endif  /* SYM_CONF_GENERIC_SUPPORT */
2004 static const struct sym_fw sym_fw2 = SYM_FW_ENTRY(sym_fw2, "LOAD/STORE-based");
2005
2006 /*
2007  *  Find the most appropriate firmware for a chip.
2008  */
2009 static const struct sym_fw *
2010 sym_find_firmware(const struct sym_pci_chip *chip)
2011 {
2012         if (chip->features & FE_LDSTR)
2013                 return &sym_fw2;
2014 #ifdef  SYM_CONF_GENERIC_SUPPORT
2015         else if (!(chip->features & (FE_PFEN|FE_NOPM|FE_DAC)))
2016                 return &sym_fw1;
2017 #endif
2018         else
2019                 return NULL;
2020 }
2021
2022 /*
2023  *  Bind a script to physical addresses.
2024  */
2025 static void sym_fw_bind_script (hcb_p np, u32 *start, int len)
2026 {
2027         u32 opcode, new, old, tmp1, tmp2;
2028         u32 *end, *cur;
2029         int relocs;
2030
2031         cur = start;
2032         end = start + len/4;
2033
2034         while (cur < end) {
2035
2036                 opcode = *cur;
2037
2038                 /*
2039                  *  If we forget to change the length
2040                  *  in scripts, a field will be
2041                  *  padded with 0. This is an illegal
2042                  *  command.
2043                  */
2044                 if (opcode == 0) {
2045                         printf ("%s: ERROR0 IN SCRIPT at %d.\n",
2046                                 sym_name(np), (int) (cur-start));
2047                         MDELAY (10000);
2048                         ++cur;
2049                         continue;
2050                 };
2051
2052                 /*
2053                  *  We use the bogus value 0xf00ff00f ;-)
2054                  *  to reserve data area in SCRIPTS.
2055                  */
2056                 if (opcode == SCR_DATA_ZERO) {
2057                         *cur++ = 0;
2058                         continue;
2059                 }
2060
2061                 if (DEBUG_FLAGS & DEBUG_SCRIPT)
2062                         printf ("%d:  <%x>\n", (int) (cur-start),
2063                                 (unsigned)opcode);
2064
2065                 /*
2066                  *  We don't have to decode ALL commands
2067                  */
2068                 switch (opcode >> 28) {
2069                 case 0xf:
2070                         /*
2071                          *  LOAD / STORE DSA relative, don't relocate.
2072                          */
2073                         relocs = 0;
2074                         break;
2075                 case 0xe:
2076                         /*
2077                          *  LOAD / STORE absolute.
2078                          */
2079                         relocs = 1;
2080                         break;
2081                 case 0xc:
2082                         /*
2083                          *  COPY has TWO arguments.
2084                          */
2085                         relocs = 2;
2086                         tmp1 = cur[1];
2087                         tmp2 = cur[2];
2088                         if ((tmp1 ^ tmp2) & 3) {
2089                                 printf ("%s: ERROR1 IN SCRIPT at %d.\n",
2090                                         sym_name(np), (int) (cur-start));
2091                                 MDELAY (10000);
2092                         }
2093                         /*
2094                          *  If PREFETCH feature not enabled, remove
2095                          *  the NO FLUSH bit if present.
2096                          */
2097                         if ((opcode & SCR_NO_FLUSH) &&
2098                             !(np->features & FE_PFEN)) {
2099                                 opcode = (opcode & ~SCR_NO_FLUSH);
2100                         }
2101                         break;
2102                 case 0x0:
2103                         /*
2104                          *  MOVE/CHMOV (absolute address)
2105                          */
2106                         if (!(np->features & FE_WIDE))
2107                                 opcode = (opcode | OPC_MOVE);
2108                         relocs = 1;
2109                         break;
2110                 case 0x1:
2111                         /*
2112                          *  MOVE/CHMOV (table indirect)
2113                          */
2114                         if (!(np->features & FE_WIDE))
2115                                 opcode = (opcode | OPC_MOVE);
2116                         relocs = 0;
2117                         break;
2118                 case 0x8:
2119                         /*
2120                          *  JUMP / CALL
2121                          *  dont't relocate if relative :-)
2122                          */
2123                         if (opcode & 0x00800000)
2124                                 relocs = 0;
2125                         else if ((opcode & 0xf8400000) == 0x80400000)/*JUMP64*/
2126                                 relocs = 2;
2127                         else
2128                                 relocs = 1;
2129                         break;
2130                 case 0x4:
2131                 case 0x5:
2132                 case 0x6:
2133                 case 0x7:
2134                         relocs = 1;
2135                         break;
2136                 default:
2137                         relocs = 0;
2138                         break;
2139                 };
2140
2141                 /*
2142                  *  Scriptify:) the opcode.
2143                  */
2144                 *cur++ = cpu_to_scr(opcode);
2145
2146                 /*
2147                  *  If no relocation, assume 1 argument
2148                  *  and just scriptize:) it.
2149                  */
2150                 if (!relocs) {
2151                         *cur = cpu_to_scr(*cur);
2152                         ++cur;
2153                         continue;
2154                 }
2155
2156                 /*
2157                  *  Otherwise performs all needed relocations.
2158                  */
2159                 while (relocs--) {
2160                         old = *cur;
2161
2162                         switch (old & RELOC_MASK) {
2163                         case RELOC_REGISTER:
2164                                 new = (old & ~RELOC_MASK) + np->mmio_ba;
2165                                 break;
2166                         case RELOC_LABEL_A:
2167                                 new = (old & ~RELOC_MASK) + np->scripta_ba;
2168                                 break;
2169                         case RELOC_LABEL_B:
2170                                 new = (old & ~RELOC_MASK) + np->scriptb_ba;
2171                                 break;
2172                         case RELOC_SOFTC:
2173                                 new = (old & ~RELOC_MASK) + np->hcb_ba;
2174                                 break;
2175                         case 0:
2176                                 /*
2177                                  *  Don't relocate a 0 address.
2178                                  *  They are mostly used for patched or
2179                                  *  script self-modified areas.
2180                                  */
2181                                 if (old == 0) {
2182                                         new = old;
2183                                         break;
2184                                 }
2185                                 /* fall through */
2186                         default:
2187                                 new = 0;
2188                                 panic("sym_fw_bind_script: "
2189                                       "weird relocation %x\n", old);
2190                                 break;
2191                         }
2192
2193                         *cur++ = cpu_to_scr(new);
2194                 }
2195         };
2196 }
2197
2198 /*---------------------------------------------------------------------------*/
2199 /*--------------------------- END OF FIRMWARES  -----------------------------*/
2200 /*---------------------------------------------------------------------------*/
2201
2202 /*
2203  *  Function prototypes.
2204  */
2205 static void sym_save_initial_setting (hcb_p np);
2206 static int  sym_prepare_setting (hcb_p np, struct sym_nvram *nvram);
2207 static int  sym_prepare_nego (hcb_p np, ccb_p cp, int nego, u_char *msgptr);
2208 static void sym_put_start_queue (hcb_p np, ccb_p cp);
2209 static void sym_chip_reset (hcb_p np);
2210 static void sym_soft_reset (hcb_p np);
2211 static void sym_start_reset (hcb_p np);
2212 static int  sym_reset_scsi_bus (hcb_p np, int enab_int);
2213 static int  sym_wakeup_done (hcb_p np);
2214 static void sym_flush_busy_queue (hcb_p np, int cam_status);
2215 static void sym_flush_comp_queue (hcb_p np, int cam_status);
2216 static void sym_init (hcb_p np, int reason);
2217 static int  sym_getsync(hcb_p np, u_char dt, u_char sfac, u_char *divp,
2218                         u_char *fakp);
2219 static void sym_setsync (hcb_p np, ccb_p cp, u_char ofs, u_char per,
2220                          u_char div, u_char fak);
2221 static void sym_setwide (hcb_p np, ccb_p cp, u_char wide);
2222 static void sym_setpprot(hcb_p np, ccb_p cp, u_char dt, u_char ofs,
2223                          u_char per, u_char wide, u_char div, u_char fak);
2224 static void sym_settrans(hcb_p np, ccb_p cp, u_char dt, u_char ofs,
2225                          u_char per, u_char wide, u_char div, u_char fak);
2226 static void sym_log_hard_error (hcb_p np, u_short sist, u_char dstat);
2227 static void sym_intr (void *arg);
2228 static void sym_poll (struct cam_sim *sim);
2229 static void sym_recover_scsi_int (hcb_p np, u_char hsts);
2230 static void sym_int_sto (hcb_p np);
2231 static void sym_int_udc (hcb_p np);
2232 static void sym_int_sbmc (hcb_p np);
2233 static void sym_int_par (hcb_p np, u_short sist);
2234 static void sym_int_ma (hcb_p np);
2235 static int  sym_dequeue_from_squeue(hcb_p np, int i, int target, int lun,
2236                                     int task);
2237 static void sym_sir_bad_scsi_status (hcb_p np, ccb_p cp);
2238 static int  sym_clear_tasks (hcb_p np, int status, int targ, int lun, int task);
2239 static void sym_sir_task_recovery (hcb_p np, int num);
2240 static int  sym_evaluate_dp (hcb_p np, ccb_p cp, u32 scr, int *ofs);
2241 static void sym_modify_dp(hcb_p np, ccb_p cp, int ofs);
2242 static int  sym_compute_residual (hcb_p np, ccb_p cp);
2243 static int  sym_show_msg (u_char * msg);
2244 static void sym_print_msg (ccb_p cp, char *label, u_char *msg);
2245 static void sym_sync_nego (hcb_p np, tcb_p tp, ccb_p cp);
2246 static void sym_ppr_nego (hcb_p np, tcb_p tp, ccb_p cp);
2247 static void sym_wide_nego (hcb_p np, tcb_p tp, ccb_p cp);
2248 static void sym_nego_default (hcb_p np, tcb_p tp, ccb_p cp);
2249 static void sym_nego_rejected (hcb_p np, tcb_p tp, ccb_p cp);
2250 static void sym_int_sir (hcb_p np);
2251 static void sym_free_ccb (hcb_p np, ccb_p cp);
2252 static ccb_p sym_get_ccb (hcb_p np, u_char tn, u_char ln, u_char tag_order);
2253 static ccb_p sym_alloc_ccb (hcb_p np);
2254 static ccb_p sym_ccb_from_dsa (hcb_p np, u32 dsa);
2255 static lcb_p sym_alloc_lcb (hcb_p np, u_char tn, u_char ln);
2256 static void sym_alloc_lcb_tags (hcb_p np, u_char tn, u_char ln);
2257 static int  sym_snooptest (hcb_p np);
2258 static void sym_selectclock(hcb_p np, u_char scntl3);
2259 static void sym_getclock (hcb_p np, int mult);
2260 static int  sym_getpciclock (hcb_p np);
2261 static void sym_complete_ok (hcb_p np, ccb_p cp);
2262 static void sym_complete_error (hcb_p np, ccb_p cp);
2263 static void sym_callout (void *arg);
2264 static int  sym_abort_scsiio (hcb_p np, union ccb *ccb, int timed_out);
2265 static void sym_reset_dev (hcb_p np, union ccb *ccb);
2266 static void sym_action (struct cam_sim *sim, union ccb *ccb);
2267 static int  sym_setup_cdb (hcb_p np, struct ccb_scsiio *csio, ccb_p cp);
2268 static void sym_setup_data_and_start (hcb_p np, struct ccb_scsiio *csio,
2269                                       ccb_p cp);
2270 static int sym_fast_scatter_sg_physical(hcb_p np, ccb_p cp,
2271                                         bus_dma_segment_t *psegs, int nsegs);
2272 static int sym_scatter_sg_physical (hcb_p np, ccb_p cp,
2273                                     bus_dma_segment_t *psegs, int nsegs);
2274 static void sym_action2 (struct cam_sim *sim, union ccb *ccb);
2275 static void sym_update_trans(hcb_p np, struct sym_trans *tip,
2276                               struct ccb_trans_settings *cts);
2277 static void sym_update_dflags(hcb_p np, u_char *flags,
2278                               struct ccb_trans_settings *cts);
2279
2280 static const struct sym_pci_chip *sym_find_pci_chip (device_t dev);
2281 static int  sym_pci_probe (device_t dev);
2282 static int  sym_pci_attach (device_t dev);
2283
2284 static void sym_pci_free (hcb_p np);
2285 static int  sym_cam_attach (hcb_p np);
2286 static void sym_cam_free (hcb_p np);
2287
2288 static void sym_nvram_setup_host (hcb_p np, struct sym_nvram *nvram);
2289 static void sym_nvram_setup_target (hcb_p np, int targ, struct sym_nvram *nvp);
2290 static int sym_read_nvram (hcb_p np, struct sym_nvram *nvp);
2291
2292 /*
2293  *  Print something which allows to retrieve the controller type,
2294  *  unit, target, lun concerned by a kernel message.
2295  */
2296 static void PRINT_TARGET (hcb_p np, int target)
2297 {
2298         printf ("%s:%d:", sym_name(np), target);
2299 }
2300
2301 static void PRINT_LUN(hcb_p np, int target, int lun)
2302 {
2303         printf ("%s:%d:%d:", sym_name(np), target, lun);
2304 }
2305
2306 static void PRINT_ADDR (ccb_p cp)
2307 {
2308         if (cp && cp->cam_ccb)
2309                 xpt_print_path(cp->cam_ccb->ccb_h.path);
2310 }
2311
2312 /*
2313  *  Take into account this ccb in the freeze count.
2314  */
2315 static void sym_freeze_cam_ccb(union ccb *ccb)
2316 {
2317         if (!(ccb->ccb_h.flags & CAM_DEV_QFRZDIS)) {
2318                 if (!(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
2319                         ccb->ccb_h.status |= CAM_DEV_QFRZN;
2320                         xpt_freeze_devq(ccb->ccb_h.path, 1);
2321                 }
2322         }
2323 }
2324
2325 /*
2326  *  Set the status field of a CAM CCB.
2327  */
2328 static __inline void sym_set_cam_status(union ccb *ccb, cam_status status)
2329 {
2330         ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2331         ccb->ccb_h.status |= status;
2332 }
2333
2334 /*
2335  *  Get the status field of a CAM CCB.
2336  */
2337 static __inline int sym_get_cam_status(union ccb *ccb)
2338 {
2339         return ccb->ccb_h.status & CAM_STATUS_MASK;
2340 }
2341
2342 /*
2343  *  Enqueue a CAM CCB.
2344  */
2345 static void sym_enqueue_cam_ccb(ccb_p cp)
2346 {
2347         hcb_p np;
2348         union ccb *ccb;
2349
2350         ccb = cp->cam_ccb;
2351         np = (hcb_p) cp->arg;
2352
2353         assert(!(ccb->ccb_h.status & CAM_SIM_QUEUED));
2354         ccb->ccb_h.status = CAM_REQ_INPROG;
2355
2356         callout_reset(&cp->ch, ccb->ccb_h.timeout * hz / 1000, sym_callout,
2357                         (caddr_t) ccb);
2358         ccb->ccb_h.status |= CAM_SIM_QUEUED;
2359         ccb->ccb_h.sym_hcb_ptr = np;
2360
2361         sym_insque_tail(sym_qptr(&ccb->ccb_h.sim_links), &np->cam_ccbq);
2362 }
2363
2364 /*
2365  *  Complete a pending CAM CCB.
2366  */
2367
2368 static void sym_xpt_done(hcb_p np, union ccb *ccb, ccb_p cp)
2369 {
2370
2371         SYM_LOCK_ASSERT(MA_OWNED);
2372
2373         if (ccb->ccb_h.status & CAM_SIM_QUEUED) {
2374                 callout_stop(&cp->ch);
2375                 sym_remque(sym_qptr(&ccb->ccb_h.sim_links));
2376                 ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
2377                 ccb->ccb_h.sym_hcb_ptr = NULL;
2378         }
2379         xpt_done(ccb);
2380 }
2381
2382 static void sym_xpt_done2(hcb_p np, union ccb *ccb, int cam_status)
2383 {
2384
2385         SYM_LOCK_ASSERT(MA_OWNED);
2386
2387         sym_set_cam_status(ccb, cam_status);
2388         xpt_done(ccb);
2389 }
2390
2391 /*
2392  *  SYMBIOS chip clock divisor table.
2393  *
2394  *  Divisors are multiplied by 10,000,000 in order to make
2395  *  calculations more simple.
2396  */
2397 #define _5M 5000000
2398 static const u32 div_10M[] =
2399         {2*_5M, 3*_5M, 4*_5M, 6*_5M, 8*_5M, 12*_5M, 16*_5M};
2400
2401 /*
2402  *  SYMBIOS chips allow burst lengths of 2, 4, 8, 16, 32, 64,
2403  *  128 transfers. All chips support at least 16 transfers
2404  *  bursts. The 825A, 875 and 895 chips support bursts of up
2405  *  to 128 transfers and the 895A and 896 support bursts of up
2406  *  to 64 transfers. All other chips support up to 16
2407  *  transfers bursts.
2408  *
2409  *  For PCI 32 bit data transfers each transfer is a DWORD.
2410  *  It is a QUADWORD (8 bytes) for PCI 64 bit data transfers.
2411  *
2412  *  We use log base 2 (burst length) as internal code, with
2413  *  value 0 meaning "burst disabled".
2414  */
2415
2416 /*
2417  *  Burst length from burst code.
2418  */
2419 #define burst_length(bc) (!(bc))? 0 : 1 << (bc)
2420
2421 /*
2422  *  Burst code from io register bits.
2423  */
2424 #define burst_code(dmode, ctest4, ctest5) \
2425         (ctest4) & 0x80? 0 : (((dmode) & 0xc0) >> 6) + ((ctest5) & 0x04) + 1
2426
2427 /*
2428  *  Set initial io register bits from burst code.
2429  */
2430 static __inline void sym_init_burst(hcb_p np, u_char bc)
2431 {
2432         np->rv_ctest4   &= ~0x80;
2433         np->rv_dmode    &= ~(0x3 << 6);
2434         np->rv_ctest5   &= ~0x4;
2435
2436         if (!bc) {
2437                 np->rv_ctest4   |= 0x80;
2438         }
2439         else {
2440                 --bc;
2441                 np->rv_dmode    |= ((bc & 0x3) << 6);
2442                 np->rv_ctest5   |= (bc & 0x4);
2443         }
2444 }
2445
2446 /*
2447  * Print out the list of targets that have some flag disabled by user.
2448  */
2449 static void sym_print_targets_flag(hcb_p np, int mask, char *msg)
2450 {
2451         int cnt;
2452         int i;
2453
2454         for (cnt = 0, i = 0 ; i < SYM_CONF_MAX_TARGET ; i++) {
2455                 if (i == np->myaddr)
2456                         continue;
2457                 if (np->target[i].usrflags & mask) {
2458                         if (!cnt++)
2459                                 printf("%s: %s disabled for targets",
2460                                         sym_name(np), msg);
2461                         printf(" %d", i);
2462                 }
2463         }
2464         if (cnt)
2465                 printf(".\n");
2466 }
2467
2468 /*
2469  *  Save initial settings of some IO registers.
2470  *  Assumed to have been set by BIOS.
2471  *  We cannot reset the chip prior to reading the
2472  *  IO registers, since informations will be lost.
2473  *  Since the SCRIPTS processor may be running, this
2474  *  is not safe on paper, but it seems to work quite
2475  *  well. :)
2476  */
2477 static void sym_save_initial_setting (hcb_p np)
2478 {
2479         np->sv_scntl0   = INB(nc_scntl0) & 0x0a;
2480         np->sv_scntl3   = INB(nc_scntl3) & 0x07;
2481         np->sv_dmode    = INB(nc_dmode)  & 0xce;
2482         np->sv_dcntl    = INB(nc_dcntl)  & 0xa8;
2483         np->sv_ctest3   = INB(nc_ctest3) & 0x01;
2484         np->sv_ctest4   = INB(nc_ctest4) & 0x80;
2485         np->sv_gpcntl   = INB(nc_gpcntl);
2486         np->sv_stest1   = INB(nc_stest1);
2487         np->sv_stest2   = INB(nc_stest2) & 0x20;
2488         np->sv_stest4   = INB(nc_stest4);
2489         if (np->features & FE_C10) {    /* Always large DMA fifo + ultra3 */
2490                 np->sv_scntl4   = INB(nc_scntl4);
2491                 np->sv_ctest5   = INB(nc_ctest5) & 0x04;
2492         }
2493         else
2494                 np->sv_ctest5   = INB(nc_ctest5) & 0x24;
2495 }
2496
2497 /*
2498  *  Prepare io register values used by sym_init() according
2499  *  to selected and supported features.
2500  */
2501 static int sym_prepare_setting(hcb_p np, struct sym_nvram *nvram)
2502 {
2503         u_char  burst_max;
2504         u32     period;
2505         int i;
2506
2507         /*
2508          *  Wide ?
2509          */
2510         np->maxwide     = (np->features & FE_WIDE)? 1 : 0;
2511
2512         /*
2513          *  Get the frequency of the chip's clock.
2514          */
2515         if      (np->features & FE_QUAD)
2516                 np->multiplier  = 4;
2517         else if (np->features & FE_DBLR)
2518                 np->multiplier  = 2;
2519         else
2520                 np->multiplier  = 1;
2521
2522         np->clock_khz   = (np->features & FE_CLK80)? 80000 : 40000;
2523         np->clock_khz   *= np->multiplier;
2524
2525         if (np->clock_khz != 40000)
2526                 sym_getclock(np, np->multiplier);
2527
2528         /*
2529          * Divisor to be used for async (timer pre-scaler).
2530          */
2531         i = np->clock_divn - 1;
2532         while (--i >= 0) {
2533                 if (10ul * SYM_CONF_MIN_ASYNC * np->clock_khz > div_10M[i]) {
2534                         ++i;
2535                         break;
2536                 }
2537         }
2538         np->rv_scntl3 = i+1;
2539
2540         /*
2541          * The C1010 uses hardwired divisors for async.
2542          * So, we just throw away, the async. divisor.:-)
2543          */
2544         if (np->features & FE_C10)
2545                 np->rv_scntl3 = 0;
2546
2547         /*
2548          * Minimum synchronous period factor supported by the chip.
2549          * Btw, 'period' is in tenths of nanoseconds.
2550          */
2551         period = (4 * div_10M[0] + np->clock_khz - 1) / np->clock_khz;
2552         if      (period <= 250)         np->minsync = 10;
2553         else if (period <= 303)         np->minsync = 11;
2554         else if (period <= 500)         np->minsync = 12;
2555         else                            np->minsync = (period + 40 - 1) / 40;
2556
2557         /*
2558          * Check against chip SCSI standard support (SCSI-2,ULTRA,ULTRA2).
2559          */
2560         if      (np->minsync < 25 &&
2561                  !(np->features & (FE_ULTRA|FE_ULTRA2|FE_ULTRA3)))
2562                 np->minsync = 25;
2563         else if (np->minsync < 12 &&
2564                  !(np->features & (FE_ULTRA2|FE_ULTRA3)))
2565                 np->minsync = 12;
2566
2567         /*
2568          * Maximum synchronous period factor supported by the chip.
2569          */
2570         period = (11 * div_10M[np->clock_divn - 1]) / (4 * np->clock_khz);
2571         np->maxsync = period > 2540 ? 254 : period / 10;
2572
2573         /*
2574          * If chip is a C1010, guess the sync limits in DT mode.
2575          */
2576         if ((np->features & (FE_C10|FE_ULTRA3)) == (FE_C10|FE_ULTRA3)) {
2577                 if (np->clock_khz == 160000) {
2578                         np->minsync_dt = 9;
2579                         np->maxsync_dt = 50;
2580                         np->maxoffs_dt = 62;
2581                 }
2582         }
2583
2584         /*
2585          *  64 bit addressing  (895A/896/1010) ?
2586          */
2587         if (np->features & FE_DAC)
2588 #ifdef __LP64__
2589                 np->rv_ccntl1   |= (XTIMOD | EXTIBMV);
2590 #else
2591                 np->rv_ccntl1   |= (DDAC);
2592 #endif
2593
2594         /*
2595          *  Phase mismatch handled by SCRIPTS (895A/896/1010) ?
2596          */
2597         if (np->features & FE_NOPM)
2598                 np->rv_ccntl0   |= (ENPMJ);
2599
2600         /*
2601          *  C1010 Errata.
2602          *  In dual channel mode, contention occurs if internal cycles
2603          *  are used. Disable internal cycles.
2604          */
2605         if (np->device_id == PCI_ID_LSI53C1010 &&
2606             np->revision_id < 0x2)
2607                 np->rv_ccntl0   |=  DILS;
2608
2609         /*
2610          *  Select burst length (dwords)
2611          */
2612         burst_max       = SYM_SETUP_BURST_ORDER;
2613         if (burst_max == 255)
2614                 burst_max = burst_code(np->sv_dmode, np->sv_ctest4,
2615                                        np->sv_ctest5);
2616         if (burst_max > 7)
2617                 burst_max = 7;
2618         if (burst_max > np->maxburst)
2619                 burst_max = np->maxburst;
2620
2621         /*
2622          *  DEL 352 - 53C810 Rev x11 - Part Number 609-0392140 - ITEM 2.
2623          *  This chip and the 860 Rev 1 may wrongly use PCI cache line
2624          *  based transactions on LOAD/STORE instructions. So we have
2625          *  to prevent these chips from using such PCI transactions in
2626          *  this driver. The generic ncr driver that does not use
2627          *  LOAD/STORE instructions does not need this work-around.
2628          */
2629         if ((np->device_id == PCI_ID_SYM53C810 &&
2630              np->revision_id >= 0x10 && np->revision_id <= 0x11) ||
2631             (np->device_id == PCI_ID_SYM53C860 &&
2632              np->revision_id <= 0x1))
2633                 np->features &= ~(FE_WRIE|FE_ERL|FE_ERMP);
2634
2635         /*
2636          *  Select all supported special features.
2637          *  If we are using on-board RAM for scripts, prefetch (PFEN)
2638          *  does not help, but burst op fetch (BOF) does.
2639          *  Disabling PFEN makes sure BOF will be used.
2640          */
2641         if (np->features & FE_ERL)
2642                 np->rv_dmode    |= ERL;         /* Enable Read Line */
2643         if (np->features & FE_BOF)
2644                 np->rv_dmode    |= BOF;         /* Burst Opcode Fetch */
2645         if (np->features & FE_ERMP)
2646                 np->rv_dmode    |= ERMP;        /* Enable Read Multiple */
2647 #if 1
2648         if ((np->features & FE_PFEN) && !np->ram_ba)
2649 #else
2650         if (np->features & FE_PFEN)
2651 #endif
2652                 np->rv_dcntl    |= PFEN;        /* Prefetch Enable */
2653         if (np->features & FE_CLSE)
2654                 np->rv_dcntl    |= CLSE;        /* Cache Line Size Enable */
2655         if (np->features & FE_WRIE)
2656                 np->rv_ctest3   |= WRIE;        /* Write and Invalidate */
2657         if (np->features & FE_DFS)
2658                 np->rv_ctest5   |= DFS;         /* Dma Fifo Size */
2659
2660         /*
2661          *  Select some other
2662          */
2663         if (SYM_SETUP_PCI_PARITY)
2664                 np->rv_ctest4   |= MPEE; /* Master parity checking */
2665         if (SYM_SETUP_SCSI_PARITY)
2666                 np->rv_scntl0   |= 0x0a; /*  full arb., ena parity, par->ATN  */
2667
2668         /*
2669          *  Get parity checking, host ID and verbose mode from NVRAM
2670          */
2671         np->myaddr = 255;
2672         sym_nvram_setup_host (np, nvram);
2673 #ifdef __sparc64__
2674         np->myaddr = OF_getscsinitid(np->device);
2675 #endif
2676
2677         /*
2678          *  Get SCSI addr of host adapter (set by bios?).
2679          */
2680         if (np->myaddr == 255) {
2681                 np->myaddr = INB(nc_scid) & 0x07;
2682                 if (!np->myaddr)
2683                         np->myaddr = SYM_SETUP_HOST_ID;
2684         }
2685
2686         /*
2687          *  Prepare initial io register bits for burst length
2688          */
2689         sym_init_burst(np, burst_max);
2690
2691         /*
2692          *  Set SCSI BUS mode.
2693          *  - LVD capable chips (895/895A/896/1010) report the
2694          *    current BUS mode through the STEST4 IO register.
2695          *  - For previous generation chips (825/825A/875),
2696          *    user has to tell us how to check against HVD,
2697          *    since a 100% safe algorithm is not possible.
2698          */
2699         np->scsi_mode = SMODE_SE;
2700         if (np->features & (FE_ULTRA2|FE_ULTRA3))
2701                 np->scsi_mode = (np->sv_stest4 & SMODE);
2702         else if (np->features & FE_DIFF) {
2703                 if (SYM_SETUP_SCSI_DIFF == 1) {
2704                         if (np->sv_scntl3) {
2705                                 if (np->sv_stest2 & 0x20)
2706                                         np->scsi_mode = SMODE_HVD;
2707                         }
2708                         else if (nvram->type == SYM_SYMBIOS_NVRAM) {
2709                                 if (!(INB(nc_gpreg) & 0x08))
2710                                         np->scsi_mode = SMODE_HVD;
2711                         }
2712                 }
2713                 else if (SYM_SETUP_SCSI_DIFF == 2)
2714                         np->scsi_mode = SMODE_HVD;
2715         }
2716         if (np->scsi_mode == SMODE_HVD)
2717                 np->rv_stest2 |= 0x20;
2718
2719         /*
2720          *  Set LED support from SCRIPTS.
2721          *  Ignore this feature for boards known to use a
2722          *  specific GPIO wiring and for the 895A, 896
2723          *  and 1010 that drive the LED directly.
2724          */
2725         if ((SYM_SETUP_SCSI_LED ||
2726              (nvram->type == SYM_SYMBIOS_NVRAM ||
2727               (nvram->type == SYM_TEKRAM_NVRAM &&
2728                np->device_id == PCI_ID_SYM53C895))) &&
2729             !(np->features & FE_LEDC) && !(np->sv_gpcntl & 0x01))
2730                 np->features |= FE_LED0;
2731
2732         /*
2733          *  Set irq mode.
2734          */
2735         switch(SYM_SETUP_IRQ_MODE & 3) {
2736         case 2:
2737                 np->rv_dcntl    |= IRQM;
2738                 break;
2739         case 1:
2740                 np->rv_dcntl    |= (np->sv_dcntl & IRQM);
2741                 break;
2742         default:
2743                 break;
2744         }
2745
2746         /*
2747          *  Configure targets according to driver setup.
2748          *  If NVRAM present get targets setup from NVRAM.
2749          */
2750         for (i = 0 ; i < SYM_CONF_MAX_TARGET ; i++) {
2751                 tcb_p tp = &np->target[i];
2752
2753                 tp->tinfo.user.scsi_version = tp->tinfo.current.scsi_version= 2;
2754                 tp->tinfo.user.spi_version  = tp->tinfo.current.spi_version = 2;
2755                 tp->tinfo.user.period = np->minsync;
2756                 if (np->features & FE_ULTRA3)
2757                         tp->tinfo.user.period = np->minsync_dt;
2758                 tp->tinfo.user.offset = np->maxoffs;
2759                 tp->tinfo.user.width  = np->maxwide ? BUS_16_BIT : BUS_8_BIT;
2760                 tp->usrflags |= (SYM_DISC_ENABLED | SYM_TAGS_ENABLED);
2761                 tp->usrtags = SYM_SETUP_MAX_TAG;
2762
2763                 sym_nvram_setup_target (np, i, nvram);
2764
2765                 /*
2766                  *  For now, guess PPR/DT support from the period
2767                  *  and BUS width.
2768                  */
2769                 if (np->features & FE_ULTRA3) {
2770                         if (tp->tinfo.user.period <= 9  &&
2771                             tp->tinfo.user.width == BUS_16_BIT) {
2772                                 tp->tinfo.user.options |= PPR_OPT_DT;
2773                                 tp->tinfo.user.offset   = np->maxoffs_dt;
2774                                 tp->tinfo.user.spi_version = 3;
2775                         }
2776                 }
2777
2778                 if (!tp->usrtags)
2779                         tp->usrflags &= ~SYM_TAGS_ENABLED;
2780         }
2781
2782         /*
2783          *  Let user know about the settings.
2784          */
2785         i = nvram->type;
2786         printf("%s: %s NVRAM, ID %d, Fast-%d, %s, %s\n", sym_name(np),
2787                 i  == SYM_SYMBIOS_NVRAM ? "Symbios" :
2788                 (i == SYM_TEKRAM_NVRAM  ? "Tekram" : "No"),
2789                 np->myaddr,
2790                 (np->features & FE_ULTRA3) ? 80 :
2791                 (np->features & FE_ULTRA2) ? 40 :
2792                 (np->features & FE_ULTRA)  ? 20 : 10,
2793                 sym_scsi_bus_mode(np->scsi_mode),
2794                 (np->rv_scntl0 & 0xa)   ? "parity checking" : "NO parity");
2795         /*
2796          *  Tell him more on demand.
2797          */
2798         if (sym_verbose) {
2799                 printf("%s: %s IRQ line driver%s\n",
2800                         sym_name(np),
2801                         np->rv_dcntl & IRQM ? "totem pole" : "open drain",
2802                         np->ram_ba ? ", using on-chip SRAM" : "");
2803                 printf("%s: using %s firmware.\n", sym_name(np), np->fw_name);
2804                 if (np->features & FE_NOPM)
2805                         printf("%s: handling phase mismatch from SCRIPTS.\n",
2806                                sym_name(np));
2807         }
2808         /*
2809          *  And still more.
2810          */
2811         if (sym_verbose > 1) {
2812                 printf ("%s: initial SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
2813                         "(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
2814                         sym_name(np), np->sv_scntl3, np->sv_dmode, np->sv_dcntl,
2815                         np->sv_ctest3, np->sv_ctest4, np->sv_ctest5);
2816
2817                 printf ("%s: final   SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
2818                         "(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
2819                         sym_name(np), np->rv_scntl3, np->rv_dmode, np->rv_dcntl,
2820                         np->rv_ctest3, np->rv_ctest4, np->rv_ctest5);
2821         }
2822         /*
2823          *  Let user be aware of targets that have some disable flags set.
2824          */
2825         sym_print_targets_flag(np, SYM_SCAN_BOOT_DISABLED, "SCAN AT BOOT");
2826         if (sym_verbose)
2827                 sym_print_targets_flag(np, SYM_SCAN_LUNS_DISABLED,
2828                                        "SCAN FOR LUNS");
2829
2830         return 0;
2831 }
2832
2833 /*
2834  *  Prepare the next negotiation message if needed.
2835  *
2836  *  Fill in the part of message buffer that contains the
2837  *  negotiation and the nego_status field of the CCB.
2838  *  Returns the size of the message in bytes.
2839  */
2840 static int sym_prepare_nego(hcb_p np, ccb_p cp, int nego, u_char *msgptr)
2841 {
2842         tcb_p tp = &np->target[cp->target];
2843         int msglen = 0;
2844
2845         /*
2846          *  Early C1010 chips need a work-around for DT
2847          *  data transfer to work.
2848          */
2849         if (!(np->features & FE_U3EN))
2850                 tp->tinfo.goal.options = 0;
2851         /*
2852          *  negotiate using PPR ?
2853          */
2854         if (tp->tinfo.goal.options & PPR_OPT_MASK)
2855                 nego = NS_PPR;
2856         /*
2857          *  negotiate wide transfers ?
2858          */
2859         else if (tp->tinfo.current.width != tp->tinfo.goal.width)
2860                 nego = NS_WIDE;
2861         /*
2862          *  negotiate synchronous transfers?
2863          */
2864         else if (tp->tinfo.current.period != tp->tinfo.goal.period ||
2865                  tp->tinfo.current.offset != tp->tinfo.goal.offset)
2866                 nego = NS_SYNC;
2867
2868         switch (nego) {
2869         case NS_SYNC:
2870                 msgptr[msglen++] = M_EXTENDED;
2871                 msgptr[msglen++] = 3;
2872                 msgptr[msglen++] = M_X_SYNC_REQ;
2873                 msgptr[msglen++] = tp->tinfo.goal.period;
2874                 msgptr[msglen++] = tp->tinfo.goal.offset;
2875                 break;
2876         case NS_WIDE:
2877                 msgptr[msglen++] = M_EXTENDED;
2878                 msgptr[msglen++] = 2;
2879                 msgptr[msglen++] = M_X_WIDE_REQ;
2880                 msgptr[msglen++] = tp->tinfo.goal.width;
2881                 break;
2882         case NS_PPR:
2883                 msgptr[msglen++] = M_EXTENDED;
2884                 msgptr[msglen++] = 6;
2885                 msgptr[msglen++] = M_X_PPR_REQ;
2886                 msgptr[msglen++] = tp->tinfo.goal.period;
2887                 msgptr[msglen++] = 0;
2888                 msgptr[msglen++] = tp->tinfo.goal.offset;
2889                 msgptr[msglen++] = tp->tinfo.goal.width;
2890                 msgptr[msglen++] = tp->tinfo.goal.options & PPR_OPT_DT;
2891                 break;
2892         };
2893
2894         cp->nego_status = nego;
2895
2896         if (nego) {
2897                 tp->nego_cp = cp; /* Keep track a nego will be performed */
2898                 if (DEBUG_FLAGS & DEBUG_NEGO) {
2899                         sym_print_msg(cp, nego == NS_SYNC ? "sync msgout" :
2900                                           nego == NS_WIDE ? "wide msgout" :
2901                                           "ppr msgout", msgptr);
2902                 };
2903         };
2904
2905         return msglen;
2906 }
2907
2908 /*
2909  *  Insert a job into the start queue.
2910  */
2911 static void sym_put_start_queue(hcb_p np, ccb_p cp)
2912 {
2913         u_short qidx;
2914
2915 #ifdef SYM_CONF_IARB_SUPPORT
2916         /*
2917          *  If the previously queued CCB is not yet done,
2918          *  set the IARB hint. The SCRIPTS will go with IARB
2919          *  for this job when starting the previous one.
2920          *  We leave devices a chance to win arbitration by
2921          *  not using more than 'iarb_max' consecutive
2922          *  immediate arbitrations.
2923          */
2924         if (np->last_cp && np->iarb_count < np->iarb_max) {
2925                 np->last_cp->host_flags |= HF_HINT_IARB;
2926                 ++np->iarb_count;
2927         }
2928         else
2929                 np->iarb_count = 0;
2930         np->last_cp = cp;
2931 #endif
2932
2933         /*
2934          *  Insert first the idle task and then our job.
2935          *  The MB should ensure proper ordering.
2936          */
2937         qidx = np->squeueput + 2;
2938         if (qidx >= MAX_QUEUE*2) qidx = 0;
2939
2940         np->squeue [qidx]          = cpu_to_scr(np->idletask_ba);
2941         MEMORY_BARRIER();
2942         np->squeue [np->squeueput] = cpu_to_scr(cp->ccb_ba);
2943
2944         np->squeueput = qidx;
2945
2946         if (DEBUG_FLAGS & DEBUG_QUEUE)
2947                 printf ("%s: queuepos=%d.\n", sym_name (np), np->squeueput);
2948
2949         /*
2950          *  Script processor may be waiting for reselect.
2951          *  Wake it up.
2952          */
2953         MEMORY_BARRIER();
2954         OUTB (nc_istat, SIGP|np->istat_sem);
2955 }
2956
2957 /*
2958  *  Soft reset the chip.
2959  *
2960  *  Raising SRST when the chip is running may cause
2961  *  problems on dual function chips (see below).
2962  *  On the other hand, LVD devices need some delay
2963  *  to settle and report actual BUS mode in STEST4.
2964  */
2965 static void sym_chip_reset (hcb_p np)
2966 {
2967         OUTB (nc_istat, SRST);
2968         UDELAY (10);
2969         OUTB (nc_istat, 0);
2970         UDELAY(2000);   /* For BUS MODE to settle */
2971 }
2972
2973 /*
2974  *  Soft reset the chip.
2975  *
2976  *  Some 896 and 876 chip revisions may hang-up if we set
2977  *  the SRST (soft reset) bit at the wrong time when SCRIPTS
2978  *  are running.
2979  *  So, we need to abort the current operation prior to
2980  *  soft resetting the chip.
2981  */
2982 static void sym_soft_reset (hcb_p np)
2983 {
2984         u_char istat;
2985         int i;
2986
2987         OUTB (nc_istat, CABRT);
2988         for (i = 1000000 ; i ; --i) {
2989                 istat = INB (nc_istat);
2990                 if (istat & SIP) {
2991                         INW (nc_sist);
2992                         continue;
2993                 }
2994                 if (istat & DIP) {
2995                         OUTB (nc_istat, 0);
2996                         INB (nc_dstat);
2997                         break;
2998                 }
2999         }
3000         if (!i)
3001                 printf("%s: unable to abort current chip operation.\n",
3002                         sym_name(np));
3003         sym_chip_reset (np);
3004 }
3005
3006 /*
3007  *  Start reset process.
3008  *
3009  *  The interrupt handler will reinitialize the chip.
3010  */
3011 static void sym_start_reset(hcb_p np)
3012 {
3013         (void) sym_reset_scsi_bus(np, 1);
3014 }
3015
3016 static int sym_reset_scsi_bus(hcb_p np, int enab_int)
3017 {
3018         u32 term;
3019         int retv = 0;
3020
3021         sym_soft_reset(np);     /* Soft reset the chip */
3022         if (enab_int)
3023                 OUTW (nc_sien, RST);
3024         /*
3025          *  Enable Tolerant, reset IRQD if present and
3026          *  properly set IRQ mode, prior to resetting the bus.
3027          */
3028         OUTB (nc_stest3, TE);
3029         OUTB (nc_dcntl, (np->rv_dcntl & IRQM));
3030         OUTB (nc_scntl1, CRST);
3031         UDELAY (200);
3032
3033         if (!SYM_SETUP_SCSI_BUS_CHECK)
3034                 goto out;
3035         /*
3036          *  Check for no terminators or SCSI bus shorts to ground.
3037          *  Read SCSI data bus, data parity bits and control signals.
3038          *  We are expecting RESET to be TRUE and other signals to be
3039          *  FALSE.
3040          */
3041         term =  INB(nc_sstat0);
3042         term =  ((term & 2) << 7) + ((term & 1) << 17); /* rst sdp0 */
3043         term |= ((INB(nc_sstat2) & 0x01) << 26) |       /* sdp1     */
3044                 ((INW(nc_sbdl) & 0xff)   << 9)  |       /* d7-0     */
3045                 ((INW(nc_sbdl) & 0xff00) << 10) |       /* d15-8    */
3046                 INB(nc_sbcl);   /* req ack bsy sel atn msg cd io    */
3047
3048         if (!(np->features & FE_WIDE))
3049                 term &= 0x3ffff;
3050
3051         if (term != (2<<7)) {
3052                 printf("%s: suspicious SCSI data while resetting the BUS.\n",
3053                         sym_name(np));
3054                 printf("%s: %sdp0,d7-0,rst,req,ack,bsy,sel,atn,msg,c/d,i/o = "
3055                         "0x%lx, expecting 0x%lx\n",
3056                         sym_name(np),
3057                         (np->features & FE_WIDE) ? "dp1,d15-8," : "",
3058                         (u_long)term, (u_long)(2<<7));
3059                 if (SYM_SETUP_SCSI_BUS_CHECK == 1)
3060                         retv = 1;
3061         }
3062 out:
3063         OUTB (nc_scntl1, 0);
3064         /* MDELAY(100); */
3065         return retv;
3066 }
3067
3068 /*
3069  *  The chip may have completed jobs. Look at the DONE QUEUE.
3070  *
3071  *  On architectures that may reorder LOAD/STORE operations,
3072  *  a memory barrier may be needed after the reading of the
3073  *  so-called `flag' and prior to dealing with the data.
3074  */
3075 static int sym_wakeup_done (hcb_p np)
3076 {
3077         ccb_p cp;
3078         int i, n;
3079         u32 dsa;
3080
3081         SYM_LOCK_ASSERT(MA_OWNED);
3082
3083         n = 0;
3084         i = np->dqueueget;
3085         while (1) {
3086                 dsa = scr_to_cpu(np->dqueue[i]);
3087                 if (!dsa)
3088                         break;
3089                 np->dqueue[i] = 0;
3090                 if ((i = i+2) >= MAX_QUEUE*2)
3091                         i = 0;
3092
3093                 cp = sym_ccb_from_dsa(np, dsa);
3094                 if (cp) {
3095                         MEMORY_BARRIER();
3096                         sym_complete_ok (np, cp);
3097                         ++n;
3098                 }
3099                 else
3100                         printf ("%s: bad DSA (%x) in done queue.\n",
3101                                 sym_name(np), (u_int) dsa);
3102         }
3103         np->dqueueget = i;
3104
3105         return n;
3106 }
3107
3108 /*
3109  *  Complete all active CCBs with error.
3110  *  Used on CHIP/SCSI RESET.
3111  */
3112 static void sym_flush_busy_queue (hcb_p np, int cam_status)
3113 {
3114         /*
3115          *  Move all active CCBs to the COMP queue
3116          *  and flush this queue.
3117          */
3118         sym_que_splice(&np->busy_ccbq, &np->comp_ccbq);
3119         sym_que_init(&np->busy_ccbq);
3120         sym_flush_comp_queue(np, cam_status);
3121 }
3122
3123 /*
3124  *  Start chip.
3125  *
3126  *  'reason' means:
3127  *     0: initialisation.
3128  *     1: SCSI BUS RESET delivered or received.
3129  *     2: SCSI BUS MODE changed.
3130  */
3131 static void sym_init (hcb_p np, int reason)
3132 {
3133         int     i;
3134         u32     phys;
3135
3136         SYM_LOCK_ASSERT(MA_OWNED);
3137
3138         /*
3139          *  Reset chip if asked, otherwise just clear fifos.
3140          */
3141         if (reason == 1)
3142                 sym_soft_reset(np);
3143         else {
3144                 OUTB (nc_stest3, TE|CSF);
3145                 OUTONB (nc_ctest3, CLF);
3146         }
3147
3148         /*
3149          *  Clear Start Queue
3150          */
3151         phys = np->squeue_ba;
3152         for (i = 0; i < MAX_QUEUE*2; i += 2) {
3153                 np->squeue[i]   = cpu_to_scr(np->idletask_ba);
3154                 np->squeue[i+1] = cpu_to_scr(phys + (i+2)*4);
3155         }
3156         np->squeue[MAX_QUEUE*2-1] = cpu_to_scr(phys);
3157
3158         /*
3159          *  Start at first entry.
3160          */
3161         np->squeueput = 0;
3162
3163         /*
3164          *  Clear Done Queue
3165          */
3166         phys = np->dqueue_ba;
3167         for (i = 0; i < MAX_QUEUE*2; i += 2) {
3168                 np->dqueue[i]   = 0;
3169                 np->dqueue[i+1] = cpu_to_scr(phys + (i+2)*4);
3170         }
3171         np->dqueue[MAX_QUEUE*2-1] = cpu_to_scr(phys);
3172
3173         /*
3174          *  Start at first entry.
3175          */
3176         np->dqueueget = 0;
3177
3178         /*
3179          *  Install patches in scripts.
3180          *  This also let point to first position the start
3181          *  and done queue pointers used from SCRIPTS.
3182          */
3183         np->fw_patch(np);
3184
3185         /*
3186          *  Wakeup all pending jobs.
3187          */
3188         sym_flush_busy_queue(np, CAM_SCSI_BUS_RESET);
3189
3190         /*
3191          *  Init chip.
3192          */
3193         OUTB (nc_istat,  0x00   );      /*  Remove Reset, abort */
3194         UDELAY (2000);  /* The 895 needs time for the bus mode to settle */
3195
3196         OUTB (nc_scntl0, np->rv_scntl0 | 0xc0);
3197                                         /*  full arb., ena parity, par->ATN  */
3198         OUTB (nc_scntl1, 0x00);         /*  odd parity, and remove CRST!! */
3199
3200         sym_selectclock(np, np->rv_scntl3);     /* Select SCSI clock */
3201
3202         OUTB (nc_scid  , RRE|np->myaddr);       /* Adapter SCSI address */
3203         OUTW (nc_respid, 1ul<<np->myaddr);      /* Id to respond to */
3204         OUTB (nc_istat , SIGP   );              /*  Signal Process */
3205         OUTB (nc_dmode , np->rv_dmode);         /* Burst length, dma mode */
3206         OUTB (nc_ctest5, np->rv_ctest5);        /* Large fifo + large burst */
3207
3208         OUTB (nc_dcntl , NOCOM|np->rv_dcntl);   /* Protect SFBR */
3209         OUTB (nc_ctest3, np->rv_ctest3);        /* Write and invalidate */
3210         OUTB (nc_ctest4, np->rv_ctest4);        /* Master parity checking */
3211
3212         /* Extended Sreq/Sack filtering not supported on the C10 */
3213         if (np->features & FE_C10)
3214                 OUTB (nc_stest2, np->rv_stest2);
3215         else
3216                 OUTB (nc_stest2, EXT|np->rv_stest2);
3217
3218         OUTB (nc_stest3, TE);                   /* TolerANT enable */
3219         OUTB (nc_stime0, 0x0c);                 /* HTH disabled  STO 0.25 sec */
3220
3221         /*
3222          *  For now, disable AIP generation on C1010-66.
3223          */
3224         if (np->device_id == PCI_ID_LSI53C1010_2)
3225                 OUTB (nc_aipcntl1, DISAIP);
3226
3227         /*
3228          *  C10101 Errata.
3229          *  Errant SGE's when in narrow. Write bits 4 & 5 of
3230          *  STEST1 register to disable SGE. We probably should do
3231          *  that from SCRIPTS for each selection/reselection, but
3232          *  I just don't want. :)
3233          */
3234         if (np->device_id == PCI_ID_LSI53C1010 &&
3235             /* np->revision_id < 0xff */ 1)
3236                 OUTB (nc_stest1, INB(nc_stest1) | 0x30);
3237
3238         /*
3239          *  DEL 441 - 53C876 Rev 5 - Part Number 609-0392787/2788 - ITEM 2.
3240          *  Disable overlapped arbitration for some dual function devices,
3241          *  regardless revision id (kind of post-chip-design feature. ;-))
3242          */
3243         if (np->device_id == PCI_ID_SYM53C875)
3244                 OUTB (nc_ctest0, (1<<5));
3245         else if (np->device_id == PCI_ID_SYM53C896)
3246                 np->rv_ccntl0 |= DPR;
3247
3248         /*
3249          *  Write CCNTL0/CCNTL1 for chips capable of 64 bit addressing
3250          *  and/or hardware phase mismatch, since only such chips
3251          *  seem to support those IO registers.
3252          */
3253         if (np->features & (FE_DAC|FE_NOPM)) {
3254                 OUTB (nc_ccntl0, np->rv_ccntl0);
3255                 OUTB (nc_ccntl1, np->rv_ccntl1);
3256         }
3257
3258         /*
3259          *  If phase mismatch handled by scripts (895A/896/1010),
3260          *  set PM jump addresses.
3261          */
3262         if (np->features & FE_NOPM) {
3263                 OUTL (nc_pmjad1, SCRIPTB_BA (np, pm_handle));
3264                 OUTL (nc_pmjad2, SCRIPTB_BA (np, pm_handle));
3265         }
3266
3267         /*
3268          *    Enable GPIO0 pin for writing if LED support from SCRIPTS.
3269          *    Also set GPIO5 and clear GPIO6 if hardware LED control.
3270          */
3271         if (np->features & FE_LED0)
3272                 OUTB(nc_gpcntl, INB(nc_gpcntl) & ~0x01);
3273         else if (np->features & FE_LEDC)
3274                 OUTB(nc_gpcntl, (INB(nc_gpcntl) & ~0x41) | 0x20);
3275
3276         /*
3277          *      enable ints
3278          */
3279         OUTW (nc_sien , STO|HTH|MA|SGE|UDC|RST|PAR);
3280         OUTB (nc_dien , MDPE|BF|SSI|SIR|IID);
3281
3282         /*
3283          *  For 895/6 enable SBMC interrupt and save current SCSI bus mode.
3284          *  Try to eat the spurious SBMC interrupt that may occur when
3285          *  we reset the chip but not the SCSI BUS (at initialization).
3286          */
3287         if (np->features & (FE_ULTRA2|FE_ULTRA3)) {
3288                 OUTONW (nc_sien, SBMC);
3289                 if (reason == 0) {
3290                         MDELAY(100);
3291                         INW (nc_sist);
3292                 }
3293                 np->scsi_mode = INB (nc_stest4) & SMODE;
3294         }
3295
3296         /*
3297          *  Fill in target structure.
3298          *  Reinitialize usrsync.
3299          *  Reinitialize usrwide.
3300          *  Prepare sync negotiation according to actual SCSI bus mode.
3301          */
3302         for (i=0;i<SYM_CONF_MAX_TARGET;i++) {
3303                 tcb_p tp = &np->target[i];
3304
3305                 tp->to_reset  = 0;
3306                 tp->head.sval = 0;
3307                 tp->head.wval = np->rv_scntl3;
3308                 tp->head.uval = 0;
3309
3310                 tp->tinfo.current.period = 0;
3311                 tp->tinfo.current.offset = 0;
3312                 tp->tinfo.current.width  = BUS_8_BIT;
3313                 tp->tinfo.current.options = 0;
3314         }
3315
3316         /*
3317          *  Download SCSI SCRIPTS to on-chip RAM if present,
3318          *  and start script processor.
3319          */
3320         if (np->ram_ba) {
3321                 if (sym_verbose > 1)
3322                         printf ("%s: Downloading SCSI SCRIPTS.\n",
3323                                 sym_name(np));
3324                 if (np->ram_ws == 8192) {
3325                         OUTRAM_OFF(4096, np->scriptb0, np->scriptb_sz);
3326                         OUTL (nc_mmws, np->scr_ram_seg);
3327                         OUTL (nc_mmrs, np->scr_ram_seg);
3328                         OUTL (nc_sfs,  np->scr_ram_seg);
3329                         phys = SCRIPTB_BA (np, start64);
3330                 }
3331                 else
3332                         phys = SCRIPTA_BA (np, init);
3333                 OUTRAM_OFF(0, np->scripta0, np->scripta_sz);
3334         }
3335         else
3336                 phys = SCRIPTA_BA (np, init);
3337
3338         np->istat_sem = 0;
3339
3340         OUTL (nc_dsa, np->hcb_ba);
3341         OUTL_DSP (phys);
3342
3343         /*
3344          *  Notify the XPT about the RESET condition.
3345          */
3346         if (reason != 0)
3347                 xpt_async(AC_BUS_RESET, np->path, NULL);
3348 }
3349
3350 /*
3351  *  Get clock factor and sync divisor for a given
3352  *  synchronous factor period.
3353  */
3354 static int
3355 sym_getsync(hcb_p np, u_char dt, u_char sfac, u_char *divp, u_char *fakp)
3356 {
3357         u32     clk = np->clock_khz;    /* SCSI clock frequency in kHz  */
3358         int     div = np->clock_divn;   /* Number of divisors supported */
3359         u32     fak;                    /* Sync factor in sxfer         */
3360         u32     per;                    /* Period in tenths of ns       */
3361         u32     kpc;                    /* (per * clk)                  */
3362         int     ret;
3363
3364         /*
3365          *  Compute the synchronous period in tenths of nano-seconds
3366          */
3367         if (dt && sfac <= 9)    per = 125;
3368         else if (sfac <= 10)    per = 250;
3369         else if (sfac == 11)    per = 303;
3370         else if (sfac == 12)    per = 500;
3371         else                    per = 40 * sfac;
3372         ret = per;
3373
3374         kpc = per * clk;
3375         if (dt)
3376                 kpc <<= 1;
3377
3378         /*
3379          *  For earliest C10 revision 0, we cannot use extra
3380          *  clocks for the setting of the SCSI clocking.
3381          *  Note that this limits the lowest sync data transfer
3382          *  to 5 Mega-transfers per second and may result in
3383          *  using higher clock divisors.
3384          */
3385 #if 1
3386         if ((np->features & (FE_C10|FE_U3EN)) == FE_C10) {
3387                 /*
3388                  *  Look for the lowest clock divisor that allows an
3389                  *  output speed not faster than the period.
3390                  */
3391                 while (div > 0) {
3392                         --div;
3393                         if (kpc > (div_10M[div] << 2)) {
3394                                 ++div;
3395                                 break;
3396                         }
3397                 }
3398                 fak = 0;                        /* No extra clocks */
3399                 if (div == np->clock_divn) {    /* Are we too fast ? */
3400                         ret = -1;
3401                 }
3402                 *divp = div;
3403                 *fakp = fak;
3404                 return ret;
3405         }
3406 #endif
3407
3408         /*
3409          *  Look for the greatest clock divisor that allows an
3410          *  input speed faster than the period.
3411          */
3412         while (div-- > 0)
3413                 if (kpc >= (div_10M[div] << 2)) break;
3414
3415         /*
3416          *  Calculate the lowest clock factor that allows an output
3417          *  speed not faster than the period, and the max output speed.
3418          *  If fak >= 1 we will set both XCLKH_ST and XCLKH_DT.
3419          *  If fak >= 2 we will also set XCLKS_ST and XCLKS_DT.
3420          */
3421         if (dt) {
3422                 fak = (kpc - 1) / (div_10M[div] << 1) + 1 - 2;
3423                 /* ret = ((2+fak)*div_10M[div])/np->clock_khz; */
3424         }
3425         else {
3426                 fak = (kpc - 1) / div_10M[div] + 1 - 4;
3427                 /* ret = ((4+fak)*div_10M[div])/np->clock_khz; */
3428         }
3429
3430         /*
3431          *  Check against our hardware limits, or bugs :).
3432          */
3433         if (fak > 2)    {fak = 2; ret = -1;}
3434
3435         /*
3436          *  Compute and return sync parameters.
3437          */
3438         *divp = div;
3439         *fakp = fak;
3440
3441         return ret;
3442 }
3443
3444 /*
3445  *  Tell the SCSI layer about the new transfer parameters.
3446  */
3447 static void
3448 sym_xpt_async_transfer_neg(hcb_p np, int target, u_int spi_valid)
3449 {
3450         struct ccb_trans_settings cts;
3451         struct cam_path *path;
3452         int sts;
3453         tcb_p tp = &np->target[target];
3454
3455         sts = xpt_create_path(&path, NULL, cam_sim_path(np->sim), target,
3456                               CAM_LUN_WILDCARD);
3457         if (sts != CAM_REQ_CMP)
3458                 return;
3459
3460         bzero(&cts, sizeof(cts));
3461
3462 #define cts__scsi (cts.proto_specific.scsi)
3463 #define cts__spi  (cts.xport_specific.spi)
3464
3465         cts.type      = CTS_TYPE_CURRENT_SETTINGS;
3466         cts.protocol  = PROTO_SCSI;
3467         cts.transport = XPORT_SPI;
3468         cts.protocol_version  = tp->tinfo.current.scsi_version;
3469         cts.transport_version = tp->tinfo.current.spi_version;
3470
3471         cts__spi.valid = spi_valid;
3472         if (spi_valid & CTS_SPI_VALID_SYNC_RATE)
3473                 cts__spi.sync_period = tp->tinfo.current.period;
3474         if (spi_valid & CTS_SPI_VALID_SYNC_OFFSET)
3475                 cts__spi.sync_offset = tp->tinfo.current.offset;
3476         if (spi_valid & CTS_SPI_VALID_BUS_WIDTH)
3477                 cts__spi.bus_width   = tp->tinfo.current.width;
3478         if (spi_valid & CTS_SPI_VALID_PPR_OPTIONS)
3479                 cts__spi.ppr_options = tp->tinfo.current.options;
3480 #undef cts__spi
3481 #undef cts__scsi
3482         xpt_setup_ccb(&cts.ccb_h, path, /*priority*/1);
3483         xpt_async(AC_TRANSFER_NEG, path, &cts);
3484         xpt_free_path(path);
3485 }
3486
3487 #define SYM_SPI_VALID_WDTR              \
3488         CTS_SPI_VALID_BUS_WIDTH |       \
3489         CTS_SPI_VALID_SYNC_RATE |       \
3490         CTS_SPI_VALID_SYNC_OFFSET
3491 #define SYM_SPI_VALID_SDTR              \
3492         CTS_SPI_VALID_SYNC_RATE |       \
3493         CTS_SPI_VALID_SYNC_OFFSET
3494 #define SYM_SPI_VALID_PPR               \
3495         CTS_SPI_VALID_PPR_OPTIONS |     \
3496         CTS_SPI_VALID_BUS_WIDTH |       \
3497         CTS_SPI_VALID_SYNC_RATE |       \
3498         CTS_SPI_VALID_SYNC_OFFSET
3499
3500 /*
3501  *  We received a WDTR.
3502  *  Let everything be aware of the changes.
3503  */
3504 static void sym_setwide(hcb_p np, ccb_p cp, u_char wide)
3505 {
3506         tcb_p tp = &np->target[cp->target];
3507
3508         sym_settrans(np, cp, 0, 0, 0, wide, 0, 0);
3509
3510         /*
3511          *  Tell the SCSI layer about the new transfer parameters.
3512          */
3513         tp->tinfo.goal.width = tp->tinfo.current.width = wide;
3514         tp->tinfo.current.offset = 0;
3515         tp->tinfo.current.period = 0;
3516         tp->tinfo.current.options = 0;
3517
3518         sym_xpt_async_transfer_neg(np, cp->target, SYM_SPI_VALID_WDTR);
3519 }
3520
3521 /*
3522  *  We received a SDTR.
3523  *  Let everything be aware of the changes.
3524  */
3525 static void
3526 sym_setsync(hcb_p np, ccb_p cp, u_char ofs, u_char per, u_char div, u_char fak)
3527 {
3528         tcb_p tp = &np->target[cp->target];
3529         u_char wide = (cp->phys.select.sel_scntl3 & EWS) ? 1 : 0;
3530
3531         sym_settrans(np, cp, 0, ofs, per, wide, div, fak);
3532
3533         /*
3534          *  Tell the SCSI layer about the new transfer parameters.
3535          */
3536         tp->tinfo.goal.period   = tp->tinfo.current.period  = per;
3537         tp->tinfo.goal.offset   = tp->tinfo.current.offset  = ofs;
3538         tp->tinfo.goal.options  = tp->tinfo.current.options = 0;
3539
3540         sym_xpt_async_transfer_neg(np, cp->target, SYM_SPI_VALID_SDTR);
3541 }
3542
3543 /*
3544  *  We received a PPR.
3545  *  Let everything be aware of the changes.
3546  */
3547 static void sym_setpprot(hcb_p np, ccb_p cp, u_char dt, u_char ofs,
3548                          u_char per, u_char wide, u_char div, u_char fak)
3549 {
3550         tcb_p tp = &np->target[cp->target];
3551
3552         sym_settrans(np, cp, dt, ofs, per, wide, div, fak);
3553
3554         /*
3555          *  Tell the SCSI layer about the new transfer parameters.
3556          */
3557         tp->tinfo.goal.width    = tp->tinfo.current.width  = wide;
3558         tp->tinfo.goal.period   = tp->tinfo.current.period = per;
3559         tp->tinfo.goal.offset   = tp->tinfo.current.offset = ofs;
3560         tp->tinfo.goal.options  = tp->tinfo.current.options = dt;
3561
3562         sym_xpt_async_transfer_neg(np, cp->target, SYM_SPI_VALID_PPR);
3563 }
3564
3565 /*
3566  *  Switch trans mode for current job and it's target.
3567  */
3568 static void sym_settrans(hcb_p np, ccb_p cp, u_char dt, u_char ofs,
3569                          u_char per, u_char wide, u_char div, u_char fak)
3570 {
3571         SYM_QUEHEAD *qp;
3572         union   ccb *ccb;
3573         tcb_p tp;
3574         u_char target = INB (nc_sdid) & 0x0f;
3575         u_char sval, wval, uval;
3576
3577         assert (cp);
3578         if (!cp) return;
3579         ccb = cp->cam_ccb;
3580         assert (ccb);
3581         if (!ccb) return;
3582         assert (target == (cp->target & 0xf));
3583         tp = &np->target[target];
3584
3585         sval = tp->head.sval;
3586         wval = tp->head.wval;
3587         uval = tp->head.uval;
3588
3589 #if 0
3590         printf("XXXX sval=%x wval=%x uval=%x (%x)\n",
3591                 sval, wval, uval, np->rv_scntl3);
3592 #endif
3593         /*
3594          *  Set the offset.
3595          */
3596         if (!(np->features & FE_C10))
3597                 sval = (sval & ~0x1f) | ofs;
3598         else
3599                 sval = (sval & ~0x3f) | ofs;
3600
3601         /*
3602          *  Set the sync divisor and extra clock factor.
3603          */
3604         if (ofs != 0) {
3605                 wval = (wval & ~0x70) | ((div+1) << 4);
3606                 if (!(np->features & FE_C10))
3607                         sval = (sval & ~0xe0) | (fak << 5);
3608                 else {
3609                         uval = uval & ~(XCLKH_ST|XCLKH_DT|XCLKS_ST|XCLKS_DT);
3610                         if (fak >= 1) uval |= (XCLKH_ST|XCLKH_DT);
3611                         if (fak >= 2) uval |= (XCLKS_ST|XCLKS_DT);
3612                 }
3613         }
3614
3615         /*
3616          *  Set the bus width.
3617          */
3618         wval = wval & ~EWS;
3619         if (wide != 0)
3620                 wval |= EWS;
3621
3622         /*
3623          *  Set misc. ultra enable bits.
3624          */
3625         if (np->features & FE_C10) {
3626                 uval = uval & ~(U3EN|AIPCKEN);
3627                 if (dt) {
3628                         assert(np->features & FE_U3EN);
3629                         uval |= U3EN;
3630                 }
3631         }
3632         else {
3633                 wval = wval & ~ULTRA;
3634                 if (per <= 12)  wval |= ULTRA;
3635         }
3636
3637         /*
3638          *   Stop there if sync parameters are unchanged.
3639          */
3640         if (tp->head.sval == sval &&
3641             tp->head.wval == wval &&
3642             tp->head.uval == uval)
3643                 return;
3644         tp->head.sval = sval;
3645         tp->head.wval = wval;
3646         tp->head.uval = uval;
3647
3648         /*
3649          *  Disable extended Sreq/Sack filtering if per < 50.
3650          *  Not supported on the C1010.
3651          */
3652         if (per < 50 && !(np->features & FE_C10))
3653                 OUTOFFB (nc_stest2, EXT);
3654
3655         /*
3656          *  set actual value and sync_status
3657          */
3658         OUTB (nc_sxfer,  tp->head.sval);
3659         OUTB (nc_scntl3, tp->head.wval);
3660
3661         if (np->features & FE_C10) {
3662                 OUTB (nc_scntl4, tp->head.uval);
3663         }
3664
3665         /*
3666          *  patch ALL busy ccbs of this target.
3667          */
3668         FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
3669                 cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
3670                 if (cp->target != target)
3671                         continue;
3672                 cp->phys.select.sel_scntl3 = tp->head.wval;
3673                 cp->phys.select.sel_sxfer  = tp->head.sval;
3674                 if (np->features & FE_C10) {
3675                         cp->phys.select.sel_scntl4 = tp->head.uval;
3676                 }
3677         }
3678 }
3679
3680 /*
3681  *  log message for real hard errors
3682  *
3683  *  sym0 targ 0?: ERROR (ds:si) (so-si-sd) (sxfer/scntl3) @ name (dsp:dbc).
3684  *            reg: r0 r1 r2 r3 r4 r5 r6 ..... rf.
3685  *
3686  *  exception register:
3687  *      ds:     dstat
3688  *      si:     sist
3689  *
3690  *  SCSI bus lines:
3691  *      so:     control lines as driven by chip.
3692  *      si:     control lines as seen by chip.
3693  *      sd:     scsi data lines as seen by chip.
3694  *
3695  *  wide/fastmode:
3696  *      sxfer:  (see the manual)
3697  *      scntl3: (see the manual)
3698  *
3699  *  current script command:
3700  *      dsp:    script address (relative to start of script).
3701  *      dbc:    first word of script command.
3702  *
3703  *  First 24 register of the chip:
3704  *      r0..rf
3705  */
3706 static void sym_log_hard_error(hcb_p np, u_short sist, u_char dstat)
3707 {
3708         u32     dsp;
3709         int     script_ofs;
3710         int     script_size;
3711         char    *script_name;
3712         u_char  *script_base;
3713         int     i;
3714
3715         dsp     = INL (nc_dsp);
3716
3717         if      (dsp > np->scripta_ba &&
3718                  dsp <= np->scripta_ba + np->scripta_sz) {
3719                 script_ofs      = dsp - np->scripta_ba;
3720                 script_size     = np->scripta_sz;
3721                 script_base     = (u_char *) np->scripta0;
3722                 script_name     = "scripta";
3723         }
3724         else if (np->scriptb_ba < dsp &&
3725                  dsp <= np->scriptb_ba + np->scriptb_sz) {
3726                 script_ofs      = dsp - np->scriptb_ba;
3727                 script_size     = np->scriptb_sz;
3728                 script_base     = (u_char *) np->scriptb0;
3729                 script_name     = "scriptb";
3730         } else {
3731                 script_ofs      = dsp;
3732                 script_size     = 0;
3733                 script_base     = 0;
3734                 script_name     = "mem";
3735         }
3736
3737         printf ("%s:%d: ERROR (%x:%x) (%x-%x-%x) (%x/%x) @ (%s %x:%08x).\n",
3738                 sym_name (np), (unsigned)INB (nc_sdid)&0x0f, dstat, sist,
3739                 (unsigned)INB (nc_socl), (unsigned)INB (nc_sbcl),
3740                 (unsigned)INB (nc_sbdl), (unsigned)INB (nc_sxfer),
3741                 (unsigned)INB (nc_scntl3), script_name, script_ofs,
3742                 (unsigned)INL (nc_dbc));
3743
3744         if (((script_ofs & 3) == 0) &&
3745             (unsigned)script_ofs < script_size) {
3746                 printf ("%s: script cmd = %08x\n", sym_name(np),
3747                         scr_to_cpu((int) *(u32 *)(script_base + script_ofs)));
3748         }
3749
3750         printf ("%s: regdump:", sym_name(np));
3751         for (i=0; i<24;i++)
3752             printf (" %02x", (unsigned)INB_OFF(i));
3753         printf (".\n");
3754
3755         /*
3756          *  PCI BUS error, read the PCI ststus register.
3757          */
3758         if (dstat & (MDPE|BF)) {
3759                 u_short pci_sts;
3760                 pci_sts = pci_read_config(np->device, PCIR_STATUS, 2);
3761                 if (pci_sts & 0xf900) {
3762                         pci_write_config(np->device, PCIR_STATUS, pci_sts, 2);
3763                         printf("%s: PCI STATUS = 0x%04x\n",
3764                                 sym_name(np), pci_sts & 0xf900);
3765                 }
3766         }
3767 }
3768
3769 /*
3770  *  chip interrupt handler
3771  *
3772  *  In normal situations, interrupt conditions occur one at
3773  *  a time. But when something bad happens on the SCSI BUS,
3774  *  the chip may raise several interrupt flags before
3775  *  stopping and interrupting the CPU. The additionnal
3776  *  interrupt flags are stacked in some extra registers
3777  *  after the SIP and/or DIP flag has been raised in the
3778  *  ISTAT. After the CPU has read the interrupt condition
3779  *  flag from SIST or DSTAT, the chip unstacks the other
3780  *  interrupt flags and sets the corresponding bits in
3781  *  SIST or DSTAT. Since the chip starts stacking once the
3782  *  SIP or DIP flag is set, there is a small window of time
3783  *  where the stacking does not occur.
3784  *
3785  *  Typically, multiple interrupt conditions may happen in
3786  *  the following situations:
3787  *
3788  *  - SCSI parity error + Phase mismatch  (PAR|MA)
3789  *    When a parity error is detected in input phase
3790  *    and the device switches to msg-in phase inside a
3791  *    block MOV.
3792  *  - SCSI parity error + Unexpected disconnect (PAR|UDC)
3793  *    When a stupid device does not want to handle the
3794  *    recovery of an SCSI parity error.
3795  *  - Some combinations of STO, PAR, UDC, ...
3796  *    When using non compliant SCSI stuff, when user is
3797  *    doing non compliant hot tampering on the BUS, when
3798  *    something really bad happens to a device, etc ...
3799  *
3800  *  The heuristic suggested by SYMBIOS to handle
3801  *  multiple interrupts is to try unstacking all
3802  *  interrupts conditions and to handle them on some
3803  *  priority based on error severity.
3804  *  This will work when the unstacking has been
3805  *  successful, but we cannot be 100 % sure of that,
3806  *  since the CPU may have been faster to unstack than
3807  *  the chip is able to stack. Hmmm ... But it seems that
3808  *  such a situation is very unlikely to happen.
3809  *
3810  *  If this happen, for example STO caught by the CPU
3811  *  then UDC happenning before the CPU have restarted
3812  *  the SCRIPTS, the driver may wrongly complete the
3813  *  same command on UDC, since the SCRIPTS didn't restart
3814  *  and the DSA still points to the same command.
3815  *  We avoid this situation by setting the DSA to an
3816  *  invalid value when the CCB is completed and before
3817  *  restarting the SCRIPTS.
3818  *
3819  *  Another issue is that we need some section of our
3820  *  recovery procedures to be somehow uninterruptible but
3821  *  the SCRIPTS processor does not provides such a
3822  *  feature. For this reason, we handle recovery preferently
3823  *  from the C code and check against some SCRIPTS critical
3824  *  sections from the C code.
3825  *
3826  *  Hopefully, the interrupt handling of the driver is now
3827  *  able to resist to weird BUS error conditions, but donnot
3828  *  ask me for any guarantee that it will never fail. :-)
3829  *  Use at your own decision and risk.
3830  */
3831 static void sym_intr1 (hcb_p np)
3832 {
3833         u_char  istat, istatc;
3834         u_char  dstat;
3835         u_short sist;
3836
3837         SYM_LOCK_ASSERT(MA_OWNED);
3838
3839         /*
3840          *  interrupt on the fly ?
3841          *
3842          *  A `dummy read' is needed to ensure that the
3843          *  clear of the INTF flag reaches the device
3844          *  before the scanning of the DONE queue.
3845          */
3846         istat = INB (nc_istat);
3847         if (istat & INTF) {
3848                 OUTB (nc_istat, (istat & SIGP) | INTF | np->istat_sem);
3849                 istat = INB (nc_istat);         /* DUMMY READ */
3850                 if (DEBUG_FLAGS & DEBUG_TINY) printf ("F ");
3851                 (void)sym_wakeup_done (np);
3852         };
3853
3854         if (!(istat & (SIP|DIP)))
3855                 return;
3856
3857 #if 0   /* We should never get this one */
3858         if (istat & CABRT)
3859                 OUTB (nc_istat, CABRT);
3860 #endif
3861
3862         /*
3863          *  PAR and MA interrupts may occur at the same time,
3864          *  and we need to know of both in order to handle
3865          *  this situation properly. We try to unstack SCSI
3866          *  interrupts for that reason. BTW, I dislike a LOT
3867          *  such a loop inside the interrupt routine.
3868          *  Even if DMA interrupt stacking is very unlikely to
3869          *  happen, we also try unstacking these ones, since
3870          *  this has no performance impact.
3871          */
3872         sist    = 0;
3873         dstat   = 0;
3874         istatc  = istat;
3875         do {
3876                 if (istatc & SIP)
3877                         sist  |= INW (nc_sist);
3878                 if (istatc & DIP)
3879                         dstat |= INB (nc_dstat);
3880                 istatc = INB (nc_istat);
3881                 istat |= istatc;
3882         } while (istatc & (SIP|DIP));
3883
3884         if (DEBUG_FLAGS & DEBUG_TINY)
3885                 printf ("<%d|%x:%x|%x:%x>",
3886                         (int)INB(nc_scr0),
3887                         dstat,sist,
3888                         (unsigned)INL(nc_dsp),
3889                         (unsigned)INL(nc_dbc));
3890         /*
3891          *  On paper, a memory barrier may be needed here.
3892          *  And since we are paranoid ... :)
3893          */
3894         MEMORY_BARRIER();
3895
3896         /*
3897          *  First, interrupts we want to service cleanly.
3898          *
3899          *  Phase mismatch (MA) is the most frequent interrupt
3900          *  for chip earlier than the 896 and so we have to service
3901          *  it as quickly as possible.
3902          *  A SCSI parity error (PAR) may be combined with a phase
3903          *  mismatch condition (MA).
3904          *  Programmed interrupts (SIR) are used to call the C code
3905          *  from SCRIPTS.
3906          *  The single step interrupt (SSI) is not used in this
3907          *  driver.
3908          */
3909         if (!(sist  & (STO|GEN|HTH|SGE|UDC|SBMC|RST)) &&
3910             !(dstat & (MDPE|BF|ABRT|IID))) {
3911                 if      (sist & PAR)    sym_int_par (np, sist);
3912                 else if (sist & MA)     sym_int_ma (np);
3913                 else if (dstat & SIR)   sym_int_sir (np);
3914                 else if (dstat & SSI)   OUTONB_STD ();
3915                 else                    goto unknown_int;
3916                 return;
3917         };
3918
3919         /*
3920          *  Now, interrupts that donnot happen in normal
3921          *  situations and that we may need to recover from.
3922          *
3923          *  On SCSI RESET (RST), we reset everything.
3924          *  On SCSI BUS MODE CHANGE (SBMC), we complete all
3925          *  active CCBs with RESET status, prepare all devices
3926          *  for negotiating again and restart the SCRIPTS.
3927          *  On STO and UDC, we complete the CCB with the corres-
3928          *  ponding status and restart the SCRIPTS.
3929          */
3930         if (sist & RST) {
3931                 xpt_print_path(np->path);
3932                 printf("SCSI BUS reset detected.\n");
3933                 sym_init (np, 1);
3934                 return;
3935         };
3936
3937         OUTB (nc_ctest3, np->rv_ctest3 | CLF);  /* clear dma fifo  */
3938         OUTB (nc_stest3, TE|CSF);               /* clear scsi fifo */
3939
3940         if (!(sist  & (GEN|HTH|SGE)) &&
3941             !(dstat & (MDPE|BF|ABRT|IID))) {
3942                 if      (sist & SBMC)   sym_int_sbmc (np);
3943                 else if (sist & STO)    sym_int_sto (np);
3944                 else if (sist & UDC)    sym_int_udc (np);
3945                 else                    goto unknown_int;
3946                 return;
3947         };
3948
3949         /*
3950          *  Now, interrupts we are not able to recover cleanly.
3951          *
3952          *  Log message for hard errors.
3953          *  Reset everything.
3954          */
3955
3956         sym_log_hard_error(np, sist, dstat);
3957
3958         if ((sist & (GEN|HTH|SGE)) ||
3959                 (dstat & (MDPE|BF|ABRT|IID))) {
3960                 sym_start_reset(np);
3961                 return;
3962         };
3963
3964 unknown_int:
3965         /*
3966          *  We just miss the cause of the interrupt. :(
3967          *  Print a message. The timeout will do the real work.
3968          */
3969         printf( "%s: unknown interrupt(s) ignored, "
3970                 "ISTAT=0x%x DSTAT=0x%x SIST=0x%x\n",
3971                 sym_name(np), istat, dstat, sist);
3972 }
3973
3974 static void sym_intr(void *arg)
3975 {
3976         hcb_p np = arg;
3977
3978         SYM_LOCK();
3979
3980         if (DEBUG_FLAGS & DEBUG_TINY) printf ("[");
3981         sym_intr1((hcb_p) arg);
3982         if (DEBUG_FLAGS & DEBUG_TINY) printf ("]");
3983
3984         SYM_UNLOCK();
3985 }
3986
3987 static void sym_poll(struct cam_sim *sim)
3988 {
3989         sym_intr1(cam_sim_softc(sim));
3990 }
3991
3992 /*
3993  *  generic recovery from scsi interrupt
3994  *
3995  *  The doc says that when the chip gets an SCSI interrupt,
3996  *  it tries to stop in an orderly fashion, by completing
3997  *  an instruction fetch that had started or by flushing
3998  *  the DMA fifo for a write to memory that was executing.
3999  *  Such a fashion is not enough to know if the instruction
4000  *  that was just before the current DSP value has been
4001  *  executed or not.
4002  *
4003  *  There are some small SCRIPTS sections that deal with
4004  *  the start queue and the done queue that may break any
4005  *  assomption from the C code if we are interrupted
4006  *  inside, so we reset if this happens. Btw, since these
4007  *  SCRIPTS sections are executed while the SCRIPTS hasn't
4008  *  started SCSI operations, it is very unlikely to happen.
4009  *
4010  *  All the driver data structures are supposed to be
4011  *  allocated from the same 4 GB memory window, so there
4012  *  is a 1 to 1 relationship between DSA and driver data
4013  *  structures. Since we are careful :) to invalidate the
4014  *  DSA when we complete a command or when the SCRIPTS
4015  *  pushes a DSA into a queue, we can trust it when it
4016  *  points to a CCB.
4017  */
4018 static void sym_recover_scsi_int (hcb_p np, u_char hsts)
4019 {
4020         u32     dsp     = INL (nc_dsp);
4021         u32     dsa     = INL (nc_dsa);
4022         ccb_p cp        = sym_ccb_from_dsa(np, dsa);
4023
4024         /*
4025          *  If we haven't been interrupted inside the SCRIPTS
4026          *  critical pathes, we can safely restart the SCRIPTS
4027          *  and trust the DSA value if it matches a CCB.
4028          */
4029         if ((!(dsp > SCRIPTA_BA (np, getjob_begin) &&
4030                dsp < SCRIPTA_BA (np, getjob_end) + 1)) &&
4031             (!(dsp > SCRIPTA_BA (np, ungetjob) &&
4032                dsp < SCRIPTA_BA (np, reselect) + 1)) &&
4033             (!(dsp > SCRIPTB_BA (np, sel_for_abort) &&
4034                dsp < SCRIPTB_BA (np, sel_for_abort_1) + 1)) &&
4035             (!(dsp > SCRIPTA_BA (np, done) &&
4036                dsp < SCRIPTA_BA (np, done_end) + 1))) {
4037                 OUTB (nc_ctest3, np->rv_ctest3 | CLF);  /* clear dma fifo  */
4038                 OUTB (nc_stest3, TE|CSF);               /* clear scsi fifo */
4039                 /*
4040                  *  If we have a CCB, let the SCRIPTS call us back for
4041                  *  the handling of the error with SCRATCHA filled with
4042                  *  STARTPOS. This way, we will be able to freeze the
4043                  *  device queue and requeue awaiting IOs.
4044                  */
4045                 if (cp) {
4046                         cp->host_status = hsts;
4047                         OUTL_DSP (SCRIPTA_BA (np, complete_error));
4048                 }
4049                 /*
4050                  *  Otherwise just restart the SCRIPTS.
4051                  */
4052                 else {
4053                         OUTL (nc_dsa, 0xffffff);
4054                         OUTL_DSP (SCRIPTA_BA (np, start));
4055                 }
4056         }
4057         else
4058                 goto reset_all;
4059
4060         return;
4061
4062 reset_all:
4063         sym_start_reset(np);
4064 }
4065
4066 /*
4067  *  chip exception handler for selection timeout
4068  */
4069 static void sym_int_sto (hcb_p np)
4070 {
4071         u32 dsp = INL (nc_dsp);
4072
4073         if (DEBUG_FLAGS & DEBUG_TINY) printf ("T");
4074
4075         if (dsp == SCRIPTA_BA (np, wf_sel_done) + 8)
4076                 sym_recover_scsi_int(np, HS_SEL_TIMEOUT);
4077         else
4078                 sym_start_reset(np);
4079 }
4080
4081 /*
4082  *  chip exception handler for unexpected disconnect
4083  */
4084 static void sym_int_udc (hcb_p np)
4085 {
4086         printf ("%s: unexpected disconnect\n", sym_name(np));
4087         sym_recover_scsi_int(np, HS_UNEXPECTED);
4088 }
4089
4090 /*
4091  *  chip exception handler for SCSI bus mode change
4092  *
4093  *  spi2-r12 11.2.3 says a transceiver mode change must
4094  *  generate a reset event and a device that detects a reset
4095  *  event shall initiate a hard reset. It says also that a
4096  *  device that detects a mode change shall set data transfer
4097  *  mode to eight bit asynchronous, etc...
4098  *  So, just reinitializing all except chip should be enough.
4099  */
4100 static void sym_int_sbmc (hcb_p np)
4101 {
4102         u_char scsi_mode = INB (nc_stest4) & SMODE;
4103
4104         /*
4105          *  Notify user.
4106          */
4107         xpt_print_path(np->path);
4108         printf("SCSI BUS mode change from %s to %s.\n",
4109                 sym_scsi_bus_mode(np->scsi_mode), sym_scsi_bus_mode(scsi_mode));
4110
4111         /*
4112          *  Should suspend command processing for a few seconds and
4113          *  reinitialize all except the chip.
4114          */
4115         sym_init (np, 2);
4116 }
4117
4118 /*
4119  *  chip exception handler for SCSI parity error.
4120  *
4121  *  When the chip detects a SCSI parity error and is
4122  *  currently executing a (CH)MOV instruction, it does
4123  *  not interrupt immediately, but tries to finish the
4124  *  transfer of the current scatter entry before
4125  *  interrupting. The following situations may occur:
4126  *
4127  *  - The complete scatter entry has been transferred
4128  *    without the device having changed phase.
4129  *    The chip will then interrupt with the DSP pointing
4130  *    to the instruction that follows the MOV.
4131  *
4132  *  - A phase mismatch occurs before the MOV finished
4133  *    and phase errors are to be handled by the C code.
4134  *    The chip will then interrupt with both PAR and MA
4135  *    conditions set.
4136  *
4137  *  - A phase mismatch occurs before the MOV finished and
4138  *    phase errors are to be handled by SCRIPTS.
4139  *    The chip will load the DSP with the phase mismatch
4140  *    JUMP address and interrupt the host processor.
4141  */
4142 static void sym_int_par (hcb_p np, u_short sist)
4143 {
4144         u_char  hsts    = INB (HS_PRT);
4145         u32     dsp     = INL (nc_dsp);
4146         u32     dbc     = INL (nc_dbc);
4147         u32     dsa     = INL (nc_dsa);
4148         u_char  sbcl    = INB (nc_sbcl);
4149         u_char  cmd     = dbc >> 24;
4150         int phase       = cmd & 7;
4151         ccb_p   cp      = sym_ccb_from_dsa(np, dsa);
4152
4153         printf("%s: SCSI parity error detected: SCR1=%d DBC=%x SBCL=%x\n",
4154                 sym_name(np), hsts, dbc, sbcl);
4155
4156         /*
4157          *  Check that the chip is connected to the SCSI BUS.
4158          */
4159         if (!(INB (nc_scntl1) & ISCON)) {
4160                 sym_recover_scsi_int(np, HS_UNEXPECTED);
4161                 return;
4162         }
4163
4164         /*
4165          *  If the nexus is not clearly identified, reset the bus.
4166          *  We will try to do better later.
4167          */
4168         if (!cp)
4169                 goto reset_all;
4170
4171         /*
4172          *  Check instruction was a MOV, direction was INPUT and
4173          *  ATN is asserted.
4174          */
4175         if ((cmd & 0xc0) || !(phase & 1) || !(sbcl & 0x8))
4176                 goto reset_all;
4177
4178         /*
4179          *  Keep track of the parity error.
4180          */
4181         OUTONB (HF_PRT, HF_EXT_ERR);
4182         cp->xerr_status |= XE_PARITY_ERR;
4183
4184         /*
4185          *  Prepare the message to send to the device.
4186          */
4187         np->msgout[0] = (phase == 7) ? M_PARITY : M_ID_ERROR;
4188
4189         /*
4190          *  If the old phase was DATA IN phase, we have to deal with
4191          *  the 3 situations described above.
4192          *  For other input phases (MSG IN and STATUS), the device
4193          *  must resend the whole thing that failed parity checking
4194          *  or signal error. So, jumping to dispatcher should be OK.
4195          */
4196         if (phase == 1 || phase == 5) {
4197                 /* Phase mismatch handled by SCRIPTS */
4198                 if (dsp == SCRIPTB_BA (np, pm_handle))
4199                         OUTL_DSP (dsp);
4200                 /* Phase mismatch handled by the C code */
4201                 else if (sist & MA)
4202                         sym_int_ma (np);
4203                 /* No phase mismatch occurred */
4204                 else {
4205                         OUTL (nc_temp, dsp);
4206                         OUTL_DSP (SCRIPTA_BA (np, dispatch));
4207                 }
4208         }
4209         else
4210                 OUTL_DSP (SCRIPTA_BA (np, clrack));
4211         return;
4212
4213 reset_all:
4214         sym_start_reset(np);
4215 }
4216
4217 /*
4218  *  chip exception handler for phase errors.
4219  *
4220  *  We have to construct a new transfer descriptor,
4221  *  to transfer the rest of the current block.
4222  */
4223 static void sym_int_ma (hcb_p np)
4224 {
4225         u32     dbc;
4226         u32     rest;
4227         u32     dsp;
4228         u32     dsa;
4229         u32     nxtdsp;
4230         u32     *vdsp;
4231         u32     oadr, olen;
4232         u32     *tblp;
4233         u32     newcmd;
4234         u_int   delta;
4235         u_char  cmd;
4236         u_char  hflags, hflags0;
4237         struct  sym_pmc *pm;
4238         ccb_p   cp;
4239
4240         dsp     = INL (nc_dsp);
4241         dbc     = INL (nc_dbc);
4242         dsa     = INL (nc_dsa);
4243
4244         cmd     = dbc >> 24;
4245         rest    = dbc & 0xffffff;
4246         delta   = 0;
4247
4248         /*
4249          *  locate matching cp if any.
4250          */
4251         cp = sym_ccb_from_dsa(np, dsa);
4252
4253         /*
4254          *  Donnot take into account dma fifo and various buffers in
4255          *  INPUT phase since the chip flushes everything before
4256          *  raising the MA interrupt for interrupted INPUT phases.
4257          *  For DATA IN phase, we will check for the SWIDE later.
4258          */
4259         if ((cmd & 7) != 1 && (cmd & 7) != 5) {
4260                 u_char ss0, ss2;
4261
4262                 if (np->features & FE_DFBC)
4263                         delta = INW (nc_dfbc);
4264                 else {
4265                         u32 dfifo;
4266
4267                         /*
4268                          * Read DFIFO, CTEST[4-6] using 1 PCI bus ownership.
4269                          */
4270                         dfifo = INL(nc_dfifo);
4271
4272                         /*
4273                          *  Calculate remaining bytes in DMA fifo.
4274                          *  (CTEST5 = dfifo >> 16)
4275                          */
4276                         if (dfifo & (DFS << 16))
4277                                 delta = ((((dfifo >> 8) & 0x300) |
4278                                           (dfifo & 0xff)) - rest) & 0x3ff;
4279                         else
4280                                 delta = ((dfifo & 0xff) - rest) & 0x7f;
4281                 }
4282
4283                 /*
4284                  *  The data in the dma fifo has not been transferred to
4285                  *  the target -> add the amount to the rest
4286                  *  and clear the data.
4287                  *  Check the sstat2 register in case of wide transfer.
4288                  */
4289                 rest += delta;
4290                 ss0  = INB (nc_sstat0);
4291                 if (ss0 & OLF) rest++;
4292                 if (!(np->features & FE_C10))
4293                         if (ss0 & ORF) rest++;
4294                 if (cp && (cp->phys.select.sel_scntl3 & EWS)) {
4295                         ss2 = INB (nc_sstat2);
4296                         if (ss2 & OLF1) rest++;
4297                         if (!(np->features & FE_C10))
4298                                 if (ss2 & ORF1) rest++;
4299                 };
4300
4301                 /*
4302                  *  Clear fifos.
4303                  */
4304                 OUTB (nc_ctest3, np->rv_ctest3 | CLF);  /* dma fifo  */
4305                 OUTB (nc_stest3, TE|CSF);               /* scsi fifo */
4306         }
4307
4308         /*
4309          *  log the information
4310          */
4311         if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE))
4312                 printf ("P%x%x RL=%d D=%d ", cmd&7, INB(nc_sbcl)&7,
4313                         (unsigned) rest, (unsigned) delta);
4314
4315         /*
4316          *  try to find the interrupted script command,
4317          *  and the address at which to continue.
4318          */
4319         vdsp    = 0;
4320         nxtdsp  = 0;
4321         if      (dsp >  np->scripta_ba &&
4322                  dsp <= np->scripta_ba + np->scripta_sz) {
4323                 vdsp = (u32 *)((char*)np->scripta0 + (dsp-np->scripta_ba-8));
4324                 nxtdsp = dsp;
4325         }
4326         else if (dsp >  np->scriptb_ba &&
4327                  dsp <= np->scriptb_ba + np->scriptb_sz) {
4328                 vdsp = (u32 *)((char*)np->scriptb0 + (dsp-np->scriptb_ba-8));
4329                 nxtdsp = dsp;
4330         }
4331
4332         /*
4333          *  log the information
4334          */
4335         if (DEBUG_FLAGS & DEBUG_PHASE) {
4336                 printf ("\nCP=%p DSP=%x NXT=%x VDSP=%p CMD=%x ",
4337                         cp, (unsigned)dsp, (unsigned)nxtdsp, vdsp, cmd);
4338         };
4339
4340         if (!vdsp) {
4341                 printf ("%s: interrupted SCRIPT address not found.\n",
4342                         sym_name (np));
4343                 goto reset_all;
4344         }
4345
4346         if (!cp) {
4347                 printf ("%s: SCSI phase error fixup: CCB already dequeued.\n",
4348                         sym_name (np));
4349                 goto reset_all;
4350         }
4351
4352         /*
4353          *  get old startaddress and old length.
4354          */
4355         oadr = scr_to_cpu(vdsp[1]);
4356
4357         if (cmd & 0x10) {       /* Table indirect */
4358                 tblp = (u32 *) ((char*) &cp->phys + oadr);
4359                 olen = scr_to_cpu(tblp[0]);
4360                 oadr = scr_to_cpu(tblp[1]);
4361         } else {
4362                 tblp = (u32 *) 0;
4363                 olen = scr_to_cpu(vdsp[0]) & 0xffffff;
4364         };
4365
4366         if (DEBUG_FLAGS & DEBUG_PHASE) {
4367                 printf ("OCMD=%x\nTBLP=%p OLEN=%x OADR=%x\n",
4368                         (unsigned) (scr_to_cpu(vdsp[0]) >> 24),
4369                         tblp,
4370                         (unsigned) olen,
4371                         (unsigned) oadr);
4372         };
4373
4374         /*
4375          *  check cmd against assumed interrupted script command.
4376          *  If dt data phase, the MOVE instruction hasn't bit 4 of
4377          *  the phase.
4378          */
4379         if (((cmd & 2) ? cmd : (cmd & ~4)) != (scr_to_cpu(vdsp[0]) >> 24)) {
4380                 PRINT_ADDR(cp);
4381                 printf ("internal error: cmd=%02x != %02x=(vdsp[0] >> 24)\n",
4382                         (unsigned)cmd, (unsigned)scr_to_cpu(vdsp[0]) >> 24);
4383
4384                 goto reset_all;
4385         };
4386
4387         /*
4388          *  if old phase not dataphase, leave here.
4389          */
4390         if (cmd & 2) {
4391                 PRINT_ADDR(cp);
4392                 printf ("phase change %x-%x %d@%08x resid=%d.\n",
4393                         cmd&7, INB(nc_sbcl)&7, (unsigned)olen,
4394                         (unsigned)oadr, (unsigned)rest);
4395                 goto unexpected_phase;
4396         };
4397
4398         /*
4399          *  Choose the correct PM save area.
4400          *
4401          *  Look at the PM_SAVE SCRIPT if you want to understand
4402          *  this stuff. The equivalent code is implemented in
4403          *  SCRIPTS for the 895A, 896 and 1010 that are able to
4404          *  handle PM from the SCRIPTS processor.
4405          */
4406         hflags0 = INB (HF_PRT);
4407         hflags = hflags0;
4408
4409         if (hflags & (HF_IN_PM0 | HF_IN_PM1 | HF_DP_SAVED)) {
4410                 if (hflags & HF_IN_PM0)
4411                         nxtdsp = scr_to_cpu(cp->phys.pm0.ret);
4412                 else if (hflags & HF_IN_PM1)
4413                         nxtdsp = scr_to_cpu(cp->phys.pm1.ret);
4414
4415                 if (hflags & HF_DP_SAVED)
4416                         hflags ^= HF_ACT_PM;
4417         }
4418
4419         if (!(hflags & HF_ACT_PM)) {
4420                 pm = &cp->phys.pm0;
4421                 newcmd = SCRIPTA_BA (np, pm0_data);
4422         }
4423         else {
4424                 pm = &cp->phys.pm1;
4425                 newcmd = SCRIPTA_BA (np, pm1_data);
4426         }
4427
4428         hflags &= ~(HF_IN_PM0 | HF_IN_PM1 | HF_DP_SAVED);
4429         if (hflags != hflags0)
4430                 OUTB (HF_PRT, hflags);
4431
4432         /*
4433          *  fillin the phase mismatch context
4434          */
4435         pm->sg.addr = cpu_to_scr(oadr + olen - rest);
4436         pm->sg.size = cpu_to_scr(rest);
4437         pm->ret     = cpu_to_scr(nxtdsp);
4438
4439         /*
4440          *  If we have a SWIDE,
4441          *  - prepare the address to write the SWIDE from SCRIPTS,
4442          *  - compute the SCRIPTS address to restart from,
4443          *  - move current data pointer context by one byte.
4444          */
4445         nxtdsp = SCRIPTA_BA (np, dispatch);
4446         if ((cmd & 7) == 1 && cp && (cp->phys.select.sel_scntl3 & EWS) &&
4447             (INB (nc_scntl2) & WSR)) {
4448                 u32 tmp;
4449
4450                 /*
4451                  *  Set up the table indirect for the MOVE
4452                  *  of the residual byte and adjust the data
4453                  *  pointer context.
4454                  */
4455                 tmp = scr_to_cpu(pm->sg.addr);
4456                 cp->phys.wresid.addr = cpu_to_scr(tmp);
4457                 pm->sg.addr = cpu_to_scr(tmp + 1);
4458                 tmp = scr_to_cpu(pm->sg.size);
4459                 cp->phys.wresid.size = cpu_to_scr((tmp&0xff000000) | 1);
4460                 pm->sg.size = cpu_to_scr(tmp - 1);
4461
4462                 /*
4463                  *  If only the residual byte is to be moved,
4464                  *  no PM context is needed.
4465                  */
4466                 if ((tmp&0xffffff) == 1)
4467                         newcmd = pm->ret;
4468
4469                 /*
4470                  *  Prepare the address of SCRIPTS that will
4471                  *  move the residual byte to memory.
4472                  */
4473                 nxtdsp = SCRIPTB_BA (np, wsr_ma_helper);
4474         }
4475
4476         if (DEBUG_FLAGS & DEBUG_PHASE) {
4477                 PRINT_ADDR(cp);
4478                 printf ("PM %x %x %x / %x %x %x.\n",
4479                         hflags0, hflags, newcmd,
4480                         (unsigned)scr_to_cpu(pm->sg.addr),
4481                         (unsigned)scr_to_cpu(pm->sg.size),
4482                         (unsigned)scr_to_cpu(pm->ret));
4483         }
4484
4485         /*
4486          *  Restart the SCRIPTS processor.
4487          */
4488         OUTL (nc_temp, newcmd);
4489         OUTL_DSP (nxtdsp);
4490         return;
4491
4492         /*
4493          *  Unexpected phase changes that occurs when the current phase
4494          *  is not a DATA IN or DATA OUT phase are due to error conditions.
4495          *  Such event may only happen when the SCRIPTS is using a
4496          *  multibyte SCSI MOVE.
4497          *
4498          *  Phase change                Some possible cause
4499          *
4500          *  COMMAND  --> MSG IN SCSI parity error detected by target.
4501          *  COMMAND  --> STATUS Bad command or refused by target.
4502          *  MSG OUT  --> MSG IN     Message rejected by target.
4503          *  MSG OUT  --> COMMAND    Bogus target that discards extended
4504          *                      negotiation messages.
4505          *
4506          *  The code below does not care of the new phase and so
4507          *  trusts the target. Why to annoy it ?
4508          *  If the interrupted phase is COMMAND phase, we restart at
4509          *  dispatcher.
4510          *  If a target does not get all the messages after selection,
4511          *  the code assumes blindly that the target discards extended
4512          *  messages and clears the negotiation status.
4513          *  If the target does not want all our response to negotiation,
4514          *  we force a SIR_NEGO_PROTO interrupt (it is a hack that avoids
4515          *  bloat for such a should_not_happen situation).
4516          *  In all other situation, we reset the BUS.
4517          *  Are these assumptions reasonnable ? (Wait and see ...)
4518          */
4519 unexpected_phase:
4520         dsp -= 8;
4521         nxtdsp = 0;
4522
4523         switch (cmd & 7) {
4524         case 2: /* COMMAND phase */
4525                 nxtdsp = SCRIPTA_BA (np, dispatch);
4526                 break;
4527 #if 0
4528         case 3: /* STATUS  phase */
4529                 nxtdsp = SCRIPTA_BA (np, dispatch);
4530                 break;
4531 #endif
4532         case 6: /* MSG OUT phase */
4533                 /*
4534                  *  If the device may want to use untagged when we want
4535                  *  tagged, we prepare an IDENTIFY without disc. granted,
4536                  *  since we will not be able to handle reselect.
4537                  *  Otherwise, we just don't care.
4538                  */
4539                 if      (dsp == SCRIPTA_BA (np, send_ident)) {
4540                         if (cp->tag != NO_TAG && olen - rest <= 3) {
4541                                 cp->host_status = HS_BUSY;
4542                                 np->msgout[0] = M_IDENTIFY | cp->lun;
4543                                 nxtdsp = SCRIPTB_BA (np, ident_break_atn);
4544                         }
4545                         else
4546                                 nxtdsp = SCRIPTB_BA (np, ident_break);
4547                 }
4548                 else if (dsp == SCRIPTB_BA (np, send_wdtr) ||
4549                          dsp == SCRIPTB_BA (np, send_sdtr) ||
4550                          dsp == SCRIPTB_BA (np, send_ppr)) {
4551                         nxtdsp = SCRIPTB_BA (np, nego_bad_phase);
4552                 }
4553                 break;
4554 #if 0
4555         case 7: /* MSG IN  phase */
4556                 nxtdsp = SCRIPTA_BA (np, clrack);
4557                 break;
4558 #endif
4559         }
4560
4561         if (nxtdsp) {
4562                 OUTL_DSP (nxtdsp);
4563                 return;
4564         }
4565
4566 reset_all:
4567         sym_start_reset(np);
4568 }
4569
4570 /*
4571  *  Dequeue from the START queue all CCBs that match
4572  *  a given target/lun/task condition (-1 means all),
4573  *  and move them from the BUSY queue to the COMP queue
4574  *  with CAM_REQUEUE_REQ status condition.
4575  *  This function is used during error handling/recovery.
4576  *  It is called with SCRIPTS not running.
4577  */
4578 static int
4579 sym_dequeue_from_squeue(hcb_p np, int i, int target, int lun, int task)
4580 {
4581         int j;
4582         ccb_p cp;
4583
4584         /*
4585          *  Make sure the starting index is within range.
4586          */
4587         assert((i >= 0) && (i < 2*MAX_QUEUE));
4588
4589         /*
4590          *  Walk until end of START queue and dequeue every job
4591          *  that matches the target/lun/task condition.
4592          */
4593         j = i;
4594         while (i != np->squeueput) {
4595                 cp = sym_ccb_from_dsa(np, scr_to_cpu(np->squeue[i]));
4596                 assert(cp);
4597 #ifdef SYM_CONF_IARB_SUPPORT
4598                 /* Forget hints for IARB, they may be no longer relevant */
4599                 cp->host_flags &= ~HF_HINT_IARB;
4600 #endif
4601                 if ((target == -1 || cp->target == target) &&
4602                     (lun    == -1 || cp->lun    == lun)    &&
4603                     (task   == -1 || cp->tag    == task)) {
4604                         sym_set_cam_status(cp->cam_ccb, CAM_REQUEUE_REQ);
4605                         sym_remque(&cp->link_ccbq);
4606                         sym_insque_tail(&cp->link_ccbq, &np->comp_ccbq);
4607                 }
4608                 else {
4609                         if (i != j)
4610                                 np->squeue[j] = np->squeue[i];
4611                         if ((j += 2) >= MAX_QUEUE*2) j = 0;
4612                 }
4613                 if ((i += 2) >= MAX_QUEUE*2) i = 0;
4614         }
4615         if (i != j)             /* Copy back the idle task if needed */
4616                 np->squeue[j] = np->squeue[i];
4617         np->squeueput = j;      /* Update our current start queue pointer */
4618
4619         return (i - j) / 2;
4620 }
4621
4622 /*
4623  *  Complete all CCBs queued to the COMP queue.
4624  *
4625  *  These CCBs are assumed:
4626  *  - Not to be referenced either by devices or
4627  *    SCRIPTS-related queues and datas.
4628  *  - To have to be completed with an error condition
4629  *    or requeued.
4630  *
4631  *  The device queue freeze count is incremented
4632  *  for each CCB that does not prevent this.
4633  *  This function is called when all CCBs involved
4634  *  in error handling/recovery have been reaped.
4635  */
4636 static void
4637 sym_flush_comp_queue(hcb_p np, int cam_status)
4638 {
4639         SYM_QUEHEAD *qp;
4640         ccb_p cp;
4641
4642         while ((qp = sym_remque_head(&np->comp_ccbq)) != NULL) {
4643                 union ccb *ccb;
4644                 cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
4645                 sym_insque_tail(&cp->link_ccbq, &np->busy_ccbq);
4646                 /* Leave quiet CCBs waiting for resources */
4647                 if (cp->host_status == HS_WAIT)
4648                         continue;
4649                 ccb = cp->cam_ccb;
4650                 if (cam_status)
4651                         sym_set_cam_status(ccb, cam_status);
4652                 sym_freeze_cam_ccb(ccb);
4653                 sym_xpt_done(np, ccb, cp);
4654                 sym_free_ccb(np, cp);
4655         }
4656 }
4657
4658 /*
4659  *  chip handler for bad SCSI status condition
4660  *
4661  *  In case of bad SCSI status, we unqueue all the tasks
4662  *  currently queued to the controller but not yet started
4663  *  and then restart the SCRIPTS processor immediately.
4664  *
4665  *  QUEUE FULL and BUSY conditions are handled the same way.
4666  *  Basically all the not yet started tasks are requeued in
4667  *  device queue and the queue is frozen until a completion.
4668  *
4669  *  For CHECK CONDITION and COMMAND TERMINATED status, we use
4670  *  the CCB of the failed command to prepare a REQUEST SENSE
4671  *  SCSI command and queue it to the controller queue.
4672  *
4673  *  SCRATCHA is assumed to have been loaded with STARTPOS
4674  *  before the SCRIPTS called the C code.
4675  */
4676 static void sym_sir_bad_scsi_status(hcb_p np, ccb_p cp)
4677 {
4678         tcb_p tp        = &np->target[cp->target];
4679         u32             startp;
4680         u_char          s_status = cp->ssss_status;
4681         u_char          h_flags  = cp->host_flags;
4682         int             msglen;
4683         int             nego;
4684         int             i;
4685
4686         SYM_LOCK_ASSERT(MA_OWNED);
4687
4688         /*
4689          *  Compute the index of the next job to start from SCRIPTS.
4690          */
4691         i = (INL (nc_scratcha) - np->squeue_ba) / 4;
4692
4693         /*
4694          *  The last CCB queued used for IARB hint may be
4695          *  no longer relevant. Forget it.
4696          */
4697 #ifdef SYM_CONF_IARB_SUPPORT
4698         if (np->last_cp)
4699                 np->last_cp = NULL;
4700 #endif
4701
4702         /*
4703          *  Now deal with the SCSI status.
4704          */
4705         switch(s_status) {
4706         case S_BUSY:
4707         case S_QUEUE_FULL:
4708                 if (sym_verbose >= 2) {
4709                         PRINT_ADDR(cp);
4710                         printf (s_status == S_BUSY ? "BUSY" : "QUEUE FULL\n");
4711                 }
4712         default:        /* S_INT, S_INT_COND_MET, S_CONFLICT */
4713                 sym_complete_error (np, cp);
4714                 break;
4715         case S_TERMINATED:
4716         case S_CHECK_COND:
4717                 /*
4718                  *  If we get an SCSI error when requesting sense, give up.
4719                  */
4720                 if (h_flags & HF_SENSE) {
4721                         sym_complete_error (np, cp);
4722                         break;
4723                 }
4724
4725                 /*
4726                  *  Dequeue all queued CCBs for that device not yet started,
4727                  *  and restart the SCRIPTS processor immediately.
4728                  */
4729                 (void) sym_dequeue_from_squeue(np, i, cp->target, cp->lun, -1);
4730                 OUTL_DSP (SCRIPTA_BA (np, start));
4731
4732                 /*
4733                  *  Save some info of the actual IO.
4734                  *  Compute the data residual.
4735                  */
4736                 cp->sv_scsi_status = cp->ssss_status;
4737                 cp->sv_xerr_status = cp->xerr_status;
4738                 cp->sv_resid = sym_compute_residual(np, cp);
4739
4740                 /*
4741                  *  Prepare all needed data structures for
4742                  *  requesting sense data.
4743                  */
4744
4745                 /*
4746                  *  identify message
4747                  */
4748                 cp->scsi_smsg2[0] = M_IDENTIFY | cp->lun;
4749                 msglen = 1;
4750
4751                 /*
4752                  *  If we are currently using anything different from
4753                  *  async. 8 bit data transfers with that target,
4754                  *  start a negotiation, since the device may want
4755                  *  to report us a UNIT ATTENTION condition due to
4756                  *  a cause we currently ignore, and we donnot want
4757                  *  to be stuck with WIDE and/or SYNC data transfer.
4758                  *
4759                  *  cp->nego_status is filled by sym_prepare_nego().
4760                  */
4761                 cp->nego_status = 0;
4762                 nego = 0;
4763                 if      (tp->tinfo.current.options & PPR_OPT_MASK)
4764                         nego = NS_PPR;
4765                 else if (tp->tinfo.current.width != BUS_8_BIT)
4766                         nego = NS_WIDE;
4767                 else if (tp->tinfo.current.offset != 0)
4768                         nego = NS_SYNC;
4769                 if (nego)
4770                         msglen +=
4771                         sym_prepare_nego (np,cp, nego, &cp->scsi_smsg2[msglen]);
4772                 /*
4773                  *  Message table indirect structure.
4774                  */
4775                 cp->phys.smsg.addr      = cpu_to_scr(CCB_BA (cp, scsi_smsg2));
4776                 cp->phys.smsg.size      = cpu_to_scr(msglen);
4777
4778                 /*
4779                  *  sense command
4780                  */
4781                 cp->phys.cmd.addr       = cpu_to_scr(CCB_BA (cp, sensecmd));
4782                 cp->phys.cmd.size       = cpu_to_scr(6);
4783
4784                 /*
4785                  *  patch requested size into sense command
4786                  */
4787                 cp->sensecmd[0]         = 0x03;
4788                 cp->sensecmd[1]         = cp->lun << 5;
4789                 if (tp->tinfo.current.scsi_version > 2 || cp->lun > 7)
4790                         cp->sensecmd[1] = 0;
4791                 cp->sensecmd[4]         = SYM_SNS_BBUF_LEN;
4792                 cp->data_len            = SYM_SNS_BBUF_LEN;
4793
4794                 /*
4795                  *  sense data
4796                  */
4797                 bzero(cp->sns_bbuf, SYM_SNS_BBUF_LEN);
4798                 cp->phys.sense.addr     = cpu_to_scr(vtobus(cp->sns_bbuf));
4799                 cp->phys.sense.size     = cpu_to_scr(SYM_SNS_BBUF_LEN);
4800
4801                 /*
4802                  *  requeue the command.
4803                  */
4804                 startp = SCRIPTB_BA (np, sdata_in);
4805
4806                 cp->phys.head.savep     = cpu_to_scr(startp);
4807                 cp->phys.head.goalp     = cpu_to_scr(startp + 16);
4808                 cp->phys.head.lastp     = cpu_to_scr(startp);
4809                 cp->startp      = cpu_to_scr(startp);
4810
4811                 cp->actualquirks = SYM_QUIRK_AUTOSAVE;
4812                 cp->host_status = cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
4813                 cp->ssss_status = S_ILLEGAL;
4814                 cp->host_flags  = (HF_SENSE|HF_DATA_IN);
4815                 cp->xerr_status = 0;
4816                 cp->extra_bytes = 0;
4817
4818                 cp->phys.head.go.start = cpu_to_scr(SCRIPTA_BA (np, select));
4819
4820                 /*
4821                  *  Requeue the command.
4822                  */
4823                 sym_put_start_queue(np, cp);
4824
4825                 /*
4826                  *  Give back to upper layer everything we have dequeued.
4827                  */
4828                 sym_flush_comp_queue(np, 0);
4829                 break;
4830         }
4831 }
4832
4833 /*
4834  *  After a device has accepted some management message
4835  *  as BUS DEVICE RESET, ABORT TASK, etc ..., or when
4836  *  a device signals a UNIT ATTENTION condition, some
4837  *  tasks are thrown away by the device. We are required
4838  *  to reflect that on our tasks list since the device
4839  *  will never complete these tasks.
4840  *
4841  *  This function move from the BUSY queue to the COMP
4842  *  queue all disconnected CCBs for a given target that
4843  *  match the following criteria:
4844  *  - lun=-1  means any logical UNIT otherwise a given one.
4845  *  - task=-1 means any task, otherwise a given one.
4846  */
4847 static int
4848 sym_clear_tasks(hcb_p np, int cam_status, int target, int lun, int task)
4849 {
4850         SYM_QUEHEAD qtmp, *qp;
4851         int i = 0;
4852         ccb_p cp;
4853
4854         /*
4855          *  Move the entire BUSY queue to our temporary queue.
4856          */
4857         sym_que_init(&qtmp);
4858         sym_que_splice(&np->busy_ccbq, &qtmp);
4859         sym_que_init(&np->busy_ccbq);
4860
4861         /*
4862          *  Put all CCBs that matches our criteria into
4863          *  the COMP queue and put back other ones into
4864          *  the BUSY queue.
4865          */
4866         while ((qp = sym_remque_head(&qtmp)) != NULL) {
4867                 union ccb *ccb;
4868                 cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
4869                 ccb = cp->cam_ccb;
4870                 if (cp->host_status != HS_DISCONNECT ||
4871                     cp->target != target             ||
4872                     (lun  != -1 && cp->lun != lun)   ||
4873                     (task != -1 &&
4874                         (cp->tag != NO_TAG && cp->scsi_smsg[2] != task))) {
4875                         sym_insque_tail(&cp->link_ccbq, &np->busy_ccbq);
4876                         continue;
4877                 }
4878                 sym_insque_tail(&cp->link_ccbq, &np->comp_ccbq);
4879
4880                 /* Preserve the software timeout condition */
4881                 if (sym_get_cam_status(ccb) != CAM_CMD_TIMEOUT)
4882                         sym_set_cam_status(ccb, cam_status);
4883                 ++i;
4884 #if 0
4885 printf("XXXX TASK @%p CLEARED\n", cp);
4886 #endif
4887         }
4888         return i;
4889 }
4890
4891 /*
4892  *  chip handler for TASKS recovery
4893  *
4894  *  We cannot safely abort a command, while the SCRIPTS
4895  *  processor is running, since we just would be in race
4896  *  with it.
4897  *
4898  *  As long as we have tasks to abort, we keep the SEM
4899  *  bit set in the ISTAT. When this bit is set, the
4900  *  SCRIPTS processor interrupts (SIR_SCRIPT_STOPPED)
4901  *  each time it enters the scheduler.
4902  *
4903  *  If we have to reset a target, clear tasks of a unit,
4904  *  or to perform the abort of a disconnected job, we
4905  *  restart the SCRIPTS for selecting the target. Once
4906  *  selected, the SCRIPTS interrupts (SIR_TARGET_SELECTED).
4907  *  If it loses arbitration, the SCRIPTS will interrupt again
4908  *  the next time it will enter its scheduler, and so on ...
4909  *
4910  *  On SIR_TARGET_SELECTED, we scan for the more
4911  *  appropriate thing to do:
4912  *
4913  *  - If nothing, we just sent a M_ABORT message to the
4914  *    target to get rid of the useless SCSI bus ownership.
4915  *    According to the specs, no tasks shall be affected.
4916  *  - If the target is to be reset, we send it a M_RESET
4917  *    message.
4918  *  - If a logical UNIT is to be cleared , we send the
4919  *    IDENTIFY(lun) + M_ABORT.
4920  *  - If an untagged task is to be aborted, we send the
4921  *    IDENTIFY(lun) + M_ABORT.
4922  *  - If a tagged task is to be aborted, we send the
4923  *    IDENTIFY(lun) + task attributes + M_ABORT_TAG.
4924  *
4925  *  Once our 'kiss of death' :) message has been accepted
4926  *  by the target, the SCRIPTS interrupts again
4927  *  (SIR_ABORT_SENT). On this interrupt, we complete
4928  *  all the CCBs that should have been aborted by the
4929  *  target according to our message.
4930  */
4931 static void sym_sir_task_recovery(hcb_p np, int num)
4932 {
4933         SYM_QUEHEAD *qp;
4934         ccb_p cp;
4935         tcb_p tp;
4936         int target=-1, lun=-1, task;
4937         int i, k;
4938
4939         switch(num) {
4940         /*
4941          *  The SCRIPTS processor stopped before starting
4942          *  the next command in order to allow us to perform
4943          *  some task recovery.
4944          */
4945         case SIR_SCRIPT_STOPPED:
4946                 /*
4947                  *  Do we have any target to reset or unit to clear ?
4948                  */
4949                 for (i = 0 ; i < SYM_CONF_MAX_TARGET ; i++) {
4950                         tp = &np->target[i];
4951                         if (tp->to_reset ||
4952                             (tp->lun0p && tp->lun0p->to_clear)) {
4953                                 target = i;
4954                                 break;
4955                         }
4956                         if (!tp->lunmp)
4957                                 continue;
4958                         for (k = 1 ; k < SYM_CONF_MAX_LUN ; k++) {
4959                                 if (tp->lunmp[k] && tp->lunmp[k]->to_clear) {
4960                                         target  = i;
4961                                         break;
4962                                 }
4963                         }
4964                         if (target != -1)
4965                                 break;
4966                 }
4967
4968                 /*
4969                  *  If not, walk the busy queue for any
4970                  *  disconnected CCB to be aborted.
4971                  */
4972                 if (target == -1) {
4973                         FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
4974                                 cp = sym_que_entry(qp,struct sym_ccb,link_ccbq);
4975                                 if (cp->host_status != HS_DISCONNECT)
4976                                         continue;
4977                                 if (cp->to_abort) {
4978                                         target = cp->target;
4979                                         break;
4980                                 }
4981                         }
4982                 }
4983
4984                 /*
4985                  *  If some target is to be selected,
4986                  *  prepare and start the selection.
4987                  */
4988                 if (target != -1) {
4989                         tp = &np->target[target];
4990                         np->abrt_sel.sel_id     = target;
4991                         np->abrt_sel.sel_scntl3 = tp->head.wval;
4992                         np->abrt_sel.sel_sxfer  = tp->head.sval;
4993                         OUTL(nc_dsa, np->hcb_ba);
4994                         OUTL_DSP (SCRIPTB_BA (np, sel_for_abort));
4995                         return;
4996                 }
4997
4998                 /*
4999                  *  Now look for a CCB to abort that haven't started yet.
5000                  *  Btw, the SCRIPTS processor is still stopped, so
5001                  *  we are not in race.
5002                  */
5003                 i = 0;
5004                 cp = NULL;
5005                 FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
5006                         cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
5007                         if (cp->host_status != HS_BUSY &&
5008                             cp->host_status != HS_NEGOTIATE)
5009                                 continue;
5010                         if (!cp->to_abort)
5011                                 continue;
5012 #ifdef SYM_CONF_IARB_SUPPORT
5013                         /*
5014                          *    If we are using IMMEDIATE ARBITRATION, we donnot
5015                          *    want to cancel the last queued CCB, since the
5016                          *    SCRIPTS may have anticipated the selection.
5017                          */
5018                         if (cp == np->last_cp) {
5019                                 cp->to_abort = 0;
5020                                 continue;
5021                         }
5022 #endif
5023                         i = 1;  /* Means we have found some */
5024                         break;
5025                 }
5026                 if (!i) {
5027                         /*
5028                          *  We are done, so we donnot need
5029                          *  to synchronize with the SCRIPTS anylonger.
5030                          *  Remove the SEM flag from the ISTAT.
5031                          */
5032                         np->istat_sem = 0;
5033                         OUTB (nc_istat, SIGP);
5034                         break;
5035                 }
5036                 /*
5037                  *  Compute index of next position in the start
5038                  *  queue the SCRIPTS intends to start and dequeue
5039                  *  all CCBs for that device that haven't been started.
5040                  */
5041                 i = (INL (nc_scratcha) - np->squeue_ba) / 4;
5042                 i = sym_dequeue_from_squeue(np, i, cp->target, cp->lun, -1);
5043
5044                 /*
5045                  *  Make sure at least our IO to abort has been dequeued.
5046                  */
5047                 assert(i && sym_get_cam_status(cp->cam_ccb) == CAM_REQUEUE_REQ);
5048
5049                 /*
5050                  *  Keep track in cam status of the reason of the abort.
5051                  */
5052                 if (cp->to_abort == 2)
5053                         sym_set_cam_status(cp->cam_ccb, CAM_CMD_TIMEOUT);
5054                 else
5055                         sym_set_cam_status(cp->cam_ccb, CAM_REQ_ABORTED);
5056
5057                 /*
5058                  *  Complete with error everything that we have dequeued.
5059                  */
5060                 sym_flush_comp_queue(np, 0);
5061                 break;
5062         /*
5063          *  The SCRIPTS processor has selected a target
5064          *  we may have some manual recovery to perform for.
5065          */
5066         case SIR_TARGET_SELECTED:
5067                 target = (INB (nc_sdid) & 0xf);
5068                 tp = &np->target[target];
5069
5070                 np->abrt_tbl.addr = cpu_to_scr(vtobus(np->abrt_msg));
5071
5072                 /*
5073                  *  If the target is to be reset, prepare a
5074                  *  M_RESET message and clear the to_reset flag
5075                  *  since we donnot expect this operation to fail.
5076                  */
5077                 if (tp->to_reset) {
5078                         np->abrt_msg[0] = M_RESET;
5079                         np->abrt_tbl.size = 1;
5080                         tp->to_reset = 0;
5081                         break;
5082                 }
5083
5084                 /*
5085                  *  Otherwise, look for some logical unit to be cleared.
5086                  */
5087                 if (tp->lun0p && tp->lun0p->to_clear)
5088                         lun = 0;
5089                 else if (tp->lunmp) {
5090                         for (k = 1 ; k < SYM_CONF_MAX_LUN ; k++) {
5091                                 if (tp->lunmp[k] && tp->lunmp[k]->to_clear) {
5092                                         lun = k;
5093                                         break;
5094                                 }
5095                         }
5096                 }
5097
5098                 /*
5099                  *  If a logical unit is to be cleared, prepare
5100                  *  an IDENTIFY(lun) + ABORT MESSAGE.
5101                  */
5102                 if (lun != -1) {
5103                         lcb_p lp = sym_lp(tp, lun);
5104                         lp->to_clear = 0; /* We donnot expect to fail here */
5105                         np->abrt_msg[0] = M_IDENTIFY | lun;
5106                         np->abrt_msg[1] = M_ABORT;
5107                         np->abrt_tbl.size = 2;
5108                         break;
5109                 }
5110
5111                 /*
5112                  *  Otherwise, look for some disconnected job to
5113                  *  abort for this target.
5114                  */
5115                 i = 0;
5116                 cp = NULL;
5117                 FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
5118                         cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
5119                         if (cp->host_status != HS_DISCONNECT)
5120                                 continue;
5121                         if (cp->target != target)
5122                                 continue;
5123                         if (!cp->to_abort)
5124                                 continue;
5125                         i = 1;  /* Means we have some */
5126                         break;
5127                 }
5128
5129                 /*
5130                  *  If we have none, probably since the device has
5131                  *  completed the command before we won abitration,
5132                  *  send a M_ABORT message without IDENTIFY.
5133                  *  According to the specs, the device must just
5134                  *  disconnect the BUS and not abort any task.
5135                  */
5136                 if (!i) {
5137                         np->abrt_msg[0] = M_ABORT;
5138                         np->abrt_tbl.size = 1;
5139                         break;
5140                 }
5141
5142                 /*
5143                  *  We have some task to abort.
5144                  *  Set the IDENTIFY(lun)
5145                  */
5146                 np->abrt_msg[0] = M_IDENTIFY | cp->lun;
5147
5148                 /*
5149                  *  If we want to abort an untagged command, we
5150                  *  will send an IDENTIFY + M_ABORT.
5151                  *  Otherwise (tagged command), we will send
5152                  *  an IDENTIFY + task attributes + ABORT TAG.
5153                  */
5154                 if (cp->tag == NO_TAG) {
5155                         np->abrt_msg[1] = M_ABORT;
5156                         np->abrt_tbl.size = 2;
5157                 }
5158                 else {
5159                         np->abrt_msg[1] = cp->scsi_smsg[1];
5160                         np->abrt_msg[2] = cp->scsi_smsg[2];
5161                         np->abrt_msg[3] = M_ABORT_TAG;
5162                         np->abrt_tbl.size = 4;
5163                 }
5164                 /*
5165                  *  Keep track of software timeout condition, since the
5166                  *  peripheral driver may not count retries on abort
5167                  *  conditions not due to timeout.
5168                  */
5169                 if (cp->to_abort == 2)
5170                         sym_set_cam_status(cp->cam_ccb, CAM_CMD_TIMEOUT);
5171                 cp->to_abort = 0; /* We donnot expect to fail here */
5172                 break;
5173
5174         /*
5175          *  The target has accepted our message and switched
5176          *  to BUS FREE phase as we expected.
5177          */
5178         case SIR_ABORT_SENT:
5179                 target = (INB (nc_sdid) & 0xf);
5180                 tp = &np->target[target];
5181
5182                 /*
5183                 **  If we didn't abort anything, leave here.
5184                 */
5185                 if (np->abrt_msg[0] == M_ABORT)
5186                         break;
5187
5188                 /*
5189                  *  If we sent a M_RESET, then a hardware reset has
5190                  *  been performed by the target.
5191                  *  - Reset everything to async 8 bit
5192                  *  - Tell ourself to negotiate next time :-)
5193                  *  - Prepare to clear all disconnected CCBs for
5194                  *    this target from our task list (lun=task=-1)
5195                  */
5196                 lun = -1;
5197                 task = -1;
5198                 if (np->abrt_msg[0] == M_RESET) {
5199                         tp->head.sval = 0;
5200                         tp->head.wval = np->rv_scntl3;
5201                         tp->head.uval = 0;
5202                         tp->tinfo.current.period = 0;
5203                         tp->tinfo.current.offset = 0;
5204                         tp->tinfo.current.width  = BUS_8_BIT;
5205                         tp->tinfo.current.options = 0;
5206                 }
5207
5208                 /*
5209                  *  Otherwise, check for the LUN and TASK(s)
5210                  *  concerned by the cancelation.
5211                  *  If it is not ABORT_TAG then it is CLEAR_QUEUE
5212                  *  or an ABORT message :-)
5213                  */
5214                 else {
5215                         lun = np->abrt_msg[0] & 0x3f;
5216                         if (np->abrt_msg[1] == M_ABORT_TAG)
5217                                 task = np->abrt_msg[2];
5218                 }
5219
5220                 /*
5221                  *  Complete all the CCBs the device should have
5222                  *  aborted due to our 'kiss of death' message.
5223                  */
5224                 i = (INL (nc_scratcha) - np->squeue_ba) / 4;
5225                 (void) sym_dequeue_from_squeue(np, i, target, lun, -1);
5226                 (void) sym_clear_tasks(np, CAM_REQ_ABORTED, target, lun, task);
5227                 sym_flush_comp_queue(np, 0);
5228
5229                 /*
5230                  *  If we sent a BDR, make uper layer aware of that.
5231                  */
5232                 if (np->abrt_msg[0] == M_RESET)
5233                         xpt_async(AC_SENT_BDR, np->path, NULL);
5234                 break;
5235         }
5236
5237         /*
5238          *  Print to the log the message we intend to send.
5239          */
5240         if (num == SIR_TARGET_SELECTED) {
5241                 PRINT_TARGET(np, target);
5242                 sym_printl_hex("control msgout:", np->abrt_msg,
5243                               np->abrt_tbl.size);
5244                 np->abrt_tbl.size = cpu_to_scr(np->abrt_tbl.size);
5245         }
5246
5247         /*
5248          *  Let the SCRIPTS processor continue.
5249          */
5250         OUTONB_STD ();
5251 }
5252
5253 /*
5254  *  Gerard's alchemy:) that deals with with the data
5255  *  pointer for both MDP and the residual calculation.
5256  *
5257  *  I didn't want to bloat the code by more than 200
5258  *  lignes for the handling of both MDP and the residual.
5259  *  This has been achieved by using a data pointer
5260  *  representation consisting in an index in the data
5261  *  array (dp_sg) and a negative offset (dp_ofs) that
5262  *  have the following meaning:
5263  *
5264  *  - dp_sg = SYM_CONF_MAX_SG
5265  *    we are at the end of the data script.
5266  *  - dp_sg < SYM_CONF_MAX_SG
5267  *    dp_sg points to the next entry of the scatter array
5268  *    we want to transfer.
5269  *  - dp_ofs < 0
5270  *    dp_ofs represents the residual of bytes of the
5271  *    previous entry scatter entry we will send first.
5272  *  - dp_ofs = 0
5273  *    no residual to send first.
5274  *
5275  *  The function sym_evaluate_dp() accepts an arbitray
5276  *  offset (basically from the MDP message) and returns
5277  *  the corresponding values of dp_sg and dp_ofs.
5278  */
5279 static int sym_evaluate_dp(hcb_p np, ccb_p cp, u32 scr, int *ofs)
5280 {
5281         u32     dp_scr;
5282         int     dp_ofs, dp_sg, dp_sgmin;
5283         int     tmp;
5284         struct sym_pmc *pm;
5285
5286         /*
5287          *  Compute the resulted data pointer in term of a script
5288          *  address within some DATA script and a signed byte offset.
5289          */
5290         dp_scr = scr;
5291         dp_ofs = *ofs;
5292         if      (dp_scr == SCRIPTA_BA (np, pm0_data))
5293                 pm = &cp->phys.pm0;
5294         else if (dp_scr == SCRIPTA_BA (np, pm1_data))
5295                 pm = &cp->phys.pm1;
5296         else
5297                 pm = NULL;
5298
5299         if (pm) {
5300                 dp_scr  = scr_to_cpu(pm->ret);
5301                 dp_ofs -= scr_to_cpu(pm->sg.size);
5302         }
5303
5304         /*
5305          *  If we are auto-sensing, then we are done.
5306          */
5307         if (cp->host_flags & HF_SENSE) {
5308                 *ofs = dp_ofs;
5309                 return 0;
5310         }
5311
5312         /*
5313          *  Deduce the index of the sg entry.
5314          *  Keep track of the index of the first valid entry.
5315          *  If result is dp_sg = SYM_CONF_MAX_SG, then we are at the
5316          *  end of the data.
5317          */
5318         tmp = scr_to_cpu(cp->phys.head.goalp);
5319         dp_sg = SYM_CONF_MAX_SG;
5320         if (dp_scr != tmp)
5321                 dp_sg -= (tmp - 8 - (int)dp_scr) / (2*4);
5322         dp_sgmin = SYM_CONF_MAX_SG - cp->segments;
5323
5324         /*
5325          *  Move to the sg entry the data pointer belongs to.
5326          *
5327          *  If we are inside the data area, we expect result to be:
5328          *
5329          *  Either,
5330          *      dp_ofs = 0 and dp_sg is the index of the sg entry
5331          *      the data pointer belongs to (or the end of the data)
5332          *  Or,
5333          *      dp_ofs < 0 and dp_sg is the index of the sg entry
5334          *      the data pointer belongs to + 1.
5335          */
5336         if (dp_ofs < 0) {
5337                 int n;
5338                 while (dp_sg > dp_sgmin) {
5339                         --dp_sg;
5340                         tmp = scr_to_cpu(cp->phys.data[dp_sg].size);
5341                         n = dp_ofs + (tmp & 0xffffff);
5342                         if (n > 0) {
5343                                 ++dp_sg;
5344                                 break;
5345                         }
5346                         dp_ofs = n;
5347                 }
5348         }
5349         else if (dp_ofs > 0) {
5350                 while (dp_sg < SYM_CONF_MAX_SG) {
5351                         tmp = scr_to_cpu(cp->phys.data[dp_sg].size);
5352                         dp_ofs -= (tmp & 0xffffff);
5353                         ++dp_sg;
5354                         if (dp_ofs <= 0)
5355                                 break;
5356                 }
5357         }
5358
5359         /*
5360          *  Make sure the data pointer is inside the data area.
5361          *  If not, return some error.
5362          */
5363         if      (dp_sg < dp_sgmin || (dp_sg == dp_sgmin && dp_ofs < 0))
5364                 goto out_err;
5365         else if (dp_sg > SYM_CONF_MAX_SG ||
5366                  (dp_sg == SYM_CONF_MAX_SG && dp_ofs > 0))
5367                 goto out_err;
5368
5369         /*
5370          *  Save the extreme pointer if needed.
5371          */
5372         if (dp_sg > cp->ext_sg ||
5373             (dp_sg == cp->ext_sg && dp_ofs > cp->ext_ofs)) {
5374                 cp->ext_sg  = dp_sg;
5375                 cp->ext_ofs = dp_ofs;
5376         }
5377
5378         /*
5379          *  Return data.
5380          */
5381         *ofs = dp_ofs;
5382         return dp_sg;
5383
5384 out_err:
5385         return -1;
5386 }
5387
5388 /*
5389  *  chip handler for MODIFY DATA POINTER MESSAGE
5390  *
5391  *  We also call this function on IGNORE WIDE RESIDUE
5392  *  messages that do not match a SWIDE full condition.
5393  *  Btw, we assume in that situation that such a message
5394  *  is equivalent to a MODIFY DATA POINTER (offset=-1).
5395  */
5396 static void sym_modify_dp(hcb_p np, ccb_p cp, int ofs)
5397 {
5398         int dp_ofs      = ofs;
5399         u32     dp_scr  = INL (nc_temp);
5400         u32     dp_ret;
5401         u32     tmp;
5402         u_char  hflags;
5403         int     dp_sg;
5404         struct  sym_pmc *pm;
5405
5406         /*
5407          *  Not supported for auto-sense.
5408          */
5409         if (cp->host_flags & HF_SENSE)
5410                 goto out_reject;
5411
5412         /*
5413          *  Apply our alchemy:) (see comments in sym_evaluate_dp()),
5414          *  to the resulted data pointer.
5415          */
5416         dp_sg = sym_evaluate_dp(np, cp, dp_scr, &dp_ofs);
5417         if (dp_sg < 0)
5418                 goto out_reject;
5419
5420         /*
5421          *  And our alchemy:) allows to easily calculate the data
5422          *  script address we want to return for the next data phase.
5423          */
5424         dp_ret = cpu_to_scr(cp->phys.head.goalp);
5425         dp_ret = dp_ret - 8 - (SYM_CONF_MAX_SG - dp_sg) * (2*4);
5426
5427         /*
5428          *  If offset / scatter entry is zero we donnot need
5429          *  a context for the new current data pointer.
5430          */
5431         if (dp_ofs == 0) {
5432                 dp_scr = dp_ret;
5433                 goto out_ok;
5434         }
5435
5436         /*
5437          *  Get a context for the new current data pointer.
5438          */
5439         hflags = INB (HF_PRT);
5440
5441         if (hflags & HF_DP_SAVED)
5442                 hflags ^= HF_ACT_PM;
5443
5444         if (!(hflags & HF_ACT_PM)) {
5445                 pm  = &cp->phys.pm0;
5446                 dp_scr = SCRIPTA_BA (np, pm0_data);
5447         }
5448         else {
5449                 pm = &cp->phys.pm1;
5450                 dp_scr = SCRIPTA_BA (np, pm1_data);
5451         }
5452
5453         hflags &= ~(HF_DP_SAVED);
5454
5455         OUTB (HF_PRT, hflags);
5456
5457         /*
5458          *  Set up the new current data pointer.
5459          *  ofs < 0 there, and for the next data phase, we
5460          *  want to transfer part of the data of the sg entry
5461          *  corresponding to index dp_sg-1 prior to returning
5462          *  to the main data script.
5463          */
5464         pm->ret = cpu_to_scr(dp_ret);
5465         tmp  = scr_to_cpu(cp->phys.data[dp_sg-1].addr);
5466         tmp += scr_to_cpu(cp->phys.data[dp_sg-1].size) + dp_ofs;
5467         pm->sg.addr = cpu_to_scr(tmp);
5468         pm->sg.size = cpu_to_scr(-dp_ofs);
5469
5470 out_ok:
5471         OUTL (nc_temp, dp_scr);
5472         OUTL_DSP (SCRIPTA_BA (np, clrack));
5473         return;
5474
5475 out_reject:
5476         OUTL_DSP (SCRIPTB_BA (np, msg_bad));
5477 }
5478
5479 /*
5480  *  chip calculation of the data residual.
5481  *
5482  *  As I used to say, the requirement of data residual
5483  *  in SCSI is broken, useless and cannot be achieved
5484  *  without huge complexity.
5485  *  But most OSes and even the official CAM require it.
5486  *  When stupidity happens to be so widely spread inside
5487  *  a community, it gets hard to convince.
5488  *
5489  *  Anyway, I don't care, since I am not going to use
5490  *  any software that considers this data residual as
5491  *  a relevant information. :)
5492  */
5493 static int sym_compute_residual(hcb_p np, ccb_p cp)
5494 {
5495         int dp_sg, dp_sgmin, resid = 0;
5496         int dp_ofs = 0;
5497
5498         /*
5499          *  Check for some data lost or just thrown away.
5500          *  We are not required to be quite accurate in this
5501          *  situation. Btw, if we are odd for output and the
5502          *  device claims some more data, it may well happen
5503          *  than our residual be zero. :-)
5504          */
5505         if (cp->xerr_status & (XE_EXTRA_DATA|XE_SODL_UNRUN|XE_SWIDE_OVRUN)) {
5506                 if (cp->xerr_status & XE_EXTRA_DATA)
5507                         resid -= cp->extra_bytes;
5508                 if (cp->xerr_status & XE_SODL_UNRUN)
5509                         ++resid;
5510                 if (cp->xerr_status & XE_SWIDE_OVRUN)
5511                         --resid;
5512         }
5513
5514         /*
5515          *  If all data has been transferred,
5516          *  there is no residual.
5517          */
5518         if (cp->phys.head.lastp == cp->phys.head.goalp)
5519                 return resid;
5520
5521         /*
5522          *  If no data transfer occurs, or if the data
5523          *  pointer is weird, return full residual.
5524          */
5525         if (cp->startp == cp->phys.head.lastp ||
5526             sym_evaluate_dp(np, cp, scr_to_cpu(cp->phys.head.lastp),
5527                             &dp_ofs) < 0) {
5528                 return cp->data_len;
5529         }
5530
5531         /*
5532          *  If we were auto-sensing, then we are done.
5533          */
5534         if (cp->host_flags & HF_SENSE) {
5535                 return -dp_ofs;
5536         }
5537
5538         /*
5539          *  We are now full comfortable in the computation
5540          *  of the data residual (2's complement).
5541          */
5542         dp_sgmin = SYM_CONF_MAX_SG - cp->segments;
5543         resid = -cp->ext_ofs;
5544         for (dp_sg = cp->ext_sg; dp_sg < SYM_CONF_MAX_SG; ++dp_sg) {
5545                 u_int tmp = scr_to_cpu(cp->phys.data[dp_sg].size);
5546                 resid += (tmp & 0xffffff);
5547         }
5548
5549         /*
5550          *  Hopefully, the result is not too wrong.
5551          */
5552         return resid;
5553 }
5554
5555 /*
5556  *  Print out the content of a SCSI message.
5557  */
5558 static int sym_show_msg (u_char * msg)
5559 {
5560         u_char i;
5561         printf ("%x",*msg);
5562         if (*msg==M_EXTENDED) {
5563                 for (i=1;i<8;i++) {
5564                         if (i-1>msg[1]) break;
5565                         printf ("-%x",msg[i]);
5566                 };
5567                 return (i+1);
5568         } else if ((*msg & 0xf0) == 0x20) {
5569                 printf ("-%x",msg[1]);
5570                 return (2);
5571         };
5572         return (1);
5573 }
5574
5575 static void sym_print_msg (ccb_p cp, char *label, u_char *msg)
5576 {
5577         PRINT_ADDR(cp);
5578         if (label)
5579                 printf ("%s: ", label);
5580
5581         (void) sym_show_msg (msg);
5582         printf (".\n");
5583 }
5584
5585 /*
5586  *  Negotiation for WIDE and SYNCHRONOUS DATA TRANSFER.
5587  *
5588  *  When we try to negotiate, we append the negotiation message
5589  *  to the identify and (maybe) simple tag message.
5590  *  The host status field is set to HS_NEGOTIATE to mark this
5591  *  situation.
5592  *
5593  *  If the target doesn't answer this message immediately
5594  *  (as required by the standard), the SIR_NEGO_FAILED interrupt
5595  *  will be raised eventually.
5596  *  The handler removes the HS_NEGOTIATE status, and sets the
5597  *  negotiated value to the default (async / nowide).
5598  *
5599  *  If we receive a matching answer immediately, we check it
5600  *  for validity, and set the values.
5601  *
5602  *  If we receive a Reject message immediately, we assume the
5603  *  negotiation has failed, and fall back to standard values.
5604  *
5605  *  If we receive a negotiation message while not in HS_NEGOTIATE
5606  *  state, it's a target initiated negotiation. We prepare a
5607  *  (hopefully) valid answer, set our parameters, and send back
5608  *  this answer to the target.
5609  *
5610  *  If the target doesn't fetch the answer (no message out phase),
5611  *  we assume the negotiation has failed, and fall back to default
5612  *  settings (SIR_NEGO_PROTO interrupt).
5613  *
5614  *  When we set the values, we adjust them in all ccbs belonging
5615  *  to this target, in the controller's register, and in the "phys"
5616  *  field of the controller's struct sym_hcb.
5617  */
5618
5619 /*
5620  *  chip handler for SYNCHRONOUS DATA TRANSFER REQUEST (SDTR) message.
5621  */
5622 static void sym_sync_nego(hcb_p np, tcb_p tp, ccb_p cp)
5623 {
5624         u_char  chg, ofs, per, fak, div;
5625         int     req = 1;
5626
5627         /*
5628          *  Synchronous request message received.
5629          */
5630         if (DEBUG_FLAGS & DEBUG_NEGO) {
5631                 sym_print_msg(cp, "sync msgin", np->msgin);
5632         };
5633
5634         /*
5635          * request or answer ?
5636          */
5637         if (INB (HS_PRT) == HS_NEGOTIATE) {
5638                 OUTB (HS_PRT, HS_BUSY);
5639                 if (cp->nego_status && cp->nego_status != NS_SYNC)
5640                         goto reject_it;
5641                 req = 0;
5642         }
5643
5644         /*
5645          *  get requested values.
5646          */
5647         chg = 0;
5648         per = np->msgin[3];
5649         ofs = np->msgin[4];
5650
5651         /*
5652          *  check values against our limits.
5653          */
5654         if (ofs) {
5655                 if (ofs > np->maxoffs)
5656                         {chg = 1; ofs = np->maxoffs;}
5657                 if (req) {
5658                         if (ofs > tp->tinfo.user.offset)
5659                                 {chg = 1; ofs = tp->tinfo.user.offset;}
5660                 }
5661         }
5662
5663         if (ofs) {
5664                 if (per < np->minsync)
5665                         {chg = 1; per = np->minsync;}
5666                 if (req) {
5667                         if (per < tp->tinfo.user.period)
5668                                 {chg = 1; per = tp->tinfo.user.period;}
5669                 }
5670         }
5671
5672         div = fak = 0;
5673         if (ofs && sym_getsync(np, 0, per, &div, &fak) < 0)
5674                 goto reject_it;
5675
5676         if (DEBUG_FLAGS & DEBUG_NEGO) {
5677                 PRINT_ADDR(cp);
5678                 printf ("sdtr: ofs=%d per=%d div=%d fak=%d chg=%d.\n",
5679                         ofs, per, div, fak, chg);
5680         }
5681
5682         /*
5683          *  This was an answer message
5684          */
5685         if (req == 0) {
5686                 if (chg)        /* Answer wasn't acceptable. */
5687                         goto reject_it;
5688                 sym_setsync (np, cp, ofs, per, div, fak);
5689                 OUTL_DSP (SCRIPTA_BA (np, clrack));
5690                 return;
5691         }
5692
5693         /*
5694          *  It was a request. Set value and
5695          *  prepare an answer message
5696          */
5697         sym_setsync (np, cp, ofs, per, div, fak);
5698
5699         np->msgout[0] = M_EXTENDED;
5700         np->msgout[1] = 3;
5701         np->msgout[2] = M_X_SYNC_REQ;
5702         np->msgout[3] = per;
5703         np->msgout[4] = ofs;
5704
5705         cp->nego_status = NS_SYNC;
5706
5707         if (DEBUG_FLAGS & DEBUG_NEGO) {
5708                 sym_print_msg(cp, "sync msgout", np->msgout);
5709         }
5710
5711         np->msgin [0] = M_NOOP;
5712
5713         OUTL_DSP (SCRIPTB_BA (np, sdtr_resp));
5714         return;
5715 reject_it:
5716         sym_setsync (np, cp, 0, 0, 0, 0);
5717         OUTL_DSP (SCRIPTB_BA (np, msg_bad));
5718 }
5719
5720 /*
5721  *  chip handler for PARALLEL PROTOCOL REQUEST (PPR) message.
5722  */
5723 static void sym_ppr_nego(hcb_p np, tcb_p tp, ccb_p cp)
5724 {
5725         u_char  chg, ofs, per, fak, dt, div, wide;
5726         int     req = 1;
5727
5728         /*
5729          * Synchronous request message received.
5730          */
5731         if (DEBUG_FLAGS & DEBUG_NEGO) {
5732                 sym_print_msg(cp, "ppr msgin", np->msgin);
5733         };
5734
5735         /*
5736          *  get requested values.
5737          */
5738         chg  = 0;
5739         per  = np->msgin[3];
5740         ofs  = np->msgin[5];
5741         wide = np->msgin[6];
5742         dt   = np->msgin[7] & PPR_OPT_DT;
5743
5744         /*
5745          * request or answer ?
5746          */
5747         if (INB (HS_PRT) == HS_NEGOTIATE) {
5748                 OUTB (HS_PRT, HS_BUSY);
5749                 if (cp->nego_status && cp->nego_status != NS_PPR)
5750                         goto reject_it;
5751                 req = 0;
5752         }
5753
5754         /*
5755          *  check values against our limits.
5756          */
5757         if (wide > np->maxwide)
5758                 {chg = 1; wide = np->maxwide;}
5759         if (!wide || !(np->features & FE_ULTRA3))
5760                 dt &= ~PPR_OPT_DT;
5761         if (req) {
5762                 if (wide > tp->tinfo.user.width)
5763                         {chg = 1; wide = tp->tinfo.user.width;}
5764         }
5765
5766         if (!(np->features & FE_U3EN))  /* Broken U3EN bit not supported */
5767                 dt &= ~PPR_OPT_DT;
5768
5769         if (dt != (np->msgin[7] & PPR_OPT_MASK)) chg = 1;
5770
5771         if (ofs) {
5772                 if (dt) {
5773                         if (ofs > np->maxoffs_dt)
5774                                 {chg = 1; ofs = np->maxoffs_dt;}
5775                 }
5776                 else if (ofs > np->maxoffs)
5777                         {chg = 1; ofs = np->maxoffs;}
5778                 if (req) {
5779                         if (ofs > tp->tinfo.user.offset)
5780                                 {chg = 1; ofs = tp->tinfo.user.offset;}
5781                 }
5782         }
5783
5784         if (ofs) {
5785                 if (dt) {
5786                         if (per < np->minsync_dt)
5787                                 {chg = 1; per = np->minsync_dt;}
5788                 }
5789                 else if (per < np->minsync)
5790                         {chg = 1; per = np->minsync;}
5791                 if (req) {
5792                         if (per < tp->tinfo.user.period)
5793                                 {chg = 1; per = tp->tinfo.user.period;}
5794                 }
5795         }
5796
5797         div = fak = 0;
5798         if (ofs && sym_getsync(np, dt, per, &div, &fak) < 0)
5799                 goto reject_it;
5800
5801         if (DEBUG_FLAGS & DEBUG_NEGO) {
5802                 PRINT_ADDR(cp);
5803                 printf ("ppr: "
5804                         "dt=%x ofs=%d per=%d wide=%d div=%d fak=%d chg=%d.\n",
5805                         dt, ofs, per, wide, div, fak, chg);
5806         }
5807
5808         /*
5809          *  It was an answer.
5810          */
5811         if (req == 0) {
5812                 if (chg)        /* Answer wasn't acceptable */
5813                         goto reject_it;
5814                 sym_setpprot (np, cp, dt, ofs, per, wide, div, fak);
5815                 OUTL_DSP (SCRIPTA_BA (np, clrack));
5816                 return;
5817         }
5818
5819         /*
5820          *  It was a request. Set value and
5821          *  prepare an answer message
5822          */
5823         sym_setpprot (np, cp, dt, ofs, per, wide, div, fak);
5824
5825         np->msgout[0] = M_EXTENDED;
5826         np->msgout[1] = 6;
5827         np->msgout[2] = M_X_PPR_REQ;
5828         np->msgout[3] = per;
5829         np->msgout[4] = 0;
5830         np->msgout[5] = ofs;
5831         np->msgout[6] = wide;
5832         np->msgout[7] = dt;
5833
5834         cp->nego_status = NS_PPR;
5835
5836         if (DEBUG_FLAGS & DEBUG_NEGO) {
5837                 sym_print_msg(cp, "ppr msgout", np->msgout);
5838         }
5839
5840         np->msgin [0] = M_NOOP;
5841
5842         OUTL_DSP (SCRIPTB_BA (np, ppr_resp));
5843         return;
5844 reject_it:
5845         sym_setpprot (np, cp, 0, 0, 0, 0, 0, 0);
5846         OUTL_DSP (SCRIPTB_BA (np, msg_bad));
5847         /*
5848          *  If it was a device response that should result in
5849          *  ST, we may want to try a legacy negotiation later.
5850          */
5851         if (!req && !dt) {
5852                 tp->tinfo.goal.options = 0;
5853                 tp->tinfo.goal.width   = wide;
5854                 tp->tinfo.goal.period  = per;
5855                 tp->tinfo.goal.offset  = ofs;
5856         }
5857 }
5858
5859 /*
5860  *  chip handler for WIDE DATA TRANSFER REQUEST (WDTR) message.
5861  */
5862 static void sym_wide_nego(hcb_p np, tcb_p tp, ccb_p cp)
5863 {
5864         u_char  chg, wide;
5865         int     req = 1;
5866
5867         /*
5868          *  Wide request message received.
5869          */
5870         if (DEBUG_FLAGS & DEBUG_NEGO) {
5871                 sym_print_msg(cp, "wide msgin", np->msgin);
5872         };
5873
5874         /*
5875          * Is it a request from the device?
5876          */
5877         if (INB (HS_PRT) == HS_NEGOTIATE) {
5878                 OUTB (HS_PRT, HS_BUSY);
5879                 if (cp->nego_status && cp->nego_status != NS_WIDE)
5880                         goto reject_it;
5881                 req = 0;
5882         }
5883
5884         /*
5885          *  get requested values.
5886          */
5887         chg  = 0;
5888         wide = np->msgin[3];
5889
5890         /*
5891          *  check values against driver limits.
5892          */
5893         if (wide > np->maxwide)
5894                 {chg = 1; wide = np->maxwide;}
5895         if (req) {
5896                 if (wide > tp->tinfo.user.width)
5897                         {chg = 1; wide = tp->tinfo.user.width;}
5898         }
5899
5900         if (DEBUG_FLAGS & DEBUG_NEGO) {
5901                 PRINT_ADDR(cp);
5902                 printf ("wdtr: wide=%d chg=%d.\n", wide, chg);
5903         }
5904
5905         /*
5906          * This was an answer message
5907          */
5908         if (req == 0) {
5909                 if (chg)        /*  Answer wasn't acceptable. */
5910                         goto reject_it;
5911                 sym_setwide (np, cp, wide);
5912
5913                 /*
5914                  * Negotiate for SYNC immediately after WIDE response.
5915                  * This allows to negotiate for both WIDE and SYNC on
5916                  * a single SCSI command (Suggested by Justin Gibbs).
5917                  */
5918                 if (tp->tinfo.goal.offset) {
5919                         np->msgout[0] = M_EXTENDED;
5920                         np->msgout[1] = 3;
5921                         np->msgout[2] = M_X_SYNC_REQ;
5922                         np->msgout[3] = tp->tinfo.goal.period;
5923                         np->msgout[4] = tp->tinfo.goal.offset;
5924
5925                         if (DEBUG_FLAGS & DEBUG_NEGO) {
5926                                 sym_print_msg(cp, "sync msgout", np->msgout);
5927                         }
5928
5929                         cp->nego_status = NS_SYNC;
5930                         OUTB (HS_PRT, HS_NEGOTIATE);
5931                         OUTL_DSP (SCRIPTB_BA (np, sdtr_resp));
5932                         return;
5933                 }
5934
5935                 OUTL_DSP (SCRIPTA_BA (np, clrack));
5936                 return;
5937         };
5938
5939         /*
5940          *  It was a request, set value and
5941          *  prepare an answer message
5942          */
5943         sym_setwide (np, cp, wide);
5944
5945         np->msgout[0] = M_EXTENDED;
5946         np->msgout[1] = 2;
5947         np->msgout[2] = M_X_WIDE_REQ;
5948         np->msgout[3] = wide;
5949
5950         np->msgin [0] = M_NOOP;
5951
5952         cp->nego_status = NS_WIDE;
5953
5954         if (DEBUG_FLAGS & DEBUG_NEGO) {
5955                 sym_print_msg(cp, "wide msgout", np->msgout);
5956         }
5957
5958         OUTL_DSP (SCRIPTB_BA (np, wdtr_resp));
5959         return;
5960 reject_it:
5961         OUTL_DSP (SCRIPTB_BA (np, msg_bad));
5962 }
5963
5964 /*
5965  *  Reset SYNC or WIDE to default settings.
5966  *
5967  *  Called when a negotiation does not succeed either
5968  *  on rejection or on protocol error.
5969  *
5970  *  If it was a PPR that made problems, we may want to
5971  *  try a legacy negotiation later.
5972  */
5973 static void sym_nego_default(hcb_p np, tcb_p tp, ccb_p cp)
5974 {
5975         /*
5976          *  any error in negotiation:
5977          *  fall back to default mode.
5978          */
5979         switch (cp->nego_status) {
5980         case NS_PPR:
5981 #if 0
5982                 sym_setpprot (np, cp, 0, 0, 0, 0, 0, 0);
5983 #else
5984                 tp->tinfo.goal.options = 0;
5985                 if (tp->tinfo.goal.period < np->minsync)
5986                         tp->tinfo.goal.period = np->minsync;
5987                 if (tp->tinfo.goal.offset > np->maxoffs)
5988                         tp->tinfo.goal.offset = np->maxoffs;
5989 #endif
5990                 break;
5991         case NS_SYNC:
5992                 sym_setsync (np, cp, 0, 0, 0, 0);
5993                 break;
5994         case NS_WIDE:
5995                 sym_setwide (np, cp, 0);
5996                 break;
5997         };
5998         np->msgin [0] = M_NOOP;
5999         np->msgout[0] = M_NOOP;
6000         cp->nego_status = 0;
6001 }
6002
6003 /*
6004  *  chip handler for MESSAGE REJECT received in response to
6005  *  a WIDE or SYNCHRONOUS negotiation.
6006  */
6007 static void sym_nego_rejected(hcb_p np, tcb_p tp, ccb_p cp)
6008 {
6009         sym_nego_default(np, tp, cp);
6010         OUTB (HS_PRT, HS_BUSY);
6011 }
6012
6013 /*
6014  *  chip exception handler for programmed interrupts.
6015  */
6016 static void sym_int_sir (hcb_p np)
6017 {
6018         u_char  num     = INB (nc_dsps);
6019         u32     dsa     = INL (nc_dsa);
6020         ccb_p   cp      = sym_ccb_from_dsa(np, dsa);
6021         u_char  target  = INB (nc_sdid) & 0x0f;
6022         tcb_p   tp      = &np->target[target];
6023         int     tmp;
6024
6025         SYM_LOCK_ASSERT(MA_OWNED);
6026
6027         if (DEBUG_FLAGS & DEBUG_TINY) printf ("I#%d", num);
6028
6029         switch (num) {
6030         /*
6031          *  Command has been completed with error condition
6032          *  or has been auto-sensed.
6033          */
6034         case SIR_COMPLETE_ERROR:
6035                 sym_complete_error(np, cp);
6036                 return;
6037         /*
6038          *  The C code is currently trying to recover from something.
6039          *  Typically, user want to abort some command.
6040          */
6041         case SIR_SCRIPT_STOPPED:
6042         case SIR_TARGET_SELECTED:
6043         case SIR_ABORT_SENT:
6044                 sym_sir_task_recovery(np, num);
6045                 return;
6046         /*
6047          *  The device didn't go to MSG OUT phase after having
6048          *  been selected with ATN. We donnot want to handle
6049          *  that.
6050          */
6051         case SIR_SEL_ATN_NO_MSG_OUT:
6052                 printf ("%s:%d: No MSG OUT phase after selection with ATN.\n",
6053                         sym_name (np), target);
6054                 goto out_stuck;
6055         /*
6056          *  The device didn't switch to MSG IN phase after
6057          *  having reseleted the initiator.
6058          */
6059         case SIR_RESEL_NO_MSG_IN:
6060                 printf ("%s:%d: No MSG IN phase after reselection.\n",
6061                         sym_name (np), target);
6062                 goto out_stuck;
6063         /*
6064          *  After reselection, the device sent a message that wasn't
6065          *  an IDENTIFY.
6066          */
6067         case SIR_RESEL_NO_IDENTIFY:
6068                 printf ("%s:%d: No IDENTIFY after reselection.\n",
6069                         sym_name (np), target);
6070                 goto out_stuck;
6071         /*
6072          *  The device reselected a LUN we donnot know about.
6073          */
6074         case SIR_RESEL_BAD_LUN:
6075                 np->msgout[0] = M_RESET;
6076                 goto out;
6077         /*
6078          *  The device reselected for an untagged nexus and we
6079          *  haven't any.
6080          */
6081         case SIR_RESEL_BAD_I_T_L:
6082                 np->msgout[0] = M_ABORT;
6083                 goto out;
6084         /*
6085          *  The device reselected for a tagged nexus that we donnot
6086          *  have.
6087          */
6088         case SIR_RESEL_BAD_I_T_L_Q:
6089                 np->msgout[0] = M_ABORT_TAG;
6090                 goto out;
6091         /*
6092          *  The SCRIPTS let us know that the device has grabbed
6093          *  our message and will abort the job.
6094          */
6095         case SIR_RESEL_ABORTED:
6096                 np->lastmsg = np->msgout[0];
6097                 np->msgout[0] = M_NOOP;
6098                 printf ("%s:%d: message %x sent on bad reselection.\n",
6099                         sym_name (np), target, np->lastmsg);
6100                 goto out;
6101         /*
6102          *  The SCRIPTS let us know that a message has been
6103          *  successfully sent to the device.
6104          */
6105         case SIR_MSG_OUT_DONE:
6106                 np->lastmsg = np->msgout[0];
6107                 np->msgout[0] = M_NOOP;
6108                 /* Should we really care of that */
6109                 if (np->lastmsg == M_PARITY || np->lastmsg == M_ID_ERROR) {
6110                         if (cp) {
6111                                 cp->xerr_status &= ~XE_PARITY_ERR;
6112                                 if (!cp->xerr_status)
6113                                         OUTOFFB (HF_PRT, HF_EXT_ERR);
6114                         }
6115                 }
6116                 goto out;
6117         /*
6118          *  The device didn't send a GOOD SCSI status.
6119          *  We may have some work to do prior to allow
6120          *  the SCRIPTS processor to continue.
6121          */
6122         case SIR_BAD_SCSI_STATUS:
6123                 if (!cp)
6124                         goto out;
6125                 sym_sir_bad_scsi_status(np, cp);
6126                 return;
6127         /*
6128          *  We are asked by the SCRIPTS to prepare a
6129          *  REJECT message.
6130          */
6131         case SIR_REJECT_TO_SEND:
6132                 sym_print_msg(cp, "M_REJECT to send for ", np->msgin);
6133                 np->msgout[0] = M_REJECT;
6134                 goto out;
6135         /*
6136          *  We have been ODD at the end of a DATA IN
6137          *  transfer and the device didn't send a
6138          *  IGNORE WIDE RESIDUE message.
6139          *  It is a data overrun condition.
6140          */
6141         case SIR_SWIDE_OVERRUN:
6142                 if (cp) {
6143                         OUTONB (HF_PRT, HF_EXT_ERR);
6144                         cp->xerr_status |= XE_SWIDE_OVRUN;
6145                 }
6146                 goto out;
6147         /*
6148          *  We have been ODD at the end of a DATA OUT
6149          *  transfer.
6150          *  It is a data underrun condition.
6151          */
6152         case SIR_SODL_UNDERRUN:
6153                 if (cp) {
6154                         OUTONB (HF_PRT, HF_EXT_ERR);
6155                         cp->xerr_status |= XE_SODL_UNRUN;
6156                 }
6157                 goto out;
6158         /*
6159          *  The device wants us to tranfer more data than
6160          *  expected or in the wrong direction.
6161          *  The number of extra bytes is in scratcha.
6162          *  It is a data overrun condition.
6163          */
6164         case SIR_DATA_OVERRUN:
6165                 if (cp) {
6166                         OUTONB (HF_PRT, HF_EXT_ERR);
6167                         cp->xerr_status |= XE_EXTRA_DATA;
6168                         cp->extra_bytes += INL (nc_scratcha);
6169                 }
6170                 goto out;
6171         /*
6172          *  The device switched to an illegal phase (4/5).
6173          */
6174         case SIR_BAD_PHASE:
6175                 if (cp) {
6176                         OUTONB (HF_PRT, HF_EXT_ERR);
6177                         cp->xerr_status |= XE_BAD_PHASE;
6178                 }
6179                 goto out;
6180         /*
6181          *  We received a message.
6182          */
6183         case SIR_MSG_RECEIVED:
6184                 if (!cp)
6185                         goto out_stuck;
6186                 switch (np->msgin [0]) {
6187                 /*
6188                  *  We received an extended message.
6189                  *  We handle MODIFY DATA POINTER, SDTR, WDTR
6190                  *  and reject all other extended messages.
6191                  */
6192                 case M_EXTENDED:
6193                         switch (np->msgin [2]) {
6194                         case M_X_MODIFY_DP:
6195                                 if (DEBUG_FLAGS & DEBUG_POINTER)
6196                                         sym_print_msg(cp,"modify DP",np->msgin);
6197                                 tmp = (np->msgin[3]<<24) + (np->msgin[4]<<16) +
6198                                       (np->msgin[5]<<8)  + (np->msgin[6]);
6199                                 sym_modify_dp(np, cp, tmp);
6200                                 return;
6201                         case M_X_SYNC_REQ:
6202                                 sym_sync_nego(np, tp, cp);
6203                                 return;
6204                         case M_X_PPR_REQ:
6205                                 sym_ppr_nego(np, tp, cp);
6206                                 return;
6207                         case M_X_WIDE_REQ:
6208                                 sym_wide_nego(np, tp, cp);
6209                                 return;
6210                         default:
6211                                 goto out_reject;
6212                         }
6213                         break;
6214                 /*
6215                  *  We received a 1/2 byte message not handled from SCRIPTS.
6216                  *  We are only expecting MESSAGE REJECT and IGNORE WIDE
6217                  *  RESIDUE messages that haven't been anticipated by
6218                  *  SCRIPTS on SWIDE full condition. Unanticipated IGNORE
6219                  *  WIDE RESIDUE messages are aliased as MODIFY DP (-1).
6220                  */
6221                 case M_IGN_RESIDUE:
6222                         if (DEBUG_FLAGS & DEBUG_POINTER)
6223                                 sym_print_msg(cp,"ign wide residue", np->msgin);
6224                         sym_modify_dp(np, cp, -1);
6225                         return;
6226                 case M_REJECT:
6227                         if (INB (HS_PRT) == HS_NEGOTIATE)
6228                                 sym_nego_rejected(np, tp, cp);
6229                         else {
6230                                 PRINT_ADDR(cp);
6231                                 printf ("M_REJECT received (%x:%x).\n",
6232                                         scr_to_cpu(np->lastmsg), np->msgout[0]);
6233                         }
6234                         goto out_clrack;
6235                         break;
6236                 default:
6237                         goto out_reject;
6238                 }
6239                 break;
6240         /*
6241          *  We received an unknown message.
6242          *  Ignore all MSG IN phases and reject it.
6243          */
6244         case SIR_MSG_WEIRD:
6245                 sym_print_msg(cp, "WEIRD message received", np->msgin);
6246                 OUTL_DSP (SCRIPTB_BA (np, msg_weird));
6247                 return;
6248         /*
6249          *  Negotiation failed.
6250          *  Target does not send us the reply.
6251          *  Remove the HS_NEGOTIATE status.
6252          */
6253         case SIR_NEGO_FAILED:
6254                 OUTB (HS_PRT, HS_BUSY);
6255         /*
6256          *  Negotiation failed.
6257          *  Target does not want answer message.
6258          */
6259         case SIR_NEGO_PROTO:
6260                 sym_nego_default(np, tp, cp);
6261                 goto out;
6262         };
6263
6264 out:
6265         OUTONB_STD ();
6266         return;
6267 out_reject:
6268         OUTL_DSP (SCRIPTB_BA (np, msg_bad));
6269         return;
6270 out_clrack:
6271         OUTL_DSP (SCRIPTA_BA (np, clrack));
6272         return;
6273 out_stuck:
6274         return;
6275 }
6276
6277 /*
6278  *  Acquire a control block
6279  */
6280 static  ccb_p sym_get_ccb (hcb_p np, u_char tn, u_char ln, u_char tag_order)
6281 {
6282         tcb_p tp = &np->target[tn];
6283         lcb_p lp = sym_lp(tp, ln);
6284         u_short tag = NO_TAG;
6285         SYM_QUEHEAD *qp;
6286         ccb_p cp = (ccb_p) NULL;
6287
6288         /*
6289          *  Look for a free CCB
6290          */
6291         if (sym_que_empty(&np->free_ccbq))
6292                 goto out;
6293         qp = sym_remque_head(&np->free_ccbq);
6294         if (!qp)
6295                 goto out;
6296         cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
6297
6298         /*
6299          *  If the LCB is not yet available and the LUN
6300          *  has been probed ok, try to allocate the LCB.
6301          */
6302         if (!lp && sym_is_bit(tp->lun_map, ln)) {
6303                 lp = sym_alloc_lcb(np, tn, ln);
6304                 if (!lp)
6305                         goto out_free;
6306         }
6307
6308         /*
6309          *  If the LCB is not available here, then the
6310          *  logical unit is not yet discovered. For those
6311          *  ones only accept 1 SCSI IO per logical unit,
6312          *  since we cannot allow disconnections.
6313          */
6314         if (!lp) {
6315                 if (!sym_is_bit(tp->busy0_map, ln))
6316                         sym_set_bit(tp->busy0_map, ln);
6317                 else
6318                         goto out_free;
6319         } else {
6320                 /*
6321                  *  If we have been asked for a tagged command.
6322                  */
6323                 if (tag_order) {
6324                         /*
6325                          *  Debugging purpose.
6326                          */
6327                         assert(lp->busy_itl == 0);
6328                         /*
6329                          *  Allocate resources for tags if not yet.
6330                          */
6331                         if (!lp->cb_tags) {
6332                                 sym_alloc_lcb_tags(np, tn, ln);
6333                                 if (!lp->cb_tags)
6334                                         goto out_free;
6335                         }
6336                         /*
6337                          *  Get a tag for this SCSI IO and set up
6338                          *  the CCB bus address for reselection,
6339                          *  and count it for this LUN.
6340                          *  Toggle reselect path to tagged.
6341                          */
6342                         if (lp->busy_itlq < SYM_CONF_MAX_TASK) {
6343                                 tag = lp->cb_tags[lp->ia_tag];
6344                                 if (++lp->ia_tag == SYM_CONF_MAX_TASK)
6345                                         lp->ia_tag = 0;
6346                                 lp->itlq_tbl[tag] = cpu_to_scr(cp->ccb_ba);
6347                                 ++lp->busy_itlq;
6348                                 lp->head.resel_sa =
6349                                         cpu_to_scr(SCRIPTA_BA (np, resel_tag));
6350                         }
6351                         else
6352                                 goto out_free;
6353                 }
6354                 /*
6355                  *  This command will not be tagged.
6356                  *  If we already have either a tagged or untagged
6357                  *  one, refuse to overlap this untagged one.
6358                  */
6359                 else {
6360                         /*
6361                          *  Debugging purpose.
6362                          */
6363                         assert(lp->busy_itl == 0 && lp->busy_itlq == 0);
6364                         /*
6365                          *  Count this nexus for this LUN.
6366                          *  Set up the CCB bus address for reselection.
6367                          *  Toggle reselect path to untagged.
6368                          */
6369                         if (++lp->busy_itl == 1) {
6370                                 lp->head.itl_task_sa = cpu_to_scr(cp->ccb_ba);
6371                                 lp->head.resel_sa =
6372                                       cpu_to_scr(SCRIPTA_BA (np, resel_no_tag));
6373                         }
6374                         else
6375                                 goto out_free;
6376                 }
6377         }
6378         /*
6379          *  Put the CCB into the busy queue.
6380          */
6381         sym_insque_tail(&cp->link_ccbq, &np->busy_ccbq);
6382
6383         /*
6384          *  Remember all informations needed to free this CCB.
6385          */
6386         cp->to_abort = 0;
6387         cp->tag    = tag;
6388         cp->target = tn;
6389         cp->lun    = ln;
6390
6391         if (DEBUG_FLAGS & DEBUG_TAGS) {
6392                 PRINT_LUN(np, tn, ln);
6393                 printf ("ccb @%p using tag %d.\n", cp, tag);
6394         }
6395
6396 out:
6397         return cp;
6398 out_free:
6399         sym_insque_head(&cp->link_ccbq, &np->free_ccbq);
6400         return NULL;
6401 }
6402
6403 /*
6404  *  Release one control block
6405  */
6406 static void sym_free_ccb(hcb_p np, ccb_p cp)
6407 {
6408         tcb_p tp = &np->target[cp->target];
6409         lcb_p lp = sym_lp(tp, cp->lun);
6410
6411         if (DEBUG_FLAGS & DEBUG_TAGS) {
6412                 PRINT_LUN(np, cp->target, cp->lun);
6413                 printf ("ccb @%p freeing tag %d.\n", cp, cp->tag);
6414         }
6415
6416         /*
6417          *  If LCB available,
6418          */
6419         if (lp) {
6420                 /*
6421                  *  If tagged, release the tag, set the relect path
6422                  */
6423                 if (cp->tag != NO_TAG) {
6424                         /*
6425                          *  Free the tag value.
6426                          */
6427                         lp->cb_tags[lp->if_tag] = cp->tag;
6428                         if (++lp->if_tag == SYM_CONF_MAX_TASK)
6429                                 lp->if_tag = 0;
6430                         /*
6431                          *  Make the reselect path invalid,
6432                          *  and uncount this CCB.
6433                          */
6434                         lp->itlq_tbl[cp->tag] = cpu_to_scr(np->bad_itlq_ba);
6435                         --lp->busy_itlq;
6436                 } else {        /* Untagged */
6437                         /*
6438                          *  Make the reselect path invalid,
6439                          *  and uncount this CCB.
6440                          */
6441                         lp->head.itl_task_sa = cpu_to_scr(np->bad_itl_ba);
6442                         --lp->busy_itl;
6443                 }
6444                 /*
6445                  *  If no JOB active, make the LUN reselect path invalid.
6446                  */
6447                 if (lp->busy_itlq == 0 && lp->busy_itl == 0)
6448                         lp->head.resel_sa =
6449                                 cpu_to_scr(SCRIPTB_BA (np, resel_bad_lun));
6450         }
6451         /*
6452          *  Otherwise, we only accept 1 IO per LUN.
6453          *  Clear the bit that keeps track of this IO.
6454          */
6455         else
6456                 sym_clr_bit(tp->busy0_map, cp->lun);
6457
6458         /*
6459          *  We donnot queue more than 1 ccb per target
6460          *  with negotiation at any time. If this ccb was
6461          *  used for negotiation, clear this info in the tcb.
6462          */
6463         if (cp == tp->nego_cp)
6464                 tp->nego_cp = NULL;
6465
6466 #ifdef SYM_CONF_IARB_SUPPORT
6467         /*
6468          *  If we just complete the last queued CCB,
6469          *  clear this info that is no longer relevant.
6470          */
6471         if (cp == np->last_cp)
6472                 np->last_cp = NULL;
6473 #endif
6474
6475         /*
6476          *  Unmap user data from DMA map if needed.
6477          */
6478         if (cp->dmamapped) {
6479                 bus_dmamap_unload(np->data_dmat, cp->dmamap);
6480                 cp->dmamapped = 0;
6481         }
6482
6483         /*
6484          *  Make this CCB available.
6485          */
6486         cp->cam_ccb = NULL;
6487         cp->host_status = HS_IDLE;
6488         sym_remque(&cp->link_ccbq);
6489         sym_insque_head(&cp->link_ccbq, &np->free_ccbq);
6490 }
6491
6492 /*
6493  *  Allocate a CCB from memory and initialize its fixed part.
6494  */
6495 static ccb_p sym_alloc_ccb(hcb_p np)
6496 {
6497         ccb_p cp = NULL;
6498         int hcode;
6499
6500         SYM_LOCK_ASSERT(MA_NOTOWNED);
6501
6502         /*
6503          *  Prevent from allocating more CCBs than we can
6504          *  queue to the controller.
6505          */
6506         if (np->actccbs >= SYM_CONF_MAX_START)
6507                 return NULL;
6508
6509         /*
6510          *  Allocate memory for this CCB.
6511          */
6512         cp = sym_calloc_dma(sizeof(struct sym_ccb), "CCB");
6513         if (!cp)
6514                 return NULL;
6515
6516         /*
6517          *  Allocate a bounce buffer for sense data.
6518          */
6519         cp->sns_bbuf = sym_calloc_dma(SYM_SNS_BBUF_LEN, "SNS_BBUF");
6520         if (!cp->sns_bbuf)
6521                 goto out_free;
6522
6523         /*
6524          *  Allocate a map for the DMA of user data.
6525          */
6526         if (bus_dmamap_create(np->data_dmat, 0, &cp->dmamap))
6527                 goto out_free;
6528         /*
6529          *  Count it.
6530          */
6531         np->actccbs++;
6532
6533         /*
6534          * Initialize the callout.
6535          */
6536         callout_init(&cp->ch, 1);
6537
6538         /*
6539          *  Compute the bus address of this ccb.
6540          */
6541         cp->ccb_ba = vtobus(cp);
6542
6543         /*
6544          *  Insert this ccb into the hashed list.
6545          */
6546         hcode = CCB_HASH_CODE(cp->ccb_ba);
6547         cp->link_ccbh = np->ccbh[hcode];
6548         np->ccbh[hcode] = cp;
6549
6550         /*
6551          *  Initialize the start and restart actions.
6552          */
6553         cp->phys.head.go.start   = cpu_to_scr(SCRIPTA_BA (np, idle));
6554         cp->phys.head.go.restart = cpu_to_scr(SCRIPTB_BA (np, bad_i_t_l));
6555
6556         /*
6557          *  Initilialyze some other fields.
6558          */
6559         cp->phys.smsg_ext.addr = cpu_to_scr(HCB_BA(np, msgin[2]));
6560
6561         /*
6562          *  Chain into free ccb queue.
6563          */
6564         sym_insque_head(&cp->link_ccbq, &np->free_ccbq);
6565
6566         return cp;
6567 out_free:
6568         if (cp->sns_bbuf)
6569                 sym_mfree_dma(cp->sns_bbuf, SYM_SNS_BBUF_LEN, "SNS_BBUF");
6570         sym_mfree_dma(cp, sizeof(*cp), "CCB");
6571         return NULL;
6572 }
6573
6574 /*
6575  *  Look up a CCB from a DSA value.
6576  */
6577 static ccb_p sym_ccb_from_dsa(hcb_p np, u32 dsa)
6578 {
6579         int hcode;
6580         ccb_p cp;
6581
6582         hcode = CCB_HASH_CODE(dsa);
6583         cp = np->ccbh[hcode];
6584         while (cp) {
6585                 if (cp->ccb_ba == dsa)
6586                         break;
6587                 cp = cp->link_ccbh;
6588         }
6589
6590         return cp;
6591 }
6592
6593 /*
6594  *  Lun control block allocation and initialization.
6595  */
6596 static lcb_p sym_alloc_lcb (hcb_p np, u_char tn, u_char ln)
6597 {
6598         tcb_p tp = &np->target[tn];
6599         lcb_p lp = sym_lp(tp, ln);
6600
6601         /*
6602          *  Already done, just return.
6603          */
6604         if (lp)
6605                 return lp;
6606         /*
6607          *  Check against some race.
6608          */
6609         assert(!sym_is_bit(tp->busy0_map, ln));
6610
6611         /*
6612          *  Allocate the LCB bus address array.
6613          *  Compute the bus address of this table.
6614          */
6615         if (ln && !tp->luntbl) {
6616                 int i;
6617
6618                 tp->luntbl = sym_calloc_dma(256, "LUNTBL");
6619                 if (!tp->luntbl)
6620                         goto fail;
6621                 for (i = 0 ; i < 64 ; i++)
6622                         tp->luntbl[i] = cpu_to_scr(vtobus(&np->badlun_sa));
6623                 tp->head.luntbl_sa = cpu_to_scr(vtobus(tp->luntbl));
6624         }
6625
6626         /*
6627          *  Allocate the table of pointers for LUN(s) > 0, if needed.
6628          */
6629         if (ln && !tp->lunmp) {
6630                 tp->lunmp = sym_calloc(SYM_CONF_MAX_LUN * sizeof(lcb_p),
6631                                    "LUNMP");
6632                 if (!tp->lunmp)
6633                         goto fail;
6634         }
6635
6636         /*
6637          *  Allocate the lcb.
6638          *  Make it available to the chip.
6639          */
6640         lp = sym_calloc_dma(sizeof(struct sym_lcb), "LCB");
6641         if (!lp)
6642                 goto fail;
6643         if (ln) {
6644                 tp->lunmp[ln] = lp;
6645                 tp->luntbl[ln] = cpu_to_scr(vtobus(lp));
6646         }
6647         else {
6648                 tp->lun0p = lp;
6649                 tp->head.lun0_sa = cpu_to_scr(vtobus(lp));
6650         }
6651
6652         /*
6653          *  Let the itl task point to error handling.
6654          */
6655         lp->head.itl_task_sa = cpu_to_scr(np->bad_itl_ba);
6656
6657         /*
6658          *  Set the reselect pattern to our default. :)
6659          */
6660         lp->head.resel_sa = cpu_to_scr(SCRIPTB_BA (np, resel_bad_lun));
6661
6662         /*
6663          *  Set user capabilities.
6664          */
6665         lp->user_flags = tp->usrflags & (SYM_DISC_ENABLED | SYM_TAGS_ENABLED);
6666
6667 fail:
6668         return lp;
6669 }
6670
6671 /*
6672  *  Allocate LCB resources for tagged command queuing.
6673  */
6674 static void sym_alloc_lcb_tags (hcb_p np, u_char tn, u_char ln)
6675 {
6676         tcb_p tp = &np->target[tn];
6677         lcb_p lp = sym_lp(tp, ln);
6678         int i;
6679
6680         /*
6681          *  If LCB not available, try to allocate it.
6682          */
6683         if (!lp && !(lp = sym_alloc_lcb(np, tn, ln)))
6684                 return;
6685
6686         /*
6687          *  Allocate the task table and and the tag allocation
6688          *  circular buffer. We want both or none.
6689          */
6690         lp->itlq_tbl = sym_calloc_dma(SYM_CONF_MAX_TASK*4, "ITLQ_TBL");
6691         if (!lp->itlq_tbl)
6692                 return;
6693         lp->cb_tags = sym_calloc(SYM_CONF_MAX_TASK, "CB_TAGS");
6694         if (!lp->cb_tags) {
6695                 sym_mfree_dma(lp->itlq_tbl, SYM_CONF_MAX_TASK*4, "ITLQ_TBL");
6696                 lp->itlq_tbl = 0;
6697                 return;
6698         }
6699
6700         /*
6701          *  Initialize the task table with invalid entries.
6702          */
6703         for (i = 0 ; i < SYM_CONF_MAX_TASK ; i++)
6704                 lp->itlq_tbl[i] = cpu_to_scr(np->notask_ba);
6705
6706         /*
6707          *  Fill up the tag buffer with tag numbers.
6708          */
6709         for (i = 0 ; i < SYM_CONF_MAX_TASK ; i++)
6710                 lp->cb_tags[i] = i;
6711
6712         /*
6713          *  Make the task table available to SCRIPTS,
6714          *  And accept tagged commands now.
6715          */
6716         lp->head.itlq_tbl_sa = cpu_to_scr(vtobus(lp->itlq_tbl));
6717 }
6718
6719 /*
6720  *  Test the pci bus snoop logic :-(
6721  *
6722  *  Has to be called with interrupts disabled.
6723  */
6724 #ifndef SYM_CONF_IOMAPPED
6725 static int sym_regtest (hcb_p np)
6726 {
6727         register volatile u32 data;
6728         /*
6729          *  chip registers may NOT be cached.
6730          *  write 0xffffffff to a read only register area,
6731          *  and try to read it back.
6732          */
6733         data = 0xffffffff;
6734         OUTL_OFF(offsetof(struct sym_reg, nc_dstat), data);
6735         data = INL_OFF(offsetof(struct sym_reg, nc_dstat));
6736 #if 1
6737         if (data == 0xffffffff) {
6738 #else
6739         if ((data & 0xe2f0fffd) != 0x02000080) {
6740 #endif
6741                 printf ("CACHE TEST FAILED: reg dstat-sstat2 readback %x.\n",
6742                         (unsigned) data);
6743                 return (0x10);
6744         };
6745         return (0);
6746 }
6747 #endif
6748
6749 static int sym_snooptest (hcb_p np)
6750 {
6751         u32     sym_rd, sym_wr, sym_bk, host_rd, host_wr, pc, dstat;
6752         int     i, err=0;
6753 #ifndef SYM_CONF_IOMAPPED
6754         err |= sym_regtest (np);
6755         if (err) return (err);
6756 #endif
6757 restart_test:
6758         /*
6759          *  Enable Master Parity Checking as we intend
6760          *  to enable it for normal operations.
6761          */
6762         OUTB (nc_ctest4, (np->rv_ctest4 & MPEE));
6763         /*
6764          *  init
6765          */
6766         pc  = SCRIPTB0_BA (np, snooptest);
6767         host_wr = 1;
6768         sym_wr  = 2;
6769         /*
6770          *  Set memory and register.
6771          */
6772         np->cache = cpu_to_scr(host_wr);
6773         OUTL (nc_temp, sym_wr);
6774         /*
6775          *  Start script (exchange values)
6776          */
6777         OUTL (nc_dsa, np->hcb_ba);
6778         OUTL_DSP (pc);
6779         /*
6780          *  Wait 'til done (with timeout)
6781          */
6782         for (i=0; i<SYM_SNOOP_TIMEOUT; i++)
6783                 if (INB(nc_istat) & (INTF|SIP|DIP))
6784                         break;
6785         if (i>=SYM_SNOOP_TIMEOUT) {
6786                 printf ("CACHE TEST FAILED: timeout.\n");
6787                 return (0x20);
6788         };
6789         /*
6790          *  Check for fatal DMA errors.
6791          */
6792         dstat = INB (nc_dstat);
6793 #if 1   /* Band aiding for broken hardwares that fail PCI parity */
6794         if ((dstat & MDPE) && (np->rv_ctest4 & MPEE)) {
6795                 printf ("%s: PCI DATA PARITY ERROR DETECTED - "
6796                         "DISABLING MASTER DATA PARITY CHECKING.\n",
6797                         sym_name(np));
6798                 np->rv_ctest4 &= ~MPEE;
6799                 goto restart_test;
6800         }
6801 #endif
6802         if (dstat & (MDPE|BF|IID)) {
6803                 printf ("CACHE TEST FAILED: DMA error (dstat=0x%02x).", dstat);
6804                 return (0x80);
6805         }
6806         /*
6807          *  Save termination position.
6808          */
6809         pc = INL (nc_dsp);
6810         /*
6811          *  Read memory and register.
6812          */
6813         host_rd = scr_to_cpu(np->cache);
6814         sym_rd  = INL (nc_scratcha);
6815         sym_bk  = INL (nc_temp);
6816
6817         /*
6818          *  Check termination position.
6819          */
6820         if (pc != SCRIPTB0_BA (np, snoopend)+8) {
6821                 printf ("CACHE TEST FAILED: script execution failed.\n");
6822                 printf ("start=%08lx, pc=%08lx, end=%08lx\n",
6823                         (u_long) SCRIPTB0_BA (np, snooptest), (u_long) pc,
6824                         (u_long) SCRIPTB0_BA (np, snoopend) +8);
6825                 return (0x40);
6826         };
6827         /*
6828          *  Show results.
6829          */
6830         if (host_wr != sym_rd) {
6831                 printf ("CACHE TEST FAILED: host wrote %d, chip read %d.\n",
6832                         (int) host_wr, (int) sym_rd);
6833                 err |= 1;
6834         };
6835         if (host_rd != sym_wr) {
6836                 printf ("CACHE TEST FAILED: chip wrote %d, host read %d.\n",
6837                         (int) sym_wr, (int) host_rd);
6838                 err |= 2;
6839         };
6840         if (sym_bk != sym_wr) {
6841                 printf ("CACHE TEST FAILED: chip wrote %d, read back %d.\n",
6842                         (int) sym_wr, (int) sym_bk);
6843                 err |= 4;
6844         };
6845
6846         return (err);
6847 }
6848
6849 /*
6850  *  Determine the chip's clock frequency.
6851  *
6852  *  This is essential for the negotiation of the synchronous
6853  *  transfer rate.
6854  *
6855  *  Note: we have to return the correct value.
6856  *  THERE IS NO SAFE DEFAULT VALUE.
6857  *
6858  *  Most NCR/SYMBIOS boards are delivered with a 40 Mhz clock.
6859  *  53C860 and 53C875 rev. 1 support fast20 transfers but
6860  *  do not have a clock doubler and so are provided with a
6861  *  80 MHz clock. All other fast20 boards incorporate a doubler
6862  *  and so should be delivered with a 40 MHz clock.
6863  *  The recent fast40 chips (895/896/895A/1010) use a 40 Mhz base
6864  *  clock and provide a clock quadrupler (160 Mhz).
6865  */
6866
6867 /*
6868  *  Select SCSI clock frequency
6869  */
6870 static void sym_selectclock(hcb_p np, u_char scntl3)
6871 {
6872         /*
6873          *  If multiplier not present or not selected, leave here.
6874          */
6875         if (np->multiplier <= 1) {
6876                 OUTB(nc_scntl3, scntl3);
6877                 return;
6878         }
6879
6880         if (sym_verbose >= 2)
6881                 printf ("%s: enabling clock multiplier\n", sym_name(np));
6882
6883         OUTB(nc_stest1, DBLEN);    /* Enable clock multiplier             */
6884         /*
6885          *  Wait for the LCKFRQ bit to be set if supported by the chip.
6886          *  Otherwise wait 20 micro-seconds.
6887          */
6888         if (np->features & FE_LCKFRQ) {
6889                 int i = 20;
6890                 while (!(INB(nc_stest4) & LCKFRQ) && --i > 0)
6891                         UDELAY (20);
6892                 if (!i)
6893                         printf("%s: the chip cannot lock the frequency\n",
6894                                 sym_name(np));
6895         } else
6896                 UDELAY (20);
6897         OUTB(nc_stest3, HSC);           /* Halt the scsi clock          */
6898         OUTB(nc_scntl3, scntl3);
6899         OUTB(nc_stest1, (DBLEN|DBLSEL));/* Select clock multiplier      */
6900         OUTB(nc_stest3, 0x00);          /* Restart scsi clock           */
6901 }
6902
6903 /*
6904  *  calculate SCSI clock frequency (in KHz)
6905  */
6906 static unsigned getfreq (hcb_p np, int gen)
6907 {
6908         unsigned int ms = 0;
6909         unsigned int f;
6910
6911         /*
6912          * Measure GEN timer delay in order
6913          * to calculate SCSI clock frequency
6914          *
6915          * This code will never execute too
6916          * many loop iterations (if DELAY is
6917          * reasonably correct). It could get
6918          * too low a delay (too high a freq.)
6919          * if the CPU is slow executing the
6920          * loop for some reason (an NMI, for
6921          * example). For this reason we will
6922          * if multiple measurements are to be
6923          * performed trust the higher delay
6924          * (lower frequency returned).
6925          */
6926         OUTW (nc_sien , 0);     /* mask all scsi interrupts */
6927         (void) INW (nc_sist);   /* clear pending scsi interrupt */
6928         OUTB (nc_dien , 0);     /* mask all dma interrupts */
6929         (void) INW (nc_sist);   /* another one, just to be sure :) */
6930         OUTB (nc_scntl3, 4);    /* set pre-scaler to divide by 3 */
6931         OUTB (nc_stime1, 0);    /* disable general purpose timer */
6932         OUTB (nc_stime1, gen);  /* set to nominal delay of 1<<gen * 125us */
6933         while (!(INW(nc_sist) & GEN) && ms++ < 100000)
6934                 UDELAY (1000);  /* count ms */
6935         OUTB (nc_stime1, 0);    /* disable general purpose timer */
6936         /*
6937          * set prescaler to divide by whatever 0 means
6938          * 0 ought to choose divide by 2, but appears
6939          * to set divide by 3.5 mode in my 53c810 ...
6940          */
6941         OUTB (nc_scntl3, 0);
6942
6943         /*
6944          * adjust for prescaler, and convert into KHz
6945          */
6946         f = ms ? ((1 << gen) * 4340) / ms : 0;
6947
6948         if (sym_verbose >= 2)
6949                 printf ("%s: Delay (GEN=%d): %u msec, %u KHz\n",
6950                         sym_name(np), gen, ms, f);
6951
6952         return f;
6953 }
6954
6955 static unsigned sym_getfreq (hcb_p np)
6956 {
6957         u_int f1, f2;
6958         int gen = 11;
6959
6960         (void) getfreq (np, gen);       /* throw away first result */
6961         f1 = getfreq (np, gen);
6962         f2 = getfreq (np, gen);
6963         if (f1 > f2) f1 = f2;           /* trust lower result   */
6964         return f1;
6965 }
6966
6967 /*
6968  *  Get/probe chip SCSI clock frequency
6969  */
6970 static void sym_getclock (hcb_p np, int mult)
6971 {
6972         unsigned char scntl3 = np->sv_scntl3;
6973         unsigned char stest1 = np->sv_stest1;
6974         unsigned f1;
6975
6976         /*
6977          *  For the C10 core, assume 40 MHz.
6978          */
6979         if (np->features & FE_C10) {
6980                 np->multiplier = mult;
6981                 np->clock_khz = 40000 * mult;
6982                 return;
6983         }
6984
6985         np->multiplier = 1;
6986         f1 = 40000;
6987         /*
6988          *  True with 875/895/896/895A with clock multiplier selected
6989          */
6990         if (mult > 1 && (stest1 & (DBLEN+DBLSEL)) == DBLEN+DBLSEL) {
6991                 if (sym_verbose >= 2)
6992                         printf ("%s: clock multiplier found\n", sym_name(np));
6993                 np->multiplier = mult;
6994         }
6995
6996         /*
6997          *  If multiplier not found or scntl3 not 7,5,3,
6998          *  reset chip and get frequency from general purpose timer.
6999          *  Otherwise trust scntl3 BIOS setting.
7000          */
7001         if (np->multiplier != mult || (scntl3 & 7) < 3 || !(scntl3 & 1)) {
7002                 OUTB (nc_stest1, 0);            /* make sure doubler is OFF */
7003                 f1 = sym_getfreq (np);
7004
7005                 if (sym_verbose)
7006                         printf ("%s: chip clock is %uKHz\n", sym_name(np), f1);
7007
7008                 if      (f1 <   45000)          f1 =  40000;
7009                 else if (f1 <   55000)          f1 =  50000;
7010                 else                            f1 =  80000;
7011
7012                 if (f1 < 80000 && mult > 1) {
7013                         if (sym_verbose >= 2)
7014                                 printf ("%s: clock multiplier assumed\n",
7015                                         sym_name(np));
7016                         np->multiplier  = mult;
7017                 }
7018         } else {
7019                 if      ((scntl3 & 7) == 3)     f1 =  40000;
7020                 else if ((scntl3 & 7) == 5)     f1 =  80000;
7021                 else                            f1 = 160000;
7022
7023                 f1 /= np->multiplier;
7024         }
7025
7026         /*
7027          *  Compute controller synchronous parameters.
7028          */
7029         f1              *= np->multiplier;
7030         np->clock_khz   = f1;
7031 }
7032
7033 /*
7034  *  Get/probe PCI clock frequency
7035  */
7036 static int sym_getpciclock (hcb_p np)
7037 {
7038         int f = 0;
7039
7040         /*
7041          *  For the C1010-33, this doesn't work.
7042          *  For the C1010-66, this will be tested when I'll have
7043          *  such a beast to play with.
7044          */
7045         if (!(np->features & FE_C10)) {
7046                 OUTB (nc_stest1, SCLK); /* Use the PCI clock as SCSI clock */
7047                 f = (int) sym_getfreq (np);
7048                 OUTB (nc_stest1, 0);
7049         }
7050         np->pciclk_khz = f;
7051
7052         return f;
7053 }
7054
7055 /*============= DRIVER ACTION/COMPLETION ====================*/
7056
7057 /*
7058  *  Print something that tells about extended errors.
7059  */
7060 static void sym_print_xerr(ccb_p cp, int x_status)
7061 {
7062         if (x_status & XE_PARITY_ERR) {
7063                 PRINT_ADDR(cp);
7064                 printf ("unrecovered SCSI parity error.\n");
7065         }
7066         if (x_status & XE_EXTRA_DATA) {
7067                 PRINT_ADDR(cp);
7068                 printf ("extraneous data discarded.\n");
7069         }
7070         if (x_status & XE_BAD_PHASE) {
7071                 PRINT_ADDR(cp);
7072                 printf ("illegal scsi phase (4/5).\n");
7073         }
7074         if (x_status & XE_SODL_UNRUN) {
7075                 PRINT_ADDR(cp);
7076                 printf ("ODD transfer in DATA OUT phase.\n");
7077         }
7078         if (x_status & XE_SWIDE_OVRUN) {
7079                 PRINT_ADDR(cp);
7080                 printf ("ODD transfer in DATA IN phase.\n");
7081         }
7082 }
7083
7084 /*
7085  *  Choose the more appropriate CAM status if
7086  *  the IO encountered an extended error.
7087  */
7088 static int sym_xerr_cam_status(int cam_status, int x_status)
7089 {
7090         if (x_status) {
7091                 if      (x_status & XE_PARITY_ERR)
7092                         cam_status = CAM_UNCOR_PARITY;
7093                 else if (x_status &(XE_EXTRA_DATA|XE_SODL_UNRUN|XE_SWIDE_OVRUN))
7094                         cam_status = CAM_DATA_RUN_ERR;
7095                 else if (x_status & XE_BAD_PHASE)
7096                         cam_status = CAM_REQ_CMP_ERR;
7097                 else
7098                         cam_status = CAM_REQ_CMP_ERR;
7099         }
7100         return cam_status;
7101 }
7102
7103 /*
7104  *  Complete execution of a SCSI command with extented
7105  *  error, SCSI status error, or having been auto-sensed.
7106  *
7107  *  The SCRIPTS processor is not running there, so we
7108  *  can safely access IO registers and remove JOBs from
7109  *  the START queue.
7110  *  SCRATCHA is assumed to have been loaded with STARTPOS
7111  *  before the SCRIPTS called the C code.
7112  */
7113 static void sym_complete_error (hcb_p np, ccb_p cp)
7114 {
7115         struct ccb_scsiio *csio;
7116         u_int cam_status;
7117         int i, sense_returned;
7118
7119         SYM_LOCK_ASSERT(MA_OWNED);
7120
7121         /*
7122          *  Paranoid check. :)
7123          */
7124         if (!cp || !cp->cam_ccb)
7125                 return;
7126
7127         if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_RESULT)) {
7128                 printf ("CCB=%lx STAT=%x/%x/%x DEV=%d/%d\n", (unsigned long)cp,
7129                         cp->host_status, cp->ssss_status, cp->host_flags,
7130                         cp->target, cp->lun);
7131                 MDELAY(100);
7132         }
7133
7134         /*
7135          *  Get CAM command pointer.
7136          */
7137         csio = &cp->cam_ccb->csio;
7138
7139         /*
7140          *  Check for extended errors.
7141          */
7142         if (cp->xerr_status) {
7143                 if (sym_verbose)
7144                         sym_print_xerr(cp, cp->xerr_status);
7145                 if (cp->host_status == HS_COMPLETE)
7146                         cp->host_status = HS_COMP_ERR;
7147         }
7148
7149         /*
7150          *  Calculate the residual.
7151          */
7152         csio->sense_resid = 0;
7153         csio->resid = sym_compute_residual(np, cp);
7154
7155         if (!SYM_CONF_RESIDUAL_SUPPORT) {/* If user does not want residuals */
7156                 csio->resid  = 0;       /* throw them away. :)             */
7157                 cp->sv_resid = 0;
7158         }
7159
7160         if (cp->host_flags & HF_SENSE) {                /* Auto sense     */
7161                 csio->scsi_status = cp->sv_scsi_status; /* Restore status */
7162                 csio->sense_resid = csio->resid;        /* Swap residuals */
7163                 csio->resid       = cp->sv_resid;
7164                 cp->sv_resid      = 0;
7165                 if (sym_verbose && cp->sv_xerr_status)
7166                         sym_print_xerr(cp, cp->sv_xerr_status);
7167                 if (cp->host_status == HS_COMPLETE &&
7168                     cp->ssss_status == S_GOOD &&
7169                     cp->xerr_status == 0) {
7170                         cam_status = sym_xerr_cam_status(CAM_SCSI_STATUS_ERROR,
7171                                                          cp->sv_xerr_status);
7172                         cam_status |= CAM_AUTOSNS_VALID;
7173                         /*
7174                          *  Bounce back the sense data to user and
7175                          *  fix the residual.
7176                          */
7177                         bzero(&csio->sense_data, sizeof(csio->sense_data));
7178                         sense_returned = SYM_SNS_BBUF_LEN - csio->sense_resid;
7179                         if (sense_returned < csio->sense_len)
7180                                 csio->sense_resid = csio->sense_len -
7181                                     sense_returned;
7182                         else
7183                                 csio->sense_resid = 0;
7184                         bcopy(cp->sns_bbuf, &csio->sense_data,
7185                             MIN(csio->sense_len, sense_returned));
7186 #if 0
7187                         /*
7188                          *  If the device reports a UNIT ATTENTION condition
7189                          *  due to a RESET condition, we should consider all
7190                          *  disconnect CCBs for this unit as aborted.
7191                          */
7192                         if (1) {
7193                                 u_char *p;
7194                                 p  = (u_char *) csio->sense_data;
7195                                 if (p[0]==0x70 && p[2]==0x6 && p[12]==0x29)
7196                                         sym_clear_tasks(np, CAM_REQ_ABORTED,
7197                                                         cp->target,cp->lun, -1);
7198                         }
7199 #endif
7200                 }
7201                 else
7202                         cam_status = CAM_AUTOSENSE_FAIL;
7203         }
7204         else if (cp->host_status == HS_COMPLETE) {      /* Bad SCSI status */
7205                 csio->scsi_status = cp->ssss_status;
7206                 cam_status = CAM_SCSI_STATUS_ERROR;
7207         }
7208         else if (cp->host_status == HS_SEL_TIMEOUT)     /* Selection timeout */
7209                 cam_status = CAM_SEL_TIMEOUT;
7210         else if (cp->host_status == HS_UNEXPECTED)      /* Unexpected BUS FREE*/
7211                 cam_status = CAM_UNEXP_BUSFREE;
7212         else {                                          /* Extended error */
7213                 if (sym_verbose) {
7214                         PRINT_ADDR(cp);
7215                         printf ("COMMAND FAILED (%x %x %x).\n",
7216                                 cp->host_status, cp->ssss_status,
7217                                 cp->xerr_status);
7218                 }
7219                 csio->scsi_status = cp->ssss_status;
7220                 /*
7221                  *  Set the most appropriate value for CAM status.
7222                  */
7223                 cam_status = sym_xerr_cam_status(CAM_REQ_CMP_ERR,
7224                                                  cp->xerr_status);
7225         }
7226
7227         /*
7228          *  Dequeue all queued CCBs for that device
7229          *  not yet started by SCRIPTS.
7230          */
7231         i = (INL (nc_scratcha) - np->squeue_ba) / 4;
7232         (void) sym_dequeue_from_squeue(np, i, cp->target, cp->lun, -1);
7233
7234         /*
7235          *  Restart the SCRIPTS processor.
7236          */
7237         OUTL_DSP (SCRIPTA_BA (np, start));
7238
7239         /*
7240          *  Synchronize DMA map if needed.
7241          */
7242         if (cp->dmamapped) {
7243                 bus_dmamap_sync(np->data_dmat, cp->dmamap,
7244                         (cp->dmamapped == SYM_DMA_READ ?
7245                                 BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE));
7246         }
7247         /*
7248          *  Add this one to the COMP queue.
7249          *  Complete all those commands with either error
7250          *  or requeue condition.
7251          */
7252         sym_set_cam_status((union ccb *) csio, cam_status);
7253         sym_remque(&cp->link_ccbq);
7254         sym_insque_head(&cp->link_ccbq, &np->comp_ccbq);
7255         sym_flush_comp_queue(np, 0);
7256 }
7257
7258 /*
7259  *  Complete execution of a successful SCSI command.
7260  *
7261  *  Only successful commands go to the DONE queue,
7262  *  since we need to have the SCRIPTS processor
7263  *  stopped on any error condition.
7264  *  The SCRIPTS processor is running while we are
7265  *  completing successful commands.
7266  */
7267 static void sym_complete_ok (hcb_p np, ccb_p cp)
7268 {
7269         struct ccb_scsiio *csio;
7270         tcb_p tp;
7271         lcb_p lp;
7272
7273         SYM_LOCK_ASSERT(MA_OWNED);
7274
7275         /*
7276          *  Paranoid check. :)
7277          */
7278         if (!cp || !cp->cam_ccb)
7279                 return;
7280         assert (cp->host_status == HS_COMPLETE);
7281
7282         /*
7283          *  Get command, target and lun pointers.
7284          */
7285         csio = &cp->cam_ccb->csio;
7286         tp = &np->target[cp->target];
7287         lp = sym_lp(tp, cp->lun);
7288
7289         /*
7290          *  Assume device discovered on first success.
7291          */
7292         if (!lp)
7293                 sym_set_bit(tp->lun_map, cp->lun);
7294
7295         /*
7296          *  If all data have been transferred, given than no
7297          *  extended error did occur, there is no residual.
7298          */
7299         csio->resid = 0;
7300         if (cp->phys.head.lastp != cp->phys.head.goalp)
7301                 csio->resid = sym_compute_residual(np, cp);
7302
7303         /*
7304          *  Wrong transfer residuals may be worse than just always
7305          *  returning zero. User can disable this feature from
7306          *  sym_conf.h. Residual support is enabled by default.
7307          */
7308         if (!SYM_CONF_RESIDUAL_SUPPORT)
7309                 csio->resid  = 0;
7310
7311         /*
7312          *  Synchronize DMA map if needed.
7313          */
7314         if (cp->dmamapped) {
7315                 bus_dmamap_sync(np->data_dmat, cp->dmamap,
7316                         (cp->dmamapped == SYM_DMA_READ ?
7317                                 BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE));
7318         }
7319         /*
7320          *  Set status and complete the command.
7321          */
7322         csio->scsi_status = cp->ssss_status;
7323         sym_set_cam_status((union ccb *) csio, CAM_REQ_CMP);
7324         sym_xpt_done(np, (union ccb *) csio, cp);
7325         sym_free_ccb(np, cp);
7326 }
7327
7328 /*
7329  *  Our callout handler
7330  */
7331 static void sym_callout(void *arg)
7332 {
7333         union ccb *ccb = (union ccb *) arg;
7334         hcb_p np = ccb->ccb_h.sym_hcb_ptr;
7335
7336         /*
7337          *  Check that the CAM CCB is still queued.
7338          */
7339         if (!np)
7340                 return;
7341
7342         SYM_LOCK();
7343
7344         switch(ccb->ccb_h.func_code) {
7345         case XPT_SCSI_IO:
7346                 (void) sym_abort_scsiio(np, ccb, 1);
7347                 break;
7348         default:
7349                 break;
7350         }
7351
7352         SYM_UNLOCK();
7353 }
7354
7355 /*
7356  *  Abort an SCSI IO.
7357  */
7358 static int sym_abort_scsiio(hcb_p np, union ccb *ccb, int timed_out)
7359 {
7360         ccb_p cp;
7361         SYM_QUEHEAD *qp;
7362
7363         SYM_LOCK_ASSERT(MA_OWNED);
7364
7365         /*
7366          *  Look up our CCB control block.
7367          */
7368         cp = NULL;
7369         FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
7370                 ccb_p cp2 = sym_que_entry(qp, struct sym_ccb, link_ccbq);
7371                 if (cp2->cam_ccb == ccb) {
7372                         cp = cp2;
7373                         break;
7374                 }
7375         }
7376         if (!cp || cp->host_status == HS_WAIT)
7377                 return -1;
7378
7379         /*
7380          *  If a previous abort didn't succeed in time,
7381          *  perform a BUS reset.
7382          */
7383         if (cp->to_abort) {
7384                 sym_reset_scsi_bus(np, 1);
7385                 return 0;
7386         }
7387
7388         /*
7389          *  Mark the CCB for abort and allow time for.
7390          */
7391         cp->to_abort = timed_out ? 2 : 1;
7392         callout_reset(&cp->ch, 10 * hz, sym_callout, (caddr_t) ccb);
7393
7394         /*
7395          *  Tell the SCRIPTS processor to stop and synchronize with us.
7396          */
7397         np->istat_sem = SEM;
7398         OUTB (nc_istat, SIGP|SEM);
7399         return 0;
7400 }
7401
7402 /*
7403  *  Reset a SCSI device (all LUNs of a target).
7404  */
7405 static void sym_reset_dev(hcb_p np, union ccb *ccb)
7406 {
7407         tcb_p tp;
7408         struct ccb_hdr *ccb_h = &ccb->ccb_h;
7409
7410         SYM_LOCK_ASSERT(MA_OWNED);
7411
7412         if (ccb_h->target_id   == np->myaddr ||
7413             ccb_h->target_id   >= SYM_CONF_MAX_TARGET ||
7414             ccb_h->target_lun  >= SYM_CONF_MAX_LUN) {
7415                 sym_xpt_done2(np, ccb, CAM_DEV_NOT_THERE);
7416                 return;
7417         }
7418
7419         tp = &np->target[ccb_h->target_id];
7420
7421         tp->to_reset = 1;
7422         sym_xpt_done2(np, ccb, CAM_REQ_CMP);
7423
7424         np->istat_sem = SEM;
7425         OUTB (nc_istat, SIGP|SEM);
7426 }
7427
7428 /*
7429  *  SIM action entry point.
7430  */
7431 static void sym_action(struct cam_sim *sim, union ccb *ccb)
7432 {
7433         hcb_p   np;
7434         tcb_p   tp;
7435         lcb_p   lp;
7436         ccb_p   cp;
7437         int     tmp;
7438         u_char  idmsg, *msgptr;
7439         u_int   msglen;
7440         struct  ccb_scsiio *csio;
7441         struct  ccb_hdr  *ccb_h;
7442
7443         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("sym_action\n"));
7444
7445         /*
7446          *  Retrieve our controller data structure.
7447          */
7448         np = (hcb_p) cam_sim_softc(sim);
7449
7450         SYM_LOCK_ASSERT(MA_OWNED);
7451
7452         /*
7453          *  The common case is SCSI IO.
7454          *  We deal with other ones elsewhere.
7455          */
7456         if (ccb->ccb_h.func_code != XPT_SCSI_IO) {
7457                 sym_action2(sim, ccb);
7458                 return;
7459         }
7460         csio  = &ccb->csio;
7461         ccb_h = &csio->ccb_h;
7462
7463         /*
7464          *  Work around races.
7465          */
7466         if ((ccb_h->status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
7467                 xpt_done(ccb);
7468                 return;
7469         }
7470
7471         /*
7472          *  Minimal checkings, so that we will not
7473          *  go outside our tables.
7474          */
7475         if (ccb_h->target_id   == np->myaddr ||
7476             ccb_h->target_id   >= SYM_CONF_MAX_TARGET ||
7477             ccb_h->target_lun  >= SYM_CONF_MAX_LUN) {
7478                 sym_xpt_done2(np, ccb, CAM_DEV_NOT_THERE);
7479                 return;
7480         }
7481
7482         /*
7483          *  Retrieve the target and lun descriptors.
7484          */
7485         tp = &np->target[ccb_h->target_id];
7486         lp = sym_lp(tp, ccb_h->target_lun);
7487
7488         /*
7489          *  Complete the 1st INQUIRY command with error
7490          *  condition if the device is flagged NOSCAN
7491          *  at BOOT in the NVRAM. This may speed up
7492          *  the boot and maintain coherency with BIOS
7493          *  device numbering. Clearing the flag allows
7494          *  user to rescan skipped devices later.
7495          *  We also return error for devices not flagged
7496          *  for SCAN LUNS in the NVRAM since some mono-lun
7497          *  devices behave badly when asked for some non
7498          *  zero LUN. Btw, this is an absolute hack.:-)
7499          */
7500         if (!(ccb_h->flags & CAM_CDB_PHYS) &&
7501             (0x12 == ((ccb_h->flags & CAM_CDB_POINTER) ?
7502                   csio->cdb_io.cdb_ptr[0] : csio->cdb_io.cdb_bytes[0]))) {
7503                 if ((tp->usrflags & SYM_SCAN_BOOT_DISABLED) ||
7504                     ((tp->usrflags & SYM_SCAN_LUNS_DISABLED) &&
7505                      ccb_h->target_lun != 0)) {
7506                         tp->usrflags &= ~SYM_SCAN_BOOT_DISABLED;
7507                         sym_xpt_done2(np, ccb, CAM_DEV_NOT_THERE);
7508                         return;
7509                 }
7510         }
7511
7512         /*
7513          *  Get a control block for this IO.
7514          */
7515         tmp = ((ccb_h->flags & CAM_TAG_ACTION_VALID) != 0);
7516         cp = sym_get_ccb(np, ccb_h->target_id, ccb_h->target_lun, tmp);
7517         if (!cp) {
7518                 sym_xpt_done2(np, ccb, CAM_RESRC_UNAVAIL);
7519                 return;
7520         }
7521
7522         /*
7523          *  Keep track of the IO in our CCB.
7524          */
7525         cp->cam_ccb = ccb;
7526
7527         /*
7528          *  Build the IDENTIFY message.
7529          */
7530         idmsg = M_IDENTIFY | cp->lun;
7531         if (cp->tag != NO_TAG || (lp && (lp->current_flags & SYM_DISC_ENABLED)))
7532                 idmsg |= 0x40;
7533
7534         msgptr = cp->scsi_smsg;
7535         msglen = 0;
7536         msgptr[msglen++] = idmsg;
7537
7538         /*
7539          *  Build the tag message if present.
7540          */
7541         if (cp->tag != NO_TAG) {
7542                 u_char order = csio->tag_action;
7543
7544                 switch(order) {
7545                 case M_ORDERED_TAG:
7546                         break;
7547                 case M_HEAD_TAG:
7548                         break;
7549                 default:
7550                         order = M_SIMPLE_TAG;
7551                 }
7552                 msgptr[msglen++] = order;
7553
7554                 /*
7555                  *  For less than 128 tags, actual tags are numbered
7556                  *  1,3,5,..2*MAXTAGS+1,since we may have to deal
7557                  *  with devices that have problems with #TAG 0 or too
7558                  *  great #TAG numbers. For more tags (up to 256),
7559                  *  we use directly our tag number.
7560                  */
7561 #if SYM_CONF_MAX_TASK > (512/4)
7562                 msgptr[msglen++] = cp->tag;
7563 #else
7564                 msgptr[msglen++] = (cp->tag << 1) + 1;
7565 #endif
7566         }
7567
7568         /*
7569          *  Build a negotiation message if needed.
7570          *  (nego_status is filled by sym_prepare_nego())
7571          */
7572         cp->nego_status = 0;
7573         if (tp->tinfo.current.width   != tp->tinfo.goal.width  ||
7574             tp->tinfo.current.period  != tp->tinfo.goal.period ||
7575             tp->tinfo.current.offset  != tp->tinfo.goal.offset ||
7576             tp->tinfo.current.options != tp->tinfo.goal.options) {
7577                 if (!tp->nego_cp && lp)
7578                         msglen += sym_prepare_nego(np, cp, 0, msgptr + msglen);
7579         }
7580
7581         /*
7582          *  Fill in our ccb
7583          */
7584
7585         /*
7586          *  Startqueue
7587          */
7588         cp->phys.head.go.start   = cpu_to_scr(SCRIPTA_BA (np, select));
7589         cp->phys.head.go.restart = cpu_to_scr(SCRIPTA_BA (np, resel_dsa));
7590
7591         /*
7592          *  select
7593          */
7594         cp->phys.select.sel_id          = cp->target;
7595         cp->phys.select.sel_scntl3      = tp->head.wval;
7596         cp->phys.select.sel_sxfer       = tp->head.sval;
7597         cp->phys.select.sel_scntl4      = tp->head.uval;
7598
7599         /*
7600          *  message
7601          */
7602         cp->phys.smsg.addr      = cpu_to_scr(CCB_BA (cp, scsi_smsg));
7603         cp->phys.smsg.size      = cpu_to_scr(msglen);
7604
7605         /*
7606          *  command
7607          */
7608         if (sym_setup_cdb(np, csio, cp) < 0) {
7609                 sym_xpt_done(np, ccb, cp);
7610                 sym_free_ccb(np, cp);
7611                 return;
7612         }
7613
7614         /*
7615          *  status
7616          */
7617 #if     0       /* Provision */
7618         cp->actualquirks        = tp->quirks;
7619 #endif
7620         cp->actualquirks        = SYM_QUIRK_AUTOSAVE;
7621         cp->host_status         = cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
7622         cp->ssss_status         = S_ILLEGAL;
7623         cp->xerr_status         = 0;
7624         cp->host_flags          = 0;
7625         cp->extra_bytes         = 0;
7626
7627         /*
7628          *  extreme data pointer.
7629          *  shall be positive, so -1 is lower than lowest.:)
7630          */
7631         cp->ext_sg  = -1;
7632         cp->ext_ofs = 0;
7633
7634         /*
7635          *  Build the data descriptor block
7636          *  and start the IO.
7637          */
7638         sym_setup_data_and_start(np, csio, cp);
7639 }
7640
7641 /*
7642  *  Setup buffers and pointers that address the CDB.
7643  *  I bet, physical CDBs will never be used on the planet,
7644  *  since they can be bounced without significant overhead.
7645  */
7646 static int sym_setup_cdb(hcb_p np, struct ccb_scsiio *csio, ccb_p cp)
7647 {
7648         struct ccb_hdr *ccb_h;
7649         u32     cmd_ba;
7650         int     cmd_len;
7651
7652         SYM_LOCK_ASSERT(MA_OWNED);
7653
7654         ccb_h = &csio->ccb_h;
7655
7656         /*
7657          *  CDB is 16 bytes max.
7658          */
7659         if (csio->cdb_len > sizeof(cp->cdb_buf)) {
7660                 sym_set_cam_status(cp->cam_ccb, CAM_REQ_INVALID);
7661                 return -1;
7662         }
7663         cmd_len = csio->cdb_len;
7664
7665         if (ccb_h->flags & CAM_CDB_POINTER) {
7666                 /* CDB is a pointer */
7667                 if (!(ccb_h->flags & CAM_CDB_PHYS)) {
7668                         /* CDB pointer is virtual */
7669                         bcopy(csio->cdb_io.cdb_ptr, cp->cdb_buf, cmd_len);
7670                         cmd_ba = CCB_BA (cp, cdb_buf[0]);
7671                 } else {
7672                         /* CDB pointer is physical */
7673 #if 0
7674                         cmd_ba = ((u32)csio->cdb_io.cdb_ptr) & 0xffffffff;
7675 #else
7676                         sym_set_cam_status(cp->cam_ccb, CAM_REQ_INVALID);
7677                         return -1;
7678 #endif
7679                 }
7680         } else {
7681                 /* CDB is in the CAM ccb (buffer) */
7682                 bcopy(csio->cdb_io.cdb_bytes, cp->cdb_buf, cmd_len);
7683                 cmd_ba = CCB_BA (cp, cdb_buf[0]);
7684         }
7685
7686         cp->phys.cmd.addr       = cpu_to_scr(cmd_ba);
7687         cp->phys.cmd.size       = cpu_to_scr(cmd_len);
7688
7689         return 0;
7690 }
7691
7692 /*
7693  *  Set up data pointers used by SCRIPTS.
7694  */
7695 static void __inline
7696 sym_setup_data_pointers(hcb_p np, ccb_p cp, int dir)
7697 {
7698         u32 lastp, goalp;
7699
7700         SYM_LOCK_ASSERT(MA_OWNED);
7701
7702         /*
7703          *  No segments means no data.
7704          */
7705         if (!cp->segments)
7706                 dir = CAM_DIR_NONE;
7707
7708         /*
7709          *  Set the data pointer.
7710          */
7711         switch(dir) {
7712         case CAM_DIR_OUT:
7713                 goalp = SCRIPTA_BA (np, data_out2) + 8;
7714                 lastp = goalp - 8 - (cp->segments * (2*4));
7715                 break;
7716         case CAM_DIR_IN:
7717                 cp->host_flags |= HF_DATA_IN;
7718                 goalp = SCRIPTA_BA (np, data_in2) + 8;
7719                 lastp = goalp - 8 - (cp->segments * (2*4));
7720                 break;
7721         case CAM_DIR_NONE:
7722         default:
7723                 lastp = goalp = SCRIPTB_BA (np, no_data);
7724                 break;
7725         }
7726
7727         cp->phys.head.lastp = cpu_to_scr(lastp);
7728         cp->phys.head.goalp = cpu_to_scr(goalp);
7729         cp->phys.head.savep = cpu_to_scr(lastp);
7730         cp->startp          = cp->phys.head.savep;
7731 }
7732
7733 /*
7734  *  Call back routine for the DMA map service.
7735  *  If bounce buffers are used (why ?), we may sleep and then
7736  *  be called there in another context.
7737  */
7738 static void
7739 sym_execute_ccb(void *arg, bus_dma_segment_t *psegs, int nsegs, int error)
7740 {
7741         ccb_p   cp;
7742         hcb_p   np;
7743         union   ccb *ccb;
7744
7745         cp  = (ccb_p) arg;
7746         ccb = cp->cam_ccb;
7747         np  = (hcb_p) cp->arg;
7748
7749         SYM_LOCK_ASSERT(MA_OWNED);
7750
7751         /*
7752          *  Deal with weird races.
7753          */
7754         if (sym_get_cam_status(ccb) != CAM_REQ_INPROG)
7755                 goto out_abort;
7756
7757         /*
7758          *  Deal with weird errors.
7759          */
7760         if (error) {
7761                 cp->dmamapped = 0;
7762                 sym_set_cam_status(cp->cam_ccb, CAM_REQ_ABORTED);
7763                 goto out_abort;
7764         }
7765
7766         /*
7767          *  Build the data descriptor for the chip.
7768          */
7769         if (nsegs) {
7770                 int retv;
7771                 /* 896 rev 1 requires to be careful about boundaries */
7772                 if (np->device_id == PCI_ID_SYM53C896 && np->revision_id <= 1)
7773                         retv = sym_scatter_sg_physical(np, cp, psegs, nsegs);
7774                 else
7775                         retv = sym_fast_scatter_sg_physical(np,cp, psegs,nsegs);
7776                 if (retv < 0) {
7777                         sym_set_cam_status(cp->cam_ccb, CAM_REQ_TOO_BIG);
7778                         goto out_abort;
7779                 }
7780         }
7781
7782         /*
7783          *  Synchronize the DMA map only if we have
7784          *  actually mapped the data.
7785          */
7786         if (cp->dmamapped) {
7787                 bus_dmamap_sync(np->data_dmat, cp->dmamap,
7788                         (cp->dmamapped == SYM_DMA_READ ?
7789                                 BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
7790         }
7791
7792         /*
7793          *  Set host status to busy state.
7794          *  May have been set back to HS_WAIT to avoid a race.
7795          */
7796         cp->host_status = cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
7797
7798         /*
7799          *  Set data pointers.
7800          */
7801         sym_setup_data_pointers(np, cp,  (ccb->ccb_h.flags & CAM_DIR_MASK));
7802
7803         /*
7804          *  Enqueue this IO in our pending queue.
7805          */
7806         sym_enqueue_cam_ccb(cp);
7807
7808         /*
7809          *  When `#ifed 1', the code below makes the driver
7810          *  panic on the first attempt to write to a SCSI device.
7811          *  It is the first test we want to do after a driver
7812          *  change that does not seem obviously safe. :)
7813          */
7814 #if 0
7815         switch (cp->cdb_buf[0]) {
7816         case 0x0A: case 0x2A: case 0xAA:
7817                 panic("XXXXXXXXXXXXX WRITE NOT YET ALLOWED XXXXXXXXXXXXXX\n");
7818                 MDELAY(10000);
7819                 break;
7820         default:
7821                 break;
7822         }
7823 #endif
7824         /*
7825          *  Activate this job.
7826          */
7827         sym_put_start_queue(np, cp);
7828         return;
7829 out_abort:
7830         sym_xpt_done(np, ccb, cp);
7831         sym_free_ccb(np, cp);
7832 }
7833
7834 /*
7835  *  How complex it gets to deal with the data in CAM.
7836  *  The Bus Dma stuff makes things still more complex.
7837  */
7838 static void
7839 sym_setup_data_and_start(hcb_p np, struct ccb_scsiio *csio, ccb_p cp)
7840 {
7841         struct ccb_hdr *ccb_h;
7842         int dir, retv;
7843
7844         SYM_LOCK_ASSERT(MA_OWNED);
7845
7846         ccb_h = &csio->ccb_h;
7847
7848         /*
7849          *  Now deal with the data.
7850          */
7851         cp->data_len = csio->dxfer_len;
7852         cp->arg      = np;
7853
7854         /*
7855          *  No direction means no data.
7856          */
7857         dir = (ccb_h->flags & CAM_DIR_MASK);
7858         if (dir == CAM_DIR_NONE) {
7859                 sym_execute_ccb(cp, NULL, 0, 0);
7860                 return;
7861         }
7862
7863         cp->dmamapped = (dir == CAM_DIR_IN) ?  SYM_DMA_READ : SYM_DMA_WRITE;
7864         retv = bus_dmamap_load_ccb(np->data_dmat, cp->dmamap,
7865                                (union ccb *)csio, sym_execute_ccb, cp, 0);
7866         if (retv == EINPROGRESS) {
7867                 cp->host_status = HS_WAIT;
7868                 xpt_freeze_simq(np->sim, 1);
7869                 csio->ccb_h.status |= CAM_RELEASE_SIMQ;
7870         }
7871 }
7872
7873 /*
7874  *  Move the scatter list to our data block.
7875  */
7876 static int
7877 sym_fast_scatter_sg_physical(hcb_p np, ccb_p cp,
7878                              bus_dma_segment_t *psegs, int nsegs)
7879 {
7880         struct sym_tblmove *data;
7881         bus_dma_segment_t *psegs2;
7882
7883         SYM_LOCK_ASSERT(MA_OWNED);
7884
7885         if (nsegs > SYM_CONF_MAX_SG)
7886                 return -1;
7887
7888         data   = &cp->phys.data[SYM_CONF_MAX_SG-1];
7889         psegs2 = &psegs[nsegs-1];
7890         cp->segments = nsegs;
7891
7892         while (1) {
7893                 data->addr = cpu_to_scr(psegs2->ds_addr);
7894                 data->size = cpu_to_scr(psegs2->ds_len);
7895                 if (DEBUG_FLAGS & DEBUG_SCATTER) {
7896                         printf ("%s scatter: paddr=%lx len=%ld\n",
7897                                 sym_name(np), (long) psegs2->ds_addr,
7898                                 (long) psegs2->ds_len);
7899                 }
7900                 if (psegs2 != psegs) {
7901                         --data;
7902                         --psegs2;
7903                         continue;
7904                 }
7905                 break;
7906         }
7907         return 0;
7908 }
7909
7910 /*
7911  *  Scatter a SG list with physical addresses into bus addressable chunks.
7912  */
7913 static int
7914 sym_scatter_sg_physical(hcb_p np, ccb_p cp, bus_dma_segment_t *psegs, int nsegs)
7915 {
7916         u_long  ps, pe, pn;
7917         u_long  k;
7918         int s, t;
7919
7920         SYM_LOCK_ASSERT(MA_OWNED);
7921
7922         s  = SYM_CONF_MAX_SG - 1;
7923         t  = nsegs - 1;
7924         ps = psegs[t].ds_addr;
7925         pe = ps + psegs[t].ds_len;
7926
7927         while (s >= 0) {
7928                 pn = (pe - 1) & ~(SYM_CONF_DMA_BOUNDARY - 1);
7929                 if (pn <= ps)
7930                         pn = ps;
7931                 k = pe - pn;
7932                 if (DEBUG_FLAGS & DEBUG_SCATTER) {
7933                         printf ("%s scatter: paddr=%lx len=%ld\n",
7934                                 sym_name(np), pn, k);
7935                 }
7936                 cp->phys.data[s].addr = cpu_to_scr(pn);
7937                 cp->phys.data[s].size = cpu_to_scr(k);
7938                 --s;
7939                 if (pn == ps) {
7940                         if (--t < 0)
7941                                 break;
7942                         ps = psegs[t].ds_addr;
7943                         pe = ps + psegs[t].ds_len;
7944                 }
7945                 else
7946                         pe = pn;
7947         }
7948
7949         cp->segments = SYM_CONF_MAX_SG - 1 - s;
7950
7951         return t >= 0 ? -1 : 0;
7952 }
7953
7954 /*
7955  *  SIM action for non performance critical stuff.
7956  */
7957 static void sym_action2(struct cam_sim *sim, union ccb *ccb)
7958 {
7959         union ccb *abort_ccb;
7960         struct ccb_hdr *ccb_h;
7961         struct ccb_pathinq *cpi;
7962         struct ccb_trans_settings *cts;
7963         struct sym_trans *tip;
7964         hcb_p   np;
7965         tcb_p   tp;
7966         lcb_p   lp;
7967         u_char dflags;
7968
7969         /*
7970          *  Retrieve our controller data structure.
7971          */
7972         np = (hcb_p) cam_sim_softc(sim);
7973
7974         SYM_LOCK_ASSERT(MA_OWNED);
7975
7976         ccb_h = &ccb->ccb_h;
7977
7978         switch (ccb_h->func_code) {
7979         case XPT_SET_TRAN_SETTINGS:
7980                 cts  = &ccb->cts;
7981                 tp = &np->target[ccb_h->target_id];
7982
7983                 /*
7984                  *  Update SPI transport settings in TARGET control block.
7985                  *  Update SCSI device settings in LUN control block.
7986                  */
7987                 lp = sym_lp(tp, ccb_h->target_lun);
7988                 if (cts->type == CTS_TYPE_CURRENT_SETTINGS) {
7989                         sym_update_trans(np, &tp->tinfo.goal, cts);
7990                         if (lp)
7991                                 sym_update_dflags(np, &lp->current_flags, cts);
7992                 }
7993                 if (cts->type == CTS_TYPE_USER_SETTINGS) {
7994                         sym_update_trans(np, &tp->tinfo.user, cts);
7995                         if (lp)
7996                                 sym_update_dflags(np, &lp->user_flags, cts);
7997                 }
7998
7999                 sym_xpt_done2(np, ccb, CAM_REQ_CMP);
8000                 break;
8001         case XPT_GET_TRAN_SETTINGS:
8002                 cts = &ccb->cts;
8003                 tp = &np->target[ccb_h->target_id];
8004                 lp = sym_lp(tp, ccb_h->target_lun);
8005
8006 #define cts__scsi (&cts->proto_specific.scsi)
8007 #define cts__spi  (&cts->xport_specific.spi)
8008                 if (cts->type == CTS_TYPE_CURRENT_SETTINGS) {
8009                         tip = &tp->tinfo.current;
8010                         dflags = lp ? lp->current_flags : 0;
8011                 }
8012                 else {
8013                         tip = &tp->tinfo.user;
8014                         dflags = lp ? lp->user_flags : tp->usrflags;
8015                 }
8016
8017                 cts->protocol  = PROTO_SCSI;
8018                 cts->transport = XPORT_SPI;
8019                 cts->protocol_version  = tip->scsi_version;
8020                 cts->transport_version = tip->spi_version;
8021
8022                 cts__spi->sync_period = tip->period;
8023                 cts__spi->sync_offset = tip->offset;
8024                 cts__spi->bus_width   = tip->width;
8025                 cts__spi->ppr_options = tip->options;
8026
8027                 cts__spi->valid = CTS_SPI_VALID_SYNC_RATE
8028                                 | CTS_SPI_VALID_SYNC_OFFSET
8029                                 | CTS_SPI_VALID_BUS_WIDTH
8030                                 | CTS_SPI_VALID_PPR_OPTIONS;
8031
8032                 cts__spi->flags &= ~CTS_SPI_FLAGS_DISC_ENB;
8033                 if (dflags & SYM_DISC_ENABLED)
8034                         cts__spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
8035                 cts__spi->valid |= CTS_SPI_VALID_DISC;
8036
8037                 cts__scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
8038                 if (dflags & SYM_TAGS_ENABLED)
8039                         cts__scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
8040                 cts__scsi->valid |= CTS_SCSI_VALID_TQ;
8041 #undef  cts__spi
8042 #undef  cts__scsi
8043                 sym_xpt_done2(np, ccb, CAM_REQ_CMP);
8044                 break;
8045         case XPT_CALC_GEOMETRY:
8046                 cam_calc_geometry(&ccb->ccg, /*extended*/1);
8047                 sym_xpt_done2(np, ccb, CAM_REQ_CMP);
8048                 break;
8049         case XPT_PATH_INQ:
8050                 cpi = &ccb->cpi;
8051                 cpi->version_num = 1;
8052                 cpi->hba_inquiry = PI_MDP_ABLE|PI_SDTR_ABLE|PI_TAG_ABLE;
8053                 if ((np->features & FE_WIDE) != 0)
8054                         cpi->hba_inquiry |= PI_WIDE_16;
8055                 cpi->target_sprt = 0;
8056                 cpi->hba_misc = PIM_UNMAPPED;
8057                 if (np->usrflags & SYM_SCAN_TARGETS_HILO)
8058                         cpi->hba_misc |= PIM_SCANHILO;
8059                 if (np->usrflags & SYM_AVOID_BUS_RESET)
8060                         cpi->hba_misc |= PIM_NOBUSRESET;
8061                 cpi->hba_eng_cnt = 0;
8062                 cpi->max_target = (np->features & FE_WIDE) ? 15 : 7;
8063                 /* Semantic problem:)LUN number max = max number of LUNs - 1 */
8064                 cpi->max_lun = SYM_CONF_MAX_LUN-1;
8065                 if (SYM_SETUP_MAX_LUN < SYM_CONF_MAX_LUN)
8066                         cpi->max_lun = SYM_SETUP_MAX_LUN-1;
8067                 cpi->bus_id = cam_sim_bus(sim);
8068                 cpi->initiator_id = np->myaddr;
8069                 cpi->base_transfer_speed = 3300;
8070                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
8071                 strncpy(cpi->hba_vid, "Symbios", HBA_IDLEN);
8072                 strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
8073                 cpi->unit_number = cam_sim_unit(sim);
8074
8075                 cpi->protocol = PROTO_SCSI;
8076                 cpi->protocol_version = SCSI_REV_2;
8077                 cpi->transport = XPORT_SPI;
8078                 cpi->transport_version = 2;
8079                 cpi->xport_specific.spi.ppr_options = SID_SPI_CLOCK_ST;
8080                 if (np->features & FE_ULTRA3) {
8081                         cpi->transport_version = 3;
8082                         cpi->xport_specific.spi.ppr_options =
8083                             SID_SPI_CLOCK_DT_ST;
8084                 }
8085                 cpi->maxio = SYM_CONF_MAX_SG * PAGE_SIZE;
8086                 sym_xpt_done2(np, ccb, CAM_REQ_CMP);
8087                 break;
8088         case XPT_ABORT:
8089                 abort_ccb = ccb->cab.abort_ccb;
8090                 switch(abort_ccb->ccb_h.func_code) {
8091                 case XPT_SCSI_IO:
8092                         if (sym_abort_scsiio(np, abort_ccb, 0) == 0) {
8093                                 sym_xpt_done2(np, ccb, CAM_REQ_CMP);
8094                                 break;
8095                         }
8096                 default:
8097                         sym_xpt_done2(np, ccb, CAM_UA_ABORT);
8098                         break;
8099                 }
8100                 break;
8101         case XPT_RESET_DEV:
8102                 sym_reset_dev(np, ccb);
8103                 break;
8104         case XPT_RESET_BUS:
8105                 sym_reset_scsi_bus(np, 0);
8106                 if (sym_verbose) {
8107                         xpt_print_path(np->path);
8108                         printf("SCSI BUS reset delivered.\n");
8109                 }
8110                 sym_init (np, 1);
8111                 sym_xpt_done2(np, ccb, CAM_REQ_CMP);
8112                 break;
8113         case XPT_ACCEPT_TARGET_IO:
8114         case XPT_CONT_TARGET_IO:
8115         case XPT_EN_LUN:
8116         case XPT_NOTIFY_ACK:
8117         case XPT_IMMED_NOTIFY:
8118         case XPT_TERM_IO:
8119         default:
8120                 sym_xpt_done2(np, ccb, CAM_REQ_INVALID);
8121                 break;
8122         }
8123 }
8124
8125 /*
8126  *  Asynchronous notification handler.
8127  */
8128 static void
8129 sym_async(void *cb_arg, u32 code, struct cam_path *path, void *args __unused)
8130 {
8131         hcb_p np;
8132         struct cam_sim *sim;
8133         u_int tn;
8134         tcb_p tp;
8135
8136         sim = (struct cam_sim *) cb_arg;
8137         np  = (hcb_p) cam_sim_softc(sim);
8138
8139         SYM_LOCK_ASSERT(MA_OWNED);
8140
8141         switch (code) {
8142         case AC_LOST_DEVICE:
8143                 tn = xpt_path_target_id(path);
8144                 if (tn >= SYM_CONF_MAX_TARGET)
8145                         break;
8146
8147                 tp = &np->target[tn];
8148
8149                 tp->to_reset  = 0;
8150                 tp->head.sval = 0;
8151                 tp->head.wval = np->rv_scntl3;
8152                 tp->head.uval = 0;
8153
8154                 tp->tinfo.current.period  = tp->tinfo.goal.period = 0;
8155                 tp->tinfo.current.offset  = tp->tinfo.goal.offset = 0;
8156                 tp->tinfo.current.width   = tp->tinfo.goal.width  = BUS_8_BIT;
8157                 tp->tinfo.current.options = tp->tinfo.goal.options = 0;
8158
8159                 break;
8160         default:
8161                 break;
8162         }
8163 }
8164
8165 /*
8166  *  Update transfer settings of a target.
8167  */
8168 static void sym_update_trans(hcb_p np, struct sym_trans *tip,
8169     struct ccb_trans_settings *cts)
8170 {
8171
8172         SYM_LOCK_ASSERT(MA_OWNED);
8173
8174         /*
8175          *  Update the infos.
8176          */
8177 #define cts__spi (&cts->xport_specific.spi)
8178         if ((cts__spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0)
8179                 tip->width = cts__spi->bus_width;
8180         if ((cts__spi->valid & CTS_SPI_VALID_SYNC_OFFSET) != 0)
8181                 tip->offset = cts__spi->sync_offset;
8182         if ((cts__spi->valid & CTS_SPI_VALID_SYNC_RATE) != 0)
8183                 tip->period = cts__spi->sync_period;
8184         if ((cts__spi->valid & CTS_SPI_VALID_PPR_OPTIONS) != 0)
8185                 tip->options = (cts__spi->ppr_options & PPR_OPT_DT);
8186         if (cts->protocol_version != PROTO_VERSION_UNSPECIFIED &&
8187             cts->protocol_version != PROTO_VERSION_UNKNOWN)
8188                 tip->scsi_version = cts->protocol_version;
8189         if (cts->transport_version != XPORT_VERSION_UNSPECIFIED &&
8190             cts->transport_version != XPORT_VERSION_UNKNOWN)
8191                 tip->spi_version = cts->transport_version;
8192 #undef cts__spi
8193         /*
8194          *  Scale against driver configuration limits.
8195          */
8196         if (tip->width  > SYM_SETUP_MAX_WIDE) tip->width  = SYM_SETUP_MAX_WIDE;
8197         if (tip->period && tip->offset) {
8198                 if (tip->offset > SYM_SETUP_MAX_OFFS) tip->offset = SYM_SETUP_MAX_OFFS;
8199                 if (tip->period < SYM_SETUP_MIN_SYNC) tip->period = SYM_SETUP_MIN_SYNC;
8200         } else {
8201                 tip->offset = 0;
8202                 tip->period = 0;
8203         }
8204
8205         /*
8206          *  Scale against actual controller BUS width.
8207          */
8208         if (tip->width > np->maxwide)
8209                 tip->width  = np->maxwide;
8210
8211         /*
8212          *  Only accept DT if controller supports and SYNC/WIDE asked.
8213          */
8214         if (!((np->features & (FE_C10|FE_ULTRA3)) == (FE_C10|FE_ULTRA3)) ||
8215             !(tip->width == BUS_16_BIT && tip->offset)) {
8216                 tip->options &= ~PPR_OPT_DT;
8217         }
8218
8219         /*
8220          *  Scale period factor and offset against controller limits.
8221          */
8222         if (tip->offset && tip->period) {
8223                 if (tip->options & PPR_OPT_DT) {
8224                         if (tip->period < np->minsync_dt)
8225                                 tip->period = np->minsync_dt;
8226                         if (tip->period > np->maxsync_dt)
8227                                 tip->period = np->maxsync_dt;
8228                         if (tip->offset > np->maxoffs_dt)
8229                                 tip->offset = np->maxoffs_dt;
8230                 }
8231                 else {
8232                         if (tip->period < np->minsync)
8233                                 tip->period = np->minsync;
8234                         if (tip->period > np->maxsync)
8235                                 tip->period = np->maxsync;
8236                         if (tip->offset > np->maxoffs)
8237                                 tip->offset = np->maxoffs;
8238                 }
8239         }
8240 }
8241
8242 /*
8243  *  Update flags for a device (logical unit).
8244  */
8245 static void
8246 sym_update_dflags(hcb_p np, u_char *flags, struct ccb_trans_settings *cts)
8247 {
8248
8249         SYM_LOCK_ASSERT(MA_OWNED);
8250
8251 #define cts__scsi (&cts->proto_specific.scsi)
8252 #define cts__spi  (&cts->xport_specific.spi)
8253         if ((cts__spi->valid & CTS_SPI_VALID_DISC) != 0) {
8254                 if ((cts__spi->flags & CTS_SPI_FLAGS_DISC_ENB) != 0)
8255                         *flags |= SYM_DISC_ENABLED;
8256                 else
8257                         *flags &= ~SYM_DISC_ENABLED;
8258         }
8259
8260         if ((cts__scsi->valid & CTS_SCSI_VALID_TQ) != 0) {
8261                 if ((cts__scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0)
8262                         *flags |= SYM_TAGS_ENABLED;
8263                 else
8264                         *flags &= ~SYM_TAGS_ENABLED;
8265         }
8266 #undef  cts__spi
8267 #undef  cts__scsi
8268 }
8269
8270 /*============= DRIVER INITIALISATION ==================*/
8271
8272 static device_method_t sym_pci_methods[] = {
8273         DEVMETHOD(device_probe,  sym_pci_probe),
8274         DEVMETHOD(device_attach, sym_pci_attach),
8275         DEVMETHOD_END
8276 };
8277
8278 static driver_t sym_pci_driver = {
8279         "sym",
8280         sym_pci_methods,
8281         1       /* no softc */
8282 };
8283
8284 static devclass_t sym_devclass;
8285
8286 DRIVER_MODULE(sym, pci, sym_pci_driver, sym_devclass, NULL, NULL);
8287 MODULE_DEPEND(sym, cam, 1, 1, 1);
8288 MODULE_DEPEND(sym, pci, 1, 1, 1);
8289
8290 static const struct sym_pci_chip sym_pci_dev_table[] = {
8291  {PCI_ID_SYM53C810, 0x0f, "810", 4, 8, 4, 64,
8292  FE_ERL}
8293  ,
8294 #ifdef SYM_DEBUG_GENERIC_SUPPORT
8295  {PCI_ID_SYM53C810, 0xff, "810a", 4,  8, 4, 1,
8296  FE_BOF}
8297  ,
8298 #else
8299  {PCI_ID_SYM53C810, 0xff, "810a", 4,  8, 4, 1,
8300  FE_CACHE_SET|FE_LDSTR|FE_PFEN|FE_BOF}
8301  ,
8302 #endif
8303  {PCI_ID_SYM53C815, 0xff, "815", 4,  8, 4, 64,
8304  FE_BOF|FE_ERL}
8305  ,
8306  {PCI_ID_SYM53C825, 0x0f, "825", 6,  8, 4, 64,
8307  FE_WIDE|FE_BOF|FE_ERL|FE_DIFF}
8308  ,
8309  {PCI_ID_SYM53C825, 0xff, "825a", 6,  8, 4, 2,
8310  FE_WIDE|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM|FE_DIFF}
8311  ,
8312  {PCI_ID_SYM53C860, 0xff, "860", 4,  8, 5, 1,
8313  FE_ULTRA|FE_CLK80|FE_CACHE_SET|FE_BOF|FE_LDSTR|FE_PFEN}
8314  ,
8315  {PCI_ID_SYM53C875, 0x01, "875", 6, 16, 5, 2,
8316  FE_WIDE|FE_ULTRA|FE_CLK80|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
8317  FE_RAM|FE_DIFF}
8318  ,
8319  {PCI_ID_SYM53C875, 0xff, "875", 6, 16, 5, 2,
8320  FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
8321  FE_RAM|FE_DIFF}
8322  ,
8323  {PCI_ID_SYM53C875_2, 0xff, "875", 6, 16, 5, 2,
8324  FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
8325  FE_RAM|FE_DIFF}
8326  ,
8327  {PCI_ID_SYM53C885, 0xff, "885", 6, 16, 5, 2,
8328  FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
8329  FE_RAM|FE_DIFF}
8330  ,
8331 #ifdef SYM_DEBUG_GENERIC_SUPPORT
8332  {PCI_ID_SYM53C895, 0xff, "895", 6, 31, 7, 2,
8333  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|
8334  FE_RAM|FE_LCKFRQ}
8335  ,
8336 #else
8337  {PCI_ID_SYM53C895, 0xff, "895", 6, 31, 7, 2,
8338  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
8339  FE_RAM|FE_LCKFRQ}
8340  ,
8341 #endif
8342  {PCI_ID_SYM53C896, 0xff, "896", 6, 31, 7, 4,
8343  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
8344  FE_RAM|FE_RAM8K|FE_64BIT|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_LCKFRQ}
8345  ,
8346  {PCI_ID_SYM53C895A, 0xff, "895a", 6, 31, 7, 4,
8347  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
8348  FE_RAM|FE_RAM8K|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_LCKFRQ}
8349  ,
8350  {PCI_ID_LSI53C1010, 0x00, "1010-33", 6, 31, 7, 8,
8351  FE_WIDE|FE_ULTRA3|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFBC|FE_LDSTR|FE_PFEN|
8352  FE_RAM|FE_RAM8K|FE_64BIT|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_CRC|
8353  FE_C10}
8354  ,
8355  {PCI_ID_LSI53C1010, 0xff, "1010-33", 6, 31, 7, 8,
8356  FE_WIDE|FE_ULTRA3|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFBC|FE_LDSTR|FE_PFEN|
8357  FE_RAM|FE_RAM8K|FE_64BIT|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_CRC|
8358  FE_C10|FE_U3EN}
8359  ,
8360  {PCI_ID_LSI53C1010_2, 0xff, "1010-66", 6, 31, 7, 8,
8361  FE_WIDE|FE_ULTRA3|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFBC|FE_LDSTR|FE_PFEN|
8362  FE_RAM|FE_RAM8K|FE_64BIT|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_66MHZ|FE_CRC|
8363  FE_C10|FE_U3EN}
8364  ,
8365  {PCI_ID_LSI53C1510D, 0xff, "1510d", 6, 31, 7, 4,
8366  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
8367  FE_RAM|FE_IO256|FE_LEDC}
8368 };
8369
8370 /*
8371  *  Look up the chip table.
8372  *
8373  *  Return a pointer to the chip entry if found,
8374  *  zero otherwise.
8375  */
8376 static const struct sym_pci_chip *
8377 sym_find_pci_chip(device_t dev)
8378 {
8379         const struct    sym_pci_chip *chip;
8380         int     i;
8381         u_short device_id;
8382         u_char  revision;
8383
8384         if (pci_get_vendor(dev) != PCI_VENDOR_NCR)
8385                 return NULL;
8386
8387         device_id = pci_get_device(dev);
8388         revision  = pci_get_revid(dev);
8389
8390         for (i = 0; i < nitems(sym_pci_dev_table); i++) {
8391                 chip = &sym_pci_dev_table[i];
8392                 if (device_id != chip->device_id)
8393                         continue;
8394                 if (revision > chip->revision_id)
8395                         continue;
8396                 return chip;
8397         }
8398
8399         return NULL;
8400 }
8401
8402 /*
8403  *  Tell upper layer if the chip is supported.
8404  */
8405 static int
8406 sym_pci_probe(device_t dev)
8407 {
8408         const struct    sym_pci_chip *chip;
8409
8410         chip = sym_find_pci_chip(dev);
8411         if (chip && sym_find_firmware(chip)) {
8412                 device_set_desc(dev, chip->name);
8413                 return (chip->lp_probe_bit & SYM_SETUP_LP_PROBE_MAP)?
8414                   BUS_PROBE_LOW_PRIORITY : BUS_PROBE_DEFAULT;
8415         }
8416         return ENXIO;
8417 }
8418
8419 /*
8420  *  Attach a sym53c8xx device.
8421  */
8422 static int
8423 sym_pci_attach(device_t dev)
8424 {
8425         const struct    sym_pci_chip *chip;
8426         u_short command;
8427         u_char  cachelnsz;
8428         struct  sym_hcb *np = NULL;
8429         struct  sym_nvram nvram;
8430         const struct    sym_fw *fw = NULL;
8431         int     i;
8432         bus_dma_tag_t   bus_dmat;
8433
8434         bus_dmat = bus_get_dma_tag(dev);
8435
8436         /*
8437          *  Only probed devices should be attached.
8438          *  We just enjoy being paranoid. :)
8439          */
8440         chip = sym_find_pci_chip(dev);
8441         if (chip == NULL || (fw = sym_find_firmware(chip)) == NULL)
8442                 return (ENXIO);
8443
8444         /*
8445          *  Allocate immediately the host control block,
8446          *  since we are only expecting to succeed. :)
8447          *  We keep track in the HCB of all the resources that
8448          *  are to be released on error.
8449          */
8450         np = __sym_calloc_dma(bus_dmat, sizeof(*np), "HCB");
8451         if (np)
8452                 np->bus_dmat = bus_dmat;
8453         else
8454                 return (ENXIO);
8455         device_set_softc(dev, np);
8456
8457         SYM_LOCK_INIT();
8458
8459         /*
8460          *  Copy some useful infos to the HCB.
8461          */
8462         np->hcb_ba       = vtobus(np);
8463         np->verbose      = bootverbose;
8464         np->device       = dev;
8465         np->device_id    = pci_get_device(dev);
8466         np->revision_id  = pci_get_revid(dev);
8467         np->features     = chip->features;
8468         np->clock_divn   = chip->nr_divisor;
8469         np->maxoffs      = chip->offset_max;
8470         np->maxburst     = chip->burst_max;
8471         np->scripta_sz   = fw->a_size;
8472         np->scriptb_sz   = fw->b_size;
8473         np->fw_setup     = fw->setup;
8474         np->fw_patch     = fw->patch;
8475         np->fw_name      = fw->name;
8476
8477 #ifdef __amd64__
8478         np->target = sym_calloc_dma(SYM_CONF_MAX_TARGET * sizeof(*(np->target)),
8479                         "TARGET");
8480         if (!np->target)
8481                 goto attach_failed;
8482 #endif
8483
8484         /*
8485          *  Initialize the CCB free and busy queues.
8486          */
8487         sym_que_init(&np->free_ccbq);
8488         sym_que_init(&np->busy_ccbq);
8489         sym_que_init(&np->comp_ccbq);
8490         sym_que_init(&np->cam_ccbq);
8491
8492         /*
8493          *  Allocate a tag for the DMA of user data.
8494          */
8495         if (bus_dma_tag_create(np->bus_dmat, 1, SYM_CONF_DMA_BOUNDARY,
8496             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
8497             BUS_SPACE_MAXSIZE_32BIT, SYM_CONF_MAX_SG, SYM_CONF_DMA_BOUNDARY,
8498             0, busdma_lock_mutex, &np->mtx, &np->data_dmat)) {
8499                 device_printf(dev, "failed to create DMA tag.\n");
8500                 goto attach_failed;
8501         }
8502
8503         /*
8504          *  Read and apply some fix-ups to the PCI COMMAND
8505          *  register. We want the chip to be enabled for:
8506          *  - BUS mastering
8507          *  - PCI parity checking (reporting would also be fine)
8508          *  - Write And Invalidate.
8509          */
8510         command = pci_read_config(dev, PCIR_COMMAND, 2);
8511         command |= PCIM_CMD_BUSMASTEREN | PCIM_CMD_PERRESPEN |
8512             PCIM_CMD_MWRICEN;
8513         pci_write_config(dev, PCIR_COMMAND, command, 2);
8514
8515         /*
8516          *  Let the device know about the cache line size,
8517          *  if it doesn't yet.
8518          */
8519         cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
8520         if (!cachelnsz) {
8521                 cachelnsz = 8;
8522                 pci_write_config(dev, PCIR_CACHELNSZ, cachelnsz, 1);
8523         }
8524
8525         /*
8526          *  Alloc/get/map/retrieve everything that deals with MMIO.
8527          */
8528         if ((command & PCIM_CMD_MEMEN) != 0) {
8529                 int regs_id = SYM_PCI_MMIO;
8530                 np->mmio_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
8531                                                       &regs_id, RF_ACTIVE);
8532         }
8533         if (!np->mmio_res) {
8534                 device_printf(dev, "failed to allocate MMIO resources\n");
8535                 goto attach_failed;
8536         }
8537         np->mmio_ba = rman_get_start(np->mmio_res);
8538
8539         /*
8540          *  Allocate the IRQ.
8541          */
8542         i = 0;
8543         np->irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &i,
8544                                              RF_ACTIVE | RF_SHAREABLE);
8545         if (!np->irq_res) {
8546                 device_printf(dev, "failed to allocate IRQ resource\n");
8547                 goto attach_failed;
8548         }
8549
8550 #ifdef  SYM_CONF_IOMAPPED
8551         /*
8552          *  User want us to use normal IO with PCI.
8553          *  Alloc/get/map/retrieve everything that deals with IO.
8554          */
8555         if ((command & PCI_COMMAND_IO_ENABLE) != 0) {
8556                 int regs_id = SYM_PCI_IO;
8557                 np->io_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT,
8558                                                     &regs_id, RF_ACTIVE);
8559         }
8560         if (!np->io_res) {
8561                 device_printf(dev, "failed to allocate IO resources\n");
8562                 goto attach_failed;
8563         }
8564
8565 #endif /* SYM_CONF_IOMAPPED */
8566
8567         /*
8568          *  If the chip has RAM.
8569          *  Alloc/get/map/retrieve the corresponding resources.
8570          */
8571         if ((np->features & (FE_RAM|FE_RAM8K)) &&
8572             (command & PCIM_CMD_MEMEN) != 0) {
8573                 int regs_id = SYM_PCI_RAM;
8574                 if (np->features & FE_64BIT)
8575                         regs_id = SYM_PCI_RAM64;
8576                 np->ram_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
8577                                                      &regs_id, RF_ACTIVE);
8578                 if (!np->ram_res) {
8579                         device_printf(dev,"failed to allocate RAM resources\n");
8580                         goto attach_failed;
8581                 }
8582                 np->ram_id  = regs_id;
8583                 np->ram_ba = rman_get_start(np->ram_res);
8584         }
8585
8586         /*
8587          *  Save setting of some IO registers, so we will
8588          *  be able to probe specific implementations.
8589          */
8590         sym_save_initial_setting (np);
8591
8592         /*
8593          *  Reset the chip now, since it has been reported
8594          *  that SCSI clock calibration may not work properly
8595          *  if the chip is currently active.
8596          */
8597         sym_chip_reset (np);
8598
8599         /*
8600          *  Try to read the user set-up.
8601          */
8602         (void) sym_read_nvram(np, &nvram);
8603
8604         /*
8605          *  Prepare controller and devices settings, according
8606          *  to chip features, user set-up and driver set-up.
8607          */
8608         (void) sym_prepare_setting(np, &nvram);
8609
8610         /*
8611          *  Check the PCI clock frequency.
8612          *  Must be performed after prepare_setting since it destroys
8613          *  STEST1 that is used to probe for the clock doubler.
8614          */
8615         i = sym_getpciclock(np);
8616         if (i > 37000)
8617                 device_printf(dev, "PCI BUS clock seems too high: %u KHz.\n",i);
8618
8619         /*
8620          *  Allocate the start queue.
8621          */
8622         np->squeue = (u32 *) sym_calloc_dma(sizeof(u32)*(MAX_QUEUE*2),"SQUEUE");
8623         if (!np->squeue)
8624                 goto attach_failed;
8625         np->squeue_ba = vtobus(np->squeue);
8626
8627         /*
8628          *  Allocate the done queue.
8629          */
8630         np->dqueue = (u32 *) sym_calloc_dma(sizeof(u32)*(MAX_QUEUE*2),"DQUEUE");
8631         if (!np->dqueue)
8632                 goto attach_failed;
8633         np->dqueue_ba = vtobus(np->dqueue);
8634
8635         /*
8636          *  Allocate the target bus address array.
8637          */
8638         np->targtbl = (u32 *) sym_calloc_dma(256, "TARGTBL");
8639         if (!np->targtbl)
8640                 goto attach_failed;
8641         np->targtbl_ba = vtobus(np->targtbl);
8642
8643         /*
8644          *  Allocate SCRIPTS areas.
8645          */
8646         np->scripta0 = sym_calloc_dma(np->scripta_sz, "SCRIPTA0");
8647         np->scriptb0 = sym_calloc_dma(np->scriptb_sz, "SCRIPTB0");
8648         if (!np->scripta0 || !np->scriptb0)
8649                 goto attach_failed;
8650
8651         /*
8652          *  Allocate the CCBs. We need at least ONE.
8653          */
8654         for (i = 0; sym_alloc_ccb(np) != NULL; i++)
8655                 ;
8656         if (i < 1)
8657                 goto attach_failed;
8658
8659         /*
8660          *  Calculate BUS addresses where we are going
8661          *  to load the SCRIPTS.
8662          */
8663         np->scripta_ba  = vtobus(np->scripta0);
8664         np->scriptb_ba  = vtobus(np->scriptb0);
8665         np->scriptb0_ba = np->scriptb_ba;
8666
8667         if (np->ram_ba) {
8668                 np->scripta_ba  = np->ram_ba;
8669                 if (np->features & FE_RAM8K) {
8670                         np->ram_ws = 8192;
8671                         np->scriptb_ba = np->scripta_ba + 4096;
8672 #ifdef __LP64__
8673                         np->scr_ram_seg = cpu_to_scr(np->scripta_ba >> 32);
8674 #endif
8675                 }
8676                 else
8677                         np->ram_ws = 4096;
8678         }
8679
8680         /*
8681          *  Copy scripts to controller instance.
8682          */
8683         bcopy(fw->a_base, np->scripta0, np->scripta_sz);
8684         bcopy(fw->b_base, np->scriptb0, np->scriptb_sz);
8685
8686         /*
8687          *  Setup variable parts in scripts and compute
8688          *  scripts bus addresses used from the C code.
8689          */
8690         np->fw_setup(np, fw);
8691
8692         /*
8693          *  Bind SCRIPTS with physical addresses usable by the
8694          *  SCRIPTS processor (as seen from the BUS = BUS addresses).
8695          */
8696         sym_fw_bind_script(np, (u32 *) np->scripta0, np->scripta_sz);
8697         sym_fw_bind_script(np, (u32 *) np->scriptb0, np->scriptb_sz);
8698
8699 #ifdef SYM_CONF_IARB_SUPPORT
8700         /*
8701          *    If user wants IARB to be set when we win arbitration
8702          *    and have other jobs, compute the max number of consecutive
8703          *    settings of IARB hints before we leave devices a chance to
8704          *    arbitrate for reselection.
8705          */
8706 #ifdef  SYM_SETUP_IARB_MAX
8707         np->iarb_max = SYM_SETUP_IARB_MAX;
8708 #else
8709         np->iarb_max = 4;
8710 #endif
8711 #endif
8712
8713         /*
8714          *  Prepare the idle and invalid task actions.
8715          */
8716         np->idletask.start      = cpu_to_scr(SCRIPTA_BA (np, idle));
8717         np->idletask.restart    = cpu_to_scr(SCRIPTB_BA (np, bad_i_t_l));
8718         np->idletask_ba         = vtobus(&np->idletask);
8719
8720         np->notask.start        = cpu_to_scr(SCRIPTA_BA (np, idle));
8721         np->notask.restart      = cpu_to_scr(SCRIPTB_BA (np, bad_i_t_l));
8722         np->notask_ba           = vtobus(&np->notask);
8723
8724         np->bad_itl.start       = cpu_to_scr(SCRIPTA_BA (np, idle));
8725         np->bad_itl.restart     = cpu_to_scr(SCRIPTB_BA (np, bad_i_t_l));
8726         np->bad_itl_ba          = vtobus(&np->bad_itl);
8727
8728         np->bad_itlq.start      = cpu_to_scr(SCRIPTA_BA (np, idle));
8729         np->bad_itlq.restart    = cpu_to_scr(SCRIPTB_BA (np,bad_i_t_l_q));
8730         np->bad_itlq_ba         = vtobus(&np->bad_itlq);
8731
8732         /*
8733          *  Allocate and prepare the lun JUMP table that is used
8734          *  for a target prior the probing of devices (bad lun table).
8735          *  A private table will be allocated for the target on the
8736          *  first INQUIRY response received.
8737          */
8738         np->badluntbl = sym_calloc_dma(256, "BADLUNTBL");
8739         if (!np->badluntbl)
8740                 goto attach_failed;
8741
8742         np->badlun_sa = cpu_to_scr(SCRIPTB_BA (np, resel_bad_lun));
8743         for (i = 0 ; i < 64 ; i++)      /* 64 luns/target, no less */
8744                 np->badluntbl[i] = cpu_to_scr(vtobus(&np->badlun_sa));
8745
8746         /*
8747          *  Prepare the bus address array that contains the bus
8748          *  address of each target control block.
8749          *  For now, assume all logical units are wrong. :)
8750          */
8751         for (i = 0 ; i < SYM_CONF_MAX_TARGET ; i++) {
8752                 np->targtbl[i] = cpu_to_scr(vtobus(&np->target[i]));
8753                 np->target[i].head.luntbl_sa =
8754                                 cpu_to_scr(vtobus(np->badluntbl));
8755                 np->target[i].head.lun0_sa =
8756                                 cpu_to_scr(vtobus(&np->badlun_sa));
8757         }
8758
8759         /*
8760          *  Now check the cache handling of the pci chipset.
8761          */
8762         if (sym_snooptest (np)) {
8763                 device_printf(dev, "CACHE INCORRECTLY CONFIGURED.\n");
8764                 goto attach_failed;
8765         };
8766
8767         /*
8768          *  Now deal with CAM.
8769          *  Hopefully, we will succeed with that one.:)
8770          */
8771         if (!sym_cam_attach(np))
8772                 goto attach_failed;
8773
8774         /*
8775          *  Sigh! we are done.
8776          */
8777         return 0;
8778
8779         /*
8780          *  We have failed.
8781          *  We will try to free all the resources we have
8782          *  allocated, but if we are a boot device, this
8783          *  will not help that much.;)
8784          */
8785 attach_failed:
8786         if (np)
8787                 sym_pci_free(np);
8788         return ENXIO;
8789 }
8790
8791 /*
8792  *  Free everything that have been allocated for this device.
8793  */
8794 static void sym_pci_free(hcb_p np)
8795 {
8796         SYM_QUEHEAD *qp;
8797         ccb_p cp;
8798         tcb_p tp;
8799         lcb_p lp;
8800         int target, lun;
8801
8802         /*
8803          *  First free CAM resources.
8804          */
8805         sym_cam_free(np);
8806
8807         /*
8808          *  Now every should be quiet for us to
8809          *  free other resources.
8810          */
8811         if (np->ram_res)
8812                 bus_release_resource(np->device, SYS_RES_MEMORY,
8813                                      np->ram_id, np->ram_res);
8814         if (np->mmio_res)
8815                 bus_release_resource(np->device, SYS_RES_MEMORY,
8816                                      SYM_PCI_MMIO, np->mmio_res);
8817         if (np->io_res)
8818                 bus_release_resource(np->device, SYS_RES_IOPORT,
8819                                      SYM_PCI_IO, np->io_res);
8820         if (np->irq_res)
8821                 bus_release_resource(np->device, SYS_RES_IRQ,
8822                                      0, np->irq_res);
8823
8824         if (np->scriptb0)
8825                 sym_mfree_dma(np->scriptb0, np->scriptb_sz, "SCRIPTB0");
8826         if (np->scripta0)
8827                 sym_mfree_dma(np->scripta0, np->scripta_sz, "SCRIPTA0");
8828         if (np->squeue)
8829                 sym_mfree_dma(np->squeue, sizeof(u32)*(MAX_QUEUE*2), "SQUEUE");
8830         if (np->dqueue)
8831                 sym_mfree_dma(np->dqueue, sizeof(u32)*(MAX_QUEUE*2), "DQUEUE");
8832
8833         while ((qp = sym_remque_head(&np->free_ccbq)) != NULL) {
8834                 cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
8835                 bus_dmamap_destroy(np->data_dmat, cp->dmamap);
8836                 sym_mfree_dma(cp->sns_bbuf, SYM_SNS_BBUF_LEN, "SNS_BBUF");
8837                 sym_mfree_dma(cp, sizeof(*cp), "CCB");
8838         }
8839
8840         if (np->badluntbl)
8841                 sym_mfree_dma(np->badluntbl, 256,"BADLUNTBL");
8842
8843         for (target = 0; target < SYM_CONF_MAX_TARGET ; target++) {
8844                 tp = &np->target[target];
8845                 for (lun = 0 ; lun < SYM_CONF_MAX_LUN ; lun++) {
8846                         lp = sym_lp(tp, lun);
8847                         if (!lp)
8848                                 continue;
8849                         if (lp->itlq_tbl)
8850                                 sym_mfree_dma(lp->itlq_tbl, SYM_CONF_MAX_TASK*4,
8851                                        "ITLQ_TBL");
8852                         if (lp->cb_tags)
8853                                 sym_mfree(lp->cb_tags, SYM_CONF_MAX_TASK,
8854                                        "CB_TAGS");
8855                         sym_mfree_dma(lp, sizeof(*lp), "LCB");
8856                 }
8857 #if SYM_CONF_MAX_LUN > 1
8858                 if (tp->lunmp)
8859                         sym_mfree(tp->lunmp, SYM_CONF_MAX_LUN*sizeof(lcb_p),
8860                                "LUNMP");
8861 #endif
8862         }
8863 #ifdef __amd64__
8864         if (np->target)
8865                 sym_mfree_dma(np->target,
8866                         SYM_CONF_MAX_TARGET * sizeof(*(np->target)), "TARGET");
8867 #endif
8868         if (np->targtbl)
8869                 sym_mfree_dma(np->targtbl, 256, "TARGTBL");
8870         if (np->data_dmat)
8871                 bus_dma_tag_destroy(np->data_dmat);
8872         if (SYM_LOCK_INITIALIZED() != 0)
8873                 SYM_LOCK_DESTROY();
8874         device_set_softc(np->device, NULL);
8875         sym_mfree_dma(np, sizeof(*np), "HCB");
8876 }
8877
8878 /*
8879  *  Allocate CAM resources and register a bus to CAM.
8880  */
8881 static int sym_cam_attach(hcb_p np)
8882 {
8883         struct cam_devq *devq = NULL;
8884         struct cam_sim *sim = NULL;
8885         struct cam_path *path = NULL;
8886         int err;
8887
8888         /*
8889          *  Establish our interrupt handler.
8890          */
8891         err = bus_setup_intr(np->device, np->irq_res,
8892                         INTR_ENTROPY | INTR_MPSAFE | INTR_TYPE_CAM,
8893                         NULL, sym_intr, np, &np->intr);
8894         if (err) {
8895                 device_printf(np->device, "bus_setup_intr() failed: %d\n",
8896                               err);
8897                 goto fail;
8898         }
8899
8900         /*
8901          *  Create the device queue for our sym SIM.
8902          */
8903         devq = cam_simq_alloc(SYM_CONF_MAX_START);
8904         if (!devq)
8905                 goto fail;
8906
8907         /*
8908          *  Construct our SIM entry.
8909          */
8910         sim = cam_sim_alloc(sym_action, sym_poll, "sym", np,
8911                         device_get_unit(np->device),
8912                         &np->mtx, 1, SYM_SETUP_MAX_TAG, devq);
8913         if (!sim)
8914                 goto fail;
8915
8916         SYM_LOCK();
8917
8918         if (xpt_bus_register(sim, np->device, 0) != CAM_SUCCESS)
8919                 goto fail;
8920         np->sim = sim;
8921
8922         if (xpt_create_path(&path, NULL,
8923                             cam_sim_path(np->sim), CAM_TARGET_WILDCARD,
8924                             CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
8925                 goto fail;
8926         }
8927         np->path = path;
8928
8929         /*
8930          *  Establish our async notification handler.
8931          */
8932         if (xpt_register_async(AC_LOST_DEVICE, sym_async, sim, path) !=
8933             CAM_REQ_CMP)
8934                 goto fail;
8935
8936         /*
8937          *  Start the chip now, without resetting the BUS, since
8938          *  it seems that this must stay under control of CAM.
8939          *  With LVD/SE capable chips and BUS in SE mode, we may
8940          *  get a spurious SMBC interrupt.
8941          */
8942         sym_init (np, 0);
8943
8944         SYM_UNLOCK();
8945
8946         return 1;
8947 fail:
8948         if (sim)
8949                 cam_sim_free(sim, FALSE);
8950         if (devq)
8951                 cam_simq_free(devq);
8952
8953         SYM_UNLOCK();
8954
8955         sym_cam_free(np);
8956
8957         return 0;
8958 }
8959
8960 /*
8961  *  Free everything that deals with CAM.
8962  */
8963 static void sym_cam_free(hcb_p np)
8964 {
8965
8966         SYM_LOCK_ASSERT(MA_NOTOWNED);
8967
8968         if (np->intr) {
8969                 bus_teardown_intr(np->device, np->irq_res, np->intr);
8970                 np->intr = NULL;
8971         }
8972
8973         SYM_LOCK();
8974
8975         if (np->sim) {
8976                 xpt_bus_deregister(cam_sim_path(np->sim));
8977                 cam_sim_free(np->sim, /*free_devq*/ TRUE);
8978                 np->sim = NULL;
8979         }
8980         if (np->path) {
8981                 xpt_free_path(np->path);
8982                 np->path = NULL;
8983         }
8984
8985         SYM_UNLOCK();
8986 }
8987
8988 /*============ OPTIONNAL NVRAM SUPPORT =================*/
8989
8990 /*
8991  *  Get host setup from NVRAM.
8992  */
8993 static void sym_nvram_setup_host (hcb_p np, struct sym_nvram *nvram)
8994 {
8995 #ifdef SYM_CONF_NVRAM_SUPPORT
8996         /*
8997          *  Get parity checking, host ID, verbose mode
8998          *  and miscellaneous host flags from NVRAM.
8999          */
9000         switch(nvram->type) {
9001         case SYM_SYMBIOS_NVRAM:
9002                 if (!(nvram->data.Symbios.flags & SYMBIOS_PARITY_ENABLE))
9003                         np->rv_scntl0  &= ~0x0a;
9004                 np->myaddr = nvram->data.Symbios.host_id & 0x0f;
9005                 if (nvram->data.Symbios.flags & SYMBIOS_VERBOSE_MSGS)
9006                         np->verbose += 1;
9007                 if (nvram->data.Symbios.flags1 & SYMBIOS_SCAN_HI_LO)
9008                         np->usrflags |= SYM_SCAN_TARGETS_HILO;
9009                 if (nvram->data.Symbios.flags2 & SYMBIOS_AVOID_BUS_RESET)
9010                         np->usrflags |= SYM_AVOID_BUS_RESET;
9011                 break;
9012         case SYM_TEKRAM_NVRAM:
9013                 np->myaddr = nvram->data.Tekram.host_id & 0x0f;
9014                 break;
9015         default:
9016                 break;
9017         }
9018 #endif
9019 }
9020
9021 /*
9022  *  Get target setup from NVRAM.
9023  */
9024 #ifdef SYM_CONF_NVRAM_SUPPORT
9025 static void sym_Symbios_setup_target(hcb_p np,int target, Symbios_nvram *nvram);
9026 static void sym_Tekram_setup_target(hcb_p np,int target, Tekram_nvram *nvram);
9027 #endif
9028
9029 static void
9030 sym_nvram_setup_target (hcb_p np, int target, struct sym_nvram *nvp)
9031 {
9032 #ifdef SYM_CONF_NVRAM_SUPPORT
9033         switch(nvp->type) {
9034         case SYM_SYMBIOS_NVRAM:
9035                 sym_Symbios_setup_target (np, target, &nvp->data.Symbios);
9036                 break;
9037         case SYM_TEKRAM_NVRAM:
9038                 sym_Tekram_setup_target (np, target, &nvp->data.Tekram);
9039                 break;
9040         default:
9041                 break;
9042         }
9043 #endif
9044 }
9045
9046 #ifdef SYM_CONF_NVRAM_SUPPORT
9047 /*
9048  *  Get target set-up from Symbios format NVRAM.
9049  */
9050 static void
9051 sym_Symbios_setup_target(hcb_p np, int target, Symbios_nvram *nvram)
9052 {
9053         tcb_p tp = &np->target[target];
9054         Symbios_target *tn = &nvram->target[target];
9055
9056         tp->tinfo.user.period = tn->sync_period ? (tn->sync_period + 3) / 4 : 0;
9057         tp->tinfo.user.width  = tn->bus_width == 0x10 ? BUS_16_BIT : BUS_8_BIT;
9058         tp->usrtags =
9059                 (tn->flags & SYMBIOS_QUEUE_TAGS_ENABLED)? SYM_SETUP_MAX_TAG : 0;
9060
9061         if (!(tn->flags & SYMBIOS_DISCONNECT_ENABLE))
9062                 tp->usrflags &= ~SYM_DISC_ENABLED;
9063         if (!(tn->flags & SYMBIOS_SCAN_AT_BOOT_TIME))
9064                 tp->usrflags |= SYM_SCAN_BOOT_DISABLED;
9065         if (!(tn->flags & SYMBIOS_SCAN_LUNS))
9066                 tp->usrflags |= SYM_SCAN_LUNS_DISABLED;
9067 }
9068
9069 /*
9070  *  Get target set-up from Tekram format NVRAM.
9071  */
9072 static void
9073 sym_Tekram_setup_target(hcb_p np, int target, Tekram_nvram *nvram)
9074 {
9075         tcb_p tp = &np->target[target];
9076         struct Tekram_target *tn = &nvram->target[target];
9077         int i;
9078
9079         if (tn->flags & TEKRAM_SYNC_NEGO) {
9080                 i = tn->sync_index & 0xf;
9081                 tp->tinfo.user.period = Tekram_sync[i];
9082         }
9083
9084         tp->tinfo.user.width =
9085                 (tn->flags & TEKRAM_WIDE_NEGO) ? BUS_16_BIT : BUS_8_BIT;
9086
9087         if (tn->flags & TEKRAM_TAGGED_COMMANDS) {
9088                 tp->usrtags = 2 << nvram->max_tags_index;
9089         }
9090
9091         if (tn->flags & TEKRAM_DISCONNECT_ENABLE)
9092                 tp->usrflags |= SYM_DISC_ENABLED;
9093
9094         /* If any device does not support parity, we will not use this option */
9095         if (!(tn->flags & TEKRAM_PARITY_CHECK))
9096                 np->rv_scntl0  &= ~0x0a; /* SCSI parity checking disabled */
9097 }
9098
9099 #ifdef  SYM_CONF_DEBUG_NVRAM
9100 /*
9101  *  Dump Symbios format NVRAM for debugging purpose.
9102  */
9103 static void sym_display_Symbios_nvram(hcb_p np, Symbios_nvram *nvram)
9104 {
9105         int i;
9106
9107         /* display Symbios nvram host data */
9108         printf("%s: HOST ID=%d%s%s%s%s%s%s\n",
9109                 sym_name(np), nvram->host_id & 0x0f,
9110                 (nvram->flags  & SYMBIOS_SCAM_ENABLE)   ? " SCAM"       :"",
9111                 (nvram->flags  & SYMBIOS_PARITY_ENABLE) ? " PARITY"     :"",
9112                 (nvram->flags  & SYMBIOS_VERBOSE_MSGS)  ? " VERBOSE"    :"",
9113                 (nvram->flags  & SYMBIOS_CHS_MAPPING)   ? " CHS_ALT"    :"",
9114                 (nvram->flags2 & SYMBIOS_AVOID_BUS_RESET)?" NO_RESET"   :"",
9115                 (nvram->flags1 & SYMBIOS_SCAN_HI_LO)    ? " HI_LO"      :"");
9116
9117         /* display Symbios nvram drive data */
9118         for (i = 0 ; i < 15 ; i++) {
9119                 struct Symbios_target *tn = &nvram->target[i];
9120                 printf("%s-%d:%s%s%s%s WIDTH=%d SYNC=%d TMO=%d\n",
9121                 sym_name(np), i,
9122                 (tn->flags & SYMBIOS_DISCONNECT_ENABLE) ? " DISC"       : "",
9123                 (tn->flags & SYMBIOS_SCAN_AT_BOOT_TIME) ? " SCAN_BOOT"  : "",
9124                 (tn->flags & SYMBIOS_SCAN_LUNS)         ? " SCAN_LUNS"  : "",
9125                 (tn->flags & SYMBIOS_QUEUE_TAGS_ENABLED)? " TCQ"        : "",
9126                 tn->bus_width,
9127                 tn->sync_period / 4,
9128                 tn->timeout);
9129         }
9130 }
9131
9132 /*
9133  *  Dump TEKRAM format NVRAM for debugging purpose.
9134  */
9135 static const u_char Tekram_boot_delay[7] = {3, 5, 10, 20, 30, 60, 120};
9136 static void sym_display_Tekram_nvram(hcb_p np, Tekram_nvram *nvram)
9137 {
9138         int i, tags, boot_delay;
9139         char *rem;
9140
9141         /* display Tekram nvram host data */
9142         tags = 2 << nvram->max_tags_index;
9143         boot_delay = 0;
9144         if (nvram->boot_delay_index < 6)
9145                 boot_delay = Tekram_boot_delay[nvram->boot_delay_index];
9146         switch((nvram->flags & TEKRAM_REMOVABLE_FLAGS) >> 6) {
9147         default:
9148         case 0: rem = "";                       break;
9149         case 1: rem = " REMOVABLE=boot device"; break;
9150         case 2: rem = " REMOVABLE=all";         break;
9151         }
9152
9153         printf("%s: HOST ID=%d%s%s%s%s%s%s%s%s%s BOOT DELAY=%d tags=%d\n",
9154                 sym_name(np), nvram->host_id & 0x0f,
9155                 (nvram->flags1 & SYMBIOS_SCAM_ENABLE)   ? " SCAM"       :"",
9156                 (nvram->flags & TEKRAM_MORE_THAN_2_DRIVES) ? " >2DRIVES"        :"",
9157                 (nvram->flags & TEKRAM_DRIVES_SUP_1GB)  ? " >1GB"       :"",
9158                 (nvram->flags & TEKRAM_RESET_ON_POWER_ON) ? " RESET"    :"",
9159                 (nvram->flags & TEKRAM_ACTIVE_NEGATION) ? " ACT_NEG"    :"",
9160                 (nvram->flags & TEKRAM_IMMEDIATE_SEEK)  ? " IMM_SEEK"   :"",
9161                 (nvram->flags & TEKRAM_SCAN_LUNS)       ? " SCAN_LUNS"  :"",
9162                 (nvram->flags1 & TEKRAM_F2_F6_ENABLED)  ? " F2_F6"      :"",
9163                 rem, boot_delay, tags);
9164
9165         /* display Tekram nvram drive data */
9166         for (i = 0; i <= 15; i++) {
9167                 int sync, j;
9168                 struct Tekram_target *tn = &nvram->target[i];
9169                 j = tn->sync_index & 0xf;
9170                 sync = Tekram_sync[j];
9171                 printf("%s-%d:%s%s%s%s%s%s PERIOD=%d\n",
9172                 sym_name(np), i,
9173                 (tn->flags & TEKRAM_PARITY_CHECK)       ? " PARITY"     : "",
9174                 (tn->flags & TEKRAM_SYNC_NEGO)          ? " SYNC"       : "",
9175                 (tn->flags & TEKRAM_DISCONNECT_ENABLE)  ? " DISC"       : "",
9176                 (tn->flags & TEKRAM_START_CMD)          ? " START"      : "",
9177                 (tn->flags & TEKRAM_TAGGED_COMMANDS)    ? " TCQ"        : "",
9178                 (tn->flags & TEKRAM_WIDE_NEGO)          ? " WIDE"       : "",
9179                 sync);
9180         }
9181 }
9182 #endif  /* SYM_CONF_DEBUG_NVRAM */
9183 #endif  /* SYM_CONF_NVRAM_SUPPORT */
9184
9185 /*
9186  *  Try reading Symbios or Tekram NVRAM
9187  */
9188 #ifdef SYM_CONF_NVRAM_SUPPORT
9189 static int sym_read_Symbios_nvram (hcb_p np, Symbios_nvram *nvram);
9190 static int sym_read_Tekram_nvram  (hcb_p np, Tekram_nvram *nvram);
9191 #endif
9192
9193 static int sym_read_nvram(hcb_p np, struct sym_nvram *nvp)
9194 {
9195 #ifdef SYM_CONF_NVRAM_SUPPORT
9196         /*
9197          *  Try to read SYMBIOS nvram.
9198          *  Try to read TEKRAM nvram if Symbios nvram not found.
9199          */
9200         if      (SYM_SETUP_SYMBIOS_NVRAM &&
9201                  !sym_read_Symbios_nvram (np, &nvp->data.Symbios)) {
9202                 nvp->type = SYM_SYMBIOS_NVRAM;
9203 #ifdef SYM_CONF_DEBUG_NVRAM
9204                 sym_display_Symbios_nvram(np, &nvp->data.Symbios);
9205 #endif
9206         }
9207         else if (SYM_SETUP_TEKRAM_NVRAM &&
9208                  !sym_read_Tekram_nvram (np, &nvp->data.Tekram)) {
9209                 nvp->type = SYM_TEKRAM_NVRAM;
9210 #ifdef SYM_CONF_DEBUG_NVRAM
9211                 sym_display_Tekram_nvram(np, &nvp->data.Tekram);
9212 #endif
9213         }
9214         else
9215                 nvp->type = 0;
9216 #else
9217         nvp->type = 0;
9218 #endif
9219         return nvp->type;
9220 }
9221
9222 #ifdef SYM_CONF_NVRAM_SUPPORT
9223 /*
9224  *  24C16 EEPROM reading.
9225  *
9226  *  GPOI0 - data in/data out
9227  *  GPIO1 - clock
9228  *  Symbios NVRAM wiring now also used by Tekram.
9229  */
9230
9231 #define SET_BIT 0
9232 #define CLR_BIT 1
9233 #define SET_CLK 2
9234 #define CLR_CLK 3
9235
9236 /*
9237  *  Set/clear data/clock bit in GPIO0
9238  */
9239 static void S24C16_set_bit(hcb_p np, u_char write_bit, u_char *gpreg,
9240                           int bit_mode)
9241 {
9242         UDELAY (5);
9243         switch (bit_mode){
9244         case SET_BIT:
9245                 *gpreg |= write_bit;
9246                 break;
9247         case CLR_BIT:
9248                 *gpreg &= 0xfe;
9249                 break;
9250         case SET_CLK:
9251                 *gpreg |= 0x02;
9252                 break;
9253         case CLR_CLK:
9254                 *gpreg &= 0xfd;
9255                 break;
9256
9257         }
9258         OUTB (nc_gpreg, *gpreg);
9259         UDELAY (5);
9260 }
9261
9262 /*
9263  *  Send START condition to NVRAM to wake it up.
9264  */
9265 static void S24C16_start(hcb_p np, u_char *gpreg)
9266 {
9267         S24C16_set_bit(np, 1, gpreg, SET_BIT);
9268         S24C16_set_bit(np, 0, gpreg, SET_CLK);
9269         S24C16_set_bit(np, 0, gpreg, CLR_BIT);
9270         S24C16_set_bit(np, 0, gpreg, CLR_CLK);
9271 }
9272
9273 /*
9274  *  Send STOP condition to NVRAM - puts NVRAM to sleep... ZZzzzz!!
9275  */
9276 static void S24C16_stop(hcb_p np, u_char *gpreg)
9277 {
9278         S24C16_set_bit(np, 0, gpreg, SET_CLK);
9279         S24C16_set_bit(np, 1, gpreg, SET_BIT);
9280 }
9281
9282 /*
9283  *  Read or write a bit to the NVRAM,
9284  *  read if GPIO0 input else write if GPIO0 output
9285  */
9286 static void S24C16_do_bit(hcb_p np, u_char *read_bit, u_char write_bit,
9287                          u_char *gpreg)
9288 {
9289         S24C16_set_bit(np, write_bit, gpreg, SET_BIT);
9290         S24C16_set_bit(np, 0, gpreg, SET_CLK);
9291         if (read_bit)
9292                 *read_bit = INB (nc_gpreg);
9293         S24C16_set_bit(np, 0, gpreg, CLR_CLK);
9294         S24C16_set_bit(np, 0, gpreg, CLR_BIT);
9295 }
9296
9297 /*
9298  *  Output an ACK to the NVRAM after reading,
9299  *  change GPIO0 to output and when done back to an input
9300  */
9301 static void S24C16_write_ack(hcb_p np, u_char write_bit, u_char *gpreg,
9302                             u_char *gpcntl)
9303 {
9304         OUTB (nc_gpcntl, *gpcntl & 0xfe);
9305         S24C16_do_bit(np, 0, write_bit, gpreg);
9306         OUTB (nc_gpcntl, *gpcntl);
9307 }
9308
9309 /*
9310  *  Input an ACK from NVRAM after writing,
9311  *  change GPIO0 to input and when done back to an output
9312  */
9313 static void S24C16_read_ack(hcb_p np, u_char *read_bit, u_char *gpreg,
9314                            u_char *gpcntl)
9315 {
9316         OUTB (nc_gpcntl, *gpcntl | 0x01);
9317         S24C16_do_bit(np, read_bit, 1, gpreg);
9318         OUTB (nc_gpcntl, *gpcntl);
9319 }
9320
9321 /*
9322  *  WRITE a byte to the NVRAM and then get an ACK to see it was accepted OK,
9323  *  GPIO0 must already be set as an output
9324  */
9325 static void S24C16_write_byte(hcb_p np, u_char *ack_data, u_char write_data,
9326                              u_char *gpreg, u_char *gpcntl)
9327 {
9328         int x;
9329
9330         for (x = 0; x < 8; x++)
9331                 S24C16_do_bit(np, 0, (write_data >> (7 - x)) & 0x01, gpreg);
9332
9333         S24C16_read_ack(np, ack_data, gpreg, gpcntl);
9334 }
9335
9336 /*
9337  *  READ a byte from the NVRAM and then send an ACK to say we have got it,
9338  *  GPIO0 must already be set as an input
9339  */
9340 static void S24C16_read_byte(hcb_p np, u_char *read_data, u_char ack_data,
9341                             u_char *gpreg, u_char *gpcntl)
9342 {
9343         int x;
9344         u_char read_bit;
9345
9346         *read_data = 0;
9347         for (x = 0; x < 8; x++) {
9348                 S24C16_do_bit(np, &read_bit, 1, gpreg);
9349                 *read_data |= ((read_bit & 0x01) << (7 - x));
9350         }
9351
9352         S24C16_write_ack(np, ack_data, gpreg, gpcntl);
9353 }
9354
9355 /*
9356  *  Read 'len' bytes starting at 'offset'.
9357  */
9358 static int sym_read_S24C16_nvram (hcb_p np, int offset, u_char *data, int len)
9359 {
9360         u_char  gpcntl, gpreg;
9361         u_char  old_gpcntl, old_gpreg;
9362         u_char  ack_data;
9363         int     retv = 1;
9364         int     x;
9365
9366         /* save current state of GPCNTL and GPREG */
9367         old_gpreg       = INB (nc_gpreg);
9368         old_gpcntl      = INB (nc_gpcntl);
9369         gpcntl          = old_gpcntl & 0x1c;
9370
9371         /* set up GPREG & GPCNTL to set GPIO0 and GPIO1 in to known state */
9372         OUTB (nc_gpreg,  old_gpreg);
9373         OUTB (nc_gpcntl, gpcntl);
9374
9375         /* this is to set NVRAM into a known state with GPIO0/1 both low */
9376         gpreg = old_gpreg;
9377         S24C16_set_bit(np, 0, &gpreg, CLR_CLK);
9378         S24C16_set_bit(np, 0, &gpreg, CLR_BIT);
9379
9380         /* now set NVRAM inactive with GPIO0/1 both high */
9381         S24C16_stop(np, &gpreg);
9382
9383         /* activate NVRAM */
9384         S24C16_start(np, &gpreg);
9385
9386         /* write device code and random address MSB */
9387         S24C16_write_byte(np, &ack_data,
9388                 0xa0 | ((offset >> 7) & 0x0e), &gpreg, &gpcntl);
9389         if (ack_data & 0x01)
9390                 goto out;
9391
9392         /* write random address LSB */
9393         S24C16_write_byte(np, &ack_data,
9394                 offset & 0xff, &gpreg, &gpcntl);
9395         if (ack_data & 0x01)
9396                 goto out;
9397
9398         /* regenerate START state to set up for reading */
9399         S24C16_start(np, &gpreg);
9400
9401         /* rewrite device code and address MSB with read bit set (lsb = 0x01) */
9402         S24C16_write_byte(np, &ack_data,
9403                 0xa1 | ((offset >> 7) & 0x0e), &gpreg, &gpcntl);
9404         if (ack_data & 0x01)
9405                 goto out;
9406
9407         /* now set up GPIO0 for inputting data */
9408         gpcntl |= 0x01;
9409         OUTB (nc_gpcntl, gpcntl);
9410
9411         /* input all requested data - only part of total NVRAM */
9412         for (x = 0; x < len; x++)
9413                 S24C16_read_byte(np, &data[x], (x == (len-1)), &gpreg, &gpcntl);
9414
9415         /* finally put NVRAM back in inactive mode */
9416         gpcntl &= 0xfe;
9417         OUTB (nc_gpcntl, gpcntl);
9418         S24C16_stop(np, &gpreg);
9419         retv = 0;
9420 out:
9421         /* return GPIO0/1 to original states after having accessed NVRAM */
9422         OUTB (nc_gpcntl, old_gpcntl);
9423         OUTB (nc_gpreg,  old_gpreg);
9424
9425         return retv;
9426 }
9427
9428 #undef SET_BIT /* 0 */
9429 #undef CLR_BIT /* 1 */
9430 #undef SET_CLK /* 2 */
9431 #undef CLR_CLK /* 3 */
9432
9433 /*
9434  *  Try reading Symbios NVRAM.
9435  *  Return 0 if OK.
9436  */
9437 static int sym_read_Symbios_nvram (hcb_p np, Symbios_nvram *nvram)
9438 {
9439         static u_char Symbios_trailer[6] = {0xfe, 0xfe, 0, 0, 0, 0};
9440         u_char *data = (u_char *) nvram;
9441         int len  = sizeof(*nvram);
9442         u_short csum;
9443         int x;
9444
9445         /* probe the 24c16 and read the SYMBIOS 24c16 area */
9446         if (sym_read_S24C16_nvram (np, SYMBIOS_NVRAM_ADDRESS, data, len))
9447                 return 1;
9448
9449         /* check valid NVRAM signature, verify byte count and checksum */
9450         if (nvram->type != 0 ||
9451             bcmp(nvram->trailer, Symbios_trailer, 6) ||
9452             nvram->byte_count != len - 12)
9453                 return 1;
9454
9455         /* verify checksum */
9456         for (x = 6, csum = 0; x < len - 6; x++)
9457                 csum += data[x];
9458         if (csum != nvram->checksum)
9459                 return 1;
9460
9461         return 0;
9462 }
9463
9464 /*
9465  *  93C46 EEPROM reading.
9466  *
9467  *  GPOI0 - data in
9468  *  GPIO1 - data out
9469  *  GPIO2 - clock
9470  *  GPIO4 - chip select
9471  *
9472  *  Used by Tekram.
9473  */
9474
9475 /*
9476  *  Pulse clock bit in GPIO0
9477  */
9478 static void T93C46_Clk(hcb_p np, u_char *gpreg)
9479 {
9480         OUTB (nc_gpreg, *gpreg | 0x04);
9481         UDELAY (2);
9482         OUTB (nc_gpreg, *gpreg);
9483 }
9484
9485 /*
9486  *  Read bit from NVRAM
9487  */
9488 static void T93C46_Read_Bit(hcb_p np, u_char *read_bit, u_char *gpreg)
9489 {
9490         UDELAY (2);
9491         T93C46_Clk(np, gpreg);
9492         *read_bit = INB (nc_gpreg);
9493 }
9494
9495 /*
9496  *  Write bit to GPIO0
9497  */
9498 static void T93C46_Write_Bit(hcb_p np, u_char write_bit, u_char *gpreg)
9499 {
9500         if (write_bit & 0x01)
9501                 *gpreg |= 0x02;
9502         else
9503                 *gpreg &= 0xfd;
9504
9505         *gpreg |= 0x10;
9506
9507         OUTB (nc_gpreg, *gpreg);
9508         UDELAY (2);
9509
9510         T93C46_Clk(np, gpreg);
9511 }
9512
9513 /*
9514  *  Send STOP condition to NVRAM - puts NVRAM to sleep... ZZZzzz!!
9515  */
9516 static void T93C46_Stop(hcb_p np, u_char *gpreg)
9517 {
9518         *gpreg &= 0xef;
9519         OUTB (nc_gpreg, *gpreg);
9520         UDELAY (2);
9521
9522         T93C46_Clk(np, gpreg);
9523 }
9524
9525 /*
9526  *  Send read command and address to NVRAM
9527  */
9528 static void T93C46_Send_Command(hcb_p np, u_short write_data,
9529                                 u_char *read_bit, u_char *gpreg)
9530 {
9531         int x;
9532
9533         /* send 9 bits, start bit (1), command (2), address (6)  */
9534         for (x = 0; x < 9; x++)
9535                 T93C46_Write_Bit(np, (u_char) (write_data >> (8 - x)), gpreg);
9536
9537         *read_bit = INB (nc_gpreg);
9538 }
9539
9540 /*
9541  *  READ 2 bytes from the NVRAM
9542  */
9543 static void T93C46_Read_Word(hcb_p np, u_short *nvram_data, u_char *gpreg)
9544 {
9545         int x;
9546         u_char read_bit;
9547
9548         *nvram_data = 0;
9549         for (x = 0; x < 16; x++) {
9550                 T93C46_Read_Bit(np, &read_bit, gpreg);
9551
9552                 if (read_bit & 0x01)
9553                         *nvram_data |=  (0x01 << (15 - x));
9554                 else
9555                         *nvram_data &= ~(0x01 << (15 - x));
9556         }
9557 }
9558
9559 /*
9560  *  Read Tekram NvRAM data.
9561  */
9562 static int T93C46_Read_Data(hcb_p np, u_short *data,int len,u_char *gpreg)
9563 {
9564         u_char  read_bit;
9565         int     x;
9566
9567         for (x = 0; x < len; x++)  {
9568
9569                 /* output read command and address */
9570                 T93C46_Send_Command(np, 0x180 | x, &read_bit, gpreg);
9571                 if (read_bit & 0x01)
9572                         return 1; /* Bad */
9573                 T93C46_Read_Word(np, &data[x], gpreg);
9574                 T93C46_Stop(np, gpreg);
9575         }
9576
9577         return 0;
9578 }
9579
9580 /*
9581  *  Try reading 93C46 Tekram NVRAM.
9582  */
9583 static int sym_read_T93C46_nvram (hcb_p np, Tekram_nvram *nvram)
9584 {
9585         u_char gpcntl, gpreg;
9586         u_char old_gpcntl, old_gpreg;
9587         int retv = 1;
9588
9589         /* save current state of GPCNTL and GPREG */
9590         old_gpreg       = INB (nc_gpreg);
9591         old_gpcntl      = INB (nc_gpcntl);
9592
9593         /* set up GPREG & GPCNTL to set GPIO0/1/2/4 in to known state, 0 in,
9594            1/2/4 out */
9595         gpreg = old_gpreg & 0xe9;
9596         OUTB (nc_gpreg, gpreg);
9597         gpcntl = (old_gpcntl & 0xe9) | 0x09;
9598         OUTB (nc_gpcntl, gpcntl);
9599
9600         /* input all of NVRAM, 64 words */
9601         retv = T93C46_Read_Data(np, (u_short *) nvram,
9602                                 sizeof(*nvram) / sizeof(short), &gpreg);
9603
9604         /* return GPIO0/1/2/4 to original states after having accessed NVRAM */
9605         OUTB (nc_gpcntl, old_gpcntl);
9606         OUTB (nc_gpreg,  old_gpreg);
9607
9608         return retv;
9609 }
9610
9611 /*
9612  *  Try reading Tekram NVRAM.
9613  *  Return 0 if OK.
9614  */
9615 static int sym_read_Tekram_nvram (hcb_p np, Tekram_nvram *nvram)
9616 {
9617         u_char *data = (u_char *) nvram;
9618         int len = sizeof(*nvram);
9619         u_short csum;
9620         int x;
9621
9622         switch (np->device_id) {
9623         case PCI_ID_SYM53C885:
9624         case PCI_ID_SYM53C895:
9625         case PCI_ID_SYM53C896:
9626                 x = sym_read_S24C16_nvram(np, TEKRAM_24C16_NVRAM_ADDRESS,
9627                                           data, len);
9628                 break;
9629         case PCI_ID_SYM53C875:
9630                 x = sym_read_S24C16_nvram(np, TEKRAM_24C16_NVRAM_ADDRESS,
9631                                           data, len);
9632                 if (!x)
9633                         break;
9634         default:
9635                 x = sym_read_T93C46_nvram(np, nvram);
9636                 break;
9637         }
9638         if (x)
9639                 return 1;
9640
9641         /* verify checksum */
9642         for (x = 0, csum = 0; x < len - 1; x += 2)
9643                 csum += data[x] + (data[x+1] << 8);
9644         if (csum != 0x1234)
9645                 return 1;
9646
9647         return 0;
9648 }
9649
9650 #endif  /* SYM_CONF_NVRAM_SUPPORT */