linux/drivers/scsi/ncr53c8xx.c
<<
>>
Prefs
   1/******************************************************************************
   2**  Device driver for the PCI-SCSI NCR538XX controller family.
   3**
   4**  Copyright (C) 1994  Wolfgang Stanglmeier
   5**
   6**  This program is free software; you can redistribute it and/or modify
   7**  it under the terms of the GNU General Public License as published by
   8**  the Free Software Foundation; either version 2 of the License, or
   9**  (at your option) any later version.
  10**
  11**  This program is distributed in the hope that it will be useful,
  12**  but WITHOUT ANY WARRANTY; without even the implied warranty of
  13**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14**  GNU General Public License for more details.
  15**
  16**  You should have received a copy of the GNU General Public License
  17**  along with this program; if not, write to the Free Software
  18**  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  19**
  20**-----------------------------------------------------------------------------
  21**
  22**  This driver has been ported to Linux from the FreeBSD NCR53C8XX driver
  23**  and is currently maintained by
  24**
  25**          Gerard Roudier              <groudier@free.fr>
  26**
  27**  Being given that this driver originates from the FreeBSD version, and
  28**  in order to keep synergy on both, any suggested enhancements and corrections
  29**  received on Linux are automatically a potential candidate for the FreeBSD 
  30**  version.
  31**
  32**  The original driver has been written for 386bsd and FreeBSD by
  33**          Wolfgang Stanglmeier        <wolf@cologne.de>
  34**          Stefan Esser                <se@mi.Uni-Koeln.de>
  35**
  36**  And has been ported to NetBSD by
  37**          Charles M. Hannum           <mycroft@gnu.ai.mit.edu>
  38**
  39**-----------------------------------------------------------------------------
  40**
  41**                     Brief history
  42**
  43**  December 10 1995 by Gerard Roudier:
  44**     Initial port to Linux.
  45**
  46**  June 23 1996 by Gerard Roudier:
  47**     Support for 64 bits architectures (Alpha).
  48**
  49**  November 30 1996 by Gerard Roudier:
  50**     Support for Fast-20 scsi.
  51**     Support for large DMA fifo and 128 dwords bursting.
  52**
  53**  February 27 1997 by Gerard Roudier:
  54**     Support for Fast-40 scsi.
  55**     Support for on-Board RAM.
  56**
  57**  May 3 1997 by Gerard Roudier:
  58**     Full support for scsi scripts instructions pre-fetching.
  59**
  60**  May 19 1997 by Richard Waltham <dormouse@farsrobt.demon.co.uk>:
  61**     Support for NvRAM detection and reading.
  62**
  63**  August 18 1997 by Cort <cort@cs.nmt.edu>:
  64**     Support for Power/PC (Big Endian).
  65**
  66**  June 20 1998 by Gerard Roudier
  67**     Support for up to 64 tags per lun.
  68**     O(1) everywhere (C and SCRIPTS) for normal cases.
  69**     Low PCI traffic for command handling when on-chip RAM is present.
  70**     Aggressive SCSI SCRIPTS optimizations.
  71**
  72**  2005 by Matthew Wilcox and James Bottomley
  73**     PCI-ectomy.  This driver now supports only the 720 chip (see the
  74**     NCR_Q720 and zalon drivers for the bus probe logic).
  75**
  76*******************************************************************************
  77*/
  78
  79/*
  80**      Supported SCSI-II features:
  81**          Synchronous negotiation
  82**          Wide negotiation        (depends on the NCR Chip)
  83**          Enable disconnection
  84**          Tagged command queuing
  85**          Parity checking
  86**          Etc...
  87**
  88**      Supported NCR/SYMBIOS chips:
  89**              53C720          (Wide,   Fast SCSI-2, intfly problems)
  90*/
  91
  92/* Name and version of the driver */
  93#define SCSI_NCR_DRIVER_NAME    "ncr53c8xx-3.4.3g"
  94
  95#define SCSI_NCR_DEBUG_FLAGS    (0)
  96
  97#include <linux/blkdev.h>
  98#include <linux/delay.h>
  99#include <linux/dma-mapping.h>
 100#include <linux/errno.h>
 101#include <linux/gfp.h>
 102#include <linux/init.h>
 103#include <linux/interrupt.h>
 104#include <linux/ioport.h>
 105#include <linux/mm.h>
 106#include <linux/module.h>
 107#include <linux/sched.h>
 108#include <linux/signal.h>
 109#include <linux/spinlock.h>
 110#include <linux/stat.h>
 111#include <linux/string.h>
 112#include <linux/time.h>
 113#include <linux/timer.h>
 114#include <linux/types.h>
 115
 116#include <asm/dma.h>
 117#include <asm/io.h>
 118
 119#include <scsi/scsi.h>
 120#include <scsi/scsi_cmnd.h>
 121#include <scsi/scsi_dbg.h>
 122#include <scsi/scsi_device.h>
 123#include <scsi/scsi_tcq.h>
 124#include <scsi/scsi_transport.h>
 125#include <scsi/scsi_transport_spi.h>
 126
 127#include "ncr53c8xx.h"
 128
 129#define NAME53C8XX              "ncr53c8xx"
 130
 131/*==========================================================
 132**
 133**      Debugging tags
 134**
 135**==========================================================
 136*/
 137
 138#define DEBUG_ALLOC    (0x0001)
 139#define DEBUG_PHASE    (0x0002)
 140#define DEBUG_QUEUE    (0x0008)
 141#define DEBUG_RESULT   (0x0010)
 142#define DEBUG_POINTER  (0x0020)
 143#define DEBUG_SCRIPT   (0x0040)
 144#define DEBUG_TINY     (0x0080)
 145#define DEBUG_TIMING   (0x0100)
 146#define DEBUG_NEGO     (0x0200)
 147#define DEBUG_TAGS     (0x0400)
 148#define DEBUG_SCATTER  (0x0800)
 149#define DEBUG_IC        (0x1000)
 150
 151/*
 152**    Enable/Disable debug messages.
 153**    Can be changed at runtime too.
 154*/
 155
 156#ifdef SCSI_NCR_DEBUG_INFO_SUPPORT
 157static int ncr_debug = SCSI_NCR_DEBUG_FLAGS;
 158        #define DEBUG_FLAGS ncr_debug
 159#else
 160        #define DEBUG_FLAGS     SCSI_NCR_DEBUG_FLAGS
 161#endif
 162
 163static inline struct list_head *ncr_list_pop(struct list_head *head)
 164{
 165        if (!list_empty(head)) {
 166                struct list_head *elem = head->next;
 167
 168                list_del(elem);
 169                return elem;
 170        }
 171
 172        return NULL;
 173}
 174
 175/*==========================================================
 176**
 177**      Simple power of two buddy-like allocator.
 178**
 179**      This simple code is not intended to be fast, but to 
 180**      provide power of 2 aligned memory allocations.
 181**      Since the SCRIPTS processor only supplies 8 bit 
 182**      arithmetic, this allocator allows simple and fast 
 183**      address calculations  from the SCRIPTS code.
 184**      In addition, cache line alignment is guaranteed for 
 185**      power of 2 cache line size.
 186**      Enhanced in linux-2.3.44 to provide a memory pool 
 187**      per pcidev to support dynamic dma mapping. (I would 
 188**      have preferred a real bus abstraction, btw).
 189**
 190**==========================================================
 191*/
 192
 193#define MEMO_SHIFT      4       /* 16 bytes minimum memory chunk */
 194#if PAGE_SIZE >= 8192
 195#define MEMO_PAGE_ORDER 0       /* 1 PAGE  maximum */
 196#else
 197#define MEMO_PAGE_ORDER 1       /* 2 PAGES maximum */
 198#endif
 199#define MEMO_FREE_UNUSED        /* Free unused pages immediately */
 200#define MEMO_WARN       1
 201#define MEMO_GFP_FLAGS  GFP_ATOMIC
 202#define MEMO_CLUSTER_SHIFT      (PAGE_SHIFT+MEMO_PAGE_ORDER)
 203#define MEMO_CLUSTER_SIZE       (1UL << MEMO_CLUSTER_SHIFT)
 204#define MEMO_CLUSTER_MASK       (MEMO_CLUSTER_SIZE-1)
 205
 206typedef u_long m_addr_t;        /* Enough bits to bit-hack addresses */
 207typedef struct device *m_bush_t;        /* Something that addresses DMAable */
 208
 209typedef struct m_link {         /* Link between free memory chunks */
 210        struct m_link *next;
 211} m_link_s;
 212
 213typedef struct m_vtob {         /* Virtual to Bus address translation */
 214        struct m_vtob *next;
 215        m_addr_t vaddr;
 216        m_addr_t baddr;
 217} m_vtob_s;
 218#define VTOB_HASH_SHIFT         5
 219#define VTOB_HASH_SIZE          (1UL << VTOB_HASH_SHIFT)
 220#define VTOB_HASH_MASK          (VTOB_HASH_SIZE-1)
 221#define VTOB_HASH_CODE(m)       \
 222        ((((m_addr_t) (m)) >> MEMO_CLUSTER_SHIFT) & VTOB_HASH_MASK)
 223
 224typedef struct m_pool {         /* Memory pool of a given kind */
 225        m_bush_t bush;
 226        m_addr_t (*getp)(struct m_pool *);
 227        void (*freep)(struct m_pool *, m_addr_t);
 228        int nump;
 229        m_vtob_s *(vtob[VTOB_HASH_SIZE]);
 230        struct m_pool *next;
 231        struct m_link h[PAGE_SHIFT-MEMO_SHIFT+MEMO_PAGE_ORDER+1];
 232} m_pool_s;
 233
 234static void *___m_alloc(m_pool_s *mp, int size)
 235{
 236        int i = 0;
 237        int s = (1 << MEMO_SHIFT);
 238        int j;
 239        m_addr_t a;
 240        m_link_s *h = mp->h;
 241
 242        if (size > (PAGE_SIZE << MEMO_PAGE_ORDER))
 243                return NULL;
 244
 245        while (size > s) {
 246                s <<= 1;
 247                ++i;
 248        }
 249
 250        j = i;
 251        while (!h[j].next) {
 252                if (s == (PAGE_SIZE << MEMO_PAGE_ORDER)) {
 253                        h[j].next = (m_link_s *)mp->getp(mp);
 254                        if (h[j].next)
 255                                h[j].next->next = NULL;
 256                        break;
 257                }
 258                ++j;
 259                s <<= 1;
 260        }
 261        a = (m_addr_t) h[j].next;
 262        if (a) {
 263                h[j].next = h[j].next->next;
 264                while (j > i) {
 265                        j -= 1;
 266                        s >>= 1;
 267                        h[j].next = (m_link_s *) (a+s);
 268                        h[j].next->next = NULL;
 269                }
 270        }
 271#ifdef DEBUG
 272        printk("___m_alloc(%d) = %p\n", size, (void *) a);
 273#endif
 274        return (void *) a;
 275}
 276
 277static void ___m_free(m_pool_s *mp, void *ptr, int size)
 278{
 279        int i = 0;
 280        int s = (1 << MEMO_SHIFT);
 281        m_link_s *q;
 282        m_addr_t a, b;
 283        m_link_s *h = mp->h;
 284
 285#ifdef DEBUG
 286        printk("___m_free(%p, %d)\n", ptr, size);
 287#endif
 288
 289        if (size > (PAGE_SIZE << MEMO_PAGE_ORDER))
 290                return;
 291
 292        while (size > s) {
 293                s <<= 1;
 294                ++i;
 295        }
 296
 297        a = (m_addr_t) ptr;
 298
 299        while (1) {
 300#ifdef MEMO_FREE_UNUSED
 301                if (s == (PAGE_SIZE << MEMO_PAGE_ORDER)) {
 302                        mp->freep(mp, a);
 303                        break;
 304                }
 305#endif
 306                b = a ^ s;
 307                q = &h[i];
 308                while (q->next && q->next != (m_link_s *) b) {
 309                        q = q->next;
 310                }
 311                if (!q->next) {
 312                        ((m_link_s *) a)->next = h[i].next;
 313                        h[i].next = (m_link_s *) a;
 314                        break;
 315                }
 316                q->next = q->next->next;
 317                a = a & b;
 318                s <<= 1;
 319                ++i;
 320        }
 321}
 322
 323static DEFINE_SPINLOCK(ncr53c8xx_lock);
 324
 325static void *__m_calloc2(m_pool_s *mp, int size, char *name, int uflags)
 326{
 327        void *p;
 328
 329        p = ___m_alloc(mp, size);
 330
 331        if (DEBUG_FLAGS & DEBUG_ALLOC)
 332                printk ("new %-10s[%4d] @%p.\n", name, size, p);
 333
 334        if (p)
 335                memset(p, 0, size);
 336        else if (uflags & MEMO_WARN)
 337                printk (NAME53C8XX ": failed to allocate %s[%d]\n", name, size);
 338
 339        return p;
 340}
 341
 342#define __m_calloc(mp, s, n)    __m_calloc2(mp, s, n, MEMO_WARN)
 343
 344static void __m_free(m_pool_s *mp, void *ptr, int size, char *name)
 345{
 346        if (DEBUG_FLAGS & DEBUG_ALLOC)
 347                printk ("freeing %-10s[%4d] @%p.\n", name, size, ptr);
 348
 349        ___m_free(mp, ptr, size);
 350
 351}
 352
 353/*
 354 * With pci bus iommu support, we use a default pool of unmapped memory 
 355 * for memory we donnot need to DMA from/to and one pool per pcidev for 
 356 * memory accessed by the PCI chip. `mp0' is the default not DMAable pool.
 357 */
 358
 359static m_addr_t ___mp0_getp(m_pool_s *mp)
 360{
 361        m_addr_t m = __get_free_pages(MEMO_GFP_FLAGS, MEMO_PAGE_ORDER);
 362        if (m)
 363                ++mp->nump;
 364        return m;
 365}
 366
 367static void ___mp0_freep(m_pool_s *mp, m_addr_t m)
 368{
 369        free_pages(m, MEMO_PAGE_ORDER);
 370        --mp->nump;
 371}
 372
 373static m_pool_s mp0 = {NULL, ___mp0_getp, ___mp0_freep};
 374
 375/*
 376 * DMAable pools.
 377 */
 378
 379/*
 380 * With pci bus iommu support, we maintain one pool per pcidev and a 
 381 * hashed reverse table for virtual to bus physical address translations.
 382 */
 383static m_addr_t ___dma_getp(m_pool_s *mp)
 384{
 385        m_addr_t vp;
 386        m_vtob_s *vbp;
 387
 388        vbp = __m_calloc(&mp0, sizeof(*vbp), "VTOB");
 389        if (vbp) {
 390                dma_addr_t daddr;
 391                vp = (m_addr_t) dma_alloc_coherent(mp->bush,
 392                                                PAGE_SIZE<<MEMO_PAGE_ORDER,
 393                                                &daddr, GFP_ATOMIC);
 394                if (vp) {
 395                        int hc = VTOB_HASH_CODE(vp);
 396                        vbp->vaddr = vp;
 397                        vbp->baddr = daddr;
 398                        vbp->next = mp->vtob[hc];
 399                        mp->vtob[hc] = vbp;
 400                        ++mp->nump;
 401                        return vp;
 402                }
 403        }
 404        if (vbp)
 405                __m_free(&mp0, vbp, sizeof(*vbp), "VTOB");
 406        return 0;
 407}
 408
 409static void ___dma_freep(m_pool_s *mp, m_addr_t m)
 410{
 411        m_vtob_s **vbpp, *vbp;
 412        int hc = VTOB_HASH_CODE(m);
 413
 414        vbpp = &mp->vtob[hc];
 415        while (*vbpp && (*vbpp)->vaddr != m)
 416                vbpp = &(*vbpp)->next;
 417        if (*vbpp) {
 418                vbp = *vbpp;
 419                *vbpp = (*vbpp)->next;
 420                dma_free_coherent(mp->bush, PAGE_SIZE<<MEMO_PAGE_ORDER,
 421                                  (void *)vbp->vaddr, (dma_addr_t)vbp->baddr);
 422                __m_free(&mp0, vbp, sizeof(*vbp), "VTOB");
 423                --mp->nump;
 424        }
 425}
 426
 427static inline m_pool_s *___get_dma_pool(m_bush_t bush)
 428{
 429        m_pool_s *mp;
 430        for (mp = mp0.next; mp && mp->bush != bush; mp = mp->next);
 431        return mp;
 432}
 433
 434static m_pool_s *___cre_dma_pool(m_bush_t bush)
 435{
 436        m_pool_s *mp;
 437        mp = __m_calloc(&mp0, sizeof(*mp), "MPOOL");
 438        if (mp) {
 439                memset(mp, 0, sizeof(*mp));
 440                mp->bush = bush;
 441                mp->getp = ___dma_getp;
 442                mp->freep = ___dma_freep;
 443                mp->next = mp0.next;
 444                mp0.next = mp;
 445        }
 446        return mp;
 447}
 448
 449static void ___del_dma_pool(m_pool_s *p)
 450{
 451        struct m_pool **pp = &mp0.next;
 452
 453        while (*pp && *pp != p)
 454                pp = &(*pp)->next;
 455        if (*pp) {
 456                *pp = (*pp)->next;
 457                __m_free(&mp0, p, sizeof(*p), "MPOOL");
 458        }
 459}
 460
 461static void *__m_calloc_dma(m_bush_t bush, int size, char *name)
 462{
 463        u_long flags;
 464        struct m_pool *mp;
 465        void *m = NULL;
 466
 467        spin_lock_irqsave(&ncr53c8xx_lock, flags);
 468        mp = ___get_dma_pool(bush);
 469        if (!mp)
 470                mp = ___cre_dma_pool(bush);
 471        if (mp)
 472                m = __m_calloc(mp, size, name);
 473        if (mp && !mp->nump)
 474                ___del_dma_pool(mp);
 475        spin_unlock_irqrestore(&ncr53c8xx_lock, flags);
 476
 477        return m;
 478}
 479
 480static void __m_free_dma(m_bush_t bush, void *m, int size, char *name)
 481{
 482        u_long flags;
 483        struct m_pool *mp;
 484
 485        spin_lock_irqsave(&ncr53c8xx_lock, flags);
 486        mp = ___get_dma_pool(bush);
 487        if (mp)
 488                __m_free(mp, m, size, name);
 489        if (mp && !mp->nump)
 490                ___del_dma_pool(mp);
 491        spin_unlock_irqrestore(&ncr53c8xx_lock, flags);
 492}
 493
 494static m_addr_t __vtobus(m_bush_t bush, void *m)
 495{
 496        u_long flags;
 497        m_pool_s *mp;
 498        int hc = VTOB_HASH_CODE(m);
 499        m_vtob_s *vp = NULL;
 500        m_addr_t a = ((m_addr_t) m) & ~MEMO_CLUSTER_MASK;
 501
 502        spin_lock_irqsave(&ncr53c8xx_lock, flags);
 503        mp = ___get_dma_pool(bush);
 504        if (mp) {
 505                vp = mp->vtob[hc];
 506                while (vp && (m_addr_t) vp->vaddr != a)
 507                        vp = vp->next;
 508        }
 509        spin_unlock_irqrestore(&ncr53c8xx_lock, flags);
 510        return vp ? vp->baddr + (((m_addr_t) m) - a) : 0;
 511}
 512
 513#define _m_calloc_dma(np, s, n)         __m_calloc_dma(np->dev, s, n)
 514#define _m_free_dma(np, p, s, n)        __m_free_dma(np->dev, p, s, n)
 515#define m_calloc_dma(s, n)              _m_calloc_dma(np, s, n)
 516#define m_free_dma(p, s, n)             _m_free_dma(np, p, s, n)
 517#define _vtobus(np, p)                  __vtobus(np->dev, p)
 518#define vtobus(p)                       _vtobus(np, p)
 519
 520/*
 521 *  Deal with DMA mapping/unmapping.
 522 */
 523
 524/* To keep track of the dma mapping (sg/single) that has been set */
 525#define __data_mapped   SCp.phase
 526#define __data_mapping  SCp.have_data_in
 527
 528static void __unmap_scsi_data(struct device *dev, struct scsi_cmnd *cmd)
 529{
 530        switch(cmd->__data_mapped) {
 531        case 2:
 532                scsi_dma_unmap(cmd);
 533                break;
 534        }
 535        cmd->__data_mapped = 0;
 536}
 537
 538static int __map_scsi_sg_data(struct device *dev, struct scsi_cmnd *cmd)
 539{
 540        int use_sg;
 541
 542        use_sg = scsi_dma_map(cmd);
 543        if (!use_sg)
 544                return 0;
 545
 546        cmd->__data_mapped = 2;
 547        cmd->__data_mapping = use_sg;
 548
 549        return use_sg;
 550}
 551
 552#define unmap_scsi_data(np, cmd)        __unmap_scsi_data(np->dev, cmd)
 553#define map_scsi_sg_data(np, cmd)       __map_scsi_sg_data(np->dev, cmd)
 554
 555/*==========================================================
 556**
 557**      Driver setup.
 558**
 559**      This structure is initialized from linux config 
 560**      options. It can be overridden at boot-up by the boot 
 561**      command line.
 562**
 563**==========================================================
 564*/
 565static struct ncr_driver_setup
 566        driver_setup                    = SCSI_NCR_DRIVER_SETUP;
 567
 568#ifndef MODULE
 569#ifdef  SCSI_NCR_BOOT_COMMAND_LINE_SUPPORT
 570static struct ncr_driver_setup
 571        driver_safe_setup __initdata    = SCSI_NCR_DRIVER_SAFE_SETUP;
 572#endif
 573#endif /* !MODULE */
 574
 575#define initverbose (driver_setup.verbose)
 576#define bootverbose (np->verbose)
 577
 578
 579/*===================================================================
 580**
 581**      Driver setup from the boot command line
 582**
 583**===================================================================
 584*/
 585
 586#ifdef MODULE
 587#define ARG_SEP ' '
 588#else
 589#define ARG_SEP ','
 590#endif
 591
 592#define OPT_TAGS                1
 593#define OPT_MASTER_PARITY       2
 594#define OPT_SCSI_PARITY         3
 595#define OPT_DISCONNECTION       4
 596#define OPT_SPECIAL_FEATURES    5
 597#define OPT_UNUSED_1            6
 598#define OPT_FORCE_SYNC_NEGO     7
 599#define OPT_REVERSE_PROBE       8
 600#define OPT_DEFAULT_SYNC        9
 601#define OPT_VERBOSE             10
 602#define OPT_DEBUG               11
 603#define OPT_BURST_MAX           12
 604#define OPT_LED_PIN             13
 605#define OPT_MAX_WIDE            14
 606#define OPT_SETTLE_DELAY        15
 607#define OPT_DIFF_SUPPORT        16
 608#define OPT_IRQM                17
 609#define OPT_PCI_FIX_UP          18
 610#define OPT_BUS_CHECK           19
 611#define OPT_OPTIMIZE            20
 612#define OPT_RECOVERY            21
 613#define OPT_SAFE_SETUP          22
 614#define OPT_USE_NVRAM           23
 615#define OPT_EXCLUDE             24
 616#define OPT_HOST_ID             25
 617
 618#ifdef SCSI_NCR_IARB_SUPPORT
 619#define OPT_IARB                26
 620#endif
 621
 622#ifdef MODULE
 623#define ARG_SEP ' '
 624#else
 625#define ARG_SEP ','
 626#endif
 627
 628#ifndef MODULE
 629static char setup_token[] __initdata = 
 630        "tags:"   "mpar:"
 631        "spar:"   "disc:"
 632        "specf:"  "ultra:"
 633        "fsn:"    "revprob:"
 634        "sync:"   "verb:"
 635        "debug:"  "burst:"
 636        "led:"    "wide:"
 637        "settle:" "diff:"
 638        "irqm:"   "pcifix:"
 639        "buschk:" "optim:"
 640        "recovery:"
 641        "safe:"   "nvram:"
 642        "excl:"   "hostid:"
 643#ifdef SCSI_NCR_IARB_SUPPORT
 644        "iarb:"
 645#endif
 646        ;       /* DONNOT REMOVE THIS ';' */
 647
 648static int __init get_setup_token(char *p)
 649{
 650        char *cur = setup_token;
 651        char *pc;
 652        int i = 0;
 653
 654        while (cur != NULL && (pc = strchr(cur, ':')) != NULL) {
 655                ++pc;
 656                ++i;
 657                if (!strncmp(p, cur, pc - cur))
 658                        return i;
 659                cur = pc;
 660        }
 661        return 0;
 662}
 663
 664static int __init sym53c8xx__setup(char *str)
 665{
 666#ifdef SCSI_NCR_BOOT_COMMAND_LINE_SUPPORT
 667        char *cur = str;
 668        char *pc, *pv;
 669        int i, val, c;
 670        int xi = 0;
 671
 672        while (cur != NULL && (pc = strchr(cur, ':')) != NULL) {
 673                char *pe;
 674
 675                val = 0;
 676                pv = pc;
 677                c = *++pv;
 678
 679                if      (c == 'n')
 680                        val = 0;
 681                else if (c == 'y')
 682                        val = 1;
 683                else
 684                        val = (int) simple_strtoul(pv, &pe, 0);
 685
 686                switch (get_setup_token(cur)) {
 687                case OPT_TAGS:
 688                        driver_setup.default_tags = val;
 689                        if (pe && *pe == '/') {
 690                                i = 0;
 691                                while (*pe && *pe != ARG_SEP && 
 692                                        i < sizeof(driver_setup.tag_ctrl)-1) {
 693                                        driver_setup.tag_ctrl[i++] = *pe++;
 694                                }
 695                                driver_setup.tag_ctrl[i] = '\0';
 696                        }
 697                        break;
 698                case OPT_MASTER_PARITY:
 699                        driver_setup.master_parity = val;
 700                        break;
 701                case OPT_SCSI_PARITY:
 702                        driver_setup.scsi_parity = val;
 703                        break;
 704                case OPT_DISCONNECTION:
 705                        driver_setup.disconnection = val;
 706                        break;
 707                case OPT_SPECIAL_FEATURES:
 708                        driver_setup.special_features = val;
 709                        break;
 710                case OPT_FORCE_SYNC_NEGO:
 711                        driver_setup.force_sync_nego = val;
 712                        break;
 713                case OPT_REVERSE_PROBE:
 714                        driver_setup.reverse_probe = val;
 715                        break;
 716                case OPT_DEFAULT_SYNC:
 717                        driver_setup.default_sync = val;
 718                        break;
 719                case OPT_VERBOSE:
 720                        driver_setup.verbose = val;
 721                        break;
 722                case OPT_DEBUG:
 723                        driver_setup.debug = val;
 724                        break;
 725                case OPT_BURST_MAX:
 726                        driver_setup.burst_max = val;
 727                        break;
 728                case OPT_LED_PIN:
 729                        driver_setup.led_pin = val;
 730                        break;
 731                case OPT_MAX_WIDE:
 732                        driver_setup.max_wide = val? 1:0;
 733                        break;
 734                case OPT_SETTLE_DELAY:
 735                        driver_setup.settle_delay = val;
 736                        break;
 737                case OPT_DIFF_SUPPORT:
 738                        driver_setup.diff_support = val;
 739                        break;
 740                case OPT_IRQM:
 741                        driver_setup.irqm = val;
 742                        break;
 743                case OPT_PCI_FIX_UP:
 744                        driver_setup.pci_fix_up = val;
 745                        break;
 746                case OPT_BUS_CHECK:
 747                        driver_setup.bus_check = val;
 748                        break;
 749                case OPT_OPTIMIZE:
 750                        driver_setup.optimize = val;
 751                        break;
 752                case OPT_RECOVERY:
 753                        driver_setup.recovery = val;
 754                        break;
 755                case OPT_USE_NVRAM:
 756                        driver_setup.use_nvram = val;
 757                        break;
 758                case OPT_SAFE_SETUP:
 759                        memcpy(&driver_setup, &driver_safe_setup,
 760                                sizeof(driver_setup));
 761                        break;
 762                case OPT_EXCLUDE:
 763                        if (xi < SCSI_NCR_MAX_EXCLUDES)
 764                                driver_setup.excludes[xi++] = val;
 765                        break;
 766                case OPT_HOST_ID:
 767                        driver_setup.host_id = val;
 768                        break;
 769#ifdef SCSI_NCR_IARB_SUPPORT
 770                case OPT_IARB:
 771                        driver_setup.iarb = val;
 772                        break;
 773#endif
 774                default:
 775                        printk("sym53c8xx_setup: unexpected boot option '%.*s' ignored\n", (int)(pc-cur+1), cur);
 776                        break;
 777                }
 778
 779                if ((cur = strchr(cur, ARG_SEP)) != NULL)
 780                        ++cur;
 781        }
 782#endif /* SCSI_NCR_BOOT_COMMAND_LINE_SUPPORT */
 783        return 1;
 784}
 785#endif /* !MODULE */
 786
 787/*===================================================================
 788**
 789**      Get device queue depth from boot command line.
 790**
 791**===================================================================
 792*/
 793#define DEF_DEPTH       (driver_setup.default_tags)
 794#define ALL_TARGETS     -2
 795#define NO_TARGET       -1
 796#define ALL_LUNS        -2
 797#define NO_LUN          -1
 798
 799static int device_queue_depth(int unit, int target, int lun)
 800{
 801        int c, h, t, u, v;
 802        char *p = driver_setup.tag_ctrl;
 803        char *ep;
 804
 805        h = -1;
 806        t = NO_TARGET;
 807        u = NO_LUN;
 808        while ((c = *p++) != 0) {
 809                v = simple_strtoul(p, &ep, 0);
 810                switch(c) {
 811                case '/':
 812                        ++h;
 813                        t = ALL_TARGETS;
 814                        u = ALL_LUNS;
 815                        break;
 816                case 't':
 817                        if (t != target)
 818                                t = (target == v) ? v : NO_TARGET;
 819                        u = ALL_LUNS;
 820                        break;
 821                case 'u':
 822                        if (u != lun)
 823                                u = (lun == v) ? v : NO_LUN;
 824                        break;
 825                case 'q':
 826                        if (h == unit &&
 827                                (t == ALL_TARGETS || t == target) &&
 828                                (u == ALL_LUNS    || u == lun))
 829                                return v;
 830                        break;
 831                case '-':
 832                        t = ALL_TARGETS;
 833                        u = ALL_LUNS;
 834                        break;
 835                default:
 836                        break;
 837                }
 838                p = ep;
 839        }
 840        return DEF_DEPTH;
 841}
 842
 843
 844/*==========================================================
 845**
 846**      The CCB done queue uses an array of CCB virtual 
 847**      addresses. Empty entries are flagged using the bogus 
 848**      virtual address 0xffffffff.
 849**
 850**      Since PCI ensures that only aligned DWORDs are accessed 
 851**      atomically, 64 bit little-endian architecture requires 
 852**      to test the high order DWORD of the entry to determine 
 853**      if it is empty or valid.
 854**
 855**      BTW, I will make things differently as soon as I will 
 856**      have a better idea, but this is simple and should work.
 857**
 858**==========================================================
 859*/
 860 
 861#define SCSI_NCR_CCB_DONE_SUPPORT
 862#ifdef  SCSI_NCR_CCB_DONE_SUPPORT
 863
 864#define MAX_DONE 24
 865#define CCB_DONE_EMPTY 0xffffffffUL
 866
 867/* All 32 bit architectures */
 868#if BITS_PER_LONG == 32
 869#define CCB_DONE_VALID(cp)  (((u_long) cp) != CCB_DONE_EMPTY)
 870
 871/* All > 32 bit (64 bit) architectures regardless endian-ness */
 872#else
 873#define CCB_DONE_VALID(cp)  \
 874        ((((u_long) cp) & 0xffffffff00000000ul) &&      \
 875         (((u_long) cp) & 0xfffffffful) != CCB_DONE_EMPTY)
 876#endif
 877
 878#endif /* SCSI_NCR_CCB_DONE_SUPPORT */
 879
 880/*==========================================================
 881**
 882**      Configuration and Debugging
 883**
 884**==========================================================
 885*/
 886
 887/*
 888**    SCSI address of this device.
 889**    The boot routines should have set it.
 890**    If not, use this.
 891*/
 892
 893#ifndef SCSI_NCR_MYADDR
 894#define SCSI_NCR_MYADDR      (7)
 895#endif
 896
 897/*
 898**    The maximum number of tags per logic unit.
 899**    Used only for disk devices that support tags.
 900*/
 901
 902#ifndef SCSI_NCR_MAX_TAGS
 903#define SCSI_NCR_MAX_TAGS    (8)
 904#endif
 905
 906/*
 907**    TAGS are actually limited to 64 tags/lun.
 908**    We need to deal with power of 2, for alignment constraints.
 909*/
 910#if     SCSI_NCR_MAX_TAGS > 64
 911#define MAX_TAGS (64)
 912#else
 913#define MAX_TAGS SCSI_NCR_MAX_TAGS
 914#endif
 915
 916#define NO_TAG  (255)
 917
 918/*
 919**      Choose appropriate type for tag bitmap.
 920*/
 921#if     MAX_TAGS > 32
 922typedef u64 tagmap_t;
 923#else
 924typedef u32 tagmap_t;
 925#endif
 926
 927/*
 928**    Number of targets supported by the driver.
 929**    n permits target numbers 0..n-1.
 930**    Default is 16, meaning targets #0..#15.
 931**    #7 .. is myself.
 932*/
 933
 934#ifdef SCSI_NCR_MAX_TARGET
 935#define MAX_TARGET  (SCSI_NCR_MAX_TARGET)
 936#else
 937#define MAX_TARGET  (16)
 938#endif
 939
 940/*
 941**    Number of logic units supported by the driver.
 942**    n enables logic unit numbers 0..n-1.
 943**    The common SCSI devices require only
 944**    one lun, so take 1 as the default.
 945*/
 946
 947#ifdef SCSI_NCR_MAX_LUN
 948#define MAX_LUN    SCSI_NCR_MAX_LUN
 949#else
 950#define MAX_LUN    (1)
 951#endif
 952
 953/*
 954**    Asynchronous pre-scaler (ns). Shall be 40
 955*/
 956 
 957#ifndef SCSI_NCR_MIN_ASYNC
 958#define SCSI_NCR_MIN_ASYNC (40)
 959#endif
 960
 961/*
 962**    The maximum number of jobs scheduled for starting.
 963**    There should be one slot per target, and one slot
 964**    for each tag of each target in use.
 965**    The calculation below is actually quite silly ...
 966*/
 967
 968#ifdef SCSI_NCR_CAN_QUEUE
 969#define MAX_START   (SCSI_NCR_CAN_QUEUE + 4)
 970#else
 971#define MAX_START   (MAX_TARGET + 7 * MAX_TAGS)
 972#endif
 973
 974/*
 975**   We limit the max number of pending IO to 250.
 976**   since we donnot want to allocate more than 1 
 977**   PAGE for 'scripth'.
 978*/
 979#if     MAX_START > 250
 980#undef  MAX_START
 981#define MAX_START 250
 982#endif
 983
 984/*
 985**    The maximum number of segments a transfer is split into.
 986**    We support up to 127 segments for both read and write.
 987**    The data scripts are broken into 2 sub-scripts.
 988**    80 (MAX_SCATTERL) segments are moved from a sub-script
 989**    in on-chip RAM. This makes data transfers shorter than 
 990**    80k (assuming 1k fs) as fast as possible.
 991*/
 992
 993#define MAX_SCATTER (SCSI_NCR_MAX_SCATTER)
 994
 995#if (MAX_SCATTER > 80)
 996#define MAX_SCATTERL    80
 997#define MAX_SCATTERH    (MAX_SCATTER - MAX_SCATTERL)
 998#else
 999#define MAX_SCATTERL    (MAX_SCATTER-1)
1000#define MAX_SCATTERH    1
1001#endif
1002
1003/*
1004**      other
1005*/
1006
1007#define NCR_SNOOP_TIMEOUT (1000000)
1008
1009/*
1010**      Other definitions
1011*/
1012
1013#define ScsiResult(host_code, scsi_code) (((host_code) << 16) + ((scsi_code) & 0x7f))
1014
1015#define initverbose (driver_setup.verbose)
1016#define bootverbose (np->verbose)
1017
1018/*==========================================================
1019**
1020**      Command control block states.
1021**
1022**==========================================================
1023*/
1024
1025#define HS_IDLE         (0)
1026#define HS_BUSY         (1)
1027#define HS_NEGOTIATE    (2)     /* sync/wide data transfer*/
1028#define HS_DISCONNECT   (3)     /* Disconnected by target */
1029
1030#define HS_DONEMASK     (0x80)
1031#define HS_COMPLETE     (4|HS_DONEMASK)
1032#define HS_SEL_TIMEOUT  (5|HS_DONEMASK) /* Selection timeout      */
1033#define HS_RESET        (6|HS_DONEMASK) /* SCSI reset             */
1034#define HS_ABORTED      (7|HS_DONEMASK) /* Transfer aborted       */
1035#define HS_TIMEOUT      (8|HS_DONEMASK) /* Software timeout       */
1036#define HS_FAIL         (9|HS_DONEMASK) /* SCSI or PCI bus errors */
1037#define HS_UNEXPECTED   (10|HS_DONEMASK)/* Unexpected disconnect  */
1038
1039/*
1040**      Invalid host status values used by the SCRIPTS processor 
1041**      when the nexus is not fully identified.
1042**      Shall never appear in a CCB.
1043*/
1044
1045#define HS_INVALMASK    (0x40)
1046#define HS_SELECTING    (0|HS_INVALMASK)
1047#define HS_IN_RESELECT  (1|HS_INVALMASK)
1048#define HS_STARTING     (2|HS_INVALMASK)
1049
1050/*
1051**      Flags set by the SCRIPT processor for commands 
1052**      that have been skipped.
1053*/
1054#define HS_SKIPMASK     (0x20)
1055
1056/*==========================================================
1057**
1058**      Software Interrupt Codes
1059**
1060**==========================================================
1061*/
1062
1063#define SIR_BAD_STATUS          (1)
1064#define SIR_XXXXXXXXXX          (2)
1065#define SIR_NEGO_SYNC           (3)
1066#define SIR_NEGO_WIDE           (4)
1067#define SIR_NEGO_FAILED         (5)
1068#define SIR_NEGO_PROTO          (6)
1069#define SIR_REJECT_RECEIVED     (7)
1070#define SIR_REJECT_SENT         (8)
1071#define SIR_IGN_RESIDUE         (9)
1072#define SIR_MISSING_SAVE        (10)
1073#define SIR_RESEL_NO_MSG_IN     (11)
1074#define SIR_RESEL_NO_IDENTIFY   (12)
1075#define SIR_RESEL_BAD_LUN       (13)
1076#define SIR_RESEL_BAD_TARGET    (14)
1077#define SIR_RESEL_BAD_I_T_L     (15)
1078#define SIR_RESEL_BAD_I_T_L_Q   (16)
1079#define SIR_DONE_OVERFLOW       (17)
1080#define SIR_INTFLY              (18)
1081#define SIR_MAX                 (18)
1082
1083/*==========================================================
1084**
1085**      Extended error codes.
1086**      xerr_status field of struct ccb.
1087**
1088**==========================================================
1089*/
1090
1091#define XE_OK           (0)
1092#define XE_EXTRA_DATA   (1)     /* unexpected data phase */
1093#define XE_BAD_PHASE    (2)     /* illegal phase (4/5)   */
1094
1095/*==========================================================
1096**
1097**      Negotiation status.
1098**      nego_status field       of struct ccb.
1099**
1100**==========================================================
1101*/
1102
1103#define NS_NOCHANGE     (0)
1104#define NS_SYNC         (1)
1105#define NS_WIDE         (2)
1106#define NS_PPR          (4)
1107
1108/*==========================================================
1109**
1110**      Misc.
1111**
1112**==========================================================
1113*/
1114
1115#define CCB_MAGIC       (0xf2691ad2)
1116
1117/*==========================================================
1118**
1119**      Declaration of structs.
1120**
1121**==========================================================
1122*/
1123
1124static struct scsi_transport_template *ncr53c8xx_transport_template = NULL;
1125
1126struct tcb;
1127struct lcb;
1128struct ccb;
1129struct ncb;
1130struct script;
1131
1132struct link {
1133        ncrcmd  l_cmd;
1134        ncrcmd  l_paddr;
1135};
1136
1137struct  usrcmd {
1138        u_long  target;
1139        u_long  lun;
1140        u_long  data;
1141        u_long  cmd;
1142};
1143
1144#define UC_SETSYNC      10
1145#define UC_SETTAGS      11
1146#define UC_SETDEBUG     12
1147#define UC_SETORDER     13
1148#define UC_SETWIDE      14
1149#define UC_SETFLAG      15
1150#define UC_SETVERBOSE   17
1151
1152#define UF_TRACE        (0x01)
1153#define UF_NODISC       (0x02)
1154#define UF_NOSCAN       (0x04)
1155
1156/*========================================================================
1157**
1158**      Declaration of structs:         target control block
1159**
1160**========================================================================
1161*/
1162struct tcb {
1163        /*----------------------------------------------------------------
1164        **      During reselection the ncr jumps to this point with SFBR 
1165        **      set to the encoded target number with bit 7 set.
1166        **      if it's not this target, jump to the next.
1167        **
1168        **      JUMP  IF (SFBR != #target#), @(next tcb)
1169        **----------------------------------------------------------------
1170        */
1171        struct link   jump_tcb;
1172
1173        /*----------------------------------------------------------------
1174        **      Load the actual values for the sxfer and the scntl3
1175        **      register (sync/wide mode).
1176        **
1177        **      SCR_COPY (1), @(sval field of this tcb), @(sxfer  register)
1178        **      SCR_COPY (1), @(wval field of this tcb), @(scntl3 register)
1179        **----------------------------------------------------------------
1180        */
1181        ncrcmd  getscr[6];
1182
1183        /*----------------------------------------------------------------
1184        **      Get the IDENTIFY message and load the LUN to SFBR.
1185        **
1186        **      CALL, <RESEL_LUN>
1187        **----------------------------------------------------------------
1188        */
1189        struct link   call_lun;
1190
1191        /*----------------------------------------------------------------
1192        **      Now look for the right lun.
1193        **
1194        **      For i = 0 to 3
1195        **              SCR_JUMP ^ IFTRUE(MASK(i, 3)), @(first lcb mod. i)
1196        **
1197        **      Recent chips will prefetch the 4 JUMPS using only 1 burst.
1198        **      It is kind of hashcoding.
1199        **----------------------------------------------------------------
1200        */
1201        struct link     jump_lcb[4];    /* JUMPs for reselection        */
1202        struct lcb *    lp[MAX_LUN];    /* The lcb's of this tcb        */
1203
1204        /*----------------------------------------------------------------
1205        **      Pointer to the ccb used for negotiation.
1206        **      Prevent from starting a negotiation for all queued commands 
1207        **      when tagged command queuing is enabled.
1208        **----------------------------------------------------------------
1209        */
1210        struct ccb *   nego_cp;
1211
1212        /*----------------------------------------------------------------
1213        **      statistical data
1214        **----------------------------------------------------------------
1215        */
1216        u_long  transfers;
1217        u_long  bytes;
1218
1219        /*----------------------------------------------------------------
1220        **      negotiation of wide and synch transfer and device quirks.
1221        **----------------------------------------------------------------
1222        */
1223#ifdef SCSI_NCR_BIG_ENDIAN
1224/*0*/   u16     period;
1225/*2*/   u_char  sval;
1226/*3*/   u_char  minsync;
1227/*0*/   u_char  wval;
1228/*1*/   u_char  widedone;
1229/*2*/   u_char  quirks;
1230/*3*/   u_char  maxoffs;
1231#else
1232/*0*/   u_char  minsync;
1233/*1*/   u_char  sval;
1234/*2*/   u16     period;
1235/*0*/   u_char  maxoffs;
1236/*1*/   u_char  quirks;
1237/*2*/   u_char  widedone;
1238/*3*/   u_char  wval;
1239#endif
1240
1241        /* User settable limits and options.  */
1242        u_char  usrsync;
1243        u_char  usrwide;
1244        u_char  usrtags;
1245        u_char  usrflag;
1246        struct scsi_target *starget;
1247};
1248
1249/*========================================================================
1250**
1251**      Declaration of structs:         lun control block
1252**
1253**========================================================================
1254*/
1255struct lcb {
1256        /*----------------------------------------------------------------
1257        **      During reselection the ncr jumps to this point
1258        **      with SFBR set to the "Identify" message.
1259        **      if it's not this lun, jump to the next.
1260        **
1261        **      JUMP  IF (SFBR != #lun#), @(next lcb of this target)
1262        **
1263        **      It is this lun. Load TEMP with the nexus jumps table 
1264        **      address and jump to RESEL_TAG (or RESEL_NOTAG).
1265        **
1266        **              SCR_COPY (4), p_jump_ccb, TEMP,
1267        **              SCR_JUMP, <RESEL_TAG>
1268        **----------------------------------------------------------------
1269        */
1270        struct link     jump_lcb;
1271        ncrcmd          load_jump_ccb[3];
1272        struct link     jump_tag;
1273        ncrcmd          p_jump_ccb;     /* Jump table bus address       */
1274
1275        /*----------------------------------------------------------------
1276        **      Jump table used by the script processor to directly jump 
1277        **      to the CCB corresponding to the reselected nexus.
1278        **      Address is allocated on 256 bytes boundary in order to 
1279        **      allow 8 bit calculation of the tag jump entry for up to 
1280        **      64 possible tags.
1281        **----------------------------------------------------------------
1282        */
1283        u32             jump_ccb_0;     /* Default table if no tags     */
1284        u32             *jump_ccb;      /* Virtual address              */
1285
1286        /*----------------------------------------------------------------
1287        **      CCB queue management.
1288        **----------------------------------------------------------------
1289        */
1290        struct list_head free_ccbq;     /* Queue of available CCBs      */
1291        struct list_head busy_ccbq;     /* Queue of busy CCBs           */
1292        struct list_head wait_ccbq;     /* Queue of waiting for IO CCBs */
1293        struct list_head skip_ccbq;     /* Queue of skipped CCBs        */
1294        u_char          actccbs;        /* Number of allocated CCBs     */
1295        u_char          busyccbs;       /* CCBs busy for this lun       */
1296        u_char          queuedccbs;     /* CCBs queued to the controller*/
1297        u_char          queuedepth;     /* Queue depth for this lun     */
1298        u_char          scdev_depth;    /* SCSI device queue depth      */
1299        u_char          maxnxs;         /* Max possible nexuses         */
1300
1301        /*----------------------------------------------------------------
1302        **      Control of tagged command queuing.
1303        **      Tags allocation is performed using a circular buffer.
1304        **      This avoids using a loop for tag allocation.
1305        **----------------------------------------------------------------
1306        */
1307        u_char          ia_tag;         /* Allocation index             */
1308        u_char          if_tag;         /* Freeing index                */
1309        u_char cb_tags[MAX_TAGS];       /* Circular tags buffer */
1310        u_char          usetags;        /* Command queuing is active    */
1311        u_char          maxtags;        /* Max nr of tags asked by user */
1312        u_char          numtags;        /* Current number of tags       */
1313
1314        /*----------------------------------------------------------------
1315        **      QUEUE FULL control and ORDERED tag control.
1316        **----------------------------------------------------------------
1317        */
1318        /*----------------------------------------------------------------
1319        **      QUEUE FULL and ORDERED tag control.
1320        **----------------------------------------------------------------
1321        */
1322        u16             num_good;       /* Nr of GOOD since QUEUE FULL  */
1323        tagmap_t        tags_umap;      /* Used tags bitmap             */
1324        tagmap_t        tags_smap;      /* Tags in use at 'tag_stime'   */
1325        u_long          tags_stime;     /* Last time we set smap=umap   */
1326        struct ccb *    held_ccb;       /* CCB held for QUEUE FULL      */
1327};
1328
1329/*========================================================================
1330**
1331**      Declaration of structs:     the launch script.
1332**
1333**========================================================================
1334**
1335**      It is part of the CCB and is called by the scripts processor to 
1336**      start or restart the data structure (nexus).
1337**      This 6 DWORDs mini script makes use of prefetching.
1338**
1339**------------------------------------------------------------------------
1340*/
1341struct launch {
1342        /*----------------------------------------------------------------
1343        **      SCR_COPY(4),    @(p_phys), @(dsa register)
1344        **      SCR_JUMP,       @(scheduler_point)
1345        **----------------------------------------------------------------
1346        */
1347        ncrcmd          setup_dsa[3];   /* Copy 'phys' address to dsa   */
1348        struct link     schedule;       /* Jump to scheduler point      */
1349        ncrcmd          p_phys;         /* 'phys' header bus address    */
1350};
1351
1352/*========================================================================
1353**
1354**      Declaration of structs:     global HEADER.
1355**
1356**========================================================================
1357**
1358**      This substructure is copied from the ccb to a global address after 
1359**      selection (or reselection) and copied back before disconnect.
1360**
1361**      These fields are accessible to the script processor.
1362**
1363**------------------------------------------------------------------------
1364*/
1365
1366struct head {
1367        /*----------------------------------------------------------------
1368        **      Saved data pointer.
1369        **      Points to the position in the script responsible for the
1370        **      actual transfer transfer of data.
1371        **      It's written after reception of a SAVE_DATA_POINTER message.
1372        **      The goalpointer points after the last transfer command.
1373        **----------------------------------------------------------------
1374        */
1375        u32             savep;
1376        u32             lastp;
1377        u32             goalp;
1378
1379        /*----------------------------------------------------------------
1380        **      Alternate data pointer.
1381        **      They are copied back to savep/lastp/goalp by the SCRIPTS 
1382        **      when the direction is unknown and the device claims data out.
1383        **----------------------------------------------------------------
1384        */
1385        u32             wlastp;
1386        u32             wgoalp;
1387
1388        /*----------------------------------------------------------------
1389        **      The virtual address of the ccb containing this header.
1390        **----------------------------------------------------------------
1391        */
1392        struct ccb *    cp;
1393
1394        /*----------------------------------------------------------------
1395        **      Status fields.
1396        **----------------------------------------------------------------
1397        */
1398        u_char          scr_st[4];      /* script status                */
1399        u_char          status[4];      /* host status. must be the     */
1400                                        /*  last DWORD of the header.   */
1401};
1402
1403/*
1404**      The status bytes are used by the host and the script processor.
1405**
1406**      The byte corresponding to the host_status must be stored in the 
1407**      last DWORD of the CCB header since it is used for command 
1408**      completion (ncr_wakeup()). Doing so, we are sure that the header 
1409**      has been entirely copied back to the CCB when the host_status is 
1410**      seen complete by the CPU.
1411**
1412**      The last four bytes (status[4]) are copied to the scratchb register
1413**      (declared as scr0..scr3 in ncr_reg.h) just after the select/reselect,
1414**      and copied back just after disconnecting.
1415**      Inside the script the XX_REG are used.
1416**
1417**      The first four bytes (scr_st[4]) are used inside the script by 
1418**      "COPY" commands.
1419**      Because source and destination must have the same alignment
1420**      in a DWORD, the fields HAVE to be at the chosen offsets.
1421**              xerr_st         0       (0x34)  scratcha
1422**              sync_st         1       (0x05)  sxfer
1423**              wide_st         3       (0x03)  scntl3
1424*/
1425
1426/*
1427**      Last four bytes (script)
1428*/
1429#define  QU_REG scr0
1430#define  HS_REG scr1
1431#define  HS_PRT nc_scr1
1432#define  SS_REG scr2
1433#define  SS_PRT nc_scr2
1434#define  PS_REG scr3
1435
1436/*
1437**      Last four bytes (host)
1438*/
1439#ifdef SCSI_NCR_BIG_ENDIAN
1440#define  actualquirks  phys.header.status[3]
1441#define  host_status   phys.header.status[2]
1442#define  scsi_status   phys.header.status[1]
1443#define  parity_status phys.header.status[0]
1444#else
1445#define  actualquirks  phys.header.status[0]
1446#define  host_status   phys.header.status[1]
1447#define  scsi_status   phys.header.status[2]
1448#define  parity_status phys.header.status[3]
1449#endif
1450
1451/*
1452**      First four bytes (script)
1453*/
1454#define  xerr_st       header.scr_st[0]
1455#define  sync_st       header.scr_st[1]
1456#define  nego_st       header.scr_st[2]
1457#define  wide_st       header.scr_st[3]
1458
1459/*
1460**      First four bytes (host)
1461*/
1462#define  xerr_status   phys.xerr_st
1463#define  nego_status   phys.nego_st
1464
1465#if 0
1466#define  sync_status   phys.sync_st
1467#define  wide_status   phys.wide_st
1468#endif
1469
1470/*==========================================================
1471**
1472**      Declaration of structs:     Data structure block
1473**
1474**==========================================================
1475**
1476**      During execution of a ccb by the script processor,
1477**      the DSA (data structure address) register points
1478**      to this substructure of the ccb.
1479**      This substructure contains the header with
1480**      the script-processor-changeable data and
1481**      data blocks for the indirect move commands.
1482**
1483**----------------------------------------------------------
1484*/
1485
1486struct dsb {
1487
1488        /*
1489        **      Header.
1490        */
1491
1492        struct head     header;
1493
1494        /*
1495        **      Table data for Script
1496        */
1497
1498        struct scr_tblsel  select;
1499        struct scr_tblmove smsg  ;
1500        struct scr_tblmove cmd   ;
1501        struct scr_tblmove sense ;
1502        struct scr_tblmove data[MAX_SCATTER];
1503};
1504
1505
1506/*========================================================================
1507**
1508**      Declaration of structs:     Command control block.
1509**
1510**========================================================================
1511*/
1512struct ccb {
1513        /*----------------------------------------------------------------
1514        **      This is the data structure which is pointed by the DSA 
1515        **      register when it is executed by the script processor.
1516        **      It must be the first entry because it contains the header 
1517        **      as first entry that must be cache line aligned.
1518        **----------------------------------------------------------------
1519        */
1520        struct dsb      phys;
1521
1522        /*----------------------------------------------------------------
1523        **      Mini-script used at CCB execution start-up.
1524        **      Load the DSA with the data structure address (phys) and 
1525        **      jump to SELECT. Jump to CANCEL if CCB is to be canceled.
1526        **----------------------------------------------------------------
1527        */
1528        struct launch   start;
1529
1530        /*----------------------------------------------------------------
1531        **      Mini-script used at CCB relection to restart the nexus.
1532        **      Load the DSA with the data structure address (phys) and 
1533        **      jump to RESEL_DSA. Jump to ABORT if CCB is to be aborted.
1534        **----------------------------------------------------------------
1535        */
1536        struct launch   restart;
1537
1538        /*----------------------------------------------------------------
1539        **      If a data transfer phase is terminated too early
1540        **      (after reception of a message (i.e. DISCONNECT)),
1541        **      we have to prepare a mini script to transfer
1542        **      the rest of the data.
1543        **----------------------------------------------------------------
1544        */
1545        ncrcmd          patch[8];
1546
1547        /*----------------------------------------------------------------
1548        **      The general SCSI driver provides a
1549        **      pointer to a control block.
1550        **----------------------------------------------------------------
1551        */
1552        struct scsi_cmnd        *cmd;           /* SCSI command                 */
1553        u_char          cdb_buf[16];    /* Copy of CDB                  */
1554        u_char          sense_buf[64];
1555        int             data_len;       /* Total data length            */
1556
1557        /*----------------------------------------------------------------
1558        **      Message areas.
1559        **      We prepare a message to be sent after selection.
1560        **      We may use a second one if the command is rescheduled 
1561        **      due to GETCC or QFULL.
1562        **      Contents are IDENTIFY and SIMPLE_TAG.
1563        **      While negotiating sync or wide transfer,
1564        **      a SDTR or WDTR message is appended.
1565        **----------------------------------------------------------------
1566        */
1567        u_char          scsi_smsg [8];
1568        u_char          scsi_smsg2[8];
1569
1570        /*----------------------------------------------------------------
1571        **      Other fields.
1572        **----------------------------------------------------------------
1573        */
1574        u_long          p_ccb;          /* BUS address of this CCB      */
1575        u_char          sensecmd[6];    /* Sense command                */
1576        u_char          tag;            /* Tag for this transfer        */
1577                                        /*  255 means no tag            */
1578        u_char          target;
1579        u_char          lun;
1580        u_char          queued;
1581        u_char          auto_sense;
1582        struct ccb *    link_ccb;       /* Host adapter CCB chain       */
1583        struct list_head link_ccbq;     /* Link to unit CCB queue       */
1584        u32             startp;         /* Initial data pointer         */
1585        u_long          magic;          /* Free / busy  CCB flag        */
1586};
1587
1588#define CCB_PHYS(cp,lbl)        (cp->p_ccb + offsetof(struct ccb, lbl))
1589
1590
1591/*========================================================================
1592**
1593**      Declaration of structs:     NCR device descriptor
1594**
1595**========================================================================
1596*/
1597struct ncb {
1598        /*----------------------------------------------------------------
1599        **      The global header.
1600        **      It is accessible to both the host and the script processor.
1601        **      Must be cache line size aligned (32 for x86) in order to 
1602        **      allow cache line bursting when it is copied to/from CCB.
1603        **----------------------------------------------------------------
1604        */
1605        struct head     header;
1606
1607        /*----------------------------------------------------------------
1608        **      CCBs management queues.
1609        **----------------------------------------------------------------
1610        */
1611        struct scsi_cmnd        *waiting_list;  /* Commands waiting for a CCB   */
1612                                        /*  when lcb is not allocated.  */
1613        struct scsi_cmnd        *done_list;     /* Commands waiting for done()  */
1614                                        /* callback to be invoked.      */ 
1615        spinlock_t      smp_lock;       /* Lock for SMP threading       */
1616
1617        /*----------------------------------------------------------------
1618        **      Chip and controller indentification.
1619        **----------------------------------------------------------------
1620        */
1621        int             unit;           /* Unit number                  */
1622        char            inst_name[16];  /* ncb instance name            */
1623
1624        /*----------------------------------------------------------------
1625        **      Initial value of some IO register bits.
1626        **      These values are assumed to have been set by BIOS, and may 
1627        **      be used for probing adapter implementation differences.
1628        **----------------------------------------------------------------
1629        */
1630        u_char  sv_scntl0, sv_scntl3, sv_dmode, sv_dcntl, sv_ctest0, sv_ctest3,
1631                sv_ctest4, sv_ctest5, sv_gpcntl, sv_stest2, sv_stest4;
1632
1633        /*----------------------------------------------------------------
1634        **      Actual initial value of IO register bits used by the 
1635        **      driver. They are loaded at initialisation according to  
1636        **      features that are to be enabled.
1637        **----------------------------------------------------------------
1638        */
1639        u_char  rv_scntl0, rv_scntl3, rv_dmode, rv_dcntl, rv_ctest0, rv_ctest3,
1640                rv_ctest4, rv_ctest5, rv_stest2;
1641
1642        /*----------------------------------------------------------------
1643        **      Targets management.
1644        **      During reselection the ncr jumps to jump_tcb.
1645        **      The SFBR register is loaded with the encoded target id.
1646        **      For i = 0 to 3
1647        **              SCR_JUMP ^ IFTRUE(MASK(i, 3)), @(next tcb mod. i)
1648        **
1649        **      Recent chips will prefetch the 4 JUMPS using only 1 burst.
1650        **      It is kind of hashcoding.
1651        **----------------------------------------------------------------
1652        */
1653        struct link     jump_tcb[4];    /* JUMPs for reselection        */
1654        struct tcb  target[MAX_TARGET]; /* Target data                  */
1655
1656        /*----------------------------------------------------------------
1657        **      Virtual and physical bus addresses of the chip.
1658        **----------------------------------------------------------------
1659        */
1660        void __iomem *vaddr;            /* Virtual and bus address of   */
1661        unsigned long   paddr;          /*  chip's IO registers.        */
1662        unsigned long   paddr2;         /* On-chip RAM bus address.     */
1663        volatile                        /* Pointer to volatile for      */
1664        struct ncr_reg  __iomem *reg;   /*  memory mapped IO.           */
1665
1666        /*----------------------------------------------------------------
1667        **      SCRIPTS virtual and physical bus addresses.
1668        **      'script'  is loaded in the on-chip RAM if present.
1669        **      'scripth' stays in main memory.
1670        **----------------------------------------------------------------
1671        */
1672        struct script   *script0;       /* Copies of script and scripth */
1673        struct scripth  *scripth0;      /*  relocated for this ncb.     */
1674        struct scripth  *scripth;       /* Actual scripth virt. address */
1675        u_long          p_script;       /* Actual script and scripth    */
1676        u_long          p_scripth;      /*  bus addresses.              */
1677
1678        /*----------------------------------------------------------------
1679        **      General controller parameters and configuration.
1680        **----------------------------------------------------------------
1681        */
1682        struct device   *dev;
1683        u_char          revision_id;    /* PCI device revision id       */
1684        u32             irq;            /* IRQ level                    */
1685        u32             features;       /* Chip features map            */
1686        u_char          myaddr;         /* SCSI id of the adapter       */
1687        u_char          maxburst;       /* log base 2 of dwords burst   */
1688        u_char          maxwide;        /* Maximum transfer width       */
1689        u_char          minsync;        /* Minimum sync period factor   */
1690        u_char          maxsync;        /* Maximum sync period factor   */
1691        u_char          maxoffs;        /* Max scsi offset              */
1692        u_char          multiplier;     /* Clock multiplier (1,2,4)     */
1693        u_char          clock_divn;     /* Number of clock divisors     */
1694        u_long          clock_khz;      /* SCSI clock frequency in KHz  */
1695
1696        /*----------------------------------------------------------------
1697        **      Start queue management.
1698        **      It is filled up by the host processor and accessed by the 
1699        **      SCRIPTS processor in order to start SCSI commands.
1700        **----------------------------------------------------------------
1701        */
1702        u16             squeueput;      /* Next free slot of the queue  */
1703        u16             actccbs;        /* Number of allocated CCBs     */
1704        u16             queuedccbs;     /* Number of CCBs in start queue*/
1705        u16             queuedepth;     /* Start queue depth            */
1706
1707        /*----------------------------------------------------------------
1708        **      Timeout handler.
1709        **----------------------------------------------------------------
1710        */
1711        struct timer_list timer;        /* Timer handler link header    */
1712        u_long          lasttime;
1713        u_long          settle_time;    /* Resetting the SCSI BUS       */
1714
1715        /*----------------------------------------------------------------
1716        **      Debugging and profiling.
1717        **----------------------------------------------------------------
1718        */
1719        struct ncr_reg  regdump;        /* Register dump                */
1720        u_long          regtime;        /* Time it has been done        */
1721
1722        /*----------------------------------------------------------------
1723        **      Miscellaneous buffers accessed by the scripts-processor.
1724        **      They shall be DWORD aligned, because they may be read or 
1725        **      written with a SCR_COPY script command.
1726        **----------------------------------------------------------------
1727        */
1728        u_char          msgout[8];      /* Buffer for MESSAGE OUT       */
1729        u_char          msgin [8];      /* Buffer for MESSAGE IN        */
1730        u32             lastmsg;        /* Last SCSI message sent       */
1731        u_char          scratch;        /* Scratch for SCSI receive     */
1732
1733        /*----------------------------------------------------------------
1734        **      Miscellaneous configuration and status parameters.
1735        **----------------------------------------------------------------
1736        */
1737        u_char          disc;           /* Diconnection allowed         */
1738        u_char          scsi_mode;      /* Current SCSI BUS mode        */
1739        u_char          order;          /* Tag order to use             */
1740        u_char          verbose;        /* Verbosity for this controller*/
1741        int             ncr_cache;      /* Used for cache test at init. */
1742        u_long          p_ncb;          /* BUS address of this NCB      */
1743
1744        /*----------------------------------------------------------------
1745        **      Command completion handling.
1746        **----------------------------------------------------------------
1747        */
1748#ifdef SCSI_NCR_CCB_DONE_SUPPORT
1749        struct ccb      *(ccb_done[MAX_DONE]);
1750        int             ccb_done_ic;
1751#endif
1752        /*----------------------------------------------------------------
1753        **      Fields that should be removed or changed.
1754        **----------------------------------------------------------------
1755        */
1756        struct ccb      *ccb;           /* Global CCB                   */
1757        struct usrcmd   user;           /* Command from user            */
1758        volatile u_char release_stage;  /* Synchronisation stage on release  */
1759};
1760
1761#define NCB_SCRIPT_PHYS(np,lbl)  (np->p_script  + offsetof (struct script, lbl))
1762#define NCB_SCRIPTH_PHYS(np,lbl) (np->p_scripth + offsetof (struct scripth,lbl))
1763
1764/*==========================================================
1765**
1766**
1767**      Script for NCR-Processor.
1768**
1769**      Use ncr_script_fill() to create the variable parts.
1770**      Use ncr_script_copy_and_bind() to make a copy and
1771**      bind to physical addresses.
1772**
1773**
1774**==========================================================
1775**
1776**      We have to know the offsets of all labels before
1777**      we reach them (for forward jumps).
1778**      Therefore we declare a struct here.
1779**      If you make changes inside the script,
1780**      DONT FORGET TO CHANGE THE LENGTHS HERE!
1781**
1782**----------------------------------------------------------
1783*/
1784
1785/*
1786**      For HP Zalon/53c720 systems, the Zalon interface
1787**      between CPU and 53c720 does prefetches, which causes
1788**      problems with self modifying scripts.  The problem
1789**      is overcome by calling a dummy subroutine after each
1790**      modification, to force a refetch of the script on
1791**      return from the subroutine.
1792*/
1793
1794#ifdef CONFIG_NCR53C8XX_PREFETCH
1795#define PREFETCH_FLUSH_CNT      2
1796#define PREFETCH_FLUSH          SCR_CALL, PADDRH (wait_dma),
1797#else
1798#define PREFETCH_FLUSH_CNT      0
1799#define PREFETCH_FLUSH
1800#endif
1801
1802/*
1803**      Script fragments which are loaded into the on-chip RAM 
1804**      of 825A, 875 and 895 chips.
1805*/
1806struct script {
1807        ncrcmd  start           [  5];
1808        ncrcmd  startpos        [  1];
1809        ncrcmd  select          [  6];
1810        ncrcmd  select2         [  9 + PREFETCH_FLUSH_CNT];
1811        ncrcmd  loadpos         [  4];
1812        ncrcmd  send_ident      [  9];
1813        ncrcmd  prepare         [  6];
1814        ncrcmd  prepare2        [  7];
1815        ncrcmd  command         [  6];
1816        ncrcmd  dispatch        [ 32];
1817        ncrcmd  clrack          [  4];
1818        ncrcmd  no_data         [ 17];
1819        ncrcmd  status          [  8];
1820        ncrcmd  msg_in          [  2];
1821        ncrcmd  msg_in2         [ 16];
1822        ncrcmd  msg_bad         [  4];
1823        ncrcmd  setmsg          [  7];
1824        ncrcmd  cleanup         [  6];
1825        ncrcmd  complete        [  9];
1826        ncrcmd  cleanup_ok      [  8 + PREFETCH_FLUSH_CNT];
1827        ncrcmd  cleanup0        [  1];
1828#ifndef SCSI_NCR_CCB_DONE_SUPPORT
1829        ncrcmd  signal          [ 12];
1830#else
1831        ncrcmd  signal          [  9];
1832        ncrcmd  done_pos        [  1];
1833        ncrcmd  done_plug       [  2];
1834        ncrcmd  done_end        [  7];
1835#endif
1836        ncrcmd  save_dp         [  7];
1837        ncrcmd  restore_dp      [  5];
1838        ncrcmd  disconnect      [ 10];
1839        ncrcmd  msg_out         [  9];
1840        ncrcmd  msg_out_done    [  7];
1841        ncrcmd  idle            [  2];
1842        ncrcmd  reselect        [  8];
1843        ncrcmd  reselected      [  8];
1844        ncrcmd  resel_dsa       [  6 + PREFETCH_FLUSH_CNT];
1845        ncrcmd  loadpos1        [  4];
1846        ncrcmd  resel_lun       [  6];
1847        ncrcmd  resel_tag       [  6];
1848        ncrcmd  jump_to_nexus   [  4 + PREFETCH_FLUSH_CNT];
1849        ncrcmd  nexus_indirect  [  4];
1850        ncrcmd  resel_notag     [  4];
1851        ncrcmd  data_in         [MAX_SCATTERL * 4];
1852        ncrcmd  data_in2        [  4];
1853        ncrcmd  data_out        [MAX_SCATTERL * 4];
1854        ncrcmd  data_out2       [  4];
1855};
1856
1857/*
1858**      Script fragments which stay in main memory for all chips.
1859*/
1860struct scripth {
1861        ncrcmd  tryloop         [MAX_START*2];
1862        ncrcmd  tryloop2        [  2];
1863#ifdef SCSI_NCR_CCB_DONE_SUPPORT
1864        ncrcmd  done_queue      [MAX_DONE*5];
1865        ncrcmd  done_queue2     [  2];
1866#endif
1867        ncrcmd  select_no_atn   [  8];
1868        ncrcmd  cancel          [  4];
1869        ncrcmd  skip            [  9 + PREFETCH_FLUSH_CNT];
1870        ncrcmd  skip2           [ 19];
1871        ncrcmd  par_err_data_in [  6];
1872        ncrcmd  par_err_other   [  4];
1873        ncrcmd  msg_reject      [  8];
1874        ncrcmd  msg_ign_residue [ 24];
1875        ncrcmd  msg_extended    [ 10];
1876        ncrcmd  msg_ext_2       [ 10];
1877        ncrcmd  msg_wdtr        [ 14];
1878        ncrcmd  send_wdtr       [  7];
1879        ncrcmd  msg_ext_3       [ 10];
1880        ncrcmd  msg_sdtr        [ 14];
1881        ncrcmd  send_sdtr       [  7];
1882        ncrcmd  nego_bad_phase  [  4];
1883        ncrcmd  msg_out_abort   [ 10];
1884        ncrcmd  hdata_in        [MAX_SCATTERH * 4];
1885        ncrcmd  hdata_in2       [  2];
1886        ncrcmd  hdata_out       [MAX_SCATTERH * 4];
1887        ncrcmd  hdata_out2      [  2];
1888        ncrcmd  reset           [  4];
1889        ncrcmd  aborttag        [  4];
1890        ncrcmd  abort           [  2];
1891        ncrcmd  abort_resel     [ 20];
1892        ncrcmd  resend_ident    [  4];
1893        ncrcmd  clratn_go_on    [  3];
1894        ncrcmd  nxtdsp_go_on    [  1];
1895        ncrcmd  sdata_in        [  8];
1896        ncrcmd  data_io         [ 18];
1897        ncrcmd  bad_identify    [ 12];
1898        ncrcmd  bad_i_t_l       [  4];
1899        ncrcmd  bad_i_t_l_q     [  4];
1900        ncrcmd  bad_target      [  8];
1901        ncrcmd  bad_status      [  8];
1902        ncrcmd  start_ram       [  4 + PREFETCH_FLUSH_CNT];
1903        ncrcmd  start_ram0      [  4];
1904        ncrcmd  sto_restart     [  5];
1905        ncrcmd  wait_dma        [  2];
1906        ncrcmd  snooptest       [  9];
1907        ncrcmd  snoopend        [  2];
1908};
1909
1910/*==========================================================
1911**
1912**
1913**      Function headers.
1914**
1915**
1916**==========================================================
1917*/
1918
1919static  void    ncr_alloc_ccb   (struct ncb *np, u_char tn, u_char ln);
1920static  void    ncr_complete    (struct ncb *np, struct ccb *cp);
1921static  void    ncr_exception   (struct ncb *np);
1922static  void    ncr_free_ccb    (struct ncb *np, struct ccb *cp);
1923static  void    ncr_init_ccb    (struct ncb *np, struct ccb *cp);
1924static  void    ncr_init_tcb    (struct ncb *np, u_char tn);
1925static  struct lcb *    ncr_alloc_lcb   (struct ncb *np, u_char tn, u_char ln);
1926static  struct lcb *    ncr_setup_lcb   (struct ncb *np, struct scsi_device *sdev);
1927static  void    ncr_getclock    (struct ncb *np, int mult);
1928static  void    ncr_selectclock (struct ncb *np, u_char scntl3);
1929static  struct ccb *ncr_get_ccb (struct ncb *np, struct scsi_cmnd *cmd);
1930static  void    ncr_chip_reset  (struct ncb *np, int delay);
1931static  void    ncr_init        (struct ncb *np, int reset, char * msg, u_long code);
1932static  int     ncr_int_sbmc    (struct ncb *np);
1933static  int     ncr_int_par     (struct ncb *np);
1934static  void    ncr_int_ma      (struct ncb *np);
1935static  void    ncr_int_sir     (struct ncb *np);
1936static  void    ncr_int_sto     (struct ncb *np);
1937static  void    ncr_negotiate   (struct ncb* np, struct tcb* tp);
1938static  int     ncr_prepare_nego(struct ncb *np, struct ccb *cp, u_char *msgptr);
1939
1940static  void    ncr_script_copy_and_bind
1941                                (struct ncb *np, ncrcmd *src, ncrcmd *dst, int len);
1942static  void    ncr_script_fill (struct script * scr, struct scripth * scripth);
1943static  int     ncr_scatter     (struct ncb *np, struct ccb *cp, struct scsi_cmnd *cmd);
1944static  void    ncr_getsync     (struct ncb *np, u_char sfac, u_char *fakp, u_char *scntl3p);
1945static  void    ncr_setsync     (struct ncb *np, struct ccb *cp, u_char scntl3, u_char sxfer);
1946static  void    ncr_setup_tags  (struct ncb *np, struct scsi_device *sdev);
1947static  void    ncr_setwide     (struct ncb *np, struct ccb *cp, u_char wide, u_char ack);
1948static  int     ncr_snooptest   (struct ncb *np);
1949static  void    ncr_timeout     (struct ncb *np);
1950static  void    ncr_wakeup      (struct ncb *np, u_long code);
1951static  void    ncr_wakeup_done (struct ncb *np);
1952static  void    ncr_start_next_ccb (struct ncb *np, struct lcb * lp, int maxn);
1953static  void    ncr_put_start_queue(struct ncb *np, struct ccb *cp);
1954
1955static void insert_into_waiting_list(struct ncb *np, struct scsi_cmnd *cmd);
1956static struct scsi_cmnd *retrieve_from_waiting_list(int to_remove, struct ncb *np, struct scsi_cmnd *cmd);
1957static void process_waiting_list(struct ncb *np, int sts);
1958
1959#define remove_from_waiting_list(np, cmd) \
1960                retrieve_from_waiting_list(1, (np), (cmd))
1961#define requeue_waiting_list(np) process_waiting_list((np), DID_OK)
1962#define reset_waiting_list(np) process_waiting_list((np), DID_RESET)
1963
1964static inline char *ncr_name (struct ncb *np)
1965{
1966        return np->inst_name;
1967}
1968
1969
1970/*==========================================================
1971**
1972**
1973**      Scripts for NCR-Processor.
1974**
1975**      Use ncr_script_bind for binding to physical addresses.
1976**
1977**
1978**==========================================================
1979**
1980**      NADDR generates a reference to a field of the controller data.
1981**      PADDR generates a reference to another part of the script.
1982**      RADDR generates a reference to a script processor register.
1983**      FADDR generates a reference to a script processor register
1984**              with offset.
1985**
1986**----------------------------------------------------------
1987*/
1988
1989#define RELOC_SOFTC     0x40000000
1990#define RELOC_LABEL     0x50000000
1991#define RELOC_REGISTER  0x60000000
1992#if 0
1993#define RELOC_KVAR      0x70000000
1994#endif
1995#define RELOC_LABELH    0x80000000
1996#define RELOC_MASK      0xf0000000
1997
1998#define NADDR(label)    (RELOC_SOFTC | offsetof(struct ncb, label))
1999#define PADDR(label)    (RELOC_LABEL | offsetof(struct script, label))
2000#define PADDRH(label)   (RELOC_LABELH | offsetof(struct scripth, label))
2001#define RADDR(label)    (RELOC_REGISTER | REG(label))
2002#define FADDR(label,ofs)(RELOC_REGISTER | ((REG(label))+(ofs)))
2003#if 0
2004#define KVAR(which)     (RELOC_KVAR | (which))
2005#endif
2006
2007#if 0
2008#define SCRIPT_KVAR_JIFFIES     (0)
2009#define SCRIPT_KVAR_FIRST               SCRIPT_KVAR_JIFFIES
2010#define SCRIPT_KVAR_LAST                SCRIPT_KVAR_JIFFIES
2011/*
2012 * Kernel variables referenced in the scripts.
2013 * THESE MUST ALL BE ALIGNED TO A 4-BYTE BOUNDARY.
2014 */
2015static void *script_kvars[] __initdata =
2016        { (void *)&jiffies };
2017#endif
2018
2019static  struct script script0 __initdata = {
2020/*--------------------------< START >-----------------------*/ {
2021        /*
2022        **      This NOP will be patched with LED ON
2023        **      SCR_REG_REG (gpreg, SCR_AND, 0xfe)
2024        */
2025        SCR_NO_OP,
2026                0,
2027        /*
2028        **      Clear SIGP.
2029        */
2030        SCR_FROM_REG (ctest2),
2031                0,
2032        /*
2033        **      Then jump to a certain point in tryloop.
2034        **      Due to the lack of indirect addressing the code
2035        **      is self modifying here.
2036        */
2037        SCR_JUMP,
2038}/*-------------------------< STARTPOS >--------------------*/,{
2039                PADDRH(tryloop),
2040
2041}/*-------------------------< SELECT >----------------------*/,{
2042        /*
2043        **      DSA     contains the address of a scheduled
2044        **              data structure.
2045        **
2046        **      SCRATCHA contains the address of the script,
2047        **              which starts the next entry.
2048        **
2049        **      Set Initiator mode.
2050        **
2051        **      (Target mode is left as an exercise for the reader)
2052        */
2053
2054        SCR_CLR (SCR_TRG),
2055                0,
2056        SCR_LOAD_REG (HS_REG, HS_SELECTING),
2057                0,
2058
2059        /*
2060        **      And try to select this target.
2061        */
2062        SCR_SEL_TBL_ATN ^ offsetof (struct dsb, select),
2063                PADDR (reselect),
2064
2065}/*-------------------------< SELECT2 >----------------------*/,{
2066        /*
2067        **      Now there are 4 possibilities:
2068        **
2069        **      (1) The ncr loses arbitration.
2070        **      This is ok, because it will try again,
2071        **      when the bus becomes idle.
2072        **      (But beware of the timeout function!)
2073        **
2074        **      (2) The ncr is reselected.
2075        **      Then the script processor takes the jump
2076        **      to the RESELECT label.
2077        **
2078        **      (3) The ncr wins arbitration.
2079        **      Then it will execute SCRIPTS instruction until 
2080        **      the next instruction that checks SCSI phase.
2081        **      Then will stop and wait for selection to be 
2082        **      complete or selection time-out to occur.
2083        **      As a result the SCRIPTS instructions until 
2084        **      LOADPOS + 2 should be executed in parallel with 
2085        **      the SCSI core performing selection.
2086        */
2087
2088        /*
2089        **      The MESSAGE_REJECT problem seems to be due to a selection 
2090        **      timing problem.
2091        **      Wait immediately for the selection to complete. 
2092        **      (2.5x behaves so)
2093        */
2094        SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2095                0,
2096
2097        /*
2098        **      Next time use the next slot.
2099        */
2100        SCR_COPY (4),
2101                RADDR (temp),
2102                PADDR (startpos),
2103        /*
2104        **      The ncr doesn't have an indirect load
2105        **      or store command. So we have to
2106        **      copy part of the control block to a
2107        **      fixed place, where we can access it.
2108        **
2109        **      We patch the address part of a
2110        **      COPY command with the DSA-register.
2111        */
2112        SCR_COPY_F (4),
2113                RADDR (dsa),
2114                PADDR (loadpos),
2115        /*
2116        **      Flush script prefetch if required
2117        */
2118        PREFETCH_FLUSH
2119        /*
2120        **      then we do the actual copy.
2121        */
2122        SCR_COPY (sizeof (struct head)),
2123        /*
2124        **      continued after the next label ...
2125        */
2126}/*-------------------------< LOADPOS >---------------------*/,{
2127                0,
2128                NADDR (header),
2129        /*
2130        **      Wait for the next phase or the selection
2131        **      to complete or time-out.
2132        */
2133        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2134                PADDR (prepare),
2135
2136}/*-------------------------< SEND_IDENT >----------------------*/,{
2137        /*
2138        **      Selection complete.
2139        **      Send the IDENTIFY and SIMPLE_TAG messages
2140        **      (and the EXTENDED_SDTR message)
2141        */
2142        SCR_MOVE_TBL ^ SCR_MSG_OUT,
2143                offsetof (struct dsb, smsg),
2144        SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
2145                PADDRH (resend_ident),
2146        SCR_LOAD_REG (scratcha, 0x80),
2147                0,
2148        SCR_COPY (1),
2149                RADDR (scratcha),
2150                NADDR (lastmsg),
2151}/*-------------------------< PREPARE >----------------------*/,{
2152        /*
2153        **      load the savep (saved pointer) into
2154        **      the TEMP register (actual pointer)
2155        */
2156        SCR_COPY (4),
2157                NADDR (header.savep),
2158                RADDR (temp),
2159        /*
2160        **      Initialize the status registers
2161        */
2162        SCR_COPY (4),
2163                NADDR (header.status),
2164                RADDR (scr0),
2165}/*-------------------------< PREPARE2 >---------------------*/,{
2166        /*
2167        **      Initialize the msgout buffer with a NOOP message.
2168        */
2169        SCR_LOAD_REG (scratcha, NOP),
2170                0,
2171        SCR_COPY (1),
2172                RADDR (scratcha),
2173                NADDR (msgout),
2174#if 0
2175        SCR_COPY (1),
2176                RADDR (scratcha),
2177                NADDR (msgin),
2178#endif
2179        /*
2180        **      Anticipate the COMMAND phase.
2181        **      This is the normal case for initial selection.
2182        */
2183        SCR_JUMP ^ IFFALSE (WHEN (SCR_COMMAND)),
2184                PADDR (dispatch),
2185
2186}/*-------------------------< COMMAND >--------------------*/,{
2187        /*
2188        **      ... and send the command
2189        */
2190        SCR_MOVE_TBL ^ SCR_COMMAND,
2191                offsetof (struct dsb, cmd),
2192        /*
2193        **      If status is still HS_NEGOTIATE, negotiation failed.
2194        **      We check this here, since we want to do that 
2195        **      only once.
2196        */
2197        SCR_FROM_REG (HS_REG),
2198                0,
2199        SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
2200                SIR_NEGO_FAILED,
2201
2202}/*-----------------------< DISPATCH >----------------------*/,{
2203        /*
2204        **      MSG_IN is the only phase that shall be 
2205        **      entered at least once for each (re)selection.
2206        **      So we test it first.
2207        */
2208        SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_IN)),
2209                PADDR (msg_in),
2210
2211        SCR_RETURN ^ IFTRUE (IF (SCR_DATA_OUT)),
2212                0,
2213        /*
2214        **      DEL 397 - 53C875 Rev 3 - Part Number 609-0392410 - ITEM 4.
2215        **      Possible data corruption during Memory Write and Invalidate.
2216        **      This work-around resets the addressing logic prior to the 
2217        **      start of the first MOVE of a DATA IN phase.
2218        **      (See Documentation/scsi/ncr53c8xx.txt for more information)
2219        */
2220        SCR_JUMPR ^ IFFALSE (IF (SCR_DATA_IN)),
2221                20,
2222        SCR_COPY (4),
2223                RADDR (scratcha),
2224                RADDR (scratcha),
2225        SCR_RETURN,
2226                0,
2227        SCR_JUMP ^ IFTRUE (IF (SCR_STATUS)),
2228                PADDR (status),
2229        SCR_JUMP ^ IFTRUE (IF (SCR_COMMAND)),
2230                PADDR (command),
2231        SCR_JUMP ^ IFTRUE (IF (SCR_MSG_OUT)),
2232                PADDR (msg_out),
2233        /*
2234        **      Discard one illegal phase byte, if required.
2235        */
2236        SCR_LOAD_REG (scratcha, XE_BAD_PHASE),
2237                0,
2238        SCR_COPY (1),
2239                RADDR (scratcha),
2240                NADDR (xerr_st),
2241        SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_OUT)),
2242                8,
2243        SCR_MOVE_ABS (1) ^ SCR_ILG_OUT,
2244                NADDR (scratch),
2245        SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_IN)),
2246                8,
2247        SCR_MOVE_ABS (1) ^ SCR_ILG_IN,
2248                NADDR (scratch),
2249        SCR_JUMP,
2250                PADDR (dispatch),
2251
2252}/*-------------------------< CLRACK >----------------------*/,{
2253        /*
2254        **      Terminate possible pending message phase.
2255        */
2256        SCR_CLR (SCR_ACK),
2257                0,
2258        SCR_JUMP,
2259                PADDR (dispatch),
2260
2261}/*-------------------------< NO_DATA >--------------------*/,{
2262        /*
2263        **      The target wants to tranfer too much data
2264        **      or in the wrong direction.
2265        **      Remember that in extended error.
2266        */
2267        SCR_LOAD_REG (scratcha, XE_EXTRA_DATA),
2268                0,
2269        SCR_COPY (1),
2270                RADDR (scratcha),
2271                NADDR (xerr_st),
2272        /*
2273        **      Discard one data byte, if required.
2274        */
2275        SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2276                8,
2277        SCR_MOVE_ABS (1) ^ SCR_DATA_OUT,
2278                NADDR (scratch),
2279        SCR_JUMPR ^ IFFALSE (IF (SCR_DATA_IN)),
2280                8,
2281        SCR_MOVE_ABS (1) ^ SCR_DATA_IN,
2282                NADDR (scratch),
2283        /*
2284        **      .. and repeat as required.
2285        */
2286        SCR_CALL,
2287                PADDR (dispatch),
2288        SCR_JUMP,
2289                PADDR (no_data),
2290
2291}/*-------------------------< STATUS >--------------------*/,{
2292        /*
2293        **      get the status
2294        */
2295        SCR_MOVE_ABS (1) ^ SCR_STATUS,
2296                NADDR (scratch),
2297        /*
2298        **      save status to scsi_status.
2299        **      mark as complete.
2300        */
2301        SCR_TO_REG (SS_REG),
2302                0,
2303        SCR_LOAD_REG (HS_REG, HS_COMPLETE),
2304                0,
2305        SCR_JUMP,
2306                PADDR (dispatch),
2307}/*-------------------------< MSG_IN >--------------------*/,{
2308        /*
2309        **      Get the first byte of the message
2310        **      and save it to SCRATCHA.
2311        **
2312        **      The script processor doesn't negate the
2313        **      ACK signal after this transfer.
2314        */
2315        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2316                NADDR (msgin[0]),
2317}/*-------------------------< MSG_IN2 >--------------------*/,{
2318        /*
2319        **      Handle this message.
2320        */
2321        SCR_JUMP ^ IFTRUE (DATA (COMMAND_COMPLETE)),
2322                PADDR (complete),
2323        SCR_JUMP ^ IFTRUE (DATA (DISCONNECT)),
2324                PADDR (disconnect),
2325        SCR_JUMP ^ IFTRUE (DATA (SAVE_POINTERS)),
2326                PADDR (save_dp),
2327        SCR_JUMP ^ IFTRUE (DATA (RESTORE_POINTERS)),
2328                PADDR (restore_dp),
2329        SCR_JUMP ^ IFTRUE (DATA (EXTENDED_MESSAGE)),
2330                PADDRH (msg_extended),
2331        SCR_JUMP ^ IFTRUE (DATA (NOP)),
2332                PADDR (clrack),
2333        SCR_JUMP ^ IFTRUE (DATA (MESSAGE_REJECT)),
2334                PADDRH (msg_reject),
2335        SCR_JUMP ^ IFTRUE (DATA (IGNORE_WIDE_RESIDUE)),
2336                PADDRH (msg_ign_residue),
2337        /*
2338        **      Rest of the messages left as
2339        **      an exercise ...
2340        **
2341        **      Unimplemented messages:
2342        **      fall through to MSG_BAD.
2343        */
2344}/*-------------------------< MSG_BAD >------------------*/,{
2345        /*
2346        **      unimplemented message - reject it.
2347        */
2348        SCR_INT,
2349                SIR_REJECT_SENT,
2350        SCR_LOAD_REG (scratcha, MESSAGE_REJECT),
2351                0,
2352}/*-------------------------< SETMSG >----------------------*/,{
2353        SCR_COPY (1),
2354                RADDR (scratcha),
2355                NADDR (msgout),
2356        SCR_SET (SCR_ATN),
2357                0,
2358        SCR_JUMP,
2359                PADDR (clrack),
2360}/*-------------------------< CLEANUP >-------------------*/,{
2361        /*
2362        **      dsa:    Pointer to ccb
2363        **            or xxxxxxFF (no ccb)
2364        **
2365        **      HS_REG:   Host-Status (<>0!)
2366        */
2367        SCR_FROM_REG (dsa),
2368                0,
2369        SCR_JUMP ^ IFTRUE (DATA (0xff)),
2370                PADDR (start),
2371        /*
2372        **      dsa is valid.
2373        **      complete the cleanup.
2374        */
2375        SCR_JUMP,
2376                PADDR (cleanup_ok),
2377
2378}/*-------------------------< COMPLETE >-----------------*/,{
2379        /*
2380        **      Complete message.
2381        **
2382        **      Copy TEMP register to LASTP in header.
2383        */
2384        SCR_COPY (4),
2385                RADDR (temp),
2386                NADDR (header.lastp),
2387        /*
2388        **      When we terminate the cycle by clearing ACK,
2389        **      the target may disconnect immediately.
2390        **
2391        **      We don't want to be told of an
2392        **      "unexpected disconnect",
2393        **      so we disable this feature.
2394        */
2395        SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2396                0,
2397        /*
2398        **      Terminate cycle ...
2399        */
2400        SCR_CLR (SCR_ACK|SCR_ATN),
2401                0,
2402        /*
2403        **      ... and wait for the disconnect.
2404        */
2405        SCR_WAIT_DISC,
2406                0,
2407}/*-------------------------< CLEANUP_OK >----------------*/,{
2408        /*
2409        **      Save host status to header.
2410        */
2411        SCR_COPY (4),
2412                RADDR (scr0),
2413                NADDR (header.status),
2414        /*
2415        **      and copy back the header to the ccb.
2416        */
2417        SCR_COPY_F (4),
2418                RADDR (dsa),
2419                PADDR (cleanup0),
2420        /*
2421        **      Flush script prefetch if required
2422        */
2423        PREFETCH_FLUSH
2424        SCR_COPY (sizeof (struct head)),
2425                NADDR (header),
2426}/*-------------------------< CLEANUP0 >--------------------*/,{
2427                0,
2428}/*-------------------------< SIGNAL >----------------------*/,{
2429        /*
2430        **      if job not completed ...
2431        */
2432        SCR_FROM_REG (HS_REG),
2433                0,
2434        /*
2435        **      ... start the next command.
2436        */
2437        SCR_JUMP ^ IFTRUE (MASK (0, (HS_DONEMASK|HS_SKIPMASK))),
2438                PADDR(start),
2439        /*
2440        **      If command resulted in not GOOD status,
2441        **      call the C code if needed.
2442        */
2443        SCR_FROM_REG (SS_REG),
2444                0,
2445        SCR_CALL ^ IFFALSE (DATA (S_GOOD)),
2446                PADDRH (bad_status),
2447
2448#ifndef SCSI_NCR_CCB_DONE_SUPPORT
2449
2450        /*
2451        **      ... signal completion to the host
2452        */
2453        SCR_INT,
2454                SIR_INTFLY,
2455        /*
2456        **      Auf zu neuen Schandtaten!
2457        */
2458        SCR_JUMP,
2459                PADDR(start),
2460
2461#else   /* defined SCSI_NCR_CCB_DONE_SUPPORT */
2462
2463        /*
2464        **      ... signal completion to the host
2465        */
2466        SCR_JUMP,
2467}/*------------------------< DONE_POS >---------------------*/,{
2468                PADDRH (done_queue),
2469}/*------------------------< DONE_PLUG >--------------------*/,{
2470        SCR_INT,
2471                SIR_DONE_OVERFLOW,
2472}/*------------------------< DONE_END >---------------------*/,{
2473        SCR_INT,
2474                SIR_INTFLY,
2475        SCR_COPY (4),
2476                RADDR (temp),
2477                PADDR (done_pos),
2478        SCR_JUMP,
2479                PADDR (start),
2480
2481#endif  /* SCSI_NCR_CCB_DONE_SUPPORT */
2482
2483}/*-------------------------< SAVE_DP >------------------*/,{
2484        /*
2485        **      SAVE_DP message:
2486        **      Copy TEMP register to SAVEP in header.
2487        */
2488        SCR_COPY (4),
2489                RADDR (temp),
2490                NADDR (header.savep),
2491        SCR_CLR (SCR_ACK),
2492                0,
2493        SCR_JUMP,
2494                PADDR (dispatch),
2495}/*-------------------------< RESTORE_DP >---------------*/,{
2496        /*
2497        **      RESTORE_DP message:
2498        **      Copy SAVEP in header to TEMP register.
2499        */
2500        SCR_COPY (4),
2501                NADDR (header.savep),
2502                RADDR (temp),
2503        SCR_JUMP,
2504                PADDR (clrack),
2505
2506}/*-------------------------< DISCONNECT >---------------*/,{
2507        /*
2508        **      DISCONNECTing  ...
2509        **
2510        **      disable the "unexpected disconnect" feature,
2511        **      and remove the ACK signal.
2512        */
2513        SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2514                0,
2515        SCR_CLR (SCR_ACK|SCR_ATN),
2516                0,
2517        /*
2518        **      Wait for the disconnect.
2519        */
2520        SCR_WAIT_DISC,
2521                0,
2522        /*
2523        **      Status is: DISCONNECTED.
2524        */
2525        SCR_LOAD_REG (HS_REG, HS_DISCONNECT),
2526                0,
2527        SCR_JUMP,
2528                PADDR (cleanup_ok),
2529
2530}/*-------------------------< MSG_OUT >-------------------*/,{
2531        /*
2532        **      The target requests a message.
2533        */
2534        SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
2535                NADDR (msgout),
2536        SCR_COPY (1),
2537                NADDR (msgout),
2538                NADDR (lastmsg),
2539        /*
2540        **      If it was no ABORT message ...
2541        */
2542        SCR_JUMP ^ IFTRUE (DATA (ABORT_TASK_SET)),
2543                PADDRH (msg_out_abort),
2544        /*
2545        **      ... wait for the next phase
2546        **      if it's a message out, send it again, ...
2547        */
2548        SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
2549                PADDR (msg_out),
2550}/*-------------------------< MSG_OUT_DONE >--------------*/,{
2551        /*
2552        **      ... else clear the message ...
2553        */
2554        SCR_LOAD_REG (scratcha, NOP),
2555                0,
2556        SCR_COPY (4),
2557                RADDR (scratcha),
2558                NADDR (msgout),
2559        /*
2560        **      ... and process the next phase
2561        */
2562        SCR_JUMP,
2563                PADDR (dispatch),
2564}/*-------------------------< IDLE >------------------------*/,{
2565        /*
2566        **      Nothing to do?
2567        **      Wait for reselect.
2568        **      This NOP will be patched with LED OFF
2569        **      SCR_REG_REG (gpreg, SCR_OR, 0x01)
2570        */
2571        SCR_NO_OP,
2572                0,
2573}/*-------------------------< RESELECT >--------------------*/,{
2574        /*
2575        **      make the DSA invalid.
2576        */
2577        SCR_LOAD_REG (dsa, 0xff),
2578                0,
2579        SCR_CLR (SCR_TRG),
2580                0,
2581        SCR_LOAD_REG (HS_REG, HS_IN_RESELECT),
2582                0,
2583        /*
2584        **      Sleep waiting for a reselection.
2585        **      If SIGP is set, special treatment.
2586        **
2587        **      Zu allem bereit ..
2588        */
2589        SCR_WAIT_RESEL,
2590                PADDR(start),
2591}/*-------------------------< RESELECTED >------------------*/,{
2592        /*
2593        **      This NOP will be patched with LED ON
2594        **      SCR_REG_REG (gpreg, SCR_AND, 0xfe)
2595        */
2596        SCR_NO_OP,
2597                0,
2598        /*
2599        **      ... zu nichts zu gebrauchen ?
2600        **
2601        **      load the target id into the SFBR
2602        **      and jump to the control block.
2603        **
2604        **      Look at the declarations of
2605        **      - struct ncb
2606        **      - struct tcb
2607        **      - struct lcb
2608        **      - struct ccb
2609        **      to understand what's going on.
2610        */
2611        SCR_REG_SFBR (ssid, SCR_AND, 0x8F),
2612                0,
2613        SCR_TO_REG (sdid),
2614                0,
2615        SCR_JUMP,
2616                NADDR (jump_tcb),
2617
2618}/*-------------------------< RESEL_DSA >-------------------*/,{
2619        /*
2620        **      Ack the IDENTIFY or TAG previously received.
2621        */
2622        SCR_CLR (SCR_ACK),
2623                0,
2624        /*
2625        **      The ncr doesn't have an indirect load
2626        **      or store command. So we have to
2627        **      copy part of the control block to a
2628        **      fixed place, where we can access it.
2629        **
2630        **      We patch the address part of a
2631        **      COPY command with the DSA-register.
2632        */
2633        SCR_COPY_F (4),
2634                RADDR (dsa),
2635                PADDR (loadpos1),
2636        /*
2637        **      Flush script prefetch if required
2638        */
2639        PREFETCH_FLUSH
2640        /*
2641        **      then we do the actual copy.
2642        */
2643        SCR_COPY (sizeof (struct head)),
2644        /*
2645        **      continued after the next label ...
2646        */
2647
2648}/*-------------------------< LOADPOS1 >-------------------*/,{
2649                0,
2650                NADDR (header),
2651        /*
2652        **      The DSA contains the data structure address.
2653        */
2654        SCR_JUMP,
2655                PADDR (prepare),
2656
2657}/*-------------------------< RESEL_LUN >-------------------*/,{
2658        /*
2659        **      come back to this point
2660        **      to get an IDENTIFY message
2661        **      Wait for a msg_in phase.
2662        */
2663        SCR_INT ^ IFFALSE (WHEN (SCR_MSG_IN)),
2664                SIR_RESEL_NO_MSG_IN,
2665        /*
2666        **      message phase.
2667        **      Read the data directly from the BUS DATA lines.
2668        **      This helps to support very old SCSI devices that 
2669        **      may reselect without sending an IDENTIFY.
2670        */
2671        SCR_FROM_REG (sbdl),
2672                0,
2673        /*
2674        **      It should be an Identify message.
2675        */
2676        SCR_RETURN,
2677                0,
2678}/*-------------------------< RESEL_TAG >-------------------*/,{
2679        /*
2680        **      Read IDENTIFY + SIMPLE + TAG using a single MOVE.
2681        **      Aggressive optimization, is'nt it?
2682        **      No need to test the SIMPLE TAG message, since the 
2683        **      driver only supports conformant devices for tags. ;-)
2684        */
2685        SCR_MOVE_ABS (3) ^ SCR_MSG_IN,
2686                NADDR (msgin),
2687        /*
2688        **      Read the TAG from the SIDL.
2689        **      Still an aggressive optimization. ;-)
2690        **      Compute the CCB indirect jump address which 
2691        **      is (#TAG*2 & 0xfc) due to tag numbering using 
2692        **      1,3,5..MAXTAGS*2+1 actual values.
2693        */
2694        SCR_REG_SFBR (sidl, SCR_SHL, 0),
2695                0,
2696        SCR_SFBR_REG (temp, SCR_AND, 0xfc),
2697                0,
2698}/*-------------------------< JUMP_TO_NEXUS >-------------------*/,{
2699        SCR_COPY_F (4),
2700                RADDR (temp),
2701                PADDR (nexus_indirect),
2702        /*
2703        **      Flush script prefetch if required
2704        */
2705        PREFETCH_FLUSH
2706        SCR_COPY (4),
2707}/*-------------------------< NEXUS_INDIRECT >-------------------*/,{
2708                0,
2709                RADDR (temp),
2710        SCR_RETURN,
2711                0,
2712}/*-------------------------< RESEL_NOTAG >-------------------*/,{
2713        /*
2714        **      No tag expected.
2715        **      Read an throw away the IDENTIFY.
2716        */
2717        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2718                NADDR (msgin),
2719        SCR_JUMP,
2720                PADDR (jump_to_nexus),
2721}/*-------------------------< DATA_IN >--------------------*/,{
2722/*
2723**      Because the size depends on the
2724**      #define MAX_SCATTERL parameter,
2725**      it is filled in at runtime.
2726**
2727**  ##===========< i=0; i<MAX_SCATTERL >=========
2728**  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
2729**  ||          PADDR (dispatch),
2730**  ||  SCR_MOVE_TBL ^ SCR_DATA_IN,
2731**  ||          offsetof (struct dsb, data[ i]),
2732**  ##==========================================
2733**
2734**---------------------------------------------------------
2735*/
27360
2737}/*-------------------------< DATA_IN2 >-------------------*/,{
2738        SCR_CALL,
2739                PADDR (dispatch),
2740        SCR_JUMP,
2741                PADDR (no_data),
2742}/*-------------------------< DATA_OUT >--------------------*/,{
2743/*
2744**      Because the size depends on the
2745**      #define MAX_SCATTERL parameter,
2746**      it is filled in at runtime.
2747**
2748**  ##===========< i=0; i<MAX_SCATTERL >=========
2749**  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2750**  ||          PADDR (dispatch),
2751**  ||  SCR_MOVE_TBL ^ SCR_DATA_OUT,
2752**  ||          offsetof (struct dsb, data[ i]),
2753**  ##==========================================
2754**
2755**---------------------------------------------------------
2756*/
27570
2758}/*-------------------------< DATA_OUT2 >-------------------*/,{
2759        SCR_CALL,
2760                PADDR (dispatch),
2761        SCR_JUMP,
2762                PADDR (no_data),
2763}/*--------------------------------------------------------*/
2764};
2765
2766static  struct scripth scripth0 __initdata = {
2767/*-------------------------< TRYLOOP >---------------------*/{
2768/*
2769**      Start the next entry.
2770**      Called addresses point to the launch script in the CCB.
2771**      They are patched by the main processor.
2772**
2773**      Because the size depends on the
2774**      #define MAX_START parameter, it is filled
2775**      in at runtime.
2776**
2777**-----------------------------------------------------------
2778**
2779**  ##===========< I=0; i<MAX_START >===========
2780**  ||  SCR_CALL,
2781**  ||          PADDR (idle),
2782**  ##==========================================
2783**
2784**-----------------------------------------------------------
2785*/
27860
2787}/*------------------------< TRYLOOP2 >---------------------*/,{
2788        SCR_JUMP,
2789                PADDRH(tryloop),
2790
2791#ifdef SCSI_NCR_CCB_DONE_SUPPORT
2792
2793}/*------------------------< DONE_QUEUE >-------------------*/,{
2794/*
2795**      Copy the CCB address to the next done entry.
2796**      Because the size depends on the
2797**      #define MAX_DONE parameter, it is filled
2798**      in at runtime.
2799**
2800**-----------------------------------------------------------
2801**
2802**  ##===========< I=0; i<MAX_DONE >===========
2803**  ||  SCR_COPY (sizeof(struct ccb *),
2804**  ||          NADDR (header.cp),
2805**  ||          NADDR (ccb_done[i]),
2806**  ||  SCR_CALL,
2807**  ||          PADDR (done_end),
2808**  ##==========================================
2809**
2810**-----------------------------------------------------------
2811*/
28120
2813}/*------------------------< DONE_QUEUE2 >------------------*/,{
2814        SCR_JUMP,
2815                PADDRH (done_queue),
2816
2817#endif /* SCSI_NCR_CCB_DONE_SUPPORT */
2818}/*------------------------< SELECT_NO_ATN >-----------------*/,{
2819        /*
2820        **      Set Initiator mode.
2821        **      And try to select this target without ATN.
2822        */
2823
2824        SCR_CLR (SCR_TRG),
2825                0,
2826        SCR_LOAD_REG (HS_REG, HS_SELECTING),
2827                0,
2828        SCR_SEL_TBL ^ offsetof (struct dsb, select),
2829                PADDR (reselect),
2830        SCR_JUMP,
2831                PADDR (select2),
2832
2833}/*-------------------------< CANCEL >------------------------*/,{
2834
2835        SCR_LOAD_REG (scratcha, HS_ABORTED),
2836                0,
2837        SCR_JUMPR,
2838                8,
2839}/*-------------------------< SKIP >------------------------*/,{
2840        SCR_LOAD_REG (scratcha, 0),
2841                0,
2842        /*
2843        **      This entry has been canceled.
2844        **      Next time use the next slot.
2845        */
2846        SCR_COPY (4),
2847                RADDR (temp),
2848                PADDR (startpos),
2849        /*
2850        **      The ncr doesn't have an indirect load
2851        **      or store command. So we have to
2852        **      copy part of the control block to a
2853        **      fixed place, where we can access it.
2854        **
2855        **      We patch the address part of a
2856        **      COPY command with the DSA-register.
2857        */
2858        SCR_COPY_F (4),
2859                RADDR (dsa),
2860                PADDRH (skip2),
2861        /*
2862        **      Flush script prefetch if required
2863        */
2864        PREFETCH_FLUSH
2865        /*
2866        **      then we do the actual copy.
2867        */
2868        SCR_COPY (sizeof (struct head)),
2869        /*
2870        **      continued after the next label ...
2871        */
2872}/*-------------------------< SKIP2 >---------------------*/,{
2873                0,
2874                NADDR (header),
2875        /*
2876        **      Initialize the status registers
2877        */
2878        SCR_COPY (4),
2879                NADDR (header.status),
2880                RADDR (scr0),
2881        /*
2882        **      Force host status.
2883        */
2884        SCR_FROM_REG (scratcha),
2885                0,
2886        SCR_JUMPR ^ IFFALSE (MASK (0, HS_DONEMASK)),
2887                16,
2888        SCR_REG_REG (HS_REG, SCR_OR, HS_SKIPMASK),
2889                0,
2890        SCR_JUMPR,
2891                8,
2892        SCR_TO_REG (HS_REG),
2893                0,
2894        SCR_LOAD_REG (SS_REG, S_GOOD),
2895                0,
2896        SCR_JUMP,
2897                PADDR (cleanup_ok),
2898
2899},/*-------------------------< PAR_ERR_DATA_IN >---------------*/{
2900        /*
2901        **      Ignore all data in byte, until next phase
2902        */
2903        SCR_JUMP ^ IFFALSE (WHEN (SCR_DATA_IN)),
2904                PADDRH (par_err_other),
2905        SCR_MOVE_ABS (1) ^ SCR_DATA_IN,
2906                NADDR (scratch),
2907        SCR_JUMPR,
2908                -24,
2909},/*-------------------------< PAR_ERR_OTHER >------------------*/{
2910        /*
2911        **      count it.
2912        */
2913        SCR_REG_REG (PS_REG, SCR_ADD, 0x01),
2914                0,
2915        /*
2916        **      jump to dispatcher.
2917        */
2918        SCR_JUMP,
2919                PADDR (dispatch),
2920}/*-------------------------< MSG_REJECT >---------------*/,{
2921        /*
2922        **      If a negotiation was in progress,
2923        **      negotiation failed.
2924        **      Otherwise, let the C code print 
2925        **      some message.
2926        */
2927        SCR_FROM_REG (HS_REG),
2928                0,
2929        SCR_INT ^ IFFALSE (DATA (HS_NEGOTIATE)),
2930                SIR_REJECT_RECEIVED,
2931        SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
2932                SIR_NEGO_FAILED,
2933        SCR_JUMP,
2934                PADDR (clrack),
2935
2936}/*-------------------------< MSG_IGN_RESIDUE >----------*/,{
2937        /*
2938        **      Terminate cycle
2939        */
2940        SCR_CLR (SCR_ACK),
2941                0,
2942        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2943                PADDR (dispatch),
2944        /*
2945        **      get residue size.
2946        */
2947        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2948                NADDR (msgin[1]),
2949        /*
2950        **      Size is 0 .. ignore message.
2951        */
2952        SCR_JUMP ^ IFTRUE (DATA (0)),
2953                PADDR (clrack),
2954        /*
2955        **      Size is not 1 .. have to interrupt.
2956        */
2957        SCR_JUMPR ^ IFFALSE (DATA (1)),
2958                40,
2959        /*
2960        **      Check for residue byte in swide register
2961        */
2962        SCR_FROM_REG (scntl2),
2963                0,
2964        SCR_JUMPR ^ IFFALSE (MASK (WSR, WSR)),
2965                16,
2966        /*
2967        **      There IS data in the swide register.
2968        **      Discard it.
2969        */
2970        SCR_REG_REG (scntl2, SCR_OR, WSR),
2971                0,
2972        SCR_JUMP,
2973                PADDR (clrack),
2974        /*
2975        **      Load again the size to the sfbr register.
2976        */
2977        SCR_FROM_REG (scratcha),
2978                0,
2979        SCR_INT,
2980                SIR_IGN_RESIDUE,
2981        SCR_JUMP,
2982                PADDR (clrack),
2983
2984}/*-------------------------< MSG_EXTENDED >-------------*/,{
2985        /*
2986        **      Terminate cycle
2987        */
2988        SCR_CLR (SCR_ACK),
2989                0,
2990        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2991                PADDR (dispatch),
2992        /*
2993        **      get length.
2994        */
2995        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2996                NADDR (msgin[1]),
2997        /*
2998        */
2999        SCR_JUMP ^ IFTRUE (DATA (3)),
3000                PADDRH (msg_ext_3),
3001        SCR_JUMP ^ IFFALSE (DATA (2)),
3002                PADDR (msg_bad),
3003}/*-------------------------< MSG_EXT_2 >----------------*/,{
3004        SCR_CLR (SCR_ACK),
3005                0,
3006        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
3007                PADDR (dispatch),
3008        /*
3009        **      get extended message code.
3010        */
3011        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3012                NADDR (msgin[2]),
3013        SCR_JUMP ^ IFTRUE (DATA (EXTENDED_WDTR)),
3014                PADDRH (msg_wdtr),
3015        /*
3016        **      unknown extended message
3017        */
3018        SCR_JUMP,
3019                PADDR (msg_bad)
3020}/*-------------------------< MSG_WDTR >-----------------*/,{
3021        SCR_CLR (SCR_ACK),
3022                0,
3023        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
3024                PADDR (dispatch),
3025        /*
3026        **      get data bus width
3027        */
3028        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3029                NADDR (msgin[3]),
3030        /*
3031        **      let the host do the real work.
3032        */
3033        SCR_INT,
3034                SIR_NEGO_WIDE,
3035        /*
3036        **      let the target fetch our answer.
3037        */
3038        SCR_SET (SCR_ATN),
3039                0,
3040        SCR_CLR (SCR_ACK),
3041                0,
3042        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
3043                PADDRH (nego_bad_phase),
3044
3045}/*-------------------------< SEND_WDTR >----------------*/,{
3046        /*
3047        **      Send the EXTENDED_WDTR
3048        */
3049        SCR_MOVE_ABS (4) ^ SCR_MSG_OUT,
3050                NADDR (msgout),
3051        SCR_COPY (1),
3052                NADDR (msgout),
3053                NADDR (lastmsg),
3054        SCR_JUMP,
3055                PADDR (msg_out_done),
3056
3057}/*-------------------------< MSG_EXT_3 >----------------*/,{
3058        SCR_CLR (SCR_ACK),
3059                0,
3060        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
3061                PADDR (dispatch),
3062        /*
3063        **      get extended message code.
3064        */
3065        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3066                NADDR (msgin[2]),
3067        SCR_JUMP ^ IFTRUE (DATA (EXTENDED_SDTR)),
3068                PADDRH (msg_sdtr),
3069        /*
3070        **      unknown extended message
3071        */
3072        SCR_JUMP,
3073                PADDR (msg_bad)
3074
3075}/*-------------------------< MSG_SDTR >-----------------*/,{
3076        SCR_CLR (SCR_ACK),
3077                0,
3078        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
3079                PADDR (dispatch),
3080        /*
3081        **      get period and offset
3082        */
3083        SCR_MOVE_ABS (2) ^ SCR_MSG_IN,
3084                NADDR (msgin[3]),
3085        /*
3086        **      let the host do the real work.
3087        */
3088        SCR_INT,
3089                SIR_NEGO_SYNC,
3090        /*
3091        **      let the target fetch our answer.
3092        */
3093        SCR_SET (SCR_ATN),
3094                0,
3095        SCR_CLR (SCR_ACK),
3096                0,
3097        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
3098                PADDRH (nego_bad_phase),
3099
3100}/*-------------------------< SEND_SDTR >-------------*/,{
3101        /*
3102        **      Send the EXTENDED_SDTR
3103        */
3104        SCR_MOVE_ABS (5) ^ SCR_MSG_OUT,
3105                NADDR (msgout),
3106        SCR_COPY (1),
3107                NADDR (msgout),
3108                NADDR (lastmsg),
3109        SCR_JUMP,
3110                PADDR (msg_out_done),
3111
3112}/*-------------------------< NEGO_BAD_PHASE >------------*/,{
3113        SCR_INT,
3114                SIR_NEGO_PROTO,
3115        SCR_JUMP,
3116                PADDR (dispatch),
3117
3118}/*-------------------------< MSG_OUT_ABORT >-------------*/,{
3119        /*
3120        **      After ABORT message,
3121        **
3122        **      expect an immediate disconnect, ...
3123        */
3124        SCR_REG_REG (scntl2, SCR_AND, 0x7f),
3125                0,
3126        SCR_CLR (SCR_ACK|SCR_ATN),
3127                0,
3128        SCR_WAIT_DISC,
3129                0,
3130        /*
3131        **      ... and set the status to "ABORTED"
3132        */
3133        SCR_LOAD_REG (HS_REG, HS_ABORTED),
3134                0,
3135        SCR_JUMP,
3136                PADDR (cleanup),
3137
3138}/*-------------------------< HDATA_IN >-------------------*/,{
3139/*
3140**      Because the size depends on the
3141**      #define MAX_SCATTERH parameter,
3142**      it is filled in at runtime.
3143**
3144**  ##==< i=MAX_SCATTERL; i<MAX_SCATTERL+MAX_SCATTERH >==
3145**  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
3146**  ||          PADDR (dispatch),
3147**  ||  SCR_MOVE_TBL ^ SCR_DATA_IN,
3148**  ||          offsetof (struct dsb, data[ i]),
3149**  ##===================================================
3150**
3151**---------------------------------------------------------
3152*/
31530
3154}/*-------------------------< HDATA_IN2 >------------------*/,{
3155        SCR_JUMP,
3156                PADDR (data_in),
3157
3158}/*-------------------------< HDATA_OUT >-------------------*/,{
3159/*
3160**      Because the size depends on the
3161**      #define MAX_SCATTERH parameter,
3162**      it is filled in at runtime.
3163**
3164**  ##==< i=MAX_SCATTERL; i<MAX_SCATTERL+MAX_SCATTERH >==
3165**  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT)),
3166**  ||          PADDR (dispatch),
3167**  ||  SCR_MOVE_TBL ^ SCR_DATA_OUT,
3168**  ||          offsetof (struct dsb, data[ i]),
3169**  ##===================================================
3170**
3171**---------------------------------------------------------
3172*/
31730
3174}/*-------------------------< HDATA_OUT2 >------------------*/,{
3175        SCR_JUMP,
3176                PADDR (data_out),
3177
3178}/*-------------------------< RESET >----------------------*/,{
3179        /*
3180        **      Send a TARGET_RESET message if bad IDENTIFY 
3181        **      received on reselection.
3182        */
3183        SCR_LOAD_REG (scratcha, ABORT_TASK),
3184                0,
3185        SCR_JUMP,
3186                PADDRH (abort_resel),
3187}/*-------------------------< ABORTTAG >-------------------*/,{
3188        /*
3189        **      Abort a wrong tag received on reselection.
3190        */
3191        SCR_LOAD_REG (scratcha, ABORT_TASK),
3192                0,
3193        SCR_JUMP,
3194                PADDRH (abort_resel),
3195}/*-------------------------< ABORT >----------------------*/,{
3196        /*
3197        **      Abort a reselection when no active CCB.
3198        */
3199        SCR_LOAD_REG (scratcha, ABORT_TASK_SET),
3200                0,
3201}/*-------------------------< ABORT_RESEL >----------------*/,{
3202        SCR_COPY (1),
3203                RADDR (scratcha),
3204                NADDR (msgout),
3205        SCR_SET (SCR_ATN),
3206                0,
3207        SCR_CLR (SCR_ACK),
3208                0,
3209        /*
3210        **      and send it.
3211        **      we expect an immediate disconnect
3212        */
3213        SCR_REG_REG (scntl2, SCR_AND, 0x7f),
3214                0,
3215        SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
3216                NADDR (msgout),
3217        SCR_COPY (1),
3218                NADDR (msgout),
3219                NADDR (lastmsg),
3220        SCR_CLR (SCR_ACK|SCR_ATN),
3221                0,
3222        SCR_WAIT_DISC,
3223                0,
3224        SCR_JUMP,
3225                PADDR (start),
3226}/*-------------------------< RESEND_IDENT >-------------------*/,{
3227        /*
3228        **      The target stays in MSG OUT phase after having acked 
3229        **      Identify [+ Tag [+ Extended message ]]. Targets shall
3230        **      behave this way on parity error.
3231        **      We must send it again all the messages.
3232        */
3233        SCR_SET (SCR_ATN), /* Shall be asserted 2 deskew delays before the  */
3234                0,         /* 1rst ACK = 90 ns. Hope the NCR is'nt too fast */
3235        SCR_JUMP,
3236                PADDR (send_ident),
3237}/*-------------------------< CLRATN_GO_ON >-------------------*/,{
3238        SCR_CLR (SCR_ATN),
3239                0,
3240        SCR_JUMP,
3241}/*-------------------------< NXTDSP_GO_ON >-------------------*/,{
3242                0,
3243}/*-------------------------< SDATA_IN >-------------------*/,{
3244        SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
3245                PADDR (dispatch),
3246        SCR_MOVE_TBL ^ SCR_DATA_IN,
3247                offsetof (struct dsb, sense),
3248        SCR_CALL,
3249                PADDR (dispatch),
3250        SCR_JUMP,
3251                PADDR (no_data),
3252}/*-------------------------< DATA_IO >--------------------*/,{
3253        /*
3254        **      We jump here if the data direction was unknown at the 
3255        **      time we had to queue the command to the scripts processor.
3256        **      Pointers had been set as follow in this situation:
3257        **        savep   -->   DATA_IO
3258        **        lastp   -->   start pointer when DATA_IN
3259        **        goalp   -->   goal  pointer when DATA_IN
3260        **        wlastp  -->   start pointer when DATA_OUT
3261        **        wgoalp  -->   goal  pointer when DATA_OUT
3262        **      This script sets savep/lastp/goalp according to the 
3263        **      direction chosen by the target.
3264        */
3265        SCR_JUMPR ^ IFTRUE (WHEN (SCR_DATA_OUT)),
3266                32,
3267        /*
3268        **      Direction is DATA IN.
3269        **      Warning: we jump here, even when phase is DATA OUT.
3270        */
3271        SCR_COPY (4),
3272                NADDR (header.lastp),
3273                NADDR (header.savep),
3274
3275        /*
3276        **      Jump to the SCRIPTS according to actual direction.
3277        */
3278        SCR_COPY (4),
3279                NADDR (header.savep),
3280                RADDR (temp),
3281        SCR_RETURN,
3282                0,
3283        /*
3284        **      Direction is DATA OUT.
3285        */
3286        SCR_COPY (4),
3287                NADDR (header.wlastp),
3288                NADDR (header.lastp),
3289        SCR_COPY (4),
3290                NADDR (header.wgoalp),
3291                NADDR (header.goalp),
3292        SCR_JUMPR,
3293                -64,
3294}/*-------------------------< BAD_IDENTIFY >---------------*/,{
3295        /*
3296        **      If message phase but not an IDENTIFY,
3297        **      get some help from the C code.
3298        **      Old SCSI device may behave so.
3299        */
3300        SCR_JUMPR ^ IFTRUE (MASK (0x80, 0x80)),
3301                16,
3302        SCR_INT,
3303                SIR_RESEL_NO_IDENTIFY,
3304        SCR_JUMP,
3305                PADDRH (reset),
3306        /*
3307        **      Message is an IDENTIFY, but lun is unknown.
3308        **      Read the message, since we got it directly 
3309        **      from the SCSI BUS data lines.
3310        **      Signal problem to C code for logging the event.
3311        **      Send an ABORT_TASK_SET to clear all pending tasks.
3312        */
3313        SCR_INT,
3314                SIR_RESEL_BAD_LUN,
3315        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3316                NADDR (msgin),
3317        SCR_JUMP,
3318                PADDRH (abort),
3319}/*-------------------------< BAD_I_T_L >------------------*/,{
3320        /*
3321        **      We donnot have a task for that I_T_L.
3322        **      Signal problem to C code for logging the event.
3323        **      Send an ABORT_TASK_SET message.
3324        */
3325        SCR_INT,
3326                SIR_RESEL_BAD_I_T_L,
3327        SCR_JUMP,
3328                PADDRH (abort),
3329}/*-------------------------< BAD_I_T_L_Q >----------------*/,{
3330        /*
3331        **      We donnot have a task that matches the tag.
3332        **      Signal problem to C code for logging the event.
3333        **      Send an ABORT_TASK message.
3334        */
3335        SCR_INT,
3336                SIR_RESEL_BAD_I_T_L_Q,
3337        SCR_JUMP,
3338                PADDRH (aborttag),
3339}/*-------------------------< BAD_TARGET >-----------------*/,{
3340        /*
3341        **      We donnot know the target that reselected us.
3342        **      Grab the first message if any (IDENTIFY).
3343        **      Signal problem to C code for logging the event.
3344        **      TARGET_RESET message.
3345        */
3346        SCR_INT,
3347                SIR_RESEL_BAD_TARGET,
3348        SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_IN)),
3349                8,
3350        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3351                NADDR (msgin),
3352        SCR_JUMP,
3353                PADDRH (reset),
3354}/*-------------------------< BAD_STATUS >-----------------*/,{
3355        /*
3356        **      If command resulted in either QUEUE FULL,
3357        **      CHECK CONDITION or COMMAND TERMINATED,
3358        **      call the C code.
3359        */
3360        SCR_INT ^ IFTRUE (DATA (S_QUEUE_FULL)),
3361                SIR_BAD_STATUS,
3362        SCR_INT ^ IFTRUE (DATA (S_CHECK_COND)),
3363                SIR_BAD_STATUS,
3364        SCR_INT ^ IFTRUE (DATA (S_TERMINATED)),
3365                SIR_BAD_STATUS,
3366        SCR_RETURN,
3367                0,
3368}/*-------------------------< START_RAM >-------------------*/,{
3369        /*
3370        **      Load the script into on-chip RAM, 
3371        **      and jump to start point.
3372        */
3373        SCR_COPY_F (4),
3374                RADDR (scratcha),
3375                PADDRH (start_ram0),
3376        /*
3377        **      Flush script prefetch if required
3378        */
3379        PREFETCH_FLUSH
3380        SCR_COPY (sizeof (struct script)),
3381}/*-------------------------< START_RAM0 >--------------------*/,{
3382                0,
3383                PADDR (start),
3384        SCR_JUMP,
3385                PADDR (start),
3386}/*-------------------------< STO_RESTART >-------------------*/,{
3387        /*
3388        **
3389        **      Repair start queue (e.g. next time use the next slot) 
3390        **      and jump to start point.
3391        */
3392        SCR_COPY (4),
3393                RADDR (temp),
3394                PADDR (startpos),
3395        SCR_JUMP,
3396                PADDR (start),
3397}/*-------------------------< WAIT_DMA >-------------------*/,{
3398        /*
3399        **      For HP Zalon/53c720 systems, the Zalon interface
3400        **      between CPU and 53c720 does prefetches, which causes
3401        **      problems with self modifying scripts.  The problem
3402        **      is overcome by calling a dummy subroutine after each
3403        **      modification, to force a refetch of the script on
3404        **      return from the subroutine.
3405        */
3406        SCR_RETURN,
3407                0,
3408}/*-------------------------< SNOOPTEST >-------------------*/,{
3409        /*
3410        **      Read the variable.
3411        */
3412        SCR_COPY (4),
3413                NADDR(ncr_cache),
3414                RADDR (scratcha),
3415        /*
3416        **      Write the variable.
3417        */
3418        SCR_COPY (4),
3419                RADDR (temp),
3420                NADDR(ncr_cache),
3421        /*
3422        **      Read back the variable.
3423        */
3424        SCR_COPY (4),
3425                NADDR(ncr_cache),
3426                RADDR (temp),
3427}/*-------------------------< SNOOPEND >-------------------*/,{
3428        /*
3429        **      And stop.
3430        */
3431        SCR_INT,
3432                99,
3433}/*--------------------------------------------------------*/
3434};
3435
3436/*==========================================================
3437**
3438**
3439**      Fill in #define dependent parts of the script
3440**
3441**
3442**==========================================================
3443*/
3444
3445void __init ncr_script_fill (struct script * scr, struct scripth * scrh)
3446{
3447        int     i;
3448        ncrcmd  *p;
3449
3450        p = scrh->tryloop;
3451        for (i=0; i<MAX_START; i++) {
3452                *p++ =SCR_CALL;
3453                *p++ =PADDR (idle);
3454        }
3455
3456        BUG_ON((u_long)p != (u_long)&scrh->tryloop + sizeof (scrh->tryloop));
3457
3458#ifdef SCSI_NCR_CCB_DONE_SUPPORT
3459
3460        p = scrh->done_queue;
3461        for (i = 0; i<MAX_DONE; i++) {
3462                *p++ =SCR_COPY (sizeof(struct ccb *));
3463                *p++ =NADDR (header.cp);
3464                *p++ =NADDR (ccb_done[i]);
3465                *p++ =SCR_CALL;
3466                *p++ =PADDR (done_end);
3467        }
3468
3469        BUG_ON((u_long)p != (u_long)&scrh->done_queue+sizeof(scrh->done_queue));
3470
3471#endif /* SCSI_NCR_CCB_DONE_SUPPORT */
3472
3473        p = scrh->hdata_in;
3474        for (i=0; i<MAX_SCATTERH; i++) {
3475                *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN));
3476                *p++ =PADDR (dispatch);
3477                *p++ =SCR_MOVE_TBL ^ SCR_DATA_IN;
3478                *p++ =offsetof (struct dsb, data[i]);
3479        }
3480
3481        BUG_ON((u_long)p != (u_long)&scrh->hdata_in + sizeof (scrh->hdata_in));
3482
3483        p = scr->data_in;
3484        for (i=MAX_SCATTERH; i<MAX_SCATTERH+MAX_SCATTERL; i++) {
3485                *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN));
3486                *p++ =PADDR (dispatch);
3487                *p++ =SCR_MOVE_TBL ^ SCR_DATA_IN;
3488                *p++ =offsetof (struct dsb, data[i]);
3489        }
3490
3491        BUG_ON((u_long)p != (u_long)&scr->data_in + sizeof (scr->data_in));
3492
3493        p = scrh->hdata_out;
3494        for (i=0; i<MAX_SCATTERH; i++) {
3495                *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT));
3496                *p++ =PADDR (dispatch);
3497                *p++ =SCR_MOVE_TBL ^ SCR_DATA_OUT;
3498                *p++ =offsetof (struct dsb, data[i]);
3499        }
3500
3501        BUG_ON((u_long)p != (u_long)&scrh->hdata_out + sizeof (scrh->hdata_out));
3502
3503        p = scr->data_out;
3504        for (i=MAX_SCATTERH; i<MAX_SCATTERH+MAX_SCATTERL; i++) {
3505                *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT));
3506                *p++ =PADDR (dispatch);
3507                *p++ =SCR_MOVE_TBL ^ SCR_DATA_OUT;
3508                *p++ =offsetof (struct dsb, data[i]);
3509        }
3510
3511        BUG_ON((u_long) p != (u_long)&scr->data_out + sizeof (scr->data_out));
3512}
3513
3514/*==========================================================
3515**
3516**
3517**      Copy and rebind a script.
3518**
3519**
3520**==========================================================
3521*/
3522
3523static void __init 
3524ncr_script_copy_and_bind (struct ncb *np, ncrcmd *src, ncrcmd *dst, int len)
3525{
3526        ncrcmd  opcode, new, old, tmp1, tmp2;
3527        ncrcmd  *start, *end;
3528        int relocs;
3529        int opchanged = 0;
3530
3531        start = src;
3532        end = src + len/4;
3533
3534        while (src < end) {
3535
3536                opcode = *src++;
3537                *dst++ = cpu_to_scr(opcode);
3538
3539                /*
3540                **      If we forget to change the length
3541                **      in struct script, a field will be
3542                **      padded with 0. This is an illegal
3543                **      command.
3544                */
3545
3546                if (opcode == 0) {
3547                        printk (KERN_ERR "%s: ERROR0 IN SCRIPT at %d.\n",
3548                                ncr_name(np), (int) (src-start-1));
3549                        mdelay(1000);
3550                }
3551
3552                if (DEBUG_FLAGS & DEBUG_SCRIPT)
3553                        printk (KERN_DEBUG "%p:  <%x>\n",
3554                                (src-1), (unsigned)opcode);
3555
3556                /*
3557                **      We don't have to decode ALL commands
3558                */
3559                switch (opcode >> 28) {
3560
3561                case 0xc:
3562                        /*
3563                        **      COPY has TWO arguments.
3564                        */
3565                        relocs = 2;
3566                        tmp1 = src[0];
3567#ifdef  RELOC_KVAR
3568                        if ((tmp1 & RELOC_MASK) == RELOC_KVAR)
3569                                tmp1 = 0;
3570#endif
3571                        tmp2 = src[1];
3572#ifdef  RELOC_KVAR
3573                        if ((tmp2 & RELOC_MASK) == RELOC_KVAR)
3574                                tmp2 = 0;
3575#endif
3576                        if ((tmp1 ^ tmp2) & 3) {
3577                                printk (KERN_ERR"%s: ERROR1 IN SCRIPT at %d.\n",
3578                                        ncr_name(np), (int) (src-start-1));
3579                                mdelay(1000);
3580                        }
3581                        /*
3582                        **      If PREFETCH feature not enabled, remove 
3583                        **      the NO FLUSH bit if present.
3584                        */
3585                        if ((opcode & SCR_NO_FLUSH) && !(np->features & FE_PFEN)) {
3586                                dst[-1] = cpu_to_scr(opcode & ~SCR_NO_FLUSH);
3587                                ++opchanged;
3588                        }
3589                        break;
3590
3591                case 0x0:
3592                        /*
3593                        **      MOVE (absolute address)
3594                        */
3595                        relocs = 1;
3596                        break;
3597
3598                case 0x8:
3599                        /*
3600                        **      JUMP / CALL
3601                        **      don't relocate if relative :-)
3602                        */
3603                        if (opcode & 0x00800000)
3604                                relocs = 0;
3605                        else
3606                                relocs = 1;
3607                        break;
3608
3609                case 0x4:
3610                case 0x5:
3611                case 0x6:
3612                case 0x7:
3613                        relocs = 1;
3614                        break;
3615
3616                default:
3617                        relocs = 0;
3618                        break;
3619                }
3620
3621                if (relocs) {
3622                        while (relocs--) {
3623                                old = *src++;
3624
3625                                switch (old & RELOC_MASK) {
3626                                case RELOC_REGISTER:
3627                                        new = (old & ~RELOC_MASK) + np->paddr;
3628                                        break;
3629                                case RELOC_LABEL:
3630                                        new = (old & ~RELOC_MASK) + np->p_script;
3631                                        break;
3632                                case RELOC_LABELH:
3633                                        new = (old & ~RELOC_MASK) + np->p_scripth;
3634                                        break;
3635                                case RELOC_SOFTC:
3636                                        new = (old & ~RELOC_MASK) + np->p_ncb;
3637                                        break;
3638#ifdef  RELOC_KVAR
3639                                case RELOC_KVAR:
3640                                        if (((old & ~RELOC_MASK) <
3641                                             SCRIPT_KVAR_FIRST) ||
3642                                            ((old & ~RELOC_MASK) >
3643                                             SCRIPT_KVAR_LAST))
3644                                                panic("ncr KVAR out of range");
3645                                        new = vtophys(script_kvars[old &
3646                                            ~RELOC_MASK]);
3647                                        break;
3648#endif
3649                                case 0:
3650                                        /* Don't relocate a 0 address. */
3651                                        if (old == 0) {
3652                                                new = old;
3653                                                break;
3654                                        }
3655                                        /* fall through */
3656                                default:
3657                                        panic("ncr_script_copy_and_bind: weird relocation %x\n", old);
3658                                        break;
3659                                }
3660
3661                                *dst++ = cpu_to_scr(new);
3662                        }
3663                } else
3664                        *dst++ = cpu_to_scr(*src++);
3665
3666        }
3667}
3668
3669/*
3670**      Linux host data structure
3671*/
3672
3673struct host_data {
3674     struct ncb *ncb;
3675};
3676
3677#define PRINT_ADDR(cmd, arg...) dev_info(&cmd->device->sdev_gendev , ## arg)
3678
3679static void ncr_print_msg(struct ccb *cp, char *label, u_char *msg)
3680{
3681        PRINT_ADDR(cp->cmd, "%s: ", label);
3682
3683        spi_print_msg(msg);
3684        printk("\n");
3685}
3686
3687/*==========================================================
3688**
3689**      NCR chip clock divisor table.
3690**      Divisors are multiplied by 10,000,000 in order to make 
3691**      calculations more simple.
3692**
3693**==========================================================
3694*/
3695
3696#define _5M 5000000
3697static u_long div_10M[] =
3698        {2*_5M, 3*_5M, 4*_5M, 6*_5M, 8*_5M, 12*_5M, 16*_5M};
3699
3700
3701/*===============================================================
3702**
3703**      Prepare io register values used by ncr_init() according 
3704**      to selected and supported features.
3705**
3706**      NCR chips allow burst lengths of 2, 4, 8, 16, 32, 64, 128 
3707**      transfers. 32,64,128 are only supported by 875 and 895 chips.
3708**      We use log base 2 (burst length) as internal code, with 
3709**      value 0 meaning "burst disabled".
3710**
3711**===============================================================
3712*/
3713
3714/*
3715 *      Burst length from burst code.
3716 */
3717#define burst_length(bc) (!(bc))? 0 : 1 << (bc)
3718
3719/*
3720 *      Burst code from io register bits.  Burst enable is ctest0 for c720
3721 */
3722#define burst_code(dmode, ctest0) \
3723        (ctest0) & 0x80 ? 0 : (((dmode) & 0xc0) >> 6) + 1
3724
3725/*
3726 *      Set initial io register bits from burst code.
3727 */
3728static inline void ncr_init_burst(struct ncb *np, u_char bc)
3729{
3730        u_char *be = &np->rv_ctest0;
3731        *be             &= ~0x80;
3732        np->rv_dmode    &= ~(0x3 << 6);
3733        np->rv_ctest5   &= ~0x4;
3734
3735        if (!bc) {
3736                *be             |= 0x80;
3737        } else {
3738                --bc;
3739                np->rv_dmode    |= ((bc & 0x3) << 6);
3740                np->rv_ctest5   |= (bc & 0x4);
3741        }
3742}
3743
3744static void __init ncr_prepare_setting(struct ncb *np)
3745{
3746        u_char  burst_max;
3747        u_long  period;
3748        int i;
3749
3750        /*
3751        **      Save assumed BIOS setting
3752        */
3753
3754        np->sv_scntl0   = INB(nc_scntl0) & 0x0a;
3755        np->sv_scntl3   = INB(nc_scntl3) & 0x07;
3756        np->sv_dmode    = INB(nc_dmode)  & 0xce;
3757        np->sv_dcntl    = INB(nc_dcntl)  & 0xa8;
3758        np->sv_ctest0   = INB(nc_ctest0) & 0x84;
3759        np->sv_ctest3   = INB(nc_ctest3) & 0x01;
3760        np->sv_ctest4   = INB(nc_ctest4) & 0x80;
3761        np->sv_ctest5   = INB(nc_ctest5) & 0x24;
3762        np->sv_gpcntl   = INB(nc_gpcntl);
3763        np->sv_stest2   = INB(nc_stest2) & 0x20;
3764        np->sv_stest4   = INB(nc_stest4);
3765
3766        /*
3767        **      Wide ?
3768        */
3769
3770        np->maxwide     = (np->features & FE_WIDE)? 1 : 0;
3771
3772        /*
3773         *  Guess the frequency of the chip's clock.
3774         */
3775        if (np->features & FE_ULTRA)
3776                np->clock_khz = 80000;
3777        else
3778                np->clock_khz = 40000;
3779
3780        /*
3781         *  Get the clock multiplier factor.
3782         */
3783        if      (np->features & FE_QUAD)
3784                np->multiplier  = 4;
3785        else if (np->features & FE_DBLR)
3786                np->multiplier  = 2;
3787        else
3788                np->multiplier  = 1;
3789
3790        /*
3791         *  Measure SCSI clock frequency for chips 
3792         *  it may vary from assumed one.
3793         */
3794        if (np->features & FE_VARCLK)
3795                ncr_getclock(np, np->multiplier);
3796
3797        /*
3798         * Divisor to be used for async (timer pre-scaler).
3799         */
3800        i = np->clock_divn - 1;
3801        while (--i >= 0) {
3802                if (10ul * SCSI_NCR_MIN_ASYNC * np->clock_khz > div_10M[i]) {
3803                        ++i;
3804                        break;
3805                }
3806        }
3807        np->rv_scntl3 = i+1;
3808
3809        /*
3810         * Minimum synchronous period factor supported by the chip.
3811         * Btw, 'period' is in tenths of nanoseconds.
3812         */
3813
3814        period = (4 * div_10M[0] + np->clock_khz - 1) / np->clock_khz;
3815        if      (period <= 250)         np->minsync = 10;
3816        else if (period <= 303)         np->minsync = 11;
3817        else if (period <= 500)         np->minsync = 12;
3818        else                            np->minsync = (period + 40 - 1) / 40;
3819
3820        /*
3821         * Check against chip SCSI standard support (SCSI-2,ULTRA,ULTRA2).
3822         */
3823
3824        if      (np->minsync < 25 && !(np->features & FE_ULTRA))
3825                np->minsync = 25;
3826
3827        /*
3828         * Maximum synchronous period factor supported by the chip.
3829         */
3830
3831        period = (11 * div_10M[np->clock_divn - 1]) / (4 * np->clock_khz);
3832        np->maxsync = period > 2540 ? 254 : period / 10;
3833
3834        /*
3835        **      Prepare initial value of other IO registers
3836        */
3837#if defined SCSI_NCR_TRUST_BIOS_SETTING
3838        np->rv_scntl0   = np->sv_scntl0;
3839        np->rv_dmode    = np->sv_dmode;
3840        np->rv_dcntl    = np->sv_dcntl;
3841        np->rv_ctest0   = np->sv_ctest0;
3842        np->rv_ctest3   = np->sv_ctest3;
3843        np->rv_ctest4   = np->sv_ctest4;
3844        np->rv_ctest5   = np->sv_ctest5;
3845        burst_max       = burst_code(np->sv_dmode, np->sv_ctest0);
3846#else
3847
3848        /*
3849        **      Select burst length (dwords)
3850        */
3851        burst_max       = driver_setup.burst_max;
3852        if (burst_max == 255)
3853                burst_max = burst_code(np->sv_dmode, np->sv_ctest0);
3854        if (burst_max > 7)
3855                burst_max = 7;
3856        if (burst_max > np->maxburst)
3857                burst_max = np->maxburst;
3858
3859        /*
3860        **      Select all supported special features
3861        */
3862        if (np->features & FE_ERL)
3863                np->rv_dmode    |= ERL;         /* Enable Read Line */
3864        if (np->features & FE_BOF)
3865                np->rv_dmode    |= BOF;         /* Burst Opcode Fetch */
3866        if (np->features & FE_ERMP)
3867                np->rv_dmode    |= ERMP;        /* Enable Read Multiple */
3868        if (np->features & FE_PFEN)
3869                np->rv_dcntl    |= PFEN;        /* Prefetch Enable */
3870        if (np->features & FE_CLSE)
3871                np->rv_dcntl    |= CLSE;        /* Cache Line Size Enable */
3872        if (np->features & FE_WRIE)
3873                np->rv_ctest3   |= WRIE;        /* Write and Invalidate */
3874        if (np->features & FE_DFS)
3875                np->rv_ctest5   |= DFS;         /* Dma Fifo Size */
3876        if (np->features & FE_MUX)
3877                np->rv_ctest4   |= MUX;         /* Host bus multiplex mode */
3878        if (np->features & FE_EA)
3879                np->rv_dcntl    |= EA;          /* Enable ACK */
3880        if (np->features & FE_EHP)
3881                np->rv_ctest0   |= EHP;         /* Even host parity */
3882
3883        /*
3884        **      Select some other
3885        */
3886        if (driver_setup.master_parity)
3887                np->rv_ctest4   |= MPEE;        /* Master parity checking */
3888        if (driver_setup.scsi_parity)
3889                np->rv_scntl0   |= 0x0a;        /*  full arb., ena parity, par->ATN  */
3890
3891        /*
3892        **  Get SCSI addr of host adapter (set by bios?).
3893        */
3894        if (np->myaddr == 255) {
3895                np->myaddr = INB(nc_scid) & 0x07;
3896                if (!np->myaddr)
3897                        np->myaddr = SCSI_NCR_MYADDR;
3898        }
3899
3900#endif /* SCSI_NCR_TRUST_BIOS_SETTING */
3901
3902        /*
3903         *      Prepare initial io register bits for burst length
3904         */
3905        ncr_init_burst(np, burst_max);
3906
3907        /*
3908        **      Set SCSI BUS mode.
3909        **
3910        **      - ULTRA2 chips (895/895A/896) report the current 
3911        **        BUS mode through the STEST4 IO register.
3912        **      - For previous generation chips (825/825A/875), 
3913        **        user has to tell us how to check against HVD, 
3914        **        since a 100% safe algorithm is not possible.
3915        */
3916        np->scsi_mode = SMODE_SE;
3917        if (np->features & FE_DIFF) {
3918                switch(driver_setup.diff_support) {
3919                case 4: /* Trust previous settings if present, then GPIO3 */
3920                        if (np->sv_scntl3) {
3921                                if (np->sv_stest2 & 0x20)
3922                                        np->scsi_mode = SMODE_HVD;
3923                                break;
3924                        }
3925                case 3: /* SYMBIOS controllers report HVD through GPIO3 */
3926                        if (INB(nc_gpreg) & 0x08)
3927                                break;
3928                case 2: /* Set HVD unconditionally */
3929                        np->scsi_mode = SMODE_HVD;
3930                case 1: /* Trust previous settings for HVD */
3931                        if (np->sv_stest2 & 0x20)
3932                                np->scsi_mode = SMODE_HVD;
3933                        break;
3934                default:/* Don't care about HVD */      
3935                        break;
3936                }
3937        }
3938        if (np->scsi_mode == SMODE_HVD)
3939                np->rv_stest2 |= 0x20;
3940
3941        /*
3942        **      Set LED support from SCRIPTS.
3943        **      Ignore this feature for boards known to use a 
3944        **      specific GPIO wiring and for the 895A or 896 
3945        **      that drive the LED directly.
3946        **      Also probe initial setting of GPIO0 as output.
3947        */
3948        if ((driver_setup.led_pin) &&
3949            !(np->features & FE_LEDC) && !(np->sv_gpcntl & 0x01))
3950                np->features |= FE_LED0;
3951
3952        /*
3953        **      Set irq mode.
3954        */
3955        switch(driver_setup.irqm & 3) {
3956        case 2:
3957                np->rv_dcntl    |= IRQM;
3958                break;
3959        case 1:
3960                np->rv_dcntl    |= (np->sv_dcntl & IRQM);
3961                break;
3962        default:
3963                break;
3964        }
3965
3966        /*
3967        **      Configure targets according to driver setup.
3968        **      Allow to override sync, wide and NOSCAN from 
3969        **      boot command line.
3970        */
3971        for (i = 0 ; i < MAX_TARGET ; i++) {
3972                struct tcb *tp = &np->target[i];
3973
3974                tp->usrsync = driver_setup.default_sync;
3975                tp->usrwide = driver_setup.max_wide;
3976                tp->usrtags = MAX_TAGS;
3977                tp->period = 0xffff;
3978                if (!driver_setup.disconnection)
3979                        np->target[i].usrflag = UF_NODISC;
3980        }
3981
3982        /*
3983        **      Announce all that stuff to user.
3984        */
3985
3986        printk(KERN_INFO "%s: ID %d, Fast-%d%s%s\n", ncr_name(np),
3987                np->myaddr,
3988                np->minsync < 12 ? 40 : (np->minsync < 25 ? 20 : 10),
3989                (np->rv_scntl0 & 0xa)   ? ", Parity Checking"   : ", NO Parity",
3990                (np->rv_stest2 & 0x20)  ? ", Differential"      : "");
3991
3992        if (bootverbose > 1) {
3993                printk (KERN_INFO "%s: initial SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
3994                        "(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
3995                        ncr_name(np), np->sv_scntl3, np->sv_dmode, np->sv_dcntl,
3996                        np->sv_ctest3, np->sv_ctest4, np->sv_ctest5);
3997
3998                printk (KERN_INFO "%s: final   SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
3999                        "(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
4000                        ncr_name(np), np->rv_scntl3, np->rv_dmode, np->rv_dcntl,
4001                        np->rv_ctest3, np->rv_ctest4, np->rv_ctest5);
4002        }
4003
4004        if (bootverbose && np->paddr2)
4005                printk (KERN_INFO "%s: on-chip RAM at 0x%lx\n",
4006                        ncr_name(np), np->paddr2);
4007}
4008
4009/*==========================================================
4010**
4011**
4012**      Done SCSI commands list management.
4013**
4014**      We donnot enter the scsi_done() callback immediately 
4015**      after a command has been seen as completed but we 
4016**      insert it into a list which is flushed outside any kind 
4017**      of driver critical section.
4018**      This allows to do minimal stuff under interrupt and 
4019**      inside critical sections and to also avoid locking up 
4020**      on recursive calls to driver entry points under SMP.
4021**      In fact, the only kernel point which is entered by the 
4022**      driver with a driver lock set is kmalloc(GFP_ATOMIC) 
4023**      that shall not reenter the driver under any circumstances,
4024**      AFAIK.
4025**
4026**==========================================================
4027*/
4028static inline void ncr_queue_done_cmd(struct ncb *np, struct scsi_cmnd *cmd)
4029{
4030        unmap_scsi_data(np, cmd);
4031        cmd->host_scribble = (char *) np->done_list;
4032        np->done_list = cmd;
4033}
4034
4035static inline void ncr_flush_done_cmds(struct scsi_cmnd *lcmd)
4036{
4037        struct scsi_cmnd *cmd;
4038
4039        while (lcmd) {
4040                cmd = lcmd;
4041                lcmd = (struct scsi_cmnd *) cmd->host_scribble;
4042                cmd->scsi_done(cmd);
4043        }
4044}
4045
4046/*==========================================================
4047**
4048**
4049**      Prepare the next negotiation message if needed.
4050**
4051**      Fill in the part of message buffer that contains the 
4052**      negotiation and the nego_status field of the CCB.
4053**      Returns the size of the message in bytes.
4054**
4055**
4056**==========================================================
4057*/
4058
4059
4060static int ncr_prepare_nego(struct ncb *np, struct ccb *cp, u_char *msgptr)
4061{
4062        struct tcb *tp = &np->target[cp->target];
4063        int msglen = 0;
4064        int nego = 0;
4065        struct scsi_target *starget = tp->starget;
4066
4067        /* negotiate wide transfers ?  */
4068        if (!tp->widedone) {
4069                if (spi_support_wide(starget)) {
4070                        nego = NS_WIDE;
4071                } else
4072                        tp->widedone=1;
4073        }
4074
4075        /* negotiate synchronous transfers?  */
4076        if (!nego && !tp->period) {
4077                if (spi_support_sync(starget)) {
4078                        nego = NS_SYNC;
4079                } else {
4080                        tp->period  =0xffff;
4081                        dev_info(&starget->dev, "target did not report SYNC.\n");
4082                }
4083        }
4084
4085        switch (nego) {
4086        case NS_SYNC:
4087                msglen += spi_populate_sync_msg(msgptr + msglen,
4088                                tp->maxoffs ? tp->minsync : 0, tp->maxoffs);
4089                break;
4090        case NS_WIDE:
4091                msglen += spi_populate_width_msg(msgptr + msglen, tp->usrwide);
4092                break;
4093        }
4094
4095        cp->nego_status = nego;
4096
4097        if (nego) {
4098                tp->nego_cp = cp;
4099                if (DEBUG_FLAGS & DEBUG_NEGO) {
4100                        ncr_print_msg(cp, nego == NS_WIDE ?
4101                                          "wide msgout":"sync_msgout", msgptr);
4102                }
4103        }
4104
4105        return msglen;
4106}
4107
4108
4109
4110/*==========================================================
4111**
4112**
4113**      Start execution of a SCSI command.
4114**      This is called from the generic SCSI driver.
4115**
4116**
4117**==========================================================
4118*/
4119static int ncr_queue_command (struct ncb *np, struct scsi_cmnd *cmd)
4120{
4121        struct scsi_device *sdev = cmd->device;
4122        struct tcb *tp = &np->target[sdev->id];
4123        struct lcb *lp = tp->lp[sdev->lun];
4124        struct ccb *cp;
4125
4126        int     segments;
4127        u_char  idmsg, *msgptr;
4128        u32     msglen;
4129        int     direction;
4130        u32     lastp, goalp;
4131
4132        /*---------------------------------------------
4133        **
4134        **      Some shortcuts ...
4135        **
4136        **---------------------------------------------
4137        */
4138        if ((sdev->id == np->myaddr       ) ||
4139                (sdev->id >= MAX_TARGET) ||
4140                (sdev->lun    >= MAX_LUN   )) {
4141                return(DID_BAD_TARGET);
4142        }
4143
4144        /*---------------------------------------------
4145        **
4146        **      Complete the 1st TEST UNIT READY command
4147        **      with error condition if the device is 
4148        **      flagged NOSCAN, in order to speed up 
4149        **      the boot.
4150        **
4151        **---------------------------------------------
4152        */
4153        if ((cmd->cmnd[0] == 0 || cmd->cmnd[0] == 0x12) && 
4154            (tp->usrflag & UF_NOSCAN)) {
4155                tp->usrflag &= ~UF_NOSCAN;
4156                return DID_BAD_TARGET;
4157        }
4158
4159        if (DEBUG_FLAGS & DEBUG_TINY) {
4160                PRINT_ADDR(cmd, "CMD=%x ", cmd->cmnd[0]);
4161        }
4162
4163        /*---------------------------------------------------
4164        **
4165        **      Assign a ccb / bind cmd.
4166        **      If resetting, shorten settle_time if necessary
4167        **      in order to avoid spurious timeouts.
4168        **      If resetting or no free ccb,
4169        **      insert cmd into the waiting list.
4170        **
4171        **----------------------------------------------------
4172        */
4173        if (np->settle_time && cmd->request->timeout >= HZ) {
4174                u_long tlimit = jiffies + cmd->request->timeout - HZ;
4175                if (time_after(np->settle_time, tlimit))
4176                        np->settle_time = tlimit;
4177        }
4178
4179        if (np->settle_time || !(cp=ncr_get_ccb (np, cmd))) {
4180                insert_into_waiting_list(np, cmd);
4181                return(DID_OK);
4182        }
4183        cp->cmd = cmd;
4184
4185        /*----------------------------------------------------
4186        **
4187        **      Build the identify / tag / sdtr message
4188        **
4189        **----------------------------------------------------
4190        */
4191
4192        idmsg = IDENTIFY(0, sdev->lun);
4193
4194        if (cp ->tag != NO_TAG ||
4195                (cp != np->ccb && np->disc && !(tp->usrflag & UF_NODISC)))
4196                idmsg |= 0x40;
4197
4198        msgptr = cp->scsi_smsg;
4199        msglen = 0;
4200        msgptr[msglen++] = idmsg;
4201
4202        if (cp->tag != NO_TAG) {
4203                char order = np->order;
4204
4205                /*
4206                **      Force ordered tag if necessary to avoid timeouts 
4207                **      and to preserve interactivity.
4208                */
4209                if (lp && time_after(jiffies, lp->tags_stime)) {
4210                        if (lp->tags_smap) {
4211                                order = ORDERED_QUEUE_TAG;
4212                                if ((DEBUG_FLAGS & DEBUG_TAGS)||bootverbose>2){ 
4213                                        PRINT_ADDR(cmd,
4214                                                "ordered tag forced.\n");
4215                                }
4216                        }
4217                        lp->tags_stime = jiffies + 3*HZ;
4218                        lp->tags_smap = lp->tags_umap;
4219                }
4220
4221                if (order == 0) {
4222                        /*
4223                        **      Ordered write ops, unordered read ops.
4224                        */
4225                        switch (cmd->cmnd[0]) {
4226                        case 0x08:  /* READ_SMALL (6) */
4227                        case 0x28:  /* READ_BIG  (10) */
4228                        case 0xa8:  /* READ_HUGE (12) */
4229                                order = SIMPLE_QUEUE_TAG;
4230                                break;
4231                        default:
4232                                order = ORDERED_QUEUE_TAG;
4233                        }
4234                }
4235                msgptr[msglen++] = order;
4236                /*
4237                **      Actual tags are numbered 1,3,5,..2*MAXTAGS+1,
4238                **      since we may have to deal with devices that have 
4239                **      problems with #TAG 0 or too great #TAG numbers.
4240                */
4241                msgptr[msglen++] = (cp->tag << 1) + 1;
4242        }
4243
4244        /*----------------------------------------------------
4245        **
4246        **      Build the data descriptors
4247        **
4248        **----------------------------------------------------
4249        */
4250
4251        direction = cmd->sc_data_direction;
4252        if (direction != DMA_NONE) {
4253                segments = ncr_scatter(np, cp, cp->cmd);
4254                if (segments < 0) {
4255                        ncr_free_ccb(np, cp);
4256                        return(DID_ERROR);
4257                }
4258        }
4259        else {
4260                cp->data_len = 0;
4261                segments = 0;
4262        }
4263
4264        /*---------------------------------------------------
4265        **
4266        **      negotiation required?
4267        **
4268        **      (nego_status is filled by ncr_prepare_nego())
4269        **
4270        **---------------------------------------------------
4271        */
4272
4273        cp->nego_status = 0;
4274
4275        if ((!tp->widedone || !tp->period) && !tp->nego_cp && lp) {
4276                msglen += ncr_prepare_nego (np, cp, msgptr + msglen);
4277        }
4278
4279        /*----------------------------------------------------
4280        **
4281        **      Determine xfer direction.
4282        **
4283        **----------------------------------------------------
4284        */
4285        if (!cp->data_len)
4286                direction = DMA_NONE;
4287
4288        /*
4289        **      If data direction is BIDIRECTIONAL, speculate FROM_DEVICE
4290        **      but prepare alternate pointers for TO_DEVICE in case 
4291        **      of our speculation will be just wrong.
4292        **      SCRIPTS will swap values if needed.
4293        */
4294        switch(direction) {
4295        case DMA_BIDIRECTIONAL:
4296        case DMA_TO_DEVICE:
4297                goalp = NCB_SCRIPT_PHYS (np, data_out2) + 8;
4298                if (segments <= MAX_SCATTERL)
4299                        lastp = goalp - 8 - (segments * 16);
4300                else {
4301                        lastp = NCB_SCRIPTH_PHYS (np, hdata_out2);
4302                        lastp -= (segments - MAX_SCATTERL) * 16;
4303                }
4304                if (direction != DMA_BIDIRECTIONAL)
4305                        break;
4306                cp->phys.header.wgoalp  = cpu_to_scr(goalp);
4307                cp->phys.header.wlastp  = cpu_to_scr(lastp);
4308                /* fall through */
4309        case DMA_FROM_DEVICE:
4310                goalp = NCB_SCRIPT_PHYS (np, data_in2) + 8;
4311                if (segments <= MAX_SCATTERL)
4312                        lastp = goalp - 8 - (segments * 16);
4313                else {
4314                        lastp = NCB_SCRIPTH_PHYS (np, hdata_in2);
4315                        lastp -= (segments - MAX_SCATTERL) * 16;
4316                }
4317                break;
4318        default:
4319        case DMA_NONE:
4320                lastp = goalp = NCB_SCRIPT_PHYS (np, no_data);
4321                break;
4322        }
4323
4324        /*
4325        **      Set all pointers values needed by SCRIPTS.
4326        **      If direction is unknown, start at data_io.
4327        */
4328        cp->phys.header.lastp = cpu_to_scr(lastp);
4329        cp->phys.header.goalp = cpu_to_scr(goalp);
4330
4331        if (direction == DMA_BIDIRECTIONAL)
4332                cp->phys.header.savep = 
4333                        cpu_to_scr(NCB_SCRIPTH_PHYS (np, data_io));
4334        else
4335                cp->phys.header.savep= cpu_to_scr(lastp);
4336
4337        /*
4338        **      Save the initial data pointer in order to be able 
4339        **      to redo the command.
4340        */
4341        cp->startp = cp->phys.header.savep;
4342
4343        /*----------------------------------------------------
4344        **
4345        **      fill in ccb
4346        **
4347        **----------------------------------------------------
4348        **
4349        **
4350        **      physical -> virtual backlink
4351        **      Generic SCSI command
4352        */
4353
4354        /*
4355        **      Startqueue
4356        */
4357        cp->start.schedule.l_paddr   = cpu_to_scr(NCB_SCRIPT_PHYS (np, select));
4358        cp->restart.schedule.l_paddr = cpu_to_scr(NCB_SCRIPT_PHYS (np, resel_dsa));
4359        /*
4360        **      select
4361        */
4362        cp->phys.select.sel_id          = sdev_id(sdev);
4363        cp->phys.select.sel_scntl3      = tp->wval;
4364        cp->phys.select.sel_sxfer       = tp->sval;
4365        /*
4366        **      message
4367        */
4368        cp->phys.smsg.addr              = cpu_to_scr(CCB_PHYS (cp, scsi_smsg));
4369        cp->phys.smsg.size              = cpu_to_scr(msglen);
4370
4371        /*
4372        **      command
4373        */
4374        memcpy(cp->cdb_buf, cmd->cmnd, min_t(int, cmd->cmd_len, sizeof(cp->cdb_buf)));
4375        cp->phys.cmd.addr               = cpu_to_scr(CCB_PHYS (cp, cdb_buf[0]));
4376        cp->phys.cmd.size               = cpu_to_scr(cmd->cmd_len);
4377
4378        /*
4379        **      status
4380        */
4381        cp->actualquirks                = 0;
4382        cp->host_status                 = cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
4383        cp->scsi_status                 = S_ILLEGAL;
4384        cp->parity_status               = 0;
4385
4386        cp->xerr_status                 = XE_OK;
4387#if 0
4388        cp->sync_status                 = tp->sval;
4389        cp->wide_status                 = tp->wval;
4390#endif
4391
4392        /*----------------------------------------------------
4393        **
4394        **      Critical region: start this job.
4395        **
4396        **----------------------------------------------------
4397        */
4398
4399        /* activate this job.  */
4400        cp->magic               = CCB_MAGIC;
4401
4402        /*
4403        **      insert next CCBs into start queue.
4404        **      2 max at a time is enough to flush the CCB wait queue.
4405        */
4406        cp->auto_sense = 0;
4407        if (lp)
4408                ncr_start_next_ccb(np, lp, 2);
4409        else
4410                ncr_put_start_queue(np, cp);
4411
4412        /* Command is successfully queued.  */
4413
4414        return DID_OK;
4415}
4416
4417
4418/*==========================================================
4419**
4420**
4421**      Insert a CCB into the start queue and wake up the 
4422**      SCRIPTS processor.
4423**
4424**
4425**==========================================================
4426*/
4427
4428static void ncr_start_next_ccb(struct ncb *np, struct lcb *lp, int maxn)
4429{
4430        struct list_head *qp;
4431        struct ccb *cp;
4432
4433        if (lp->held_ccb)
4434                return;
4435
4436        while (maxn-- && lp->queuedccbs < lp->queuedepth) {
4437                qp = ncr_list_pop(&lp->wait_ccbq);
4438                if (!qp)
4439                        break;
4440                ++lp->queuedccbs;
4441                cp = list_entry(qp, struct ccb, link_ccbq);
4442                list_add_tail(qp, &lp->busy_ccbq);
4443                lp->jump_ccb[cp->tag == NO_TAG ? 0 : cp->tag] =
4444                        cpu_to_scr(CCB_PHYS (cp, restart));
4445                ncr_put_start_queue(np, cp);
4446        }
4447}
4448
4449static void ncr_put_start_queue(struct ncb *np, struct ccb *cp)
4450{
4451        u16     qidx;
4452
4453        /*
4454        **      insert into start queue.
4455        */
4456        if (!np->squeueput) np->squeueput = 1;
4457        qidx = np->squeueput + 2;
4458        if (qidx >= MAX_START + MAX_START) qidx = 1;
4459
4460        np->scripth->tryloop [qidx] = cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
4461        MEMORY_BARRIER();
4462        np->scripth->tryloop [np->squeueput] = cpu_to_scr(CCB_PHYS (cp, start));
4463
4464        np->squeueput = qidx;
4465        ++np->queuedccbs;
4466        cp->queued = 1;
4467
4468        if (DEBUG_FLAGS & DEBUG_QUEUE)
4469                printk ("%s: queuepos=%d.\n", ncr_name (np), np->squeueput);
4470
4471        /*
4472        **      Script processor may be waiting for reselect.
4473        **      Wake it up.
4474        */
4475        MEMORY_BARRIER();
4476        OUTB (nc_istat, SIGP);
4477}
4478
4479
4480static int ncr_reset_scsi_bus(struct ncb *np, int enab_int, int settle_delay)
4481{
4482        u32 term;
4483        int retv = 0;
4484
4485        np->settle_time = jiffies + settle_delay * HZ;
4486
4487        if (bootverbose > 1)
4488                printk("%s: resetting, "
4489                        "command processing suspended for %d seconds\n",
4490                        ncr_name(np), settle_delay);
4491
4492        ncr_chip_reset(np, 100);
4493        udelay(2000);   /* The 895 needs time for the bus mode to settle */
4494        if (enab_int)
4495                OUTW (nc_sien, RST);
4496        /*
4497        **      Enable Tolerant, reset IRQD if present and 
4498        **      properly set IRQ mode, prior to resetting the bus.
4499        */
4500        OUTB (nc_stest3, TE);
4501        OUTB (nc_scntl1, CRST);
4502        udelay(200);
4503
4504        if (!driver_setup.bus_check)
4505                goto out;
4506        /*
4507        **      Check for no terminators or SCSI bus shorts to ground.
4508        **      Read SCSI data bus, data parity bits and control signals.
4509        **      We are expecting RESET to be TRUE and other signals to be 
4510        **      FALSE.
4511        */
4512
4513        term =  INB(nc_sstat0);
4514        term =  ((term & 2) << 7) + ((term & 1) << 17); /* rst sdp0 */
4515        term |= ((INB(nc_sstat2) & 0x01) << 26) |       /* sdp1     */
4516                ((INW(nc_sbdl) & 0xff)   << 9)  |       /* d7-0     */
4517                ((INW(nc_sbdl) & 0xff00) << 10) |       /* d15-8    */
4518                INB(nc_sbcl);   /* req ack bsy sel atn msg cd io    */
4519
4520        if (!(np->features & FE_WIDE))
4521                term &= 0x3ffff;
4522
4523        if (term != (2<<7)) {
4524                printk("%s: suspicious SCSI data while resetting the BUS.\n",
4525                        ncr_name(np));
4526                printk("%s: %sdp0,d7-0,rst,req,ack,bsy,sel,atn,msg,c/d,i/o = "
4527                        "0x%lx, expecting 0x%lx\n",
4528                        ncr_name(np),
4529                        (np->features & FE_WIDE) ? "dp1,d15-8," : "",
4530                        (u_long)term, (u_long)(2<<7));
4531                if (driver_setup.bus_check == 1)
4532                        retv = 1;
4533        }
4534out:
4535        OUTB (nc_scntl1, 0);
4536        return retv;
4537}
4538
4539/*
4540 * Start reset process.
4541 * If reset in progress do nothing.
4542 * The interrupt handler will reinitialize the chip.
4543 * The timeout handler will wait for settle_time before 
4544 * clearing it and so resuming command processing.
4545 */
4546static void ncr_start_reset(struct ncb *np)
4547{
4548        if (!np->settle_time) {
4549                ncr_reset_scsi_bus(np, 1, driver_setup.settle_delay);
4550        }
4551}
4552 
4553/*==========================================================
4554**
4555**
4556**      Reset the SCSI BUS.
4557**      This is called from the generic SCSI driver.
4558**
4559**
4560**==========================================================
4561*/
4562static int ncr_reset_bus (struct ncb *np, struct scsi_cmnd *cmd, int sync_reset)
4563{
4564/*      struct scsi_device        *device    = cmd->device; */
4565        struct ccb *cp;
4566        int found;
4567
4568/*
4569 * Return immediately if reset is in progress.
4570 */
4571        if (np->settle_time) {
4572                return FAILED;
4573        }
4574/*
4575 * Start the reset process.
4576 * The script processor is then assumed to be stopped.
4577 * Commands will now be queued in the waiting list until a settle 
4578 * delay of 2 seconds will be completed.
4579 */
4580        ncr_start_reset(np);
4581/*
4582 * First, look in the wakeup list
4583 */
4584        for (found=0, cp=np->ccb; cp; cp=cp->link_ccb) {
4585                /*
4586                **      look for the ccb of this command.
4587                */
4588                if (cp->host_status == HS_IDLE) continue;
4589                if (cp->cmd == cmd) {
4590                        found = 1;
4591                        break;
4592                }
4593        }
4594/*
4595 * Then, look in the waiting list
4596 */
4597        if (!found && retrieve_from_waiting_list(0, np, cmd))
4598                found = 1;
4599/*
4600 * Wake-up all awaiting commands with DID_RESET.
4601 */
4602        reset_waiting_list(np);
4603/*
4604 * Wake-up all pending commands with HS_RESET -> DID_RESET.
4605 */
4606        ncr_wakeup(np, HS_RESET);
4607/*
4608 * If the involved command was not in a driver queue, and the 
4609 * scsi driver told us reset is synchronous, and the command is not 
4610 * currently in the waiting list, complete it with DID_RESET status,
4611 * in order to keep it alive.
4612 */
4613        if (!found && sync_reset && !retrieve_from_waiting_list(0, np, cmd)) {
4614                cmd->result = ScsiResult(DID_RESET, 0);
4615                ncr_queue_done_cmd(np, cmd);
4616        }
4617
4618        return SUCCESS;
4619}
4620
4621#if 0 /* unused and broken.. */
4622/*==========================================================
4623**
4624**
4625**      Abort an SCSI command.
4626**      This is called from the generic SCSI driver.
4627**
4628**
4629**==========================================================
4630*/
4631static int ncr_abort_command (struct ncb *np, struct scsi_cmnd *cmd)
4632{
4633/*      struct scsi_device        *device    = cmd->device; */
4634        struct ccb *cp;
4635        int found;
4636        int retv;
4637
4638/*
4639 * First, look for the scsi command in the waiting list
4640 */
4641        if (remove_from_waiting_list(np, cmd)) {
4642                cmd->result = ScsiResult(DID_ABORT, 0);
4643                ncr_queue_done_cmd(np, cmd);
4644                return SCSI_ABORT_SUCCESS;
4645        }
4646
4647/*
4648 * Then, look in the wakeup list
4649 */
4650        for (found=0, cp=np->ccb; cp; cp=cp->link_ccb) {
4651                /*
4652                **      look for the ccb of this command.
4653                */
4654                if (cp->host_status == HS_IDLE) continue;
4655                if (cp->cmd == cmd) {
4656                        found = 1;
4657                        break;
4658                }
4659        }
4660
4661        if (!found) {
4662                return SCSI_ABORT_NOT_RUNNING;
4663        }
4664
4665        if (np->settle_time) {
4666                return SCSI_ABORT_SNOOZE;
4667        }
4668
4669        /*
4670        **      If the CCB is active, patch schedule jumps for the 
4671        **      script to abort the command.
4672        */
4673
4674        switch(cp->host_status) {
4675        case HS_BUSY:
4676        case HS_NEGOTIATE:
4677                printk ("%s: abort ccb=%p (cancel)\n", ncr_name (np), cp);
4678                        cp->start.schedule.l_paddr =
4679                                cpu_to_scr(NCB_SCRIPTH_PHYS (np, cancel));
4680                retv = SCSI_ABORT_PENDING;
4681                break;
4682        case HS_DISCONNECT:
4683                cp->restart.schedule.l_paddr =
4684                                cpu_to_scr(NCB_SCRIPTH_PHYS (np, abort));
4685                retv = SCSI_ABORT_PENDING;
4686                break;
4687        default:
4688                retv = SCSI_ABORT_NOT_RUNNING;
4689                break;
4690
4691        }
4692
4693        /*
4694        **      If there are no requests, the script
4695        **      processor will sleep on SEL_WAIT_RESEL.
4696        **      Let's wake it up, since it may have to work.
4697        */
4698        OUTB (nc_istat, SIGP);
4699
4700        return retv;
4701}
4702#endif
4703
4704static void ncr_detach(struct ncb *np)
4705{
4706        struct ccb *cp;
4707        struct tcb *tp;
4708        struct lcb *lp;
4709        int target, lun;
4710        int i;
4711        char inst_name[16];
4712
4713        /* Local copy so we don't access np after freeing it! */
4714        strlcpy(inst_name, ncr_name(np), sizeof(inst_name));
4715
4716        printk("%s: releasing host resources\n", ncr_name(np));
4717
4718/*
4719**      Stop the ncr_timeout process
4720**      Set release_stage to 1 and wait that ncr_timeout() set it to 2.
4721*/
4722
4723#ifdef DEBUG_NCR53C8XX
4724        printk("%s: stopping the timer\n", ncr_name(np));
4725#endif
4726        np->release_stage = 1;
4727        for (i = 50 ; i && np->release_stage != 2 ; i--)
4728                mdelay(100);
4729        if (np->release_stage != 2)
4730                printk("%s: the timer seems to be already stopped\n", ncr_name(np));
4731        else np->release_stage = 2;
4732
4733/*
4734**      Disable chip interrupts
4735*/
4736
4737#ifdef DEBUG_NCR53C8XX
4738        printk("%s: disabling chip interrupts\n", ncr_name(np));
4739#endif
4740        OUTW (nc_sien , 0);
4741        OUTB (nc_dien , 0);
4742
4743        /*
4744        **      Reset NCR chip
4745        **      Restore bios setting for automatic clock detection.
4746        */
4747
4748        printk("%s: resetting chip\n", ncr_name(np));
4749        ncr_chip_reset(np, 100);
4750
4751        OUTB(nc_dmode,  np->sv_dmode);
4752        OUTB(nc_dcntl,  np->sv_dcntl);
4753        OUTB(nc_ctest0, np->sv_ctest0);
4754        OUTB(nc_ctest3, np->sv_ctest3);
4755        OUTB(nc_ctest4, np->sv_ctest4);
4756        OUTB(nc_ctest5, np->sv_ctest5);
4757        OUTB(nc_gpcntl, np->sv_gpcntl);
4758        OUTB(nc_stest2, np->sv_stest2);
4759
4760        ncr_selectclock(np, np->sv_scntl3);
4761
4762        /*
4763        **      Free allocated ccb(s)
4764        */
4765
4766        while ((cp=np->ccb->link_ccb) != NULL) {
4767                np->ccb->link_ccb = cp->link_ccb;
4768                if (cp->host_status) {
4769                printk("%s: shall free an active ccb (host_status=%d)\n",
4770                        ncr_name(np), cp->host_status);
4771                }
4772#ifdef DEBUG_NCR53C8XX
4773        printk("%s: freeing ccb (%lx)\n", ncr_name(np), (u_long) cp);
4774#endif
4775                m_free_dma(cp, sizeof(*cp), "CCB");
4776        }
4777
4778        /* Free allocated tp(s) */
4779
4780        for (target = 0; target < MAX_TARGET ; target++) {
4781                tp=&np->target[target];
4782                for (lun = 0 ; lun < MAX_LUN ; lun++) {
4783                        lp = tp->lp[lun];
4784                        if (lp) {
4785#ifdef DEBUG_NCR53C8XX
4786        printk("%s: freeing lp (%lx)\n", ncr_name(np), (u_long) lp);
4787#endif
4788                                if (lp->jump_ccb != &lp->jump_ccb_0)
4789                                        m_free_dma(lp->jump_ccb,256,"JUMP_CCB");
4790                                m_free_dma(lp, sizeof(*lp), "LCB");
4791                        }
4792                }
4793        }
4794
4795        if (np->scripth0)
4796                m_free_dma(np->scripth0, sizeof(struct scripth), "SCRIPTH");
4797        if (np->script0)
4798                m_free_dma(np->script0, sizeof(struct script), "SCRIPT");
4799        if (np->ccb)
4800                m_free_dma(np->ccb, sizeof(struct ccb), "CCB");
4801        m_free_dma(np, sizeof(struct ncb), "NCB");
4802
4803        printk("%s: host resources successfully released\n", inst_name);
4804}
4805
4806/*==========================================================
4807**
4808**
4809**      Complete execution of a SCSI command.
4810**      Signal completion to the generic SCSI driver.
4811**
4812**
4813**==========================================================
4814*/
4815
4816void ncr_complete (struct ncb *np, struct ccb *cp)
4817{
4818        struct scsi_cmnd *cmd;
4819        struct tcb *tp;
4820        struct lcb *lp;
4821
4822        /*
4823        **      Sanity check
4824        */
4825
4826        if (!cp || cp->magic != CCB_MAGIC || !cp->cmd)
4827                return;
4828
4829        /*
4830        **      Print minimal debug information.
4831        */
4832
4833        if (DEBUG_FLAGS & DEBUG_TINY)
4834                printk ("CCB=%lx STAT=%x/%x\n", (unsigned long)cp,
4835                        cp->host_status,cp->scsi_status);
4836
4837        /*
4838        **      Get command, target and lun pointers.
4839        */
4840
4841        cmd = cp->cmd;
4842        cp->cmd = NULL;
4843        tp = &np->target[cmd->device->id];
4844        lp = tp->lp[cmd->device->lun];
4845
4846        /*
4847        **      We donnot queue more than 1 ccb per target 
4848        **      with negotiation at any time. If this ccb was 
4849        **      used for negotiation, clear this info in the tcb.
4850        */
4851
4852        if (cp == tp->nego_cp)
4853                tp->nego_cp = NULL;
4854
4855        /*
4856        **      If auto-sense performed, change scsi status.
4857        */
4858        if (cp->auto_sense) {
4859                cp->scsi_status = cp->auto_sense;
4860        }
4861
4862        /*
4863        **      If we were recovering from queue full or performing 
4864        **      auto-sense, requeue skipped CCBs to the wait queue.
4865        */
4866
4867        if (lp && lp->held_ccb) {
4868                if (cp == lp->held_ccb) {
4869                        list_splice_init(&lp->skip_ccbq, &lp->wait_ccbq);
4870                        lp->held_ccb = NULL;
4871                }
4872        }
4873
4874        /*
4875        **      Check for parity errors.
4876        */
4877
4878        if (cp->parity_status > 1) {
4879                PRINT_ADDR(cmd, "%d parity error(s).\n",cp->parity_status);
4880        }
4881
4882        /*
4883        **      Check for extended errors.
4884        */
4885
4886        if (cp->xerr_status != XE_OK) {
4887                switch (cp->xerr_status) {
4888                case XE_EXTRA_DATA:
4889                        PRINT_ADDR(cmd, "extraneous data discarded.\n");
4890                        break;
4891                case XE_BAD_PHASE:
4892                        PRINT_ADDR(cmd, "invalid scsi phase (4/5).\n");
4893                        break;
4894                default:
4895                        PRINT_ADDR(cmd, "extended error %d.\n",
4896                                        cp->xerr_status);
4897                        break;
4898                }
4899                if (cp->host_status==HS_COMPLETE)
4900                        cp->host_status = HS_FAIL;
4901        }
4902
4903        /*
4904        **      Print out any error for debugging purpose.
4905        */
4906        if (DEBUG_FLAGS & (DEBUG_RESULT|DEBUG_TINY)) {
4907                if (cp->host_status!=HS_COMPLETE || cp->scsi_status!=S_GOOD) {
4908                        PRINT_ADDR(cmd, "ERROR: cmd=%x host_status=%x "
4909                                        "scsi_status=%x\n", cmd->cmnd[0],
4910                                        cp->host_status, cp->scsi_status);
4911                }
4912        }
4913
4914        /*
4915        **      Check the status.
4916        */
4917        if (   (cp->host_status == HS_COMPLETE)
4918                && (cp->scsi_status == S_GOOD ||
4919                    cp->scsi_status == S_COND_MET)) {
4920                /*
4921                 *      All went well (GOOD status).
4922                 *      CONDITION MET status is returned on 
4923                 *      `Pre-Fetch' or `Search data' success.
4924                 */
4925                cmd->result = ScsiResult(DID_OK, cp->scsi_status);
4926
4927                /*
4928                **      @RESID@
4929                **      Could dig out the correct value for resid,
4930                **      but it would be quite complicated.
4931                */
4932                /* if (cp->phys.header.lastp != cp->phys.header.goalp) */
4933
4934                /*
4935                **      Allocate the lcb if not yet.
4936                */
4937                if (!lp)
4938                        ncr_alloc_lcb (np, cmd->device->id, cmd->device->lun);
4939
4940                tp->bytes     += cp->data_len;
4941                tp->transfers ++;
4942
4943                /*
4944                **      If tags was reduced due to queue full,
4945                **      increase tags if 1000 good status received.
4946                */
4947                if (lp && lp->usetags && lp->numtags < lp->maxtags) {
4948                        ++lp->num_good;
4949                        if (lp->num_good >= 1000) {
4950                                lp->num_good = 0;
4951                                ++lp->numtags;
4952                                ncr_setup_tags (np, cmd->device);
4953                        }
4954                }
4955        } else if ((cp->host_status == HS_COMPLETE)
4956                && (cp->scsi_status == S_CHECK_COND)) {
4957                /*
4958                **   Check condition code
4959                */
4960                cmd->result = ScsiResult(DID_OK, S_CHECK_COND);
4961
4962                /*
4963                **      Copy back sense data to caller's buffer.
4964                */
4965                memcpy(cmd->sense_buffer, cp->sense_buf,
4966                       min_t(size_t, SCSI_SENSE_BUFFERSIZE,
4967                             sizeof(cp->sense_buf)));
4968
4969                if (DEBUG_FLAGS & (DEBUG_RESULT|DEBUG_TINY)) {
4970                        u_char *p = cmd->sense_buffer;
4971                        int i;
4972                        PRINT_ADDR(cmd, "sense data:");
4973                        for (i=0; i<14; i++) printk (" %x", *p++);
4974                        printk (".\n");
4975                }
4976        } else if ((cp->host_status == HS_COMPLETE)
4977                && (cp->scsi_status == S_CONFLICT)) {
4978                /*
4979                **   Reservation Conflict condition code
4980                */
4981                cmd->result = ScsiResult(DID_OK, S_CONFLICT);
4982        
4983        } else if ((cp->host_status == HS_COMPLETE)
4984                && (cp->scsi_status == S_BUSY ||
4985                    cp->scsi_status == S_QUEUE_FULL)) {
4986
4987                /*
4988                **   Target is busy.
4989                */
4990                cmd->result = ScsiResult(DID_OK, cp->scsi_status);
4991
4992        } else if ((cp->host_status == HS_SEL_TIMEOUT)
4993                || (cp->host_status == HS_TIMEOUT)) {
4994
4995                /*
4996                **   No response
4997                */
4998                cmd->result = ScsiResult(DID_TIME_OUT, cp->scsi_status);
4999
5000        } else if (cp->host_status == HS_RESET) {
5001
5002                /*
5003                **   SCSI bus reset
5004                */
5005                cmd->result = ScsiResult(DID_RESET, cp->scsi_status);
5006
5007        } else if (cp->host_status == HS_ABORTED) {
5008
5009                /*
5010                **   Transfer aborted
5011                */
5012                cmd->result = ScsiResult(DID_ABORT, cp->scsi_status);
5013
5014        } else {
5015
5016                /*
5017                **  Other protocol messes
5018                */
5019                PRINT_ADDR(cmd, "COMMAND FAILED (%x %x) @%p.\n",
5020                        cp->host_status, cp->scsi_status, cp);
5021
5022                cmd->result = ScsiResult(DID_ERROR, cp->scsi_status);
5023        }
5024
5025        /*
5026        **      trace output
5027        */
5028
5029        if (tp->usrflag & UF_TRACE) {
5030                u_char * p;
5031                int i;
5032                PRINT_ADDR(cmd, " CMD:");
5033                p = (u_char*) &cmd->cmnd[0];
5034                for (i=0; i<cmd->cmd_len; i++) printk (" %x", *p++);
5035
5036                if (cp->host_status==HS_COMPLETE) {
5037                        switch (cp->scsi_status) {
5038                        case S_GOOD:
5039                                printk ("  GOOD");
5040                                break;
5041                        case S_CHECK_COND:
5042                                printk ("  SENSE:");
5043                                p = (u_char*) &cmd->sense_buffer;
5044                                for (i=0; i<14; i++)
5045                                        printk (" %x", *p++);
5046                                break;
5047                        default:
5048                                printk ("  STAT: %x\n", cp->scsi_status);
5049                                break;
5050                        }
5051                } else printk ("  HOSTERROR: %x", cp->host_status);
5052                printk ("\n");
5053        }
5054
5055        /*
5056        **      Free this ccb
5057        */
5058        ncr_free_ccb (np, cp);
5059
5060        /*
5061        **      requeue awaiting scsi commands for this lun.
5062        */
5063        if (lp && lp->queuedccbs < lp->queuedepth &&
5064            !list_empty(&lp->wait_ccbq))
5065                ncr_start_next_ccb(np, lp, 2);
5066
5067        /*
5068        **      requeue awaiting scsi commands for this controller.
5069        */
5070        if (np->waiting_list)
5071                requeue_waiting_list(np);
5072
5073        /*
5074        **      signal completion to generic driver.
5075        */
5076        ncr_queue_done_cmd(np, cmd);
5077}
5078
5079/*==========================================================
5080**
5081**
5082**      Signal all (or one) control block done.
5083**
5084**
5085**==========================================================
5086*/
5087
5088/*
5089**      This CCB has been skipped by the NCR.
5090**      Queue it in the corresponding unit queue.
5091*/
5092static void ncr_ccb_skipped(struct ncb *np, struct ccb *cp)
5093{
5094        struct tcb *tp = &np->target[cp->target];
5095        struct lcb *lp = tp->lp[cp->lun];
5096
5097        if (lp && cp != np->ccb) {
5098                cp->host_status &= ~HS_SKIPMASK;
5099                cp->start.schedule.l_paddr = 
5100                        cpu_to_scr(NCB_SCRIPT_PHYS (np, select));
5101                list_move_tail(&cp->link_ccbq, &lp->skip_ccbq);
5102                if (cp->queued) {
5103                        --lp->queuedccbs;
5104                }
5105        }
5106        if (cp->queued) {
5107                --np->queuedccbs;
5108                cp->queued = 0;
5109        }
5110}
5111
5112/*
5113**      The NCR has completed CCBs.
5114**      Look at the DONE QUEUE if enabled, otherwise scan all CCBs
5115*/
5116void ncr_wakeup_done (struct ncb *np)
5117{
5118        struct ccb *cp;
5119#ifdef SCSI_NCR_CCB_DONE_SUPPORT
5120        int i, j;
5121
5122        i = np->ccb_done_ic;
5123        while (1) {
5124                j = i+1;
5125                if (j >= MAX_DONE)
5126                        j = 0;
5127
5128                cp = np->ccb_done[j];
5129                if (!CCB_DONE_VALID(cp))
5130                        break;
5131
5132                np->ccb_done[j] = (struct ccb *)CCB_DONE_EMPTY;
5133                np->scripth->done_queue[5*j + 4] =
5134                                cpu_to_scr(NCB_SCRIPT_PHYS (np, done_plug));
5135                MEMORY_BARRIER();
5136                np->scripth->done_queue[5*i + 4] =
5137                                cpu_to_scr(NCB_SCRIPT_PHYS (np, done_end));
5138
5139                if (cp->host_status & HS_DONEMASK)
5140                        ncr_complete (np, cp);
5141                else if (cp->host_status & HS_SKIPMASK)
5142                        ncr_ccb_skipped (np, cp);
5143
5144                i = j;
5145        }
5146        np->ccb_done_ic = i;
5147#else
5148        cp = np->ccb;
5149        while (cp) {
5150                if (cp->host_status & HS_DONEMASK)
5151                        ncr_complete (np, cp);
5152                else if (cp->host_status & HS_SKIPMASK)
5153                        ncr_ccb_skipped (np, cp);
5154                cp = cp->link_ccb;
5155        }
5156#endif
5157}
5158
5159/*
5160**      Complete all active CCBs.
5161*/
5162void ncr_wakeup (struct ncb *np, u_long code)
5163{
5164        struct ccb *cp = np->ccb;
5165
5166        while (cp) {
5167                if (cp->host_status != HS_IDLE) {
5168                        cp->host_status = code;
5169                        ncr_complete (np, cp);
5170                }
5171                cp = cp->link_ccb;
5172        }
5173}
5174
5175/*
5176** Reset ncr chip.
5177*/
5178
5179/* Some initialisation must be done immediately following reset, for 53c720,
5180 * at least.  EA (dcntl bit 5) isn't set here as it is set once only in
5181 * the _detect function.
5182 */
5183static void ncr_chip_reset(struct ncb *np, int delay)
5184{
5185        OUTB (nc_istat,  SRST);
5186        udelay(delay);
5187        OUTB (nc_istat,  0   );
5188
5189        if (np->features & FE_EHP)
5190                OUTB (nc_ctest0, EHP);
5191        if (np->features & FE_MUX)
5192                OUTB (nc_ctest4, MUX);
5193}
5194
5195
5196/*==========================================================
5197**
5198**
5199**      Start NCR chip.
5200**
5201**
5202**==========================================================
5203*/
5204
5205void ncr_init (struct ncb *np, int reset, char * msg, u_long code)
5206{
5207        int     i;
5208
5209        /*
5210        **      Reset chip if asked, otherwise just clear fifos.
5211        */
5212
5213        if (reset) {
5214                OUTB (nc_istat,  SRST);
5215                udelay(100);
5216        }
5217        else {
5218                OUTB (nc_stest3, TE|CSF);
5219                OUTONB (nc_ctest3, CLF);
5220        }
5221 
5222        /*
5223        **      Message.
5224        */
5225
5226        if (msg) printk (KERN_INFO "%s: restart (%s).\n", ncr_name (np), msg);
5227
5228        /*
5229        **      Clear Start Queue
5230        */
5231        np->queuedepth = MAX_START - 1; /* 1 entry needed as end marker */
5232        for (i = 1; i < MAX_START + MAX_START; i += 2)
5233                np->scripth0->tryloop[i] =
5234                                cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
5235
5236        /*
5237        **      Start at first entry.
5238        */
5239        np->squeueput = 0;
5240        np->script0->startpos[0] = cpu_to_scr(NCB_SCRIPTH_PHYS (np, tryloop));
5241
5242#ifdef SCSI_NCR_CCB_DONE_SUPPORT
5243        /*
5244        **      Clear Done Queue
5245        */
5246        for (i = 0; i < MAX_DONE; i++) {
5247                np->ccb_done[i] = (struct ccb *)CCB_DONE_EMPTY;
5248                np->scripth0->done_queue[5*i + 4] =
5249                        cpu_to_scr(NCB_SCRIPT_PHYS (np, done_end));
5250        }
5251#endif
5252
5253        /*
5254        **      Start at first entry.
5255        */
5256        np->script0->done_pos[0] = cpu_to_scr(NCB_SCRIPTH_PHYS (np,done_queue));
5257        np->ccb_done_ic = MAX_DONE-1;
5258        np->scripth0->done_queue[5*(MAX_DONE-1) + 4] =
5259                        cpu_to_scr(NCB_SCRIPT_PHYS (np, done_plug));
5260
5261        /*
5262        **      Wakeup all pending jobs.
5263        */
5264        ncr_wakeup (np, code);
5265
5266        /*
5267        **      Init chip.
5268        */
5269
5270        /*
5271        ** Remove reset; big delay because the 895 needs time for the
5272        ** bus mode to settle
5273        */
5274        ncr_chip_reset(np, 2000);
5275
5276        OUTB (nc_scntl0, np->rv_scntl0 | 0xc0);
5277                                        /*  full arb., ena parity, par->ATN  */
5278        OUTB (nc_scntl1, 0x00);         /*  odd parity, and remove CRST!! */
5279
5280        ncr_selectclock(np, np->rv_scntl3);     /* Select SCSI clock */
5281
5282        OUTB (nc_scid  , RRE|np->myaddr);       /* Adapter SCSI address */
5283        OUTW (nc_respid, 1ul<<np->myaddr);      /* Id to respond to */
5284        OUTB (nc_istat , SIGP   );              /*  Signal Process */
5285        OUTB (nc_dmode , np->rv_dmode);         /* Burst length, dma mode */
5286        OUTB (nc_ctest5, np->rv_ctest5);        /* Large fifo + large burst */
5287
5288        OUTB (nc_dcntl , NOCOM|np->rv_dcntl);   /* Protect SFBR */
5289        OUTB (nc_ctest0, np->rv_ctest0);        /* 720: CDIS and EHP */
5290        OUTB (nc_ctest3, np->rv_ctest3);        /* Write and invalidate */
5291        OUTB (nc_ctest4, np->rv_ctest4);        /* Master parity checking */
5292
5293        OUTB (nc_stest2, EXT|np->rv_stest2);    /* Extended Sreq/Sack filtering */
5294        OUTB (nc_stest3, TE);                   /* TolerANT enable */
5295        OUTB (nc_stime0, 0x0c   );              /* HTH disabled  STO 0.25 sec */
5296
5297        /*
5298        **      Disable disconnects.
5299        */
5300
5301        np->disc = 0;
5302
5303        /*
5304        **    Enable GPIO0 pin for writing if LED support.
5305        */
5306
5307        if (np->features & FE_LED0) {
5308                OUTOFFB (nc_gpcntl, 0x01);
5309        }
5310
5311        /*
5312        **      enable ints
5313        */
5314
5315        OUTW (nc_sien , STO|HTH|MA|SGE|UDC|RST|PAR);
5316        OUTB (nc_dien , MDPE|BF|ABRT|SSI|SIR|IID);
5317
5318        /*
5319        **      Fill in target structure.
5320        **      Reinitialize usrsync.
5321        **      Reinitialize usrwide.
5322        **      Prepare sync negotiation according to actual SCSI bus mode.
5323        */
5324
5325        for (i=0;i<MAX_TARGET;i++) {
5326                struct tcb *tp = &np->target[i];
5327
5328                tp->sval    = 0;
5329                tp->wval    = np->rv_scntl3;
5330
5331                if (tp->usrsync != 255) {
5332                        if (tp->usrsync <= np->maxsync) {
5333                                if (tp->usrsync < np->minsync) {
5334                                        tp->usrsync = np->minsync;
5335                                }
5336                        }
5337                        else
5338                                tp->usrsync = 255;
5339                }
5340
5341                if (tp->usrwide > np->maxwide)
5342                        tp->usrwide = np->maxwide;
5343
5344        }
5345
5346        /*
5347        **    Start script processor.
5348        */
5349        if (np->paddr2) {
5350                if (bootverbose)
5351                        printk ("%s: Downloading SCSI SCRIPTS.\n",
5352                                ncr_name(np));
5353                OUTL (nc_scratcha, vtobus(np->script0));
5354                OUTL_DSP (NCB_SCRIPTH_PHYS (np, start_ram));
5355        }
5356        else
5357                OUTL_DSP (NCB_SCRIPT_PHYS (np, start));
5358}
5359
5360/*==========================================================
5361**
5362**      Prepare the negotiation values for wide and
5363**      synchronous transfers.
5364**
5365**==========================================================
5366*/
5367
5368static void ncr_negotiate (struct ncb* np, struct tcb* tp)
5369{
5370        /*
5371        **      minsync unit is 4ns !
5372        */
5373
5374        u_long minsync = tp->usrsync;
5375
5376        /*
5377        **      SCSI bus mode limit
5378        */
5379
5380        if (np->scsi_mode && np->scsi_mode == SMODE_SE) {
5381                if (minsync < 12) minsync = 12;
5382        }
5383
5384        /*
5385        **      our limit ..
5386        */
5387
5388        if (minsync < np->minsync)
5389                minsync = np->minsync;
5390
5391        /*
5392        **      divider limit
5393        */
5394
5395        if (minsync > np->maxsync)
5396                minsync = 255;
5397
5398        if (tp->maxoffs > np->maxoffs)
5399                tp->maxoffs = np->maxoffs;
5400
5401        tp->minsync = minsync;
5402        tp->maxoffs = (minsync<255 ? tp->maxoffs : 0);
5403
5404        /*
5405        **      period=0: has to negotiate sync transfer
5406        */
5407
5408        tp->period=0;
5409
5410        /*
5411        **      widedone=0: has to negotiate wide transfer
5412        */
5413        tp->widedone=0;
5414}
5415
5416/*==========================================================
5417**
5418**      Get clock factor and sync divisor for a given 
5419**      synchronous factor period.
5420**      Returns the clock factor (in sxfer) and scntl3 
5421**      synchronous divisor field.
5422**
5423**==========================================================
5424*/
5425
5426static void ncr_getsync(struct ncb *np, u_char sfac, u_char *fakp, u_char *scntl3p)
5427{
5428        u_long  clk = np->clock_khz;    /* SCSI clock frequency in kHz  */
5429        int     div = np->clock_divn;   /* Number of divisors supported */
5430        u_long  fak;                    /* Sync factor in sxfer         */
5431        u_long  per;                    /* Period in tenths of ns       */
5432        u_long  kpc;                    /* (per * clk)                  */
5433
5434        /*
5435        **      Compute the synchronous period in tenths of nano-seconds
5436        */
5437        if      (sfac <= 10)    per = 250;
5438        else if (sfac == 11)    per = 303;
5439        else if (sfac == 12)    per = 500;
5440        else                    per = 40 * sfac;
5441
5442        /*
5443        **      Look for the greatest clock divisor that allows an 
5444        **      input speed faster than the period.
5445        */
5446        kpc = per * clk;
5447        while (--div > 0)
5448                if (kpc >= (div_10M[div] << 2)) break;
5449
5450        /*
5451        **      Calculate the lowest clock factor that allows an output 
5452        **      speed not faster than the period.
5453        */
5454        fak = (kpc - 1) / div_10M[div] + 1;
5455
5456#if 0   /* This optimization does not seem very useful */
5457
5458        per = (fak * div_10M[div]) / clk;
5459
5460        /*
5461        **      Why not to try the immediate lower divisor and to choose 
5462        **      the one that allows the fastest output speed ?
5463        **      We don't want input speed too much greater than output speed.
5464        */
5465        if (div >= 1 && fak < 8) {
5466                u_long fak2, per2;
5467                fak2 = (kpc - 1) / div_10M[div-1] + 1;
5468                per2 = (fak2 * div_10M[div-1]) / clk;
5469                if (per2 < per && fak2 <= 8) {
5470                        fak = fak2;
5471                        per = per2;
5472                        --div;
5473                }
5474        }
5475#endif
5476
5477        if (fak < 4) fak = 4;   /* Should never happen, too bad ... */
5478
5479        /*
5480        **      Compute and return sync parameters for the ncr
5481        */
5482        *fakp           = fak - 4;
5483        *scntl3p        = ((div+1) << 4) + (sfac < 25 ? 0x80 : 0);
5484}
5485
5486
5487/*==========================================================
5488**
5489**      Set actual values, sync status and patch all ccbs of 
5490**      a target according to new sync/wide agreement.
5491**
5492**==========================================================
5493*/
5494
5495static void ncr_set_sync_wide_status (struct ncb *np, u_char target)
5496{
5497        struct ccb *cp;
5498        struct tcb *tp = &np->target[target];
5499
5500        /*
5501        **      set actual value and sync_status
5502        */
5503        OUTB (nc_sxfer, tp->sval);
5504        np->sync_st = tp->sval;
5505        OUTB (nc_scntl3, tp->wval);
5506        np->wide_st = tp->wval;
5507
5508        /*
5509        **      patch ALL ccbs of this target.
5510        */
5511        for (cp = np->ccb; cp; cp = cp->link_ccb) {
5512                if (!cp->cmd) continue;
5513                if (scmd_id(cp->cmd) != target) continue;
5514#if 0
5515                cp->sync_status = tp->sval;
5516                cp->wide_status = tp->wval;
5517#endif
5518                cp->phys.select.sel_scntl3 = tp->wval;
5519                cp->phys.select.sel_sxfer  = tp->sval;
5520        }
5521}
5522
5523/*==========================================================
5524**
5525**      Switch sync mode for current job and it's target
5526**
5527**==========================================================
5528*/
5529
5530static void ncr_setsync (struct ncb *np, struct ccb *cp, u_char scntl3, u_char sxfer)
5531{
5532        struct scsi_cmnd *cmd = cp->cmd;
5533        struct tcb *tp;
5534        u_char target = INB (nc_sdid) & 0x0f;
5535        u_char idiv;
5536
5537        BUG_ON(target != (scmd_id(cmd) & 0xf));
5538
5539        tp = &np->target[target];
5540
5541        if (!scntl3 || !(sxfer & 0x1f))
5542                scntl3 = np->rv_scntl3;
5543        scntl3 = (scntl3 & 0xf0) | (tp->wval & EWS) | (np->rv_scntl3 & 0x07);
5544
5545        /*
5546        **      Deduce the value of controller sync period from scntl3.
5547        **      period is in tenths of nano-seconds.
5548        */
5549
5550        idiv = ((scntl3 >> 4) & 0x7);
5551        if ((sxfer & 0x1f) && idiv)
5552                tp->period = (((sxfer>>5)+4)*div_10M[idiv-1])/np->clock_khz;
5553        else
5554                tp->period = 0xffff;
5555
5556        /* Stop there if sync parameters are unchanged */
5557        if (tp->sval == sxfer && tp->wval == scntl3)
5558                return;
5559        tp->sval = sxfer;
5560        tp->wval = scntl3;
5561
5562        if (sxfer & 0x01f) {
5563                /* Disable extended Sreq/Sack filtering */
5564                if (tp->period <= 2000)
5565                        OUTOFFB(nc_stest2, EXT);
5566        }
5567 
5568        spi_display_xfer_agreement(tp->starget);
5569
5570        /*
5571        **      set actual value and sync_status
5572        **      patch ALL ccbs of this target.
5573        */
5574        ncr_set_sync_wide_status(np, target);
5575}
5576
5577/*==========================================================
5578**
5579**      Switch wide mode for current job and it's target
5580**      SCSI specs say: a SCSI device that accepts a WDTR 
5581**      message shall reset the synchronous agreement to 
5582**      asynchronous mode.
5583**
5584**==========================================================
5585*/
5586
5587static void ncr_setwide (struct ncb *np, struct ccb *cp, u_char wide, u_char ack)
5588{
5589        struct scsi_cmnd *cmd = cp->cmd;
5590        u16 target = INB (nc_sdid) & 0x0f;
5591        struct tcb *tp;
5592        u_char  scntl3;
5593        u_char  sxfer;
5594
5595        BUG_ON(target != (scmd_id(cmd) & 0xf));
5596
5597        tp = &np->target[target];
5598        tp->widedone  =  wide+1;
5599        scntl3 = (tp->wval & (~EWS)) | (wide ? EWS : 0);
5600
5601        sxfer = ack ? 0 : tp->sval;
5602
5603        /*
5604        **       Stop there if sync/wide parameters are unchanged
5605        */
5606        if (tp->sval == sxfer && tp->wval == scntl3) return;
5607        tp->sval = sxfer;
5608        tp->wval = scntl3;
5609
5610        /*
5611        **      Bells and whistles   ;-)
5612        */
5613        if (bootverbose >= 2) {
5614                dev_info(&cmd->device->sdev_target->dev, "WIDE SCSI %sabled.\n",
5615                                (scntl3 & EWS) ? "en" : "dis");
5616        }
5617
5618        /*
5619        **      set actual value and sync_status
5620        **      patch ALL ccbs of this target.
5621        */
5622        ncr_set_sync_wide_status(np, target);
5623}
5624
5625/*==========================================================
5626**
5627**      Switch tagged mode for a target.
5628**
5629**==========================================================
5630*/
5631
5632static void ncr_setup_tags (struct ncb *np, struct scsi_device *sdev)
5633{
5634        unsigned char tn = sdev->id, ln = sdev->lun;
5635        struct tcb *tp = &np->target[tn];
5636        struct lcb *lp = tp->lp[ln];
5637        u_char   reqtags, maxdepth;
5638
5639        /*
5640        **      Just in case ...
5641        */
5642        if ((!tp) || (!lp) || !sdev)
5643                return;
5644
5645        /*
5646        **      If SCSI device queue depth is not yet set, leave here.
5647        */
5648        if (!lp->scdev_depth)
5649                return;
5650
5651        /*
5652        **      Donnot allow more tags than the SCSI driver can queue 
5653        **      for this device.
5654        **      Donnot allow more tags than we can handle.
5655        */
5656        maxdepth = lp->scdev_depth;
5657        if (maxdepth > lp->maxnxs)      max