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