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