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