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