The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/dev/sym/sym_hipd.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

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

Cache object: 8baa16514934edda52886f3ec2dffd5c


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.