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