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