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