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