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