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