linux-bk/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*******************************************************************************
  73*/
  74
  75/*
  76**      Supported SCSI-II features:
  77**          Synchronous negotiation
  78**          Wide negotiation        (depends on the NCR Chip)
  79**          Enable disconnection
  80**          Tagged command queuing
  81**          Parity checking
  82**          Etc...
  83**
  84**      Supported NCR/SYMBIOS chips:
  85**              53C720          (Wide,   Fast SCSI-2, HP Zalon)
  86**              53C810          (8 bits, Fast SCSI-2, no rom BIOS) 
  87**              53C815          (8 bits, Fast SCSI-2, on board rom BIOS)
  88**              53C820          (Wide,   Fast SCSI-2, no rom BIOS)
  89**              53C825          (Wide,   Fast SCSI-2, on board rom BIOS)
  90**              53C860          (8 bits, Fast 20,     no rom BIOS)
  91**              53C875          (Wide,   Fast 20,     on board rom BIOS)
  92**              53C895          (Wide,   Fast 40,     on board rom BIOS)
  93**              53C895A         (Wide,   Fast 40,     on board rom BIOS)
  94**              53C896          (Wide,   Fast 40,     on board rom BIOS)
  95**              53C897          (Wide,   Fast 40,     on board rom BIOS)
  96**              53C1510D        (Wide,   Fast 40,     on board rom BIOS)
  97**
  98**      Other features:
  99**              Memory mapped IO (linux-1.3.X and above only)
 100**              Module
 101**              Shared IRQ (since linux-1.3.72)
 102*/
 103
 104/*
 105**      Name and version of the driver
 106*/
 107#define SCSI_NCR_DRIVER_NAME    "ncr53c8xx-3.4.3b-20010512"
 108
 109#define SCSI_NCR_DEBUG_FLAGS    (0)
 110
 111/*==========================================================
 112**
 113**      Include files
 114**
 115**==========================================================
 116*/
 117
 118#define LinuxVersionCode(v, p, s) (((v)<<16)+((p)<<8)+(s))
 119
 120#include <linux/module.h>
 121#include <asm/dma.h>
 122#include <asm/io.h>
 123#include <asm/system.h>
 124#if LINUX_VERSION_CODE >= LinuxVersionCode(2,3,17)
 125#include <linux/spinlock.h>
 126#elif LINUX_VERSION_CODE >= LinuxVersionCode(2,1,93)
 127#include <asm/spinlock.h>
 128#endif
 129#include <linux/delay.h>
 130#include <linux/signal.h>
 131#include <linux/sched.h>
 132#include <linux/errno.h>
 133#include <linux/pci.h>
 134#include <linux/dma-mapping.h>
 135#include <linux/interrupt.h>
 136#include <linux/string.h>
 137#include <linux/mm.h>
 138#include <linux/ioport.h>
 139#include <linux/time.h>
 140#include <linux/timer.h>
 141#include <linux/stat.h>
 142
 143#include <linux/version.h>
 144#include <linux/blk.h>
 145
 146#if LINUX_VERSION_CODE >= LinuxVersionCode(2,1,35)
 147#include <linux/init.h>
 148#endif
 149
 150#ifndef __init
 151#define __init
 152#endif
 153#ifndef __initdata
 154#define __initdata
 155#endif
 156
 157#if LINUX_VERSION_CODE <= LinuxVersionCode(2,1,92)
 158#include <linux/bios32.h>
 159#endif
 160
 161#include "scsi.h"
 162#include "hosts.h"
 163
 164#include <linux/types.h>
 165
 166/*
 167**      Define BITS_PER_LONG for earlier linux versions.
 168*/
 169#ifndef BITS_PER_LONG
 170#if (~0UL) == 0xffffffffUL
 171#define BITS_PER_LONG   32
 172#else
 173#define BITS_PER_LONG   64
 174#endif
 175#endif
 176
 177/*
 178**      Define the BSD style u_int32 and u_int64 type.
 179**      Are in fact u_int32_t and u_int64_t :-)
 180*/
 181typedef u32 u_int32;
 182typedef u64 u_int64;
 183typedef u_long          vm_offset_t;
 184
 185#ifdef __hppa__
 186/*
 187 * Yuck.  Current plan is to use ncr58c8xx.c for non-pci big endian
 188 * chips, and sym53c8xx.c for pci little endian chips.  Define this
 189 * here so it gets seen by sym53c8xx_defs.h, pulled in via ncr53c8xx.h.
 190 */
 191#define SCSI_NCR_BIG_ENDIAN
 192/* INTFLY interrupts don't always seem to get serviced atm..... */
 193#define SIMULATED_INTFLY
 194#endif
 195
 196#if defined(CONFIG_SCSI_ZALON) || defined(CONFIG_SCSI_ZALON_MODULE)
 197#define ENABLE_SCSI_ZALON
 198#include <asm/parisc-device.h>
 199#include "zalon.h"
 200#endif
 201
 202#include "ncr53c8xx.h"
 203
 204/*
 205**      Donnot compile integrity checking code for Linux-2.3.0 
 206**      and above since SCSI data structures are not ready yet.
 207*/
 208/* #if LINUX_VERSION_CODE < LinuxVersionCode(2,3,0) */
 209#if 0
 210#define SCSI_NCR_INTEGRITY_CHECKING
 211#endif
 212
 213#define NAME53C                 "ncr53c"
 214#define NAME53C8XX              "ncr53c8xx"
 215#define DRIVER_SMP_LOCK         ncr53c8xx_lock
 216
 217#include "sym53c8xx_comm.h"
 218
 219/*==========================================================
 220**
 221**      The CCB done queue uses an array of CCB virtual 
 222**      addresses. Empty entries are flagged using the bogus 
 223**      virtual address 0xffffffff.
 224**
 225**      Since PCI ensures that only aligned DWORDs are accessed 
 226**      atomically, 64 bit little-endian architecture requires 
 227**      to test the high order DWORD of the entry to determine 
 228**      if it is empty or valid.
 229**
 230**      BTW, I will make things differently as soon as I will 
 231**      have a better idea, but this is simple and should work.
 232**
 233**==========================================================
 234*/
 235 
 236#define SCSI_NCR_CCB_DONE_SUPPORT
 237#ifdef  SCSI_NCR_CCB_DONE_SUPPORT
 238
 239#define MAX_DONE 24
 240#define CCB_DONE_EMPTY 0xffffffffUL
 241
 242/* All 32 bit architectures */
 243#if BITS_PER_LONG == 32
 244#define CCB_DONE_VALID(cp)  (((u_long) cp) != CCB_DONE_EMPTY)
 245
 246/* All > 32 bit (64 bit) architectures regardless endian-ness */
 247#else
 248#define CCB_DONE_VALID(cp)  \
 249        ((((u_long) cp) & 0xffffffff00000000ul) &&      \
 250         (((u_long) cp) & 0xfffffffful) != CCB_DONE_EMPTY)
 251#endif
 252
 253#endif /* SCSI_NCR_CCB_DONE_SUPPORT */
 254
 255/*==========================================================
 256**
 257**      Configuration and Debugging
 258**
 259**==========================================================
 260*/
 261
 262/*
 263**    SCSI address of this device.
 264**    The boot routines should have set it.
 265**    If not, use this.
 266*/
 267
 268#ifndef SCSI_NCR_MYADDR
 269#define SCSI_NCR_MYADDR      (7)
 270#endif
 271
 272/*
 273**    The maximum number of tags per logic unit.
 274**    Used only for disk devices that support tags.
 275*/
 276
 277#ifndef SCSI_NCR_MAX_TAGS
 278#define SCSI_NCR_MAX_TAGS    (8)
 279#endif
 280
 281/*
 282**    TAGS are actually limited to 64 tags/lun.
 283**    We need to deal with power of 2, for alignment constraints.
 284*/
 285#if     SCSI_NCR_MAX_TAGS > 64
 286#define MAX_TAGS (64)
 287#else
 288#define MAX_TAGS SCSI_NCR_MAX_TAGS
 289#endif
 290
 291#define NO_TAG  (255)
 292
 293/*
 294**      Choose appropriate type for tag bitmap.
 295*/
 296#if     MAX_TAGS > 32
 297typedef u_int64 tagmap_t;
 298#else
 299typedef u_int32 tagmap_t;
 300#endif
 301
 302/*
 303**    Number of targets supported by the driver.
 304**    n permits target numbers 0..n-1.
 305**    Default is 16, meaning targets #0..#15.
 306**    #7 .. is myself.
 307*/
 308
 309#ifdef SCSI_NCR_MAX_TARGET
 310#define MAX_TARGET  (SCSI_NCR_MAX_TARGET)
 311#else
 312#define MAX_TARGET  (16)
 313#endif
 314
 315/*
 316**    Number of logic units supported by the driver.
 317**    n enables logic unit numbers 0..n-1.
 318**    The common SCSI devices require only
 319**    one lun, so take 1 as the default.
 320*/
 321
 322#ifdef SCSI_NCR_MAX_LUN
 323#define MAX_LUN    SCSI_NCR_MAX_LUN
 324#else
 325#define MAX_LUN    (1)
 326#endif
 327
 328/*
 329**    Asynchronous pre-scaler (ns). Shall be 40
 330*/
 331 
 332#ifndef SCSI_NCR_MIN_ASYNC
 333#define SCSI_NCR_MIN_ASYNC (40)
 334#endif
 335
 336/*
 337**    The maximum number of jobs scheduled for starting.
 338**    There should be one slot per target, and one slot
 339**    for each tag of each target in use.
 340**    The calculation below is actually quite silly ...
 341*/
 342
 343#ifdef SCSI_NCR_CAN_QUEUE
 344#define MAX_START   (SCSI_NCR_CAN_QUEUE + 4)
 345#else
 346#define MAX_START   (MAX_TARGET + 7 * MAX_TAGS)
 347#endif
 348
 349/*
 350**   We limit the max number of pending IO to 250.
 351**   since we donnot want to allocate more than 1 
 352**   PAGE for 'scripth'.
 353*/
 354#if     MAX_START > 250
 355#undef  MAX_START
 356#define MAX_START 250
 357#endif
 358
 359/*
 360**    The maximum number of segments a transfer is split into.
 361**    We support up to 127 segments for both read and write.
 362**    The data scripts are broken into 2 sub-scripts.
 363**    80 (MAX_SCATTERL) segments are moved from a sub-script 
 364**    in on-chip RAM. This makes data transfers shorter than 
 365**    80k (assuming 1k fs) as fast as possible.
 366*/
 367
 368#define MAX_SCATTER (SCSI_NCR_MAX_SCATTER)
 369
 370#if (MAX_SCATTER > 80)
 371#define MAX_SCATTERL    80
 372#define MAX_SCATTERH    (MAX_SCATTER - MAX_SCATTERL)
 373#else
 374#define MAX_SCATTERL    (MAX_SCATTER-1)
 375#define MAX_SCATTERH    1
 376#endif
 377
 378/*
 379**      other
 380*/
 381
 382#define NCR_SNOOP_TIMEOUT (1000000)
 383
 384/*
 385**      Head of list of NCR boards
 386**
 387**      For kernel version < 1.3.70, host is retrieved by its irq level.
 388**      For later kernels, the internal host control block address 
 389**      (struct ncb) is used as device id parameter of the irq stuff.
 390*/
 391
 392static struct Scsi_Host         *first_host     = NULL;
 393static Scsi_Host_Template       *the_template   = NULL; 
 394
 395/*
 396**      Other definitions
 397*/
 398
 399#define ScsiResult(host_code, scsi_code) (((host_code) << 16) + ((scsi_code) & 0x7f))
 400
 401static void ncr53c8xx_intr(int irq, void *dev_id, struct pt_regs * regs);
 402static void ncr53c8xx_timeout(unsigned long np);
 403static int ncr53c8xx_proc_info(char *buffer, char **start, off_t offset,
 404                        int length, int hostno, int func);
 405
 406#define initverbose (driver_setup.verbose)
 407#define bootverbose (np->verbose)
 408
 409#ifdef SCSI_NCR_NVRAM_SUPPORT
 410static u_char Tekram_sync[16] __initdata =
 411        {25,31,37,43, 50,62,75,125, 12,15,18,21, 6,7,9,10};
 412#endif /* SCSI_NCR_NVRAM_SUPPORT */
 413
 414/*==========================================================
 415**
 416**      Command control block states.
 417**
 418**==========================================================
 419*/
 420
 421#define HS_IDLE         (0)
 422#define HS_BUSY         (1)
 423#define HS_NEGOTIATE    (2)     /* sync/wide data transfer*/
 424#define HS_DISCONNECT   (3)     /* Disconnected by target */
 425
 426#define HS_DONEMASK     (0x80)
 427#define HS_COMPLETE     (4|HS_DONEMASK)
 428#define HS_SEL_TIMEOUT  (5|HS_DONEMASK) /* Selection timeout      */
 429#define HS_RESET        (6|HS_DONEMASK) /* SCSI reset             */
 430#define HS_ABORTED      (7|HS_DONEMASK) /* Transfer aborted       */
 431#define HS_TIMEOUT      (8|HS_DONEMASK) /* Software timeout       */
 432#define HS_FAIL         (9|HS_DONEMASK) /* SCSI or PCI bus errors */
 433#define HS_UNEXPECTED   (10|HS_DONEMASK)/* Unexpected disconnect  */
 434
 435/*
 436**      Invalid host status values used by the SCRIPTS processor 
 437**      when the nexus is not fully identified.
 438**      Shall never appear in a CCB.
 439*/
 440
 441#define HS_INVALMASK    (0x40)
 442#define HS_SELECTING    (0|HS_INVALMASK)
 443#define HS_IN_RESELECT  (1|HS_INVALMASK)
 444#define HS_STARTING     (2|HS_INVALMASK)
 445
 446/*
 447**      Flags set by the SCRIPT processor for commands 
 448**      that have been skipped.
 449*/
 450#define HS_SKIPMASK     (0x20)
 451
 452/*==========================================================
 453**
 454**      Software Interrupt Codes
 455**
 456**==========================================================
 457*/
 458
 459#define SIR_BAD_STATUS          (1)
 460#define SIR_XXXXXXXXXX          (2)
 461#define SIR_NEGO_SYNC           (3)
 462#define SIR_NEGO_WIDE           (4)
 463#define SIR_NEGO_FAILED         (5)
 464#define SIR_NEGO_PROTO          (6)
 465#define SIR_REJECT_RECEIVED     (7)
 466#define SIR_REJECT_SENT         (8)
 467#define SIR_IGN_RESIDUE         (9)
 468#define SIR_MISSING_SAVE        (10)
 469#define SIR_RESEL_NO_MSG_IN     (11)
 470#define SIR_RESEL_NO_IDENTIFY   (12)
 471#define SIR_RESEL_BAD_LUN       (13)
 472#define SIR_RESEL_BAD_TARGET    (14)
 473#define SIR_RESEL_BAD_I_T_L     (15)
 474#define SIR_RESEL_BAD_I_T_L_Q   (16)
 475#define SIR_DONE_OVERFLOW       (17)
 476#define SIR_INTFLY              (18)
 477#define SIR_MAX                 (18)
 478
 479/*==========================================================
 480**
 481**      Extended error codes.
 482**      xerr_status field of struct ccb.
 483**
 484**==========================================================
 485*/
 486
 487#define XE_OK           (0)
 488#define XE_EXTRA_DATA   (1)     /* unexpected data phase */
 489#define XE_BAD_PHASE    (2)     /* illegal phase (4/5)   */
 490
 491/*==========================================================
 492**
 493**      Negotiation status.
 494**      nego_status field       of struct ccb.
 495**
 496**==========================================================
 497*/
 498
 499#define NS_NOCHANGE     (0)
 500#define NS_SYNC         (1)
 501#define NS_WIDE         (2)
 502#define NS_PPR          (4)
 503
 504/*==========================================================
 505**
 506**      "Special features" of targets.
 507**      quirks field            of struct tcb.
 508**      actualquirks field      of struct ccb.
 509**
 510**==========================================================
 511*/
 512
 513#define QUIRK_AUTOSAVE  (0x01)
 514#define QUIRK_NOMSG     (0x02)
 515#define QUIRK_NOSYNC    (0x10)
 516#define QUIRK_NOWIDE16  (0x20)
 517
 518/*==========================================================
 519**
 520**      Capability bits in Inquire response byte 7.
 521**
 522**==========================================================
 523*/
 524
 525#define INQ7_QUEUE      (0x02)
 526#define INQ7_SYNC       (0x10)
 527#define INQ7_WIDE16     (0x20)
 528
 529/*==========================================================
 530**
 531**      Misc.
 532**
 533**==========================================================
 534*/
 535
 536#define CCB_MAGIC       (0xf2691ad2)
 537
 538/*==========================================================
 539**
 540**      Declaration of structs.
 541**
 542**==========================================================
 543*/
 544
 545struct tcb;
 546struct lcb;
 547struct ccb;
 548struct ncb;
 549struct script;
 550
 551typedef struct ncb * ncb_p;
 552typedef struct tcb * tcb_p;
 553typedef struct lcb * lcb_p;
 554typedef struct ccb * ccb_p;
 555
 556struct link {
 557        ncrcmd  l_cmd;
 558        ncrcmd  l_paddr;
 559};
 560
 561struct  usrcmd {
 562        u_long  target;
 563        u_long  lun;
 564        u_long  data;
 565        u_long  cmd;
 566};
 567
 568#define UC_SETSYNC      10
 569#define UC_SETTAGS      11
 570#define UC_SETDEBUG     12
 571#define UC_SETORDER     13
 572#define UC_SETWIDE      14
 573#define UC_SETFLAG      15
 574#define UC_SETVERBOSE   17
 575
 576#define UF_TRACE        (0x01)
 577#define UF_NODISC       (0x02)
 578#define UF_NOSCAN       (0x04)
 579
 580/*========================================================================
 581**
 582**      Declaration of structs:         target control block
 583**
 584**========================================================================
 585*/
 586struct tcb {
 587        /*----------------------------------------------------------------
 588        **      During reselection the ncr jumps to this point with SFBR 
 589        **      set to the encoded target number with bit 7 set.
 590        **      if it's not this target, jump to the next.
 591        **
 592        **      JUMP  IF (SFBR != #target#), @(next tcb)
 593        **----------------------------------------------------------------
 594        */
 595        struct link   jump_tcb;
 596
 597        /*----------------------------------------------------------------
 598        **      Load the actual values for the sxfer and the scntl3
 599        **      register (sync/wide mode).
 600        **
 601        **      SCR_COPY (1), @(sval field of this tcb), @(sxfer  register)
 602        **      SCR_COPY (1), @(wval field of this tcb), @(scntl3 register)
 603        **----------------------------------------------------------------
 604        */
 605        ncrcmd  getscr[6];
 606
 607        /*----------------------------------------------------------------
 608        **      Get the IDENTIFY message and load the LUN to SFBR.
 609        **
 610        **      CALL, <RESEL_LUN>
 611        **----------------------------------------------------------------
 612        */
 613        struct link   call_lun;
 614
 615        /*----------------------------------------------------------------
 616        **      Now look for the right lun.
 617        **
 618        **      For i = 0 to 3
 619        **              SCR_JUMP ^ IFTRUE(MASK(i, 3)), @(first lcb mod. i)
 620        **
 621        **      Recent chips will prefetch the 4 JUMPS using only 1 burst.
 622        **      It is kind of hashcoding.
 623        **----------------------------------------------------------------
 624        */
 625        struct link     jump_lcb[4];    /* JUMPs for reselection        */
 626        lcb_p           lp[MAX_LUN];    /* The lcb's of this tcb        */
 627        u_char          inq_done;       /* Target capabilities received */
 628        u_char          inq_byte7;      /* Contains these capabilities  */
 629
 630        /*----------------------------------------------------------------
 631        **      Pointer to the ccb used for negotiation.
 632        **      Prevent from starting a negotiation for all queued commands 
 633        **      when tagged command queuing is enabled.
 634        **----------------------------------------------------------------
 635        */
 636        ccb_p   nego_cp;
 637
 638        /*----------------------------------------------------------------
 639        **      statistical data
 640        **----------------------------------------------------------------
 641        */
 642        u_long  transfers;
 643        u_long  bytes;
 644
 645        /*----------------------------------------------------------------
 646        **      negotiation of wide and synch transfer and device quirks.
 647        **----------------------------------------------------------------
 648        */
 649#ifdef SCSI_NCR_BIG_ENDIAN
 650/*0*/   u_short period;
 651/*2*/   u_char  sval;
 652/*3*/   u_char  minsync;
 653/*0*/   u_char  wval;
 654/*1*/   u_char  widedone;
 655/*2*/   u_char  quirks;
 656/*3*/   u_char  maxoffs;
 657#else
 658/*0*/   u_char  minsync;
 659/*1*/   u_char  sval;
 660/*2*/   u_short period;
 661/*0*/   u_char  maxoffs;
 662/*1*/   u_char  quirks;
 663/*2*/   u_char  widedone;
 664/*3*/   u_char  wval;
 665#endif
 666
 667#ifdef SCSI_NCR_INTEGRITY_CHECKING
 668        u_char  ic_min_sync;
 669        u_char  ic_max_width;
 670        u_char  ic_maximums_set;
 671        u_char  ic_done;
 672#endif
 673
 674        /*----------------------------------------------------------------
 675        **      User settable limits and options.
 676        **      These limits are read from the NVRAM if present.
 677        **----------------------------------------------------------------
 678        */
 679        u_char  usrsync;
 680        u_char  usrwide;
 681        u_char  usrtags;
 682        u_char  usrflag;
 683};
 684
 685/*========================================================================
 686**
 687**      Declaration of structs:         lun control block
 688**
 689**========================================================================
 690*/
 691struct lcb {
 692        /*----------------------------------------------------------------
 693        **      During reselection the ncr jumps to this point
 694        **      with SFBR set to the "Identify" message.
 695        **      if it's not this lun, jump to the next.
 696        **
 697        **      JUMP  IF (SFBR != #lun#), @(next lcb of this target)
 698        **
 699        **      It is this lun. Load TEMP with the nexus jumps table 
 700        **      address and jump to RESEL_TAG (or RESEL_NOTAG).
 701        **
 702        **              SCR_COPY (4), p_jump_ccb, TEMP,
 703        **              SCR_JUMP, <RESEL_TAG>
 704        **----------------------------------------------------------------
 705        */
 706        struct link     jump_lcb;
 707        ncrcmd          load_jump_ccb[3];
 708        struct link     jump_tag;
 709        ncrcmd          p_jump_ccb;     /* Jump table bus address       */
 710
 711        /*----------------------------------------------------------------
 712        **      Jump table used by the script processor to directly jump 
 713        **      to the CCB corresponding to the reselected nexus.
 714        **      Address is allocated on 256 bytes boundary in order to 
 715        **      allow 8 bit calculation of the tag jump entry for up to 
 716        **      64 possible tags.
 717        **----------------------------------------------------------------
 718        */
 719        u_int32         jump_ccb_0;     /* Default table if no tags     */
 720        u_int32         *jump_ccb;      /* Virtual address              */
 721
 722        /*----------------------------------------------------------------
 723        **      CCB queue management.
 724        **----------------------------------------------------------------
 725        */
 726        XPT_QUEHEAD     free_ccbq;      /* Queue of available CCBs      */
 727        XPT_QUEHEAD     busy_ccbq;      /* Queue of busy CCBs           */
 728        XPT_QUEHEAD     wait_ccbq;      /* Queue of waiting for IO CCBs */
 729        XPT_QUEHEAD     skip_ccbq;      /* Queue of skipped CCBs        */
 730        u_char          actccbs;        /* Number of allocated CCBs     */
 731        u_char          busyccbs;       /* CCBs busy for this lun       */
 732        u_char          queuedccbs;     /* CCBs queued to the controller*/
 733        u_char          queuedepth;     /* Queue depth for this lun     */
 734        u_char          scdev_depth;    /* SCSI device queue depth      */
 735        u_char          maxnxs;         /* Max possible nexuses         */
 736
 737        /*----------------------------------------------------------------
 738        **      Control of tagged command queuing.
 739        **      Tags allocation is performed using a circular buffer.
 740        **      This avoids using a loop for tag allocation.
 741        **----------------------------------------------------------------
 742        */
 743        u_char          ia_tag;         /* Allocation index             */
 744        u_char          if_tag;         /* Freeing index                */
 745        u_char cb_tags[MAX_TAGS];       /* Circular tags buffer */
 746        u_char          usetags;        /* Command queuing is active    */
 747        u_char          maxtags;        /* Max nr of tags asked by user */
 748        u_char          numtags;        /* Current number of tags       */
 749        u_char          inq_byte7;      /* Store unit CmdQ capabitility */
 750
 751        /*----------------------------------------------------------------
 752        **      QUEUE FULL control and ORDERED tag control.
 753        **----------------------------------------------------------------
 754        */
 755        /*----------------------------------------------------------------
 756        **      QUEUE FULL and ORDERED tag control.
 757        **----------------------------------------------------------------
 758        */
 759        u_short         num_good;       /* Nr of GOOD since QUEUE FULL  */
 760        tagmap_t        tags_umap;      /* Used tags bitmap             */
 761        tagmap_t        tags_smap;      /* Tags in use at 'tag_stime'   */
 762        u_long          tags_stime;     /* Last time we set smap=umap   */
 763        ccb_p           held_ccb;       /* CCB held for QUEUE FULL      */
 764};
 765
 766/*========================================================================
 767**
 768**      Declaration of structs:     the launch script.
 769**
 770**========================================================================
 771**
 772**      It is part of the CCB and is called by the scripts processor to 
 773**      start or restart the data structure (nexus).
 774**      This 6 DWORDs mini script makes use of prefetching.
 775**
 776**------------------------------------------------------------------------
 777*/
 778struct launch {
 779        /*----------------------------------------------------------------
 780        **      SCR_COPY(4),    @(p_phys), @(dsa register)
 781        **      SCR_JUMP,       @(scheduler_point)
 782        **----------------------------------------------------------------
 783        */
 784        ncrcmd          setup_dsa[3];   /* Copy 'phys' address to dsa   */
 785        struct link     schedule;       /* Jump to scheduler point      */
 786        ncrcmd          p_phys;         /* 'phys' header bus address    */
 787};
 788
 789/*========================================================================
 790**
 791**      Declaration of structs:     global HEADER.
 792**
 793**========================================================================
 794**
 795**      This substructure is copied from the ccb to a global address after 
 796**      selection (or reselection) and copied back before disconnect.
 797**
 798**      These fields are accessible to the script processor.
 799**
 800**------------------------------------------------------------------------
 801*/
 802
 803struct head {
 804        /*----------------------------------------------------------------
 805        **      Saved data pointer.
 806        **      Points to the position in the script responsible for the
 807        **      actual transfer transfer of data.
 808        **      It's written after reception of a SAVE_DATA_POINTER message.
 809        **      The goalpointer points after the last transfer command.
 810        **----------------------------------------------------------------
 811        */
 812        u_int32         savep;
 813        u_int32         lastp;
 814        u_int32         goalp;
 815
 816        /*----------------------------------------------------------------
 817        **      Alternate data pointer.
 818        **      They are copied back to savep/lastp/goalp by the SCRIPTS 
 819        **      when the direction is unknown and the device claims data out.
 820        **----------------------------------------------------------------
 821        */
 822        u_int32         wlastp;
 823        u_int32         wgoalp;
 824
 825        /*----------------------------------------------------------------
 826        **      The virtual address of the ccb containing this header.
 827        **----------------------------------------------------------------
 828        */
 829        ccb_p   cp;
 830
 831        /*----------------------------------------------------------------
 832        **      Status fields.
 833        **----------------------------------------------------------------
 834        */
 835        u_char          scr_st[4];      /* script status                */
 836        u_char          status[4];      /* host status. must be the     */
 837                                        /*  last DWORD of the header.   */
 838};
 839
 840/*
 841**      The status bytes are used by the host and the script processor.
 842**
 843**      The byte corresponding to the host_status must be stored in the 
 844**      last DWORD of the CCB header since it is used for command 
 845**      completion (ncr_wakeup()). Doing so, we are sure that the header 
 846**      has been entirely copied back to the CCB when the host_status is 
 847**      seen complete by the CPU.
 848**
 849**      The last four bytes (status[4]) are copied to the scratchb register
 850**      (declared as scr0..scr3 in ncr_reg.h) just after the select/reselect,
 851**      and copied back just after disconnecting.
 852**      Inside the script the XX_REG are used.
 853**
 854**      The first four bytes (scr_st[4]) are used inside the script by 
 855**      "COPY" commands.
 856**      Because source and destination must have the same alignment
 857**      in a DWORD, the fields HAVE to be at the choosen offsets.
 858**              xerr_st         0       (0x34)  scratcha
 859**              sync_st         1       (0x05)  sxfer
 860**              wide_st         3       (0x03)  scntl3
 861*/
 862
 863/*
 864**      Last four bytes (script)
 865*/
 866#define  QU_REG scr0
 867#define  HS_REG scr1
 868#define  HS_PRT nc_scr1
 869#define  SS_REG scr2
 870#define  SS_PRT nc_scr2
 871#define  PS_REG scr3
 872
 873/*
 874**      Last four bytes (host)
 875*/
 876#ifdef SCSI_NCR_BIG_ENDIAN
 877#define  actualquirks  phys.header.status[3]
 878#define  host_status   phys.header.status[2]
 879#define  scsi_status   phys.header.status[1]
 880#define  parity_status phys.header.status[0]
 881#else
 882#define  actualquirks  phys.header.status[0]
 883#define  host_status   phys.header.status[1]
 884#define  scsi_status   phys.header.status[2]
 885#define  parity_status phys.header.status[3]
 886#endif
 887
 888/*
 889**      First four bytes (script)
 890*/
 891#define  xerr_st       header.scr_st[0]
 892#define  sync_st       header.scr_st[1]
 893#define  nego_st       header.scr_st[2]
 894#define  wide_st       header.scr_st[3]
 895
 896/*
 897**      First four bytes (host)
 898*/
 899#define  xerr_status   phys.xerr_st
 900#define  nego_status   phys.nego_st
 901
 902#if 0
 903#define  sync_status   phys.sync_st
 904#define  wide_status   phys.wide_st
 905#endif
 906
 907/*==========================================================
 908**
 909**      Declaration of structs:     Data structure block
 910**
 911**==========================================================
 912**
 913**      During execution of a ccb by the script processor,
 914**      the DSA (data structure address) register points
 915**      to this substructure of the ccb.
 916**      This substructure contains the header with
 917**      the script-processor-changable data and
 918**      data blocks for the indirect move commands.
 919**
 920**----------------------------------------------------------
 921*/
 922
 923struct dsb {
 924
 925        /*
 926        **      Header.
 927        */
 928
 929        struct head     header;
 930
 931        /*
 932        **      Table data for Script
 933        */
 934
 935        struct scr_tblsel  select;
 936        struct scr_tblmove smsg  ;
 937        struct scr_tblmove cmd   ;
 938        struct scr_tblmove sense ;
 939        struct scr_tblmove data [MAX_SCATTER];
 940};
 941
 942
 943/*========================================================================
 944**
 945**      Declaration of structs:     Command control block.
 946**
 947**========================================================================
 948*/
 949struct ccb {
 950        /*----------------------------------------------------------------
 951        **      This is the data structure which is pointed by the DSA 
 952        **      register when it is executed by the script processor.
 953        **      It must be the first entry because it contains the header 
 954        **      as first entry that must be cache line aligned.
 955        **----------------------------------------------------------------
 956        */
 957        struct dsb      phys;
 958
 959        /*----------------------------------------------------------------
 960        **      Mini-script used at CCB execution start-up.
 961        **      Load the DSA with the data structure address (phys) and 
 962        **      jump to SELECT. Jump to CANCEL if CCB is to be canceled.
 963        **----------------------------------------------------------------
 964        */
 965        struct launch   start;
 966
 967        /*----------------------------------------------------------------
 968        **      Mini-script used at CCB relection to restart the nexus.
 969        **      Load the DSA with the data structure address (phys) and 
 970        **      jump to RESEL_DSA. Jump to ABORT if CCB is to be aborted.
 971        **----------------------------------------------------------------
 972        */
 973        struct launch   restart;
 974
 975        /*----------------------------------------------------------------
 976        **      If a data transfer phase is terminated too early
 977        **      (after reception of a message (i.e. DISCONNECT)),
 978        **      we have to prepare a mini script to transfer
 979        **      the rest of the data.
 980        **----------------------------------------------------------------
 981        */
 982        ncrcmd          patch[8];
 983
 984        /*----------------------------------------------------------------
 985        **      The general SCSI driver provides a
 986        **      pointer to a control block.
 987        **----------------------------------------------------------------
 988        */
 989        Scsi_Cmnd       *cmd;           /* SCSI command                 */
 990        u_char          cdb_buf[16];    /* Copy of CDB                  */
 991        u_char          sense_buf[64];
 992        int             data_len;       /* Total data length            */
 993
 994        /*----------------------------------------------------------------
 995        **      Message areas.
 996        **      We prepare a message to be sent after selection.
 997        **      We may use a second one if the command is rescheduled 
 998        **      due to GETCC or QFULL.
 999        **      Contents are IDENTIFY and SIMPLE_TAG.
1000        **      While negotiating sync or wide transfer,
1001        **      a SDTR or WDTR message is appended.
1002        **----------------------------------------------------------------
1003        */
1004        u_char          scsi_smsg [8];
1005        u_char          scsi_smsg2[8];
1006
1007        /*----------------------------------------------------------------
1008        **      Other fields.
1009        **----------------------------------------------------------------
1010        */
1011        u_long          p_ccb;          /* BUS address of this CCB      */
1012        u_char          sensecmd[6];    /* Sense command                */
1013        u_char          tag;            /* Tag for this transfer        */
1014                                        /*  255 means no tag            */
1015        u_char          target;
1016        u_char          lun;
1017        u_char          queued;
1018        u_char          auto_sense;
1019        ccb_p           link_ccb;       /* Host adapter CCB chain       */
1020        XPT_QUEHEAD     link_ccbq;      /* Link to unit CCB queue       */
1021        u_int32         startp;         /* Initial data pointer         */
1022        u_long          magic;          /* Free / busy  CCB flag        */
1023};
1024
1025#define CCB_PHYS(cp,lbl)        (cp->p_ccb + offsetof(struct ccb, lbl))
1026
1027
1028/*========================================================================
1029**
1030**      Declaration of structs:     NCR device descriptor
1031**
1032**========================================================================
1033*/
1034struct ncb {
1035        /*----------------------------------------------------------------
1036        **      The global header.
1037        **      It is accessible to both the host and the script processor.
1038        **      Must be cache line size aligned (32 for x86) in order to 
1039        **      allow cache line bursting when it is copied to/from CCB.
1040        **----------------------------------------------------------------
1041        */
1042        struct head     header;
1043
1044        /*----------------------------------------------------------------
1045        **      CCBs management queues.
1046        **----------------------------------------------------------------
1047        */
1048        Scsi_Cmnd       *waiting_list;  /* Commands waiting for a CCB   */
1049                                        /*  when lcb is not allocated.  */
1050        Scsi_Cmnd       *done_list;     /* Commands waiting for done()  */
1051                                        /* callback to be invoked.      */ 
1052#if LINUX_VERSION_CODE >= LinuxVersionCode(2,1,93)
1053        spinlock_t      smp_lock;       /* Lock for SMP threading       */
1054#endif
1055
1056        /*----------------------------------------------------------------
1057        **      Chip and controller indentification.
1058        **----------------------------------------------------------------
1059        */
1060        int             unit;           /* Unit number                  */
1061        char            chip_name[8];   /* Chip name                    */
1062        char            inst_name[16];  /* ncb instance name            */
1063
1064        /*----------------------------------------------------------------
1065        **      Initial value of some IO register bits.
1066        **      These values are assumed to have been set by BIOS, and may 
1067        **      be used for probing adapter implementation differences.
1068        **----------------------------------------------------------------
1069        */
1070        u_char  sv_scntl0, sv_scntl3, sv_dmode, sv_dcntl, sv_ctest0, sv_ctest3,
1071                sv_ctest4, sv_ctest5, sv_gpcntl, sv_stest2, sv_stest4;
1072
1073        /*----------------------------------------------------------------
1074        **      Actual initial value of IO register bits used by the 
1075        **      driver. They are loaded at initialisation according to  
1076        **      features that are to be enabled.
1077        **----------------------------------------------------------------
1078        */
1079        u_char  rv_scntl0, rv_scntl3, rv_dmode, rv_dcntl, rv_ctest0, rv_ctest3,
1080                rv_ctest4, rv_ctest5, rv_stest2;
1081
1082        /*----------------------------------------------------------------
1083        **      Targets management.
1084        **      During reselection the ncr jumps to jump_tcb.
1085        **      The SFBR register is loaded with the encoded target id.
1086        **      For i = 0 to 3
1087        **              SCR_JUMP ^ IFTRUE(MASK(i, 3)), @(next tcb mod. i)
1088        **
1089        **      Recent chips will prefetch the 4 JUMPS using only 1 burst.
1090        **      It is kind of hashcoding.
1091        **----------------------------------------------------------------
1092        */
1093        struct link     jump_tcb[4];    /* JUMPs for reselection        */
1094        struct tcb  target[MAX_TARGET]; /* Target data                  */
1095
1096        /*----------------------------------------------------------------
1097        **      Virtual and physical bus addresses of the chip.
1098        **----------------------------------------------------------------
1099        */
1100        vm_offset_t     vaddr;          /* Virtual and bus address of   */
1101        vm_offset_t     paddr;          /*  chip's IO registers.        */
1102        vm_offset_t     paddr2;         /* On-chip RAM bus address.     */
1103        volatile                        /* Pointer to volatile for      */
1104        struct ncr_reg  *reg;           /*  memory mapped IO.           */
1105
1106        /*----------------------------------------------------------------
1107        **      SCRIPTS virtual and physical bus addresses.
1108        **      'script'  is loaded in the on-chip RAM if present.
1109        **      'scripth' stays in main memory.
1110        **----------------------------------------------------------------
1111        */
1112        struct script   *script0;       /* Copies of script and scripth */
1113        struct scripth  *scripth0;      /*  relocated for this ncb.     */
1114        struct scripth  *scripth;       /* Actual scripth virt. address */
1115        u_long          p_script;       /* Actual script and scripth    */
1116        u_long          p_scripth;      /*  bus addresses.              */
1117
1118        /*----------------------------------------------------------------
1119        **      General controller parameters and configuration.
1120        **----------------------------------------------------------------
1121        */
1122        device_t        dev;
1123        u_short         device_id;      /* PCI device id                */
1124        u_char          revision_id;    /* PCI device revision id       */
1125        u_char          bus;            /* PCI BUS number               */
1126        u_char          device_fn;      /* PCI BUS device and function  */
1127        u_long          base_io;        /* IO space base address        */
1128        u_int           irq;            /* IRQ level                    */
1129        u_int           features;       /* Chip features map            */
1130        u_char          myaddr;         /* SCSI id of the adapter       */
1131        u_char          maxburst;       /* log base 2 of dwords burst   */
1132        u_char          maxwide;        /* Maximum transfer width       */
1133        u_char          minsync;        /* Minimum sync period factor   */
1134        u_char          maxsync;        /* Maximum sync period factor   */
1135        u_char          maxoffs;        /* Max scsi offset              */
1136        u_char          multiplier;     /* Clock multiplier (1,2,4)     */
1137        u_char          clock_divn;     /* Number of clock divisors     */
1138        u_long          clock_khz;      /* SCSI clock frequency in KHz  */
1139
1140        /*----------------------------------------------------------------
1141        **      Start queue management.
1142        **      It is filled up by the host processor and accessed by the 
1143        **      SCRIPTS processor in order to start SCSI commands.
1144        **----------------------------------------------------------------
1145        */
1146        u_short         squeueput;      /* Next free slot of the queue  */
1147        u_short         actccbs;        /* Number of allocated CCBs     */
1148        u_short         queuedccbs;     /* Number of CCBs in start queue*/
1149        u_short         queuedepth;     /* Start queue depth            */
1150
1151        /*----------------------------------------------------------------
1152        **      Timeout handler.
1153        **----------------------------------------------------------------
1154        */
1155        struct timer_list timer;        /* Timer handler link header    */
1156        u_long          lasttime;
1157        u_long          settle_time;    /* Resetting the SCSI BUS       */
1158
1159        /*----------------------------------------------------------------
1160        **      Debugging and profiling.
1161        **----------------------------------------------------------------
1162        */
1163        struct ncr_reg  regdump;        /* Register dump                */
1164        u_long          regtime;        /* Time it has been done        */
1165
1166        /*----------------------------------------------------------------
1167        **      Miscellaneous buffers accessed by the scripts-processor.
1168        **      They shall be DWORD aligned, because they may be read or 
1169        **      written with a SCR_COPY script command.
1170        **----------------------------------------------------------------
1171        */
1172        u_char          msgout[8];      /* Buffer for MESSAGE OUT       */
1173        u_char          msgin [8];      /* Buffer for MESSAGE IN        */
1174        u_int32         lastmsg;        /* Last SCSI message sent       */
1175        u_char          scratch;        /* Scratch for SCSI receive     */
1176
1177        /*----------------------------------------------------------------
1178        **      Miscellaneous configuration and status parameters.
1179        **----------------------------------------------------------------
1180        */
1181        u_char          disc;           /* Diconnection allowed         */
1182        u_char          scsi_mode;      /* Current SCSI BUS mode        */
1183        u_char          order;          /* Tag order to use             */
1184        u_char          verbose;        /* Verbosity for this controller*/
1185        int             ncr_cache;      /* Used for cache test at init. */
1186        u_long          p_ncb;          /* BUS address of this NCB      */
1187
1188        /*----------------------------------------------------------------
1189        **      Command completion handling.
1190        **----------------------------------------------------------------
1191        */
1192#ifdef SCSI_NCR_CCB_DONE_SUPPORT
1193        struct ccb      *(ccb_done[MAX_DONE]);
1194        int             ccb_done_ic;
1195#endif
1196        /*----------------------------------------------------------------
1197        **      Fields that should be removed or changed.
1198        **----------------------------------------------------------------
1199        */
1200        struct ccb      *ccb;           /* Global CCB                   */
1201        struct usrcmd   user;           /* Command from user            */
1202        volatile u_char release_stage;  /* Synchronisation stage on release  */
1203
1204#ifdef SCSI_NCR_INTEGRITY_CHECKING
1205        /*----------------------------------------------------------------
1206        **      Fields that are used for integrity check
1207        **----------------------------------------------------------------
1208        */
1209        unsigned char check_integrity; /* Enable midlayer integ.check on
1210                                        * bus scan. */
1211        unsigned char check_integ_par;  /* Set if par or Init. Det. error
1212                                         * used only during integ check */
1213#endif
1214};
1215
1216#define NCB_SCRIPT_PHYS(np,lbl)  (np->p_script  + offsetof (struct script, lbl))
1217#define NCB_SCRIPTH_PHYS(np,lbl) (np->p_scripth + offsetof (struct scripth,lbl))
1218
1219/*==========================================================
1220**
1221**
1222**      Script for NCR-Processor.
1223**
1224**      Use ncr_script_fill() to create the variable parts.
1225**      Use ncr_script_copy_and_bind() to make a copy and
1226**      bind to physical addresses.
1227**
1228**
1229**==========================================================
1230**
1231**      We have to know the offsets of all labels before
1232**      we reach them (for forward jumps).
1233**      Therefore we declare a struct here.
1234**      If you make changes inside the script,
1235**      DONT FORGET TO CHANGE THE LENGTHS HERE!
1236**
1237**----------------------------------------------------------
1238*/
1239
1240/*
1241**      For HP Zalon/53c720 systems, the Zalon interface
1242**      between CPU and 53c720 does prefetches, which causes
1243**      problems with self modifying scripts.  The problem
1244**      is overcome by calling a dummy subroutine after each
1245**      modification, to force a refetch of the script on
1246**      return from the subroutine.
1247*/
1248
1249#ifdef ENABLE_SCSI_ZALON
1250#define PREFETCH_FLUSH_CNT      2
1251#define PREFETCH_FLUSH          SCR_CALL, PADDRH (wait_dma),
1252#else
1253#define PREFETCH_FLUSH_CNT      0
1254#define PREFETCH_FLUSH
1255#endif
1256
1257/*
1258**      Script fragments which are loaded into the on-chip RAM 
1259**      of 825A, 875 and 895 chips.
1260*/
1261struct script {
1262        ncrcmd  start           [  5];
1263        ncrcmd  startpos        [  1];
1264        ncrcmd  select          [  6];
1265        ncrcmd  select2         [  9 + PREFETCH_FLUSH_CNT];
1266        ncrcmd  loadpos         [  4];
1267        ncrcmd  send_ident      [  9];
1268        ncrcmd  prepare         [  6];
1269        ncrcmd  prepare2        [  7];
1270        ncrcmd  command         [  6];
1271        ncrcmd  dispatch        [ 32];
1272        ncrcmd  clrack          [  4];
1273        ncrcmd  no_data         [ 17];
1274        ncrcmd  status          [  8];
1275        ncrcmd  msg_in          [  2];
1276        ncrcmd  msg_in2         [ 16];
1277        ncrcmd  msg_bad         [  4];
1278        ncrcmd  setmsg          [  7];
1279        ncrcmd  cleanup         [  6];
1280        ncrcmd  complete        [  9];
1281        ncrcmd  cleanup_ok      [  8 + PREFETCH_FLUSH_CNT];
1282        ncrcmd  cleanup0        [  1];
1283#ifndef SCSI_NCR_CCB_DONE_SUPPORT
1284        ncrcmd  signal          [ 12];
1285#else
1286        ncrcmd  signal          [  9];
1287        ncrcmd  done_pos        [  1];
1288        ncrcmd  done_plug       [  2];
1289        ncrcmd  done_end        [  7];
1290#endif
1291        ncrcmd  save_dp         [  7];
1292        ncrcmd  restore_dp      [  5];
1293        ncrcmd  disconnect      [ 17];
1294        ncrcmd  msg_out         [  9];
1295        ncrcmd  msg_out_done    [  7];
1296        ncrcmd  idle            [  2];
1297        ncrcmd  reselect        [  8];
1298        ncrcmd  reselected      [  8];
1299        ncrcmd  resel_dsa       [  6 + PREFETCH_FLUSH_CNT];
1300        ncrcmd  loadpos1        [  4];
1301        ncrcmd  resel_lun       [  6];
1302        ncrcmd  resel_tag       [  6];
1303        ncrcmd  jump_to_nexus   [  4 + PREFETCH_FLUSH_CNT];
1304        ncrcmd  nexus_indirect  [  4];
1305        ncrcmd  resel_notag     [  4];
1306        ncrcmd  data_in         [MAX_SCATTERL * 4];
1307        ncrcmd  data_in2        [  4];
1308        ncrcmd  data_out        [MAX_SCATTERL * 4];
1309        ncrcmd  data_out2       [  4];
1310};
1311
1312/*
1313**      Script fragments which stay in main memory for all chips.
1314*/
1315struct scripth {
1316        ncrcmd  tryloop         [MAX_START*2];
1317        ncrcmd  tryloop2        [  2];
1318#ifdef SCSI_NCR_CCB_DONE_SUPPORT
1319        ncrcmd  done_queue      [MAX_DONE*5];
1320        ncrcmd  done_queue2     [  2];
1321#endif
1322        ncrcmd  select_no_atn   [  8];
1323        ncrcmd  cancel          [  4];
1324        ncrcmd  skip            [  9 + PREFETCH_FLUSH_CNT];
1325        ncrcmd  skip2           [ 19];
1326        ncrcmd  par_err_data_in [  6];
1327        ncrcmd  par_err_other   [  4];
1328        ncrcmd  msg_reject      [  8];
1329        ncrcmd  msg_ign_residue [ 24];
1330        ncrcmd  msg_extended    [ 10];
1331        ncrcmd  msg_ext_2       [ 10];
1332        ncrcmd  msg_wdtr        [ 14];
1333        ncrcmd  send_wdtr       [  7];
1334        ncrcmd  msg_ext_3       [ 10];
1335        ncrcmd  msg_sdtr        [ 14];
1336        ncrcmd  send_sdtr       [  7];
1337        ncrcmd  nego_bad_phase  [  4];
1338        ncrcmd  msg_out_abort   [ 10];
1339        ncrcmd  hdata_in        [MAX_SCATTERH * 4];
1340        ncrcmd  hdata_in2       [  2];
1341        ncrcmd  hdata_out       [MAX_SCATTERH * 4];
1342        ncrcmd  hdata_out2      [  2];
1343        ncrcmd  reset           [  4];
1344        ncrcmd  aborttag        [  4];
1345        ncrcmd  abort           [  2];
1346        ncrcmd  abort_resel     [ 20];
1347        ncrcmd  resend_ident    [  4];
1348        ncrcmd  clratn_go_on    [  3];
1349        ncrcmd  nxtdsp_go_on    [  1];
1350        ncrcmd  sdata_in        [  8];
1351        ncrcmd  data_io         [ 18];
1352        ncrcmd  bad_identify    [ 12];
1353        ncrcmd  bad_i_t_l       [  4];
1354        ncrcmd  bad_i_t_l_q     [  4];
1355        ncrcmd  bad_target      [  8];
1356        ncrcmd  bad_status      [  8];
1357        ncrcmd  start_ram       [  4 + PREFETCH_FLUSH_CNT];
1358        ncrcmd  start_ram0      [  4];
1359        ncrcmd  sto_restart     [  5];
1360        ncrcmd  wait_dma        [  2];
1361        ncrcmd  snooptest       [  9];
1362        ncrcmd  snoopend        [  2];
1363};
1364
1365/*==========================================================
1366**
1367**
1368**      Function headers.
1369**
1370**
1371**==========================================================
1372*/
1373
1374static  void    ncr_alloc_ccb   (ncb_p np, u_char tn, u_char ln);
1375static  void    ncr_complete    (ncb_p np, ccb_p cp);
1376static  void    ncr_exception   (ncb_p np);
1377static  void    ncr_free_ccb    (ncb_p np, ccb_p cp);
1378static  void    ncr_init_ccb    (ncb_p np, ccb_p cp);
1379static  void    ncr_init_tcb    (ncb_p np, u_char tn);
1380static  lcb_p   ncr_alloc_lcb   (ncb_p np, u_char tn, u_char ln);
1381static  lcb_p   ncr_setup_lcb   (ncb_p np, u_char tn, u_char ln,
1382                                 u_char *inq_data);
1383static  void    ncr_getclock    (ncb_p np, int mult);
1384static  void    ncr_selectclock (ncb_p np, u_char scntl3);
1385static  ccb_p   ncr_get_ccb     (ncb_p np, u_char tn, u_char ln);
1386static  void    ncr_chip_reset  (ncb_p np, int delay);
1387static  void    ncr_init        (ncb_p np, int reset, char * msg, u_long code);
1388static  int     ncr_int_sbmc    (ncb_p np);
1389static  int     ncr_int_par     (ncb_p np);
1390static  void    ncr_int_ma      (ncb_p np);
1391static  void    ncr_int_sir     (ncb_p np);
1392static  void    ncr_int_sto     (ncb_p np);
1393static  u_long  ncr_lookup      (char* id);
1394static  void    ncr_negotiate   (struct ncb* np, struct tcb* tp);
1395static  int     ncr_prepare_nego(ncb_p np, ccb_p cp, u_char *msgptr);
1396#ifdef SCSI_NCR_INTEGRITY_CHECKING
1397static  int     ncr_ic_nego(ncb_p np, ccb_p cp, Scsi_Cmnd *cmd, u_char *msgptr);
1398#endif
1399
1400static  void    ncr_script_copy_and_bind
1401                                (ncb_p np, ncrcmd *src, ncrcmd *dst, int len);
1402static  void    ncr_script_fill (struct script * scr, struct scripth * scripth);
1403static  int     ncr_scatter     (ncb_p np, ccb_p cp, Scsi_Cmnd *cmd);
1404static  void    ncr_getsync     (ncb_p np, u_char sfac, u_char *fakp, u_char *scntl3p);
1405static  void    ncr_setsync     (ncb_p np, ccb_p cp, u_char scntl3, u_char sxfer);
1406static  void    ncr_setup_tags  (ncb_p np, u_char tn, u_char ln);
1407static  void    ncr_setwide     (ncb_p np, ccb_p cp, u_char wide, u_char ack);
1408static  int     ncr_show_msg    (u_char * msg);
1409static  void    ncr_print_msg   (ccb_p cp, char *label, u_char *msg);
1410static  int     ncr_snooptest   (ncb_p np);
1411static  void    ncr_timeout     (ncb_p np);
1412static  void    ncr_wakeup      (ncb_p np, u_long code);
1413static  void    ncr_wakeup_done (ncb_p np);
1414static  void    ncr_start_next_ccb (ncb_p np, lcb_p lp, int maxn);
1415static  void    ncr_put_start_queue(ncb_p np, ccb_p cp);
1416static  void    ncr_start_reset (ncb_p np);
1417static  int     ncr_reset_scsi_bus (ncb_p np, int enab_int, int settle_delay);
1418
1419#ifdef SCSI_NCR_USER_COMMAND_SUPPORT
1420static  void    ncr_usercmd     (ncb_p np);
1421#endif
1422
1423static int ncr_attach (Scsi_Host_Template *tpnt, int unit, ncr_device *device);
1424
1425static void insert_into_waiting_list(ncb_p np, Scsi_Cmnd *cmd);
1426static Scsi_Cmnd *retrieve_from_waiting_list(int to_remove, ncb_p np, Scsi_Cmnd *cmd);
1427static void process_waiting_list(ncb_p np, int sts);
1428
1429#define remove_from_waiting_list(np, cmd) \
1430                retrieve_from_waiting_list(1, (np), (cmd))
1431#define requeue_waiting_list(np) process_waiting_list((np), DID_OK)
1432#define reset_waiting_list(np) process_waiting_list((np), DID_RESET)
1433
1434static inline char *ncr_name (ncb_p np)
1435{
1436        return np->inst_name;
1437}
1438
1439
1440/*==========================================================
1441**
1442**
1443**      Scripts for NCR-Processor.
1444**
1445**      Use ncr_script_bind for binding to physical addresses.
1446**
1447**
1448**==========================================================
1449**
1450**      NADDR generates a reference to a field of the controller data.
1451**      PADDR generates a reference to another part of the script.
1452**      RADDR generates a reference to a script processor register.
1453**      FADDR generates a reference to a script processor register
1454**              with offset.
1455**
1456**----------------------------------------------------------
1457*/
1458
1459#define RELOC_SOFTC     0x40000000
1460#define RELOC_LABEL     0x50000000
1461#define RELOC_REGISTER  0x60000000
1462#if 0
1463#define RELOC_KVAR      0x70000000
1464#endif
1465#define RELOC_LABELH    0x80000000
1466#define RELOC_MASK      0xf0000000
1467
1468#define NADDR(label)    (RELOC_SOFTC | offsetof(struct ncb, label))
1469#define PADDR(label)    (RELOC_LABEL | offsetof(struct script, label))
1470#define PADDRH(label)   (RELOC_LABELH | offsetof(struct scripth, label))
1471#define RADDR(label)    (RELOC_REGISTER | REG(label))
1472#define FADDR(label,ofs)(RELOC_REGISTER | ((REG(label))+(ofs)))
1473#if 0
1474#define KVAR(which)     (RELOC_KVAR | (which))
1475#endif
1476
1477#if 0
1478#define SCRIPT_KVAR_JIFFIES     (0)
1479#define SCRIPT_KVAR_FIRST               SCRIPT_KVAR_JIFFIES
1480#define SCRIPT_KVAR_LAST                SCRIPT_KVAR_JIFFIES
1481/*
1482 * Kernel variables referenced in the scripts.
1483 * THESE MUST ALL BE ALIGNED TO A 4-BYTE BOUNDARY.
1484 */
1485static void *script_kvars[] __initdata =
1486        { (void *)&jiffies };
1487#endif
1488
1489static  struct script script0 __initdata = {
1490/*--------------------------< START >-----------------------*/ {
1491        /*
1492        **      This NOP will be patched with LED ON
1493        **      SCR_REG_REG (gpreg, SCR_AND, 0xfe)
1494        */
1495        SCR_NO_OP,
1496                0,
1497        /*
1498        **      Clear SIGP.
1499        */
1500        SCR_FROM_REG (ctest2),
1501                0,
1502        /*
1503        **      Then jump to a certain point in tryloop.
1504        **      Due to the lack of indirect addressing the code
1505        **      is self modifying here.
1506        */
1507        SCR_JUMP,
1508}/*-------------------------< STARTPOS >--------------------*/,{
1509                PADDRH(tryloop),
1510
1511}/*-------------------------< SELECT >----------------------*/,{
1512        /*
1513        **      DSA     contains the address of a scheduled
1514        **              data structure.
1515        **
1516        **      SCRATCHA contains the address of the script,
1517        **              which starts the next entry.
1518        **
1519        **      Set Initiator mode.
1520        **
1521        **      (Target mode is left as an exercise for the reader)
1522        */
1523
1524        SCR_CLR (SCR_TRG),
1525                0,
1526        SCR_LOAD_REG (HS_REG, HS_SELECTING),
1527                0,
1528
1529        /*
1530        **      And try to select this target.
1531        */
1532        SCR_SEL_TBL_ATN ^ offsetof (struct dsb, select),
1533                PADDR (reselect),
1534
1535}/*-------------------------< SELECT2 >----------------------*/,{
1536        /*
1537        **      Now there are 4 possibilities:
1538        **
1539        **      (1) The ncr looses arbitration.
1540        **      This is ok, because it will try again,
1541        **      when the bus becomes idle.
1542        **      (But beware of the timeout function!)
1543        **
1544        **      (2) The ncr is reselected.
1545        **      Then the script processor takes the jump
1546        **      to the RESELECT label.
1547        **
1548        **      (3) The ncr wins arbitration.
1549        **      Then it will execute SCRIPTS instruction until 
1550        **      the next instruction that checks SCSI phase.
1551        **      Then will stop and wait for selection to be 
1552        **      complete or selection time-out to occur.
1553        **      As a result the SCRIPTS instructions until 
1554        **      LOADPOS + 2 should be executed in parallel with 
1555        **      the SCSI core performing selection.
1556        */
1557
1558        /*
1559        **      The M_REJECT problem seems to be due to a selection 
1560        **      timing problem.
1561        **      Wait immediately for the selection to complete. 
1562        **      (2.5x behaves so)
1563        */
1564        SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_OUT)),
1565                0,
1566
1567        /*
1568        **      Next time use the next slot.
1569        */
1570        SCR_COPY (4),
1571                RADDR (temp),
1572                PADDR (startpos),
1573        /*
1574        **      The ncr doesn't have an indirect load
1575        **      or store command. So we have to
1576        **      copy part of the control block to a
1577        **      fixed place, where we can access it.
1578        **
1579        **      We patch the address part of a
1580        **      COPY command with the DSA-register.
1581        */
1582        SCR_COPY_F (4),
1583                RADDR (dsa),
1584                PADDR (loadpos),
1585        /*
1586        **      Flush script prefetch if required
1587        */
1588        PREFETCH_FLUSH
1589        /*
1590        **      then we do the actual copy.
1591        */
1592        SCR_COPY (sizeof (struct head)),
1593        /*
1594        **      continued after the next label ...
1595        */
1596}/*-------------------------< LOADPOS >---------------------*/,{
1597                0,
1598                NADDR (header),
1599        /*
1600        **      Wait for the next phase or the selection
1601        **      to complete or time-out.
1602        */
1603        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
1604                PADDR (prepare),
1605
1606}/*-------------------------< SEND_IDENT >----------------------*/,{
1607        /*
1608        **      Selection complete.
1609        **      Send the IDENTIFY and SIMPLE_TAG messages
1610        **      (and the M_X_SYNC_REQ message)
1611        */
1612        SCR_MOVE_TBL ^ SCR_MSG_OUT,
1613                offsetof (struct dsb, smsg),
1614        SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
1615                PADDRH (resend_ident),
1616        SCR_LOAD_REG (scratcha, 0x80),
1617                0,
1618        SCR_COPY (1),
1619                RADDR (scratcha),
1620                NADDR (lastmsg),
1621}/*-------------------------< PREPARE >----------------------*/,{
1622        /*
1623        **      load the savep (saved pointer) into
1624        **      the TEMP register (actual pointer)
1625        */
1626        SCR_COPY (4),
1627                NADDR (header.savep),
1628                RADDR (temp),
1629        /*
1630        **      Initialize the status registers
1631        */
1632        SCR_COPY (4),
1633                NADDR (header.status),
1634                RADDR (scr0),
1635}/*-------------------------< PREPARE2 >---------------------*/,{
1636        /*
1637        **      Initialize the msgout buffer with a NOOP message.
1638        */
1639        SCR_LOAD_REG (scratcha, M_NOOP),
1640                0,
1641        SCR_COPY (1),
1642                RADDR (scratcha),
1643                NADDR (msgout),
1644#if 0
1645        SCR_COPY (1),
1646                RADDR (scratcha),
1647                NADDR (msgin),
1648#endif
1649        /*
1650        **      Anticipate the COMMAND phase.
1651        **      This is the normal case for initial selection.
1652        */
1653        SCR_JUMP ^ IFFALSE (WHEN (SCR_COMMAND)),
1654                PADDR (dispatch),
1655
1656}/*-------------------------< COMMAND >--------------------*/,{
1657        /*
1658        **      ... and send the command
1659        */
1660        SCR_MOVE_TBL ^ SCR_COMMAND,
1661                offsetof (struct dsb, cmd),
1662        /*
1663        **      If status is still HS_NEGOTIATE, negotiation failed.
1664        **      We check this here, since we want to do that 
1665        **      only once.
1666        */
1667        SCR_FROM_REG (HS_REG),
1668                0,
1669        SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
1670                SIR_NEGO_FAILED,
1671
1672}/*-----------------------< DISPATCH >----------------------*/,{
1673        /*
1674        **      MSG_IN is the only phase that shall be 
1675        **      entered at least once for each (re)selection.
1676        **      So we test it first.
1677        */
1678        SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_IN)),
1679                PADDR (msg_in),
1680
1681        SCR_RETURN ^ IFTRUE (IF (SCR_DATA_OUT)),
1682                0,
1683        /*
1684        **      DEL 397 - 53C875 Rev 3 - Part Number 609-0392410 - ITEM 4.
1685        **      Possible data corruption during Memory Write and Invalidate.
1686        **      This work-around resets the addressing logic prior to the 
1687        **      start of the first MOVE of a DATA IN phase.
1688        **      (See Documentation/scsi/ncr53c8xx.txt for more information)
1689        */
1690        SCR_JUMPR ^ IFFALSE (IF (SCR_DATA_IN)),
1691                20,
1692        SCR_COPY (4),
1693                RADDR (scratcha),
1694                RADDR (scratcha),
1695        SCR_RETURN,
1696                0,
1697        SCR_JUMP ^ IFTRUE (IF (SCR_STATUS)),
1698                PADDR (status),
1699        SCR_JUMP ^ IFTRUE (IF (SCR_COMMAND)),
1700                PADDR (command),
1701        SCR_JUMP ^ IFTRUE (IF (SCR_MSG_OUT)),
1702                PADDR (msg_out),
1703        /*
1704        **      Discard one illegal phase byte, if required.
1705        */
1706        SCR_LOAD_REG (scratcha, XE_BAD_PHASE),
1707                0,
1708        SCR_COPY (1),
1709                RADDR (scratcha),
1710                NADDR (xerr_st),
1711        SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_OUT)),
1712                8,
1713        SCR_MOVE_ABS (1) ^ SCR_ILG_OUT,
1714                NADDR (scratch),
1715        SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_IN)),
1716                8,
1717        SCR_MOVE_ABS (1) ^ SCR_ILG_IN,
1718                NADDR (scratch),
1719        SCR_JUMP,
1720                PADDR (dispatch),
1721
1722}/*-------------------------< CLRACK >----------------------*/,{
1723        /*
1724        **      Terminate possible pending message phase.
1725        */
1726        SCR_CLR (SCR_ACK),
1727                0,
1728        SCR_JUMP,
1729                PADDR (dispatch),
1730
1731}/*-------------------------< NO_DATA >--------------------*/,{
1732        /*
1733        **      The target wants to tranfer too much data
1734        **      or in the wrong direction.
1735        **      Remember that in extended error.
1736        */
1737        SCR_LOAD_REG (scratcha, XE_EXTRA_DATA),
1738                0,
1739        SCR_COPY (1),
1740                RADDR (scratcha),
1741                NADDR (xerr_st),
1742        /*
1743        **      Discard one data byte, if required.
1744        */
1745        SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_OUT)),
1746                8,
1747        SCR_MOVE_ABS (1) ^ SCR_DATA_OUT,
1748                NADDR (scratch),
1749        SCR_JUMPR ^ IFFALSE (IF (SCR_DATA_IN)),
1750                8,
1751        SCR_MOVE_ABS (1) ^ SCR_DATA_IN,
1752                NADDR (scratch),
1753        /*
1754        **      .. and repeat as required.
1755        */
1756        SCR_CALL,
1757                PADDR (dispatch),
1758        SCR_JUMP,
1759                PADDR (no_data),
1760
1761}/*-------------------------< STATUS >--------------------*/,{
1762        /*
1763        **      get the status
1764        */
1765        SCR_MOVE_ABS (1) ^ SCR_STATUS,
1766                NADDR (scratch),
1767        /*
1768        **      save status to scsi_status.
1769        **      mark as complete.
1770        */
1771        SCR_TO_REG (SS_REG),
1772                0,
1773        SCR_LOAD_REG (HS_REG, HS_COMPLETE),
1774                0,
1775        SCR_JUMP,
1776                PADDR (dispatch),
1777}/*-------------------------< MSG_IN >--------------------*/,{
1778        /*
1779        **      Get the first byte of the message
1780        **      and save it to SCRATCHA.
1781        **
1782        **      The script processor doesn't negate the
1783        **      ACK signal after this transfer.
1784        */
1785        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
1786                NADDR (msgin[0]),
1787}/*-------------------------< MSG_IN2 >--------------------*/,{
1788        /*
1789        **      Handle this message.
1790        */
1791        SCR_JUMP ^ IFTRUE (DATA (M_COMPLETE)),
1792                PADDR (complete),
1793        SCR_JUMP ^ IFTRUE (DATA (M_DISCONNECT)),
1794                PADDR (disconnect),
1795        SCR_JUMP ^ IFTRUE (DATA (M_SAVE_DP)),
1796                PADDR (save_dp),
1797        SCR_JUMP ^ IFTRUE (DATA (M_RESTORE_DP)),
1798                PADDR (restore_dp),
1799        SCR_JUMP ^ IFTRUE (DATA (M_EXTENDED)),
1800                PADDRH (msg_extended),
1801        SCR_JUMP ^ IFTRUE (DATA (M_NOOP)),
1802                PADDR (clrack),
1803        SCR_JUMP ^ IFTRUE (DATA (M_REJECT)),
1804                PADDRH (msg_reject),
1805        SCR_JUMP ^ IFTRUE (DATA (M_IGN_RESIDUE)),
1806                PADDRH (msg_ign_residue),
1807        /*
1808        **      Rest of the messages left as
1809        **      an exercise ...
1810        **
1811        **      Unimplemented messages:
1812        **      fall through to MSG_BAD.
1813        */
1814}/*-------------------------< MSG_BAD >------------------*/,{
1815        /*
1816        **      unimplemented message - reject it.
1817        */
1818        SCR_INT,
1819                SIR_REJECT_SENT,
1820        SCR_LOAD_REG (scratcha, M_REJECT),
1821                0,
1822}/*-------------------------< SETMSG >----------------------*/,{
1823        SCR_COPY (1),
1824                RADDR (scratcha),
1825                NADDR (msgout),
1826        SCR_SET (SCR_ATN),
1827                0,
1828        SCR_JUMP,
1829                PADDR (clrack),
1830}/*-------------------------< CLEANUP >-------------------*/,{
1831        /*
1832        **      dsa:    Pointer to ccb
1833        **            or xxxxxxFF (no ccb)
1834        **
1835        **      HS_REG:   Host-Status (<>0!)
1836        */
1837        SCR_FROM_REG (dsa),
1838                0,
1839        SCR_JUMP ^ IFTRUE (DATA (0xff)),
1840                PADDR (start),
1841        /*
1842        **      dsa is valid.
1843        **      complete the cleanup.
1844        */
1845        SCR_JUMP,
1846                PADDR (cleanup_ok),
1847
1848}/*-------------------------< COMPLETE >-----------------*/,{
1849        /*
1850        **      Complete message.
1851        **
1852        **      Copy TEMP register to LASTP in header.
1853        */
1854        SCR_COPY (4),
1855                RADDR (temp),
1856                NADDR (header.lastp),
1857        /*
1858        **      When we terminate the cycle by clearing ACK,
1859        **      the target may disconnect immediately.
1860        **
1861        **      We don't want to be told of an
1862        **      "unexpected disconnect",
1863        **      so we disable this feature.
1864        */
1865        SCR_REG_REG (scntl2, SCR_AND, 0x7f),
1866                0,
1867        /*
1868        **      Terminate cycle ...
1869        */
1870        SCR_CLR (SCR_ACK|SCR_ATN),
1871                0,
1872        /*
1873        **      ... and wait for the disconnect.
1874        */
1875        SCR_WAIT_DISC,
1876                0,
1877}/*-------------------------< CLEANUP_OK >----------------*/,{
1878        /*
1879        **      Save host status to header.
1880        */
1881        SCR_COPY (4),
1882                RADDR (scr0),
1883                NADDR (header.status),
1884        /*
1885        **      and copy back the header to the ccb.
1886        */
1887        SCR_COPY_F (4),
1888                RADDR (dsa),
1889                PADDR (cleanup0),
1890        /*
1891        **      Flush script prefetch if required
1892        */
1893        PREFETCH_FLUSH
1894        SCR_COPY (sizeof (struct head)),
1895                NADDR (header),
1896}/*-------------------------< CLEANUP0 >--------------------*/,{
1897                0,
1898}/*-------------------------< SIGNAL >----------------------*/,{
1899        /*
1900        **      if job not completed ...
1901        */
1902        SCR_FROM_REG (HS_REG),
1903                0,
1904        /*
1905        **      ... start the next command.
1906        */
1907        SCR_JUMP ^ IFTRUE (MASK (0, (HS_DONEMASK|HS_SKIPMASK))),
1908                PADDR(start),
1909        /*
1910        **      If command resulted in not GOOD status,
1911        **      call the C code if needed.
1912        */
1913        SCR_FROM_REG (SS_REG),
1914                0,
1915        SCR_CALL ^ IFFALSE (DATA (S_GOOD)),
1916                PADDRH (bad_status),
1917
1918#ifndef SCSI_NCR_CCB_DONE_SUPPORT
1919
1920        /*
1921        **      ... signal completion to the host
1922        */
1923#ifdef SIMULATED_INTFLY
1924        SCR_INT,
1925                SIR_INTFLY,
1926#else
1927        SCR_INT_FLY,
1928                0,
1929#endif
1930        /*
1931        **      Auf zu neuen Schandtaten!
1932        */
1933        SCR_JUMP,
1934                PADDR(start),
1935
1936#else   /* defined SCSI_NCR_CCB_DONE_SUPPORT */
1937
1938        /*
1939        **      ... signal completion to the host
1940        */
1941        SCR_JUMP,
1942}/*------------------------< DONE_POS >---------------------*/,{
1943                PADDRH (done_queue),
1944}/*------------------------< DONE_PLUG >--------------------*/,{
1945        SCR_INT,
1946                SIR_DONE_OVERFLOW,
1947}/*------------------------< DONE_END >---------------------*/,{
1948#ifdef SIMULATED_INTFLY
1949        SCR_INT,
1950                SIR_INTFLY,
1951#else
1952        SCR_INT_FLY,
1953                0,
1954#endif
1955        SCR_COPY (4),
1956                RADDR (temp),
1957                PADDR (done_pos),
1958        SCR_JUMP,
1959                PADDR (start),
1960
1961#endif  /* SCSI_NCR_CCB_DONE_SUPPORT */
1962
1963}/*-------------------------< SAVE_DP >------------------*/,{
1964        /*
1965        **      SAVE_DP message:
1966        **      Copy TEMP register to SAVEP in header.
1967        */
1968        SCR_COPY (4),
1969                RADDR (temp),
1970                NADDR (header.savep),
1971        SCR_CLR (SCR_ACK),
1972                0,
1973        SCR_JUMP,
1974                PADDR (dispatch),
1975}/*-------------------------< RESTORE_DP >---------------*/,{
1976        /*
1977        **      RESTORE_DP message:
1978        **      Copy SAVEP in header to TEMP register.
1979        */
1980        SCR_COPY (4),
1981                NADDR (header.savep),
1982                RADDR (temp),
1983        SCR_JUMP,
1984                PADDR (clrack),
1985
1986}/*-------------------------< DISCONNECT >---------------*/,{
1987        /*
1988        **      DISCONNECTing  ...
1989        **
1990        **      disable the "unexpected disconnect" feature,
1991        **      and remove the ACK signal.
1992        */
1993        SCR_REG_REG (scntl2, SCR_AND, 0x7f),
1994                0,
1995        SCR_CLR (SCR_ACK|SCR_ATN),
1996                0,
1997        /*
1998        **      Wait for the disconnect.
1999        */
2000        SCR_WAIT_DISC,
2001                0,
2002        /*
2003        **      Status is: DISCONNECTED.
2004        */
2005        SCR_LOAD_REG (HS_REG, HS_DISCONNECT),
2006                0,
2007        /*
2008        **      If QUIRK_AUTOSAVE is set,
2009        **      do an "save pointer" operation.
2010        */
2011        SCR_FROM_REG (QU_REG),
2012                0,
2013        SCR_JUMP ^ IFFALSE (MASK (QUIRK_AUTOSAVE, QUIRK_AUTOSAVE)),
2014                PADDR (cleanup_ok),
2015        /*
2016        **      like SAVE_DP message:
2017        **      Copy TEMP register to SAVEP in header.
2018        */
2019        SCR_COPY (4),
2020                RADDR (temp),
2021                NADDR (header.savep),
2022        SCR_JUMP,
2023                PADDR (cleanup_ok),
2024
2025}/*-------------------------< MSG_OUT >-------------------*/,{
2026        /*
2027        **      The target requests a message.
2028        */
2029        SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
2030                NADDR (msgout),
2031        SCR_COPY (1),
2032                NADDR (msgout),
2033                NADDR (lastmsg),
2034        /*
2035        **      If it was no ABORT message ...
2036        */
2037        SCR_JUMP ^ IFTRUE (DATA (M_ABORT)),
2038                PADDRH (msg_out_abort),
2039        /*
2040        **      ... wait for the next phase
2041        **      if it's a message out, send it again, ...
2042        */
2043        SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
2044                PADDR (msg_out),
2045}/*-------------------------< MSG_OUT_DONE >--------------*/,{
2046        /*
2047        **      ... else clear the message ...
2048        */
2049        SCR_LOAD_REG (scratcha, M_NOOP),
2050                0,
2051        SCR_COPY (4),
2052                RADDR (scratcha),
2053                NADDR (msgout),
2054        /*
2055        **      ... and process the next phase
2056        */
2057        SCR_JUMP,
2058                PADDR (dispatch),
2059}/*-------------------------< IDLE >------------------------*/,{
2060        /*
2061        **      Nothing to do?
2062        **      Wait for reselect.
2063        **      This NOP will be patched with LED OFF
2064        **      SCR_REG_REG (gpreg, SCR_OR, 0x01)
2065        */
2066        SCR_NO_OP,
2067                0,
2068}/*-------------------------< RESELECT >--------------------*/,{
2069        /*
2070        **      make the DSA invalid.
2071        */
2072        SCR_LOAD_REG (dsa, 0xff),
2073                0,
2074        SCR_CLR (SCR_TRG),
2075                0,
2076        SCR_LOAD_REG (HS_REG, HS_IN_RESELECT),
2077                0,
2078        /*
2079        **      Sleep waiting for a reselection.
2080        **      If SIGP is set, special treatment.
2081        **
2082        **      Zu allem bereit ..
2083        */
2084        SCR_WAIT_RESEL,
2085                PADDR(start),
2086}/*-------------------------< RESELECTED >------------------*/,{
2087        /*
2088        **      This NOP will be patched with LED ON
2089        **      SCR_REG_REG (gpreg, SCR_AND, 0xfe)
2090        */
2091        SCR_NO_OP,
2092                0,
2093        /*
2094        **      ... zu nichts zu gebrauchen ?
2095        **
2096        **      load the target id into the SFBR
2097        **      and jump to the control block.
2098        **
2099        **      Look at the declarations of
2100        **      - struct ncb
2101        **      - struct tcb
2102        **      - struct lcb
2103        **      - struct ccb
2104        **      to understand what's going on.
2105        */
2106        SCR_REG_SFBR (ssid, SCR_AND, 0x8F),
2107                0,
2108        SCR_TO_REG (sdid),
2109                0,
2110        SCR_JUMP,
2111                NADDR (jump_tcb),
2112
2113}/*-------------------------< RESEL_DSA >-------------------*/,{
2114        /*
2115        **      Ack the IDENTIFY or TAG previously received.
2116        */
2117        SCR_CLR (SCR_ACK),
2118                0,
2119        /*
2120        **      The ncr doesn't have an indirect load
2121        **      or store command. So we have to
2122        **      copy part of the control block to a
2123        **      fixed place, where we can access it.
2124        **
2125        **      We patch the address part of a
2126        **      COPY command with the DSA-register.
2127        */
2128        SCR_COPY_F (4),
2129                RADDR (dsa),
2130                PADDR (loadpos1),
2131        /*
2132        **      Flush script prefetch if required
2133        */
2134        PREFETCH_FLUSH
2135        /*
2136        **      then we do the actual copy.
2137        */
2138        SCR_COPY (sizeof (struct head)),
2139        /*
2140        **      continued after the next label ...
2141        */
2142
2143}/*-------------------------< LOADPOS1 >-------------------*/,{
2144                0,
2145                NADDR (header),
2146        /*
2147        **      The DSA contains the data structure address.
2148        */
2149        SCR_JUMP,
2150                PADDR (prepare),
2151
2152}/*-------------------------< RESEL_LUN >-------------------*/,{
2153        /*
2154        **      come back to this point
2155        **      to get an IDENTIFY message
2156        **      Wait for a msg_in phase.
2157        */
2158        SCR_INT ^ IFFALSE (WHEN (SCR_MSG_IN)),
2159                SIR_RESEL_NO_MSG_IN,
2160        /*
2161        **      message phase.
2162        **      Read the data directly from the BUS DATA lines.
2163        **      This helps to support very old SCSI devices that 
2164        **      may reselect without sending an IDENTIFY.
2165        */
2166        SCR_FROM_REG (sbdl),
2167                0,
2168        /*
2169        **      It should be an Identify message.
2170        */
2171        SCR_RETURN,
2172                0,
2173}/*-------------------------< RESEL_TAG >-------------------*/,{
2174        /*
2175        **      Read IDENTIFY + SIMPLE + TAG using a single MOVE.
2176        **      Agressive optimization, is'nt it?
2177        **      No need to test the SIMPLE TAG message, since the 
2178        **      driver only supports conformant devices for tags. ;-)
2179        */
2180        SCR_MOVE_ABS (3) ^ SCR_MSG_IN,
2181                NADDR (msgin),
2182        /*
2183        **      Read the TAG from the SIDL.
2184        **      Still an aggressive optimization. ;-)
2185        **      Compute the CCB indirect jump address which 
2186        **      is (#TAG*2 & 0xfc) due to tag numbering using 
2187        **      1,3,5..MAXTAGS*2+1 actual values.
2188        */
2189        SCR_REG_SFBR (sidl, SCR_SHL, 0),
2190                0,
2191        SCR_SFBR_REG (temp, SCR_AND, 0xfc),
2192                0,
2193}/*-------------------------< JUMP_TO_NEXUS >-------------------*/,{
2194        SCR_COPY_F (4),
2195                RADDR (temp),
2196                PADDR (nexus_indirect),
2197        /*
2198        **      Flush script prefetch if required
2199        */
2200        PREFETCH_FLUSH
2201        SCR_COPY (4),
2202}/*-------------------------< NEXUS_INDIRECT >-------------------*/,{
2203                0,
2204                RADDR (temp),
2205        SCR_RETURN,
2206                0,
2207}/*-------------------------< RESEL_NOTAG >-------------------*/,{
2208        /*
2209        **      No tag expected.
2210        **      Read an throw away the IDENTIFY.
2211        */
2212        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2213                NADDR (msgin),
2214        SCR_JUMP,
2215                PADDR (jump_to_nexus),
2216}/*-------------------------< DATA_IN >--------------------*/,{
2217/*
2218**      Because the size depends on the
2219**      #define MAX_SCATTERL parameter,
2220**      it is filled in at runtime.
2221**
2222**  ##===========< i=0; i<MAX_SCATTERL >=========
2223**  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
2224**  ||          PADDR (dispatch),
2225**  ||  SCR_MOVE_TBL ^ SCR_DATA_IN,
2226**  ||          offsetof (struct dsb, data[ i]),
2227**  ##==========================================
2228**
2229**---------------------------------------------------------
2230*/
22310
2232}/*-------------------------< DATA_IN2 >-------------------*/,{
2233        SCR_CALL,
2234                PADDR (dispatch),
2235        SCR_JUMP,
2236                PADDR (no_data),
2237}/*-------------------------< DATA_OUT >--------------------*/,{
2238/*
2239**      Because the size depends on the
2240**      #define MAX_SCATTERL parameter,
2241**      it is filled in at runtime.
2242**
2243**  ##===========< i=0; i<MAX_SCATTERL >=========
2244**  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2245**  ||          PADDR (dispatch),
2246**  ||  SCR_MOVE_TBL ^ SCR_DATA_OUT,
2247**  ||          offsetof (struct dsb, data[ i]),
2248**  ##==========================================
2249**
2250**---------------------------------------------------------
2251*/
22520
2253}/*-------------------------< DATA_OUT2 >-------------------*/,{
2254        SCR_CALL,
2255                PADDR (dispatch),
2256        SCR_JUMP,
2257                PADDR (no_data),
2258}/*--------------------------------------------------------*/
2259};
2260
2261static  struct scripth scripth0 __initdata = {
2262/*-------------------------< TRYLOOP >---------------------*/{
2263/*
2264**      Start the next entry.
2265**      Called addresses point to the launch script in the CCB.
2266**      They are patched by the main processor.
2267**
2268**      Because the size depends on the
2269**      #define MAX_START parameter, it is filled
2270**      in at runtime.
2271**
2272**-----------------------------------------------------------
2273**
2274**  ##===========< I=0; i<MAX_START >===========
2275**  ||  SCR_CALL,
2276**  ||          PADDR (idle),
2277**  ##==========================================
2278**
2279**-----------------------------------------------------------
2280*/
22810
2282}/*------------------------< TRYLOOP2 >---------------------*/,{
2283        SCR_JUMP,
2284                PADDRH(tryloop),
2285
2286#ifdef SCSI_NCR_CCB_DONE_SUPPORT
2287
2288}/*------------------------< DONE_QUEUE >-------------------*/,{
2289/*
2290**      Copy the CCB address to the next done entry.
2291**      Because the size depends on the
2292**      #define MAX_DONE parameter, it is filled
2293**      in at runtime.
2294**
2295**-----------------------------------------------------------
2296**
2297**  ##===========< I=0; i<MAX_DONE >===========
2298**  ||  SCR_COPY (sizeof(ccb_p)),
2299**  ||          NADDR (header.cp),
2300**  ||          NADDR (ccb_done[i]),
2301**  ||  SCR_CALL,
2302**  ||          PADDR (done_end),
2303**  ##==========================================
2304**
2305**-----------------------------------------------------------
2306*/
23070
2308}/*------------------------< DONE_QUEUE2 >------------------*/,{
2309        SCR_JUMP,
2310                PADDRH (done_queue),
2311
2312#endif /* SCSI_NCR_CCB_DONE_SUPPORT */
2313}/*------------------------< SELECT_NO_ATN >-----------------*/,{
2314        /*
2315        **      Set Initiator mode.
2316        **      And try to select this target without ATN.
2317        */
2318
2319        SCR_CLR (SCR_TRG),
2320                0,
2321        SCR_LOAD_REG (HS_REG, HS_SELECTING),
2322                0,
2323        SCR_SEL_TBL ^ offsetof (struct dsb, select),
2324                PADDR (reselect),
2325        SCR_JUMP,
2326                PADDR (select2),
2327
2328}/*-------------------------< CANCEL >------------------------*/,{
2329
2330        SCR_LOAD_REG (scratcha, HS_ABORTED),
2331                0,
2332        SCR_JUMPR,
2333                8,
2334}/*-------------------------< SKIP >------------------------*/,{
2335        SCR_LOAD_REG (scratcha, 0),
2336                0,
2337        /*
2338        **      This entry has been canceled.
2339        **      Next time use the next slot.
2340        */
2341        SCR_COPY (4),
2342                RADDR (temp),
2343                PADDR (startpos),
2344        /*
2345        **      The ncr doesn't have an indirect load
2346        **      or store command. So we have to
2347        **      copy part of the control block to a
2348        **      fixed place, where we can access it.
2349        **
2350        **      We patch the address part of a
2351        **      COPY command with the DSA-register.
2352        */
2353        SCR_COPY_F (4),
2354                RADDR (dsa),
2355                PADDRH (skip2),
2356        /*
2357        **      Flush script prefetch if required
2358        */
2359        PREFETCH_FLUSH
2360        /*
2361        **      then we do the actual copy.
2362        */
2363        SCR_COPY (sizeof (struct head)),
2364        /*
2365        **      continued after the next label ...
2366        */
2367}/*-------------------------< SKIP2 >---------------------*/,{
2368                0,
2369                NADDR (header),
2370        /*
2371        **      Initialize the status registers
2372        */
2373        SCR_COPY (4),
2374                NADDR (header.status),
2375                RADDR (scr0),
2376        /*
2377        **      Force host status.
2378        */
2379        SCR_FROM_REG (scratcha),
2380                0,
2381        SCR_JUMPR ^ IFFALSE (MASK (0, HS_DONEMASK)),
2382                16,
2383        SCR_REG_REG (HS_REG, SCR_OR, HS_SKIPMASK),
2384                0,
2385        SCR_JUMPR,
2386                8,
2387        SCR_TO_REG (HS_REG),
2388                0,
2389        SCR_LOAD_REG (SS_REG, S_GOOD),
2390                0,
2391        SCR_JUMP,
2392                PADDR (cleanup_ok),
2393
2394},/*-------------------------< PAR_ERR_DATA_IN >---------------*/{
2395        /*
2396        **      Ignore all data in byte, until next phase
2397        */
2398        SCR_JUMP ^ IFFALSE (WHEN (SCR_DATA_IN)),
2399                PADDRH (par_err_other),
2400        SCR_MOVE_ABS (1) ^ SCR_DATA_IN,
2401                NADDR (scratch),
2402        SCR_JUMPR,
2403                -24,
2404},/*-------------------------< PAR_ERR_OTHER >------------------*/{
2405        /*
2406        **      count it.
2407        */
2408        SCR_REG_REG (PS_REG, SCR_ADD, 0x01),
2409                0,
2410        /*
2411        **      jump to dispatcher.
2412        */
2413        SCR_JUMP,
2414                PADDR (dispatch),
2415}/*-------------------------< MSG_REJECT >---------------*/,{
2416        /*
2417        **      If a negotiation was in progress,
2418        **      negotiation failed.
2419        **      Otherwise, let the C code print 
2420        **      some message.
2421        */
2422        SCR_FROM_REG (HS_REG),
2423                0,
2424        SCR_INT ^ IFFALSE (DATA (HS_NEGOTIATE)),
2425                SIR_REJECT_RECEIVED,
2426        SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
2427                SIR_NEGO_FAILED,
2428        SCR_JUMP,
2429                PADDR (clrack),
2430
2431}/*-------------------------< MSG_IGN_RESIDUE >----------*/,{
2432        /*
2433        **      Terminate cycle
2434        */
2435        SCR_CLR (SCR_ACK),
2436                0,
2437        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2438                PADDR (dispatch),
2439        /*
2440        **      get residue size.
2441        */
2442        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2443                NADDR (msgin[1]),
2444        /*
2445        **      Size is 0 .. ignore message.
2446        */
2447        SCR_JUMP ^ IFTRUE (DATA (0)),
2448                PADDR (clrack),
2449        /*
2450        **      Size is not 1 .. have to interrupt.
2451        */
2452        SCR_JUMPR ^ IFFALSE (DATA (1)),
2453                40,
2454        /*
2455        **      Check for residue byte in swide register
2456        */
2457        SCR_FROM_REG (scntl2),
2458                0,
2459        SCR_JUMPR ^ IFFALSE (MASK (WSR, WSR)),
2460                16,
2461        /*
2462        **      There IS data in the swide register.
2463        **      Discard it.
2464        */
2465        SCR_REG_REG (scntl2, SCR_OR, WSR),
2466                0,
2467        SCR_JUMP,
2468                PADDR (clrack),
2469        /*
2470        **      Load again the size to the sfbr register.
2471        */
2472        SCR_FROM_REG (scratcha),
2473                0,
2474        SCR_INT,
2475                SIR_IGN_RESIDUE,
2476        SCR_JUMP,
2477                PADDR (clrack),
2478
2479}/*-------------------------< MSG_EXTENDED >-------------*/,{
2480        /*
2481        **      Terminate cycle
2482        */
2483        SCR_CLR (SCR_ACK),
2484                0,
2485        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2486                PADDR (dispatch),
2487        /*
2488        **      get length.
2489        */
2490        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2491                NADDR (msgin[1]),
2492        /*
2493        */
2494        SCR_JUMP ^ IFTRUE (DATA (3)),
2495                PADDRH (msg_ext_3),
2496        SCR_JUMP ^ IFFALSE (DATA (2)),
2497                PADDR (msg_bad),
2498}/*-------------------------< MSG_EXT_2 >----------------*/,{
2499        SCR_CLR (SCR_ACK),
2500                0,
2501        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2502                PADDR (dispatch),
2503        /*
2504        **      get extended message code.
2505        */
2506        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2507                NADDR (msgin[2]),
2508        SCR_JUMP ^ IFTRUE (DATA (M_X_WIDE_REQ)),
2509                PADDRH (msg_wdtr),
2510        /*
2511        **      unknown extended message
2512        */
2513        SCR_JUMP,
2514                PADDR (msg_bad)
2515}/*-------------------------< MSG_WDTR >-----------------*/,{
2516        SCR_CLR (SCR_ACK),
2517                0,
2518        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2519                PADDR (dispatch),
2520        /*
2521        **      get data bus width
2522        */
2523        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2524                NADDR (msgin[3]),
2525        /*
2526        **      let the host do the real work.
2527        */
2528        SCR_INT,
2529                SIR_NEGO_WIDE,
2530        /*
2531        **      let the target fetch our answer.
2532        */
2533        SCR_SET (SCR_ATN),
2534                0,
2535        SCR_CLR (SCR_ACK),
2536                0,
2537        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2538                PADDRH (nego_bad_phase),
2539
2540}/*-------------------------< SEND_WDTR >----------------*/,{
2541        /*
2542        **      Send the M_X_WIDE_REQ
2543        */
2544        SCR_MOVE_ABS (4) ^ SCR_MSG_OUT,
2545                NADDR (msgout),
2546        SCR_COPY (1),
2547                NADDR (msgout),
2548                NADDR (lastmsg),
2549        SCR_JUMP,
2550                PADDR (msg_out_done),
2551
2552}/*-------------------------< MSG_EXT_3 >----------------*/,{
2553        SCR_CLR (SCR_ACK),
2554                0,
2555        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2556                PADDR (dispatch),
2557        /*
2558        **      get extended message code.
2559        */
2560        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2561                NADDR (msgin[2]),
2562        SCR_JUMP ^ IFTRUE (DATA (M_X_SYNC_REQ)),
2563                PADDRH (msg_sdtr),
2564        /*
2565        **      unknown extended message
2566        */
2567        SCR_JUMP,
2568                PADDR (msg_bad)
2569
2570}/*-------------------------< MSG_SDTR >-----------------*/,{
2571        SCR_CLR (SCR_ACK),
2572                0,
2573        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2574                PADDR (dispatch),
2575        /*
2576        **      get period and offset
2577        */
2578        SCR_MOVE_ABS (2) ^ SCR_MSG_IN,
2579                NADDR (msgin[3]),
2580        /*
2581        **      let the host do the real work.
2582        */
2583        SCR_INT,
2584                SIR_NEGO_SYNC,
2585        /*
2586        **      let the target fetch our answer.
2587        */
2588        SCR_SET (SCR_ATN),
2589                0,
2590        SCR_CLR (SCR_ACK),
2591                0,
2592        SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2593                PADDRH (nego_bad_phase),
2594
2595}/*-------------------------< SEND_SDTR >-------------*/,{
2596        /*
2597        **      Send the M_X_SYNC_REQ
2598        */
2599        SCR_MOVE_ABS (5) ^ SCR_MSG_OUT,
2600                NADDR (msgout),
2601        SCR_COPY (1),
2602                NADDR (msgout),
2603                NADDR (lastmsg),
2604        SCR_JUMP,
2605                PADDR (msg_out_done),
2606
2607}/*-------------------------< NEGO_BAD_PHASE >------------*/,{
2608        SCR_INT,
2609                SIR_NEGO_PROTO,
2610        SCR_JUMP,
2611                PADDR (dispatch),
2612
2613}/*-------------------------< MSG_OUT_ABORT >-------------*/,{
2614        /*
2615        **      After ABORT message,
2616        **
2617        **      expect an immediate disconnect, ...
2618        */
2619        SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2620                0,
2621        SCR_CLR (SCR_ACK|SCR_ATN),
2622                0,
2623        SCR_WAIT_DISC,
2624                0,
2625        /*
2626        **      ... and set the status to "ABORTED"
2627        */
2628        SCR_LOAD_REG (HS_REG, HS_ABORTED),
2629                0,
2630        SCR_JUMP,
2631                PADDR (cleanup),
2632
2633}/*-------------------------< HDATA_IN >-------------------*/,{
2634/*
2635**      Because the size depends on the
2636**      #define MAX_SCATTERH parameter,
2637**      it is filled in at runtime.
2638**
2639**  ##==< i=MAX_SCATTERL; i<MAX_SCATTERL+MAX_SCATTERH >==
2640**  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
2641**  ||          PADDR (dispatch),
2642**  ||  SCR_MOVE_TBL ^ SCR_DATA_IN,
2643**  ||          offsetof (struct dsb, data[ i]),
2644**  ##===================================================
2645**
2646**---------------------------------------------------------
2647*/
26480
2649}/*-------------------------< HDATA_IN2 >------------------*/,{
2650        SCR_JUMP,
2651                PADDR (data_in),
2652
2653}/*-------------------------< HDATA_OUT >-------------------*/,{
2654/*
2655**      Because the size depends on the
2656**      #define MAX_SCATTERH parameter,
2657**      it is filled in at runtime.
2658**
2659**  ##==< i=MAX_SCATTERL; i<MAX_SCATTERL+MAX_SCATTERH >==
2660**  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2661**  ||          PADDR (dispatch),
2662**  ||  SCR_MOVE_TBL ^ SCR_DATA_OUT,
2663**  ||          offsetof (struct dsb, data[ i]),
2664**  ##===================================================
2665**
2666**---------------------------------------------------------
2667*/
26680
2669}/*-------------------------< HDATA_OUT2 >------------------*/,{
2670        SCR_JUMP,
2671                PADDR (data_out),
2672
2673}/*-------------------------< RESET >----------------------*/,{
2674        /*
2675        **      Send a M_RESET message if bad IDENTIFY 
2676        **      received on reselection.
2677        */
2678        SCR_LOAD_REG (scratcha, M_ABORT_TAG),
2679                0,
2680        SCR_JUMP,
2681                PADDRH (abort_resel),
2682}/*-------------------------< ABORTTAG >-------------------*/,{
2683        /*
2684        **      Abort a wrong tag received on reselection.
2685        */
2686        SCR_LOAD_REG (scratcha, M_ABORT_TAG),
2687                0,
2688        SCR_JUMP,
2689                PADDRH (abort_resel),
2690}/*-------------------------< ABORT >----------------------*/,{
2691        /*
2692        **      Abort a reselection when no active CCB.
2693        */
2694        SCR_LOAD_REG (scratcha, M_ABORT),
2695                0,
2696}/*-------------------------< ABORT_RESEL >----------------*/,{
2697        SCR_COPY (1),
2698                RADDR (scratcha),
2699                NADDR (msgout),
2700        SCR_SET (SCR_ATN),
2701                0,
2702        SCR_CLR (SCR_ACK),
2703                0,
2704        /*
2705        **      and send it.
2706        **      we expect an immediate disconnect
2707        */
2708        SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2709                0,
2710        SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
2711                NADDR (msgout),
2712        SCR_COPY (1),
2713                NADDR (msgout),
2714                NADDR (lastmsg),
2715        SCR_CLR (SCR_ACK|SCR_ATN),
2716                0,
2717        SCR_WAIT_DISC,
2718                0,
2719        SCR_JUMP,
2720                PADDR (start),
2721}/*-------------------------< RESEND_IDENT >-------------------*/,{
2722        /*
2723        **      The target stays in MSG OUT phase after having acked 
2724        **      Identify [+ Tag [+ Extended message ]]. Targets shall
2725        **      behave this way on parity error.
2726        **      We must send it again all the messages.
2727        */
2728        SCR_SET (SCR_ATN), /* Shall be asserted 2 deskew delays before the  */
2729                0,         /* 1rst ACK = 90 ns. Hope the NCR is'nt too fast */
2730        SCR_JUMP,
2731                PADDR (send_ident),
2732}/*-------------------------< CLRATN_GO_ON >-------------------*/,{
2733        SCR_CLR (SCR_ATN),
2734                0,
2735        SCR_JUMP,
2736}/*-------------------------< NXTDSP_GO_ON >-------------------*/,{
2737                0,
2738}/*-------------------------< SDATA_IN >-------------------*/,{
2739        SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
2740                PADDR (dispatch),
2741        SCR_MOVE_TBL ^ SCR_DATA_IN,
2742                offsetof (struct dsb, sense),
2743        SCR_CALL,
2744                PADDR (dispatch),
2745        SCR_JUMP,
2746                PADDR (no_data),
2747}/*-------------------------< DATA_IO >--------------------*/,{
2748        /*
2749        **      We jump here if the data direction was unknown at the 
2750        **      time we had to queue the command to the scripts processor.
2751        **      Pointers had been set as follow in this situation:
2752        **        savep   -->   DATA_IO
2753        **        lastp   -->   start pointer when DATA_IN
2754        **        goalp   -->   goal  pointer when DATA_IN
2755        **        wlastp  -->   start pointer when DATA_OUT
2756        **        wgoalp  -->   goal  pointer when DATA_OUT
2757        **      This script sets savep/lastp/goalp according to the 
2758        **      direction chosen by the target.
2759        */
2760        SCR_JUMPR ^ IFTRUE (WHEN (SCR_DATA_OUT)),
2761                32,
2762        /*
2763        **      Direction is DATA IN.
2764        **      Warning: we jump here, even when phase is DATA OUT.
2765        */
2766        SCR_COPY (4),
2767                NADDR (header.lastp),
2768                NADDR (header.savep),
2769
2770        /*
2771        **      Jump to the SCRIPTS according to actual direction.
2772        */
2773        SCR_COPY (4),
2774                NADDR (header.savep),
2775                RADDR (temp),
2776        SCR_RETURN,
2777                0,
2778        /*
2779        **      Direction is DATA OUT.
2780        */
2781        SCR_COPY (4),
2782                NADDR (header.wlastp),
2783                NADDR (header.lastp),
2784        SCR_COPY (4),
2785                NADDR (header.wgoalp),
2786                NADDR (header.goalp),
2787        SCR_JUMPR,
2788                -64,
2789}/*-------------------------< BAD_IDENTIFY >---------------*/,{
2790        /*
2791        **      If message phase but not an IDENTIFY,
2792        **      get some help from the C code.
2793        **      Old SCSI device may behave so.
2794        */
2795        SCR_JUMPR ^ IFTRUE (MASK (0x80, 0x80)),
2796                16,
2797        SCR_INT,
2798                SIR_RESEL_NO_IDENTIFY,
2799        SCR_JUMP,
2800                PADDRH (reset),
2801        /*
2802        **      Message is an IDENTIFY, but lun is unknown.
2803        **      Read the message, since we got it directly 
2804        **      from the SCSI BUS data lines.
2805        **      Signal problem to C code for logging the event.
2806        **      Send a M_ABORT to clear all pending tasks.
2807        */
2808        SCR_INT,
2809                SIR_RESEL_BAD_LUN,
2810        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2811                NADDR (msgin),
2812        SCR_JUMP,
2813                PADDRH (abort),
2814}/*-------------------------< BAD_I_T_L >------------------*/,{
2815        /*
2816        **      We donnot have a task for that I_T_L.
2817        **      Signal problem to C code for logging the event.
2818        **      Send a M_ABORT message.
2819        */
2820        SCR_INT,
2821                SIR_RESEL_BAD_I_T_L,
2822        SCR_JUMP,
2823                PADDRH (abort),
2824}/*-------------------------< BAD_I_T_L_Q >----------------*/,{
2825        /*
2826        **      We donnot have a task that matches the tag.
2827        **      Signal problem to C code for logging the event.
2828        **      Send a M_ABORTTAG message.
2829        */
2830        SCR_INT,
2831                SIR_RESEL_BAD_I_T_L_Q,
2832        SCR_JUMP,
2833                PADDRH (aborttag),
2834}/*-------------------------< BAD_TARGET >-----------------*/,{
2835        /*
2836        **      We donnot know the target that reselected us.
2837        **      Grab the first message if any (IDENTIFY).
2838        **      Signal problem to C code for logging the event.
2839        **      M_RESET message.
2840        */
2841        SCR_INT,
2842                SIR_RESEL_BAD_TARGET,
2843        SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_IN)),
2844                8,
2845        SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2846                NADDR (msgin),
2847        SCR_JUMP,
2848                PADDRH (reset),
2849}/*-------------------------< BAD_STATUS >-----------------*/,{
2850        /*
2851        **      If command resulted in either QUEUE FULL,
2852        **      CHECK CONDITION or COMMAND TERMINATED,
2853        **      call the C code.
2854        */
2855        SCR_INT ^ IFTRUE (DATA (S_QUEUE_FULL)),
2856                SIR_BAD_STATUS,
2857        SCR_INT ^ IFTRUE (DATA (S_CHECK_COND)),
2858                SIR_BAD_STATUS,
2859        SCR_INT ^ IFTRUE (DATA (S_TERMINATED)),
2860                SIR_BAD_STATUS,
2861        SCR_RETURN,
2862                0,
2863}/*-------------------------< START_RAM >-------------------*/,{
2864        /*
2865        **      Load the script into on-chip RAM, 
2866        **      and jump to start point.
2867        */
2868        SCR_COPY_F (4),
2869                RADDR (scratcha),
2870                PADDRH (start_ram0),
2871        /*
2872        **      Flush script prefetch if required
2873        */
2874        PREFETCH_FLUSH
2875        SCR_COPY (sizeof (struct script)),
2876}/*-------------------------< START_RAM0 >--------------------*/,{
2877                0,
2878                PADDR (start),
2879        SCR_JUMP,
2880                PADDR (start),
2881}/*-------------------------< STO_RESTART >-------------------*/,{
2882        /*
2883        **
2884        **      Repair start queue (e.g. next time use the next slot) 
2885        **      and jump to start point.
2886        */
2887        SCR_COPY (4),
2888                RADDR (temp),
2889                PADDR (startpos),
2890        SCR_JUMP,
2891                PADDR (start),
2892}/*-------------------------< WAIT_DMA >-------------------*/,{
2893        /*
2894        **      For HP Zalon/53c720 systems, the Zalon interface
2895        **      between CPU and 53c720 does prefetches, which causes
2896        **      problems with self modifying scripts.  The problem
2897        **      is overcome by calling a dummy subroutine after each
2898        **      modification, to force a refetch of the script on
2899        **      return from the subroutine.
2900        */
2901        SCR_RETURN,
2902                0,
2903}/*-------------------------< SNOOPTEST >-------------------*/,{
2904        /*
2905        **      Read the variable.
2906        */
2907        SCR_COPY (4),
2908                NADDR(ncr_cache),
2909                RADDR (scratcha),
2910        /*
2911        **      Write the variable.
2912        */
2913        SCR_COPY (4),
2914                RADDR (temp),
2915                NADDR(ncr_cache),
2916        /*
2917        **      Read back the variable.
2918        */
2919        SCR_COPY (4),
2920                NADDR(ncr_cache),
2921                RADDR (temp),
2922}/*-------------------------< SNOOPEND >-------------------*/,{
2923        /*
2924        **      And stop.
2925        */
2926        SCR_INT,
2927                99,
2928}/*--------------------------------------------------------*/
2929};
2930
2931/*==========================================================
2932**
2933**
2934**      Fill in #define dependent parts of the script
2935**
2936**
2937**==========================================================
2938*/
2939
2940void __init ncr_script_fill (struct script * scr, struct scripth * scrh)
2941{
2942        int     i;
2943        ncrcmd  *p;
2944
2945        p = scrh->tryloop;
2946        for (i=0; i<MAX_START; i++) {
2947                *p++ =SCR_CALL;
2948                *p++ =PADDR (idle);
2949        };
2950
2951        assert ((u_long)p == (u_long)&scrh->tryloop + sizeof (scrh->tryloop));
2952
2953#ifdef SCSI_NCR_CCB_DONE_SUPPORT
2954
2955        p = scrh->done_queue;
2956        for (i = 0; i<MAX_DONE; i++) {
2957                *p++ =SCR_COPY (sizeof(ccb_p));
2958                *p++ =NADDR (header.cp);
2959                *p++ =NADDR (ccb_done[i]);
2960                *p++ =SCR_CALL;
2961                *p++ =PADDR (done_end);
2962        }
2963
2964        assert ((u_long)p ==(u_long)&scrh->done_queue+sizeof(scrh->done_queue));
2965
2966#endif /* SCSI_NCR_CCB_DONE_SUPPORT */
2967
2968        p = scrh->hdata_in;
2969        for (i=0; i<MAX_SCATTERH; i++) {
2970                *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN));
2971                *p++ =PADDR (dispatch);
2972                *p++ =SCR_MOVE_TBL ^ SCR_DATA_IN;
2973                *p++ =offsetof (struct dsb, data[i]);
2974        };
2975        assert ((u_long)p == (u_long)&scrh->hdata_in + sizeof (scrh->hdata_in));
2976
2977        p = scr->data_in;
2978        for (i=MAX_SCATTERH; i<MAX_SCATTERH+MAX_SCATTERL; i++) {
2979                *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN));
2980                *p++ =PADDR (dispatch);
2981                *p++ =SCR_MOVE_TBL ^ SCR_DATA_IN;
2982                *p++ =offsetof (struct dsb, data[i]);
2983        };
2984        assert ((u_long)p == (u_long)&scr->data_in + sizeof (scr->data_in));
2985
2986        p = scrh->hdata_out;
2987        for (i=0; i<MAX_SCATTERH; i++) {
2988                *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT));
2989                *p++ =PADDR (dispatch);
2990                *p++ =SCR_MOVE_TBL ^ SCR_DATA_OUT;
2991                *p++ =offsetof (struct dsb, data[i]);
2992        };
2993        assert ((u_long)p==(u_long)&scrh->hdata_out + sizeof (scrh->hdata_out));
2994
2995        p = scr->data_out;
2996        for (i=MAX_SCATTERH; i<MAX_SCATTERH+MAX_SCATTERL; i++) {
2997                *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT));
2998                *p++ =PADDR (dispatch);
2999                *p++ =SCR_MOVE_TBL ^ SCR_DATA_OUT;
3000                *p++ =offsetof (struct dsb, data[i]);
3001        };
3002
3003        assert ((u_long)p == (u_long)&scr->data_out + sizeof (scr->data_out));
3004}
3005
3006/*==========================================================
3007**
3008**
3009**      Copy and rebind a script.
3010**
3011**
3012**==========================================================
3013*/
3014
3015static void __init 
3016ncr_script_copy_and_bind (ncb_p np, ncrcmd *src, ncrcmd *dst, int len)
3017{
3018        ncrcmd  opcode, new, old, tmp1, tmp2;
3019        ncrcmd  *start, *end;
3020        int relocs;
3021        int opchanged = 0;
3022
3023        start = src;
3024        end = src + len/4;
3025
3026        while (src < end) {
3027
3028                opcode = *src++;
3029                *dst++ = cpu_to_scr(opcode);
3030
3031                /*
3032                **      If we forget to change the length
3033                **      in struct script, a field will be
3034                **      padded with 0. This is an illegal
3035                **      command.
3036                */
3037
3038                if (opcode == 0) {
3039                        printk (KERN_ERR "%s: ERROR0 IN SCRIPT at %d.\n",
3040                                ncr_name(np), (int) (src-start-1));
3041                        MDELAY (1000);
3042                };
3043
3044                if (DEBUG_FLAGS & DEBUG_SCRIPT)
3045                        printk (KERN_DEBUG "%p:  <%x>\n",
3046                                (src-1), (unsigned)opcode);
3047
3048                /*
3049                **      We don't have to decode ALL commands
3050                */
3051                switch (opcode >> 28) {
3052
3053                case 0xc:
3054                        /*
3055                        **      COPY has TWO arguments.
3056                        */
3057                        relocs = 2;
3058                        tmp1 = src[0];
3059#ifdef  RELOC_KVAR
3060                        if ((tmp1 & RELOC_MASK) == RELOC_KVAR)
3061                                tmp1 = 0;
3062#endif
3063                        tmp2 = src[1];
3064#ifdef  RELOC_KVAR
3065                        if ((tmp2 & RELOC_MASK) == RELOC_KVAR)
3066                                tmp2 = 0;
3067#endif
3068                        if ((tmp1 ^ tmp2) & 3) {
3069                                printk (KERN_ERR"%s: ERROR1 IN SCRIPT at %d.\n",
3070                                        ncr_name(np), (int) (src-start-1));
3071                                MDELAY (1000);
3072                        }
3073                        /*
3074                        **      If PREFETCH feature not enabled, remove 
3075                        **      the NO FLUSH bit if present.
3076                        */
3077                        if ((opcode & SCR_NO_FLUSH) && !(np->features & FE_PFEN)) {
3078                                dst[-1] = cpu_to_scr(opcode & ~SCR_NO_FLUSH);
3079                                ++opchanged;
3080                        }
3081                        break;
3082
3083                case 0x0:
3084                        /*
3085                        **      MOVE (absolute address)
3086                        */
3087                        relocs = 1;
3088                        break;
3089
3090                case 0x8:
3091                        /*
3092                        **      JUMP / CALL
3093                        **      dont't relocate if relative :-)
3094                        */
3095                        if (opcode & 0x00800000)
3096                                relocs = 0;
3097                        else
3098                                relocs = 1;
3099                        break;
3100
3101                case 0x4:
3102                case 0x5:
3103                case 0x6:
3104                case 0x7:
3105                        relocs = 1;
3106                        break;
3107
3108                default:
3109                        relocs = 0;
3110                        break;
3111                };
3112
3113                if (relocs) {
3114                        while (relocs--) {
3115                                old = *src++;
3116
3117                                switch (old & RELOC_MASK) {
3118                                case RELOC_REGISTER:
3119                                        new = (old & ~RELOC_MASK) + np->paddr;
3120                                        break;
3121                                case RELOC_LABEL:
3122                                        new = (old & ~RELOC_MASK) + np->p_script;
3123                                        break;
3124                                case RELOC_LABELH:
3125                                        new = (old & ~RELOC_MASK) + np->p_scripth;
3126                                        break;
3127                                case RELOC_SOFTC:
3128                                        new = (old & ~RELOC_MASK) + np->p_ncb;
3129                                        break;
3130#ifdef  RELOC_KVAR
3131                                case RELOC_KVAR:
3132                                        if (((old & ~RELOC_MASK) <
3133                                             SCRIPT_KVAR_FIRST) ||
3134                                            ((old & ~RELOC_MASK) >
3135                                             SCRIPT_KVAR_LAST))
3136                                                panic("ncr KVAR out of range");
3137                                        new = vtophys(script_kvars[old &
3138                                            ~RELOC_MASK]);
3139                                        break;
3140#endif
3141                                case 0:
3142                                        /* Don't relocate a 0 address. */
3143                                        if (old == 0) {
3144                                                new = old;
3145                                                break;
3146                                        }
3147                                        /* fall through */
3148                                default:
3149                                        panic("ncr_script_copy_and_bind: weird relocation %x\n", old);
3150                                        break;
3151                                }
3152
3153                                *dst++ = cpu_to_scr(new);
3154                        }
3155                } else
3156                        *dst++ = cpu_to_scr(*src++);
3157
3158        };
3159}
3160
3161/*==========================================================
3162**
3163**
3164**      Auto configuration:  attach and init a host adapter.
3165**
3166**
3167**==========================================================
3168*/
3169
3170/*
3171**      Linux host data structure
3172**
3173**      The script area is allocated in the host data structure
3174**      because kmalloc() returns NULL during scsi initialisations
3175**      with Linux 1.2.X
3176*/
3177
3178struct host_data {
3179     struct ncb *ncb;
3180};
3181
3182/*
3183**      Print something which allows to retrieve the controller type, unit,
3184**      target, lun concerned by a kernel message.
3185*/
3186
3187static void PRINT_TARGET(ncb_p np, int target)
3188{
3189        printk(KERN_INFO "%s-<%d,*>: ", ncr_name(np), target);
3190}
3191
3192static void PRINT_LUN(ncb_p np, int target, int lun)
3193{
3194        printk(KERN_INFO "%s-<%d,%d>: ", ncr_name(np), target, lun);
3195}
3196
3197static void PRINT_ADDR(Scsi_Cmnd *cmd)
3198{
3199        struct host_data *host_data = (struct host_data *) cmd->host->hostdata;
3200        PRINT_LUN(host_data->ncb, cmd->target, cmd->lun);
3201}
3202
3203/*==========================================================
3204**
3205**      NCR chip clock divisor table.
3206**      Divisors are multiplied by 10,000,000 in order to make 
3207**      calculations more simple.
3208**
3209**==========================================================
3210*/
3211
3212#define _5M 5000000
3213static u_long div_10M[] =
3214        {2*_5M, 3*_5M, 4*_5M, 6*_5M, 8*_5M, 12*_5M, 16*_5M};
3215
3216
3217/*===============================================================
3218**
3219**      Prepare io register values used by ncr_init() according 
3220**      to selected and supported features.
3221**
3222**      NCR chips allow burst lengths of 2, 4, 8, 16, 32, 64, 128 
3223**      transfers. 32,64,128 are only supported by 875 and 895 chips.
3224**      We use log base 2 (burst length) as internal code, with 
3225**      value 0 meaning "burst disabled".
3226**
3227**===============================================================
3228*/
3229
3230/*
3231 *      Burst length from burst code.
3232 */
3233#define burst_length(bc) (!(bc))? 0 : 1 << (bc)
3234
3235/*
3236 *      Burst code from io register bits.  Burst enable is ctest0 for c720,
3237 *      ctest4 for others.
3238 */
3239#define burst_code(dmode, ctest0, ctest4, ctest5) \
3240        (np->device_id == PSEUDO_ZALON_720_ID) ? \
3241        (ctest0) & 0x80? 0 : (((dmode) & 0xc0) >> 6) + 1 : \
3242        (ctest4) & 0x80? 0 : (((dmode) & 0xc0) >> 6) + ((ctest5) & 0x04) + 1
3243
3244/*
3245 *      Set initial io register bits from burst code.
3246 */
3247static inline void ncr_init_burst(ncb_p np, u_char bc)
3248{
3249        u_char *be = (np->device_id == PSEUDO_ZALON_720_ID) ?
3250                &np->rv_ctest0 : &np->rv_ctest4;
3251        *be             &= ~0x80;
3252        np->rv_dmode    &= ~(0x3 << 6);
3253        np->rv_ctest5   &= ~0x4;
3254
3255        if (!bc) {
3256                *be             |= 0x80;
3257        }
3258        else {
3259                --bc;
3260                np->rv_dmode    |= ((bc & 0x3) << 6);
3261                np->rv_ctest5   |= (bc & 0x4);
3262        }
3263}
3264
3265#ifdef SCSI_NCR_NVRAM_SUPPORT
3266
3267/*
3268**      Get target set-up from Symbios format NVRAM.
3269*/
3270
3271static void __init 
3272ncr_Symbios_setup_target(ncb_p np, int target, Symbios_nvram *nvram)
3273{
3274        tcb_p tp = &np->target[target];
3275        Symbios_target *tn = &nvram->target[target];
3276
3277        tp->usrsync = tn->sync_period ? (tn->sync_period + 3) / 4 : 255;
3278        tp->usrwide = tn->bus_width == 0x10 ? 1 : 0;
3279        tp->usrtags =
3280                (tn->flags & SYMBIOS_QUEUE_TAGS_ENABLED)? MAX_TAGS : 0;
3281
3282        if (!(tn->flags & SYMBIOS_DISCONNECT_ENABLE))
3283                tp->usrflag |= UF_NODISC;
3284        if (!(tn->flags & SYMBIOS_SCAN_AT_BOOT_TIME))
3285                tp->usrflag |= UF_NOSCAN;
3286}
3287
3288/*
3289**      Get target set-up from Tekram format NVRAM.
3290*/
3291
3292static void __init 
3293ncr_Tekram_setup_target(ncb_p np, int target, Tekram_nvram *nvram)
3294{
3295        tcb_p tp = &np->target[target];
3296        struct Tekram_target *tn = &nvram->target[target];
3297        int i;
3298
3299        if (tn->flags & TEKRAM_SYNC_NEGO) {
3300                i = tn->sync_index & 0xf;
3301                tp->usrsync = Tekram_sync[i];
3302        }
3303
3304        tp->usrwide = (tn->flags & TEKRAM_WIDE_NEGO) ? 1 : 0;
3305
3306        if (tn->flags & TEKRAM_TAGGED_COMMANDS) {
3307                tp->usrtags = 2 << nvram->max_tags_index;
3308        }
3309
3310        if (!(tn->flags & TEKRAM_DISCONNECT_ENABLE))
3311                tp->usrflag = UF_NODISC;
3312 
3313        /* If any device does not support parity, we will not use this option */
3314        if (!(tn->flags & TEKRAM_PARITY_CHECK))
3315                np->rv_scntl0  &= ~0x0a; /* SCSI parity checking disabled */
3316}
3317#endif /* SCSI_NCR_NVRAM_SUPPORT */
3318
3319static int __init ncr_prepare_setting(ncb_p np, ncr_nvram *nvram)
3320{
3321        u_char  burst_max;
3322        u_long  period;
3323        int i;
3324
3325        /*
3326        **      Save assumed BIOS setting
3327        */
3328
3329        np->sv_scntl0   = INB(nc_scntl0) & 0x0a;
3330        np->sv_scntl3   = INB(nc_scntl3) & 0x07;
3331        np->sv_dmode    = INB(nc_dmode)  & 0xce;
3332        np->sv_dcntl    = INB(nc_dcntl)  & 0xa8;
3333        np->sv_ctest0   = INB(nc_ctest0) & 0x84;
3334        np->sv_ctest3   = INB(nc_ctest3) & 0x01;
3335        np->sv_ctest4   = INB(nc_ctest4) & 0x80;
3336        np->sv_ctest5   = INB(nc_ctest5) & 0x24;
3337        np->sv_gpcntl   = INB(nc_gpcntl);
3338        np->sv_stest2   = INB(nc_stest2) & 0x20;
3339        np->sv_stest4   = INB(nc_stest4);
3340
3341        /*
3342        **      Wide ?
3343        */
3344
3345        np->maxwide     = (np->features & FE_WIDE)? 1 : 0;
3346
3347        /*
3348         *  Guess the frequency of the chip's clock.
3349         */
3350        if      (np->features & (FE_ULTRA3 | FE_ULTRA2))
3351                np->clock_khz = 160000;
3352        else if (np->features & FE_ULTRA)
3353                np->clock_khz = 80000;
3354        else
3355                np->clock_khz = 40000;
3356
3357        /*
3358         *  Get the clock multiplier factor.
3359         */
3360        if      (np->features & FE_QUAD)
3361                np->multiplier  = 4;
3362        else if (np->features & FE_DBLR)
3363                np->multiplier  = 2;
3364        else
3365                np->multiplier  = 1;
3366
3367        /*
3368         *  Measure SCSI clock frequency for chips 
3369         *  it may vary from assumed one.
3370         */
3371        if (np->features & FE_VARCLK)
3372                ncr_getclock(np, np->multiplier);
3373
3374        /*
3375         * Divisor to be used for async (timer pre-scaler).
3376         */
3377        i = np->clock_divn - 1;
3378        while (--i >= 0) {
3379                if (10ul * SCSI_NCR_MIN_ASYNC * np->clock_khz > div_10M[i]) {
3380                        ++i;
3381                        break;
3382                }
3383        }
3384        np->rv_scntl3 = i+1;
3385
3386        /*
3387         * Minimum synchronous period factor supported by the chip.
3388         * Btw, 'period' is in tenths of nanoseconds.
3389         */
3390
3391        period = (4 * div_10M[0] + np->clock_khz - 1) / np->clock_khz;
3392        if      (period <= 250)         np->minsync = 10;
3393        else if (period <= 303)         np->minsync = 11;
3394        else if (period <= 500)         np->minsync = 12;
3395        else                            np->minsync = (period + 40 - 1) / 40;
3396
3397        /*
3398         * Check against chip SCSI standard support (SCSI-2,ULTRA,ULTRA2).
3399         */
3400
3401        if      (np->minsync < 25 && !(np->features & (FE_ULTRA|FE_ULTRA2)))
3402                np->minsync = 25;
3403        else if (np->minsync < 12 && !(np->features & FE_ULTRA2))
3404                np->minsync = 12;
3405
3406        /*
3407         * Maximum synchronous period factor supported by the chip.
3408         */
3409
3410        period = (11 * div_10M[np->clock_divn - 1]) / (4 * np->clock_khz);
3411        np->maxsync = period > 2540 ? 254 : period / 10;
3412
3413        /*
3414        **      Prepare initial value of other IO registers
3415        */
3416#if defined SCSI_NCR_TRUST_BIOS_SETTING
3417        np->rv_scntl0   = np->sv_scntl0;
3418        np->rv_dmode    = np->sv_dmode;
3419        np->rv_dcntl    = np->sv_dcntl;
3420        np->rv_ctest0   = np->sv_ctest0;
3421        np->rv_ctest3   = np->sv_ctest3;
3422        np->rv_ctest4   = np->sv_ctest4;
3423        np->rv_ctest5   = np->sv_ctest5;
3424        burst_max       = burst_code(np->sv_dmode, np->sv_ctest0, np->sv_ctest4, np->sv_ctest5);
3425#else
3426
3427        /*
3428        **      Select burst length (dwords)
3429        */
3430        burst_max       = driver_setup.burst_max;
3431        if (burst_max == 255)
3432                burst_max = burst_code(np->sv_dmode, np->sv_ctest0, np->sv_ctest4, np->sv_ctest5);
3433        if (burst_max > 7)
3434                burst_max = 7;
3435        if (burst_max > np->maxburst)
3436                burst_max = np->maxburst;
3437
3438        /*
3439        **      Select all supported special features
3440        */
3441        if (np->features & FE_ERL)
3442                np->rv_dmode    |= ERL;         /* Enable Read Line */
3443        if (np->features & FE_BOF)
3444                np->rv_dmode    |= BOF;         /* Burst Opcode Fetch */
3445        if (np->features & FE_ERMP)
3446                np->rv_dmode    |= ERMP;        /* Enable Read Multiple */
3447        if (np->features & FE_PFEN)
3448                np->rv_dcntl    |= PFEN;        /* Prefetch Enable */
3449        if (np->features & FE_CLSE)
3450                np->rv_dcntl    |= CLSE;        /* Cache Line Size Enable */
3451        if (np->features & FE_WRIE)
3452                np->rv_ctest3   |= WRIE;        /* Write and Invalidate */
3453        if (np->features & FE_DFS)
3454                np->rv_ctest5   |= DFS;         /* Dma Fifo Size */
3455        if (np->features & FE_MUX)
3456                np->rv_ctest4   |= MUX;         /* Host bus multiplex mode */
3457        if (np->features & FE_EA)
3458                np->rv_dcntl    |= EA;          /* Enable ACK */
3459        if (np->features & FE_EHP)
3460                np->rv_ctest0   |= EHP;         /* Even host parity */
3461
3462        /*
3463        **      Select some other
3464        */
3465        if (driver_setup.master_parity)
3466                np->rv_ctest4   |= MPEE;        /* Master parity checking */
3467        if (driver_setup.scsi_parity)
3468                np->rv_scntl0   |= 0x0a;        /*  full arb., ena parity, par->ATN  */
3469
3470#ifdef SCSI_NCR_NVRAM_SUPPORT
3471        /*
3472        **      Get parity checking, host ID and verbose mode from NVRAM
3473        **/
3474        if (nvram) {
3475                switch(nvram->type) {
3476                case SCSI_NCR_TEKRAM_NVRAM:
3477                        np->myaddr = nvram->data.Tekram.host_id & 0x0f;
3478                        break;
3479                case SCSI_NCR_SYMBIOS_NVRAM:
3480                        if (!(nvram->data.Symbios.flags & SYMBIOS_PARITY_ENABLE))
3481                                np->rv_scntl0  &= ~0x0a;
3482                        np->myaddr = nvram->data.Symbios.host_id & 0x0f;
3483                        if (nvram->data.Symbios.flags & SYMBIOS_VERBOSE_MSGS)
3484                                np->verbose += 1;
3485                        break;
3486                }
3487        }
3488#endif
3489        /*
3490        **  Get SCSI addr of host adapter (set by bios?).
3491        */
3492        if (np->myaddr == 255) {
3493                np->myaddr = INB(nc_scid) & 0x07;
3494                if (!np->myaddr)
3495                        np->myaddr = SCSI_NCR_MYADDR;
3496        }
3497
3498#endif /* SCSI_NCR_TRUST_BIOS_SETTING */
3499
3500        /*
3501         *      Prepare initial io register bits for burst length
3502         */
3503        ncr_init_burst(np, burst_max);
3504
3505        /*
3506        **      Set SCSI BUS mode.
3507        **
3508        **      - ULTRA2 chips (895/895A/896) report the current 
3509        **        BUS mode through the STEST4 IO register.
3510        **      - For previous generation chips (825/825A/875), 
3511        **        user has to tell us how to check against HVD, 
3512        **        since a 100% safe algorithm is not possible.
3513        */
3514        np->scsi_mode = SMODE_SE;
3515        if      (np->features & FE_ULTRA2)
3516                np->scsi_mode = (np->sv_stest4 & SMODE);
3517        else if (np->features & FE_DIFF) {
3518                switch(driver_setup.diff_support) {
3519                case 4: /* Trust previous settings if present, then GPIO3 */
3520                        if (np->sv_scntl3) {
3521                                if (np->sv_stest2 & 0x20)
3522                                        np->scsi_mode = SMODE_HVD;
3523                                break;
3524                        }
3525                case 3: /* SYMBIOS controllers report HVD through GPIO3 */
3526                        if (nvram && nvram->type != SCSI_NCR_SYMBIOS_NVRAM)
3527                                break;
3528                        if (INB(nc_gpreg) & 0x08)
3529                                break;
3530                case 2: /* Set HVD unconditionally */
3531                        np->scsi_mode = SMODE_HVD;
3532                case 1: /* Trust previous settings for HVD */
3533                        if (np->sv_stest2 & 0x20)
3534                                np->scsi_mode = SMODE_HVD;
3535                        break;
3536                default:/* Don't care about HVD */      
3537                        break;
3538                }
3539        }
3540        if (np->scsi_mode == SMODE_HVD)
3541                np->rv_stest2 |= 0x20;
3542
3543        /*
3544        **      Set LED support from SCRIPTS.
3545        **      Ignore this feature for boards known to use a 
3546        **      specific GPIO wiring and for the 895A or 896 
3547        **      that drive the LED directly.
3548        **      Also probe initial setting of GPIO0 as output.
3549        */
3550        if ((driver_setup.led_pin ||
3551             (nvram && nvram->type == SCSI_NCR_SYMBIOS_NVRAM)) &&
3552            !(np->features & FE_LEDC) && !(np->sv_gpcntl & 0x01))
3553                np->features |= FE_LED0;
3554
3555        /*
3556        **      Set irq mode.
3557        */
3558        switch(driver_setup.irqm & 3) {
3559        case 2:
3560                np->rv_dcntl    |= IRQM;
3561                break;
3562        case 1:
3563                np->rv_dcntl    |= (np->sv_dcntl & IRQM);
3564                break;
3565        default:
3566                break;
3567        }
3568
3569        /*
3570        **      Configure targets according to driver setup.
3571        **      If NVRAM present get targets setup from NVRAM.
3572        **      Allow to override sync, wide and NOSCAN from 
3573        **      boot command line.
3574        */
3575        for (i = 0 ; i < MAX_TARGET ; i++) {
3576                tcb_p tp = &np->target[i];
3577
3578                tp->usrsync = 255;
3579#ifdef SCSI_NCR_NVRAM_SUPPORT
3580                if (nvram) {
3581                        switch(nvram->type) {
3582                        case SCSI_NCR_TEKRAM_NVRAM:
3583                                ncr_Tekram_setup_target(np, i, &nvram->data.Tekram);
3584                                break;
3585                        case SCSI_NCR_SYMBIOS_NVRAM:
3586                                ncr_Symbios_setup_target(np, i, &nvram->data.Symbios);
3587                                break;
3588                        }
3589                        if (driver_setup.use_nvram & 0x2)
3590                                tp->usrsync = driver_setup.default_sync;
3591                        if (driver_setup.use_nvram & 0x4)
3592                                tp->usrwide = driver_setup.max_wide;
3593                        if (driver_setup.use_nvram & 0x8)
3594                                tp->usrflag &= ~UF_NOSCAN;
3595                }
3596                else {
3597#else
3598                if (1) {
3599#endif
3600                        tp->usrsync = driver_setup.default_sync;
3601                        tp->usrwide = driver_setup.max_wide;
3602                        tp->usrtags = MAX_TAGS;
3603                        if (!driver_setup.disconnection)
3604                                np->target[i].usrflag = UF_NODISC;
3605                }
3606        }
3607
3608        /*
3609        **      Announce all that stuff to user.
3610        */
3611
3612        i = nvram ? nvram->type : 0;
3613        printk(KERN_INFO "%s: %sID %d, Fast-%d%s%s\n", ncr_name(np),
3614                i  == SCSI_NCR_SYMBIOS_NVRAM ? "Symbios format NVRAM, " :
3615                (i == SCSI_NCR_TEKRAM_NVRAM  ? "Tekram format NVRAM, " : ""),
3616                np->myaddr,
3617                np->minsync < 12 ? 40 : (np->minsync < 25 ? 20 : 10),
3618                (np->rv_scntl0 & 0xa)   ? ", Parity Checking"   : ", NO Parity",
3619                (np->rv_stest2 & 0x20)  ? ", Differential"      : "");
3620
3621        if (bootverbose > 1) {
3622                printk (KERN_INFO "%s: initial SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
3623                        "(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
3624                        ncr_name(np), np->sv_scntl3, np->sv_dmode, np->sv_dcntl,
3625                        np->sv_ctest3, np->sv_ctest4, np->sv_ctest5);
3626
3627                printk (KERN_INFO "%s: final   SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
3628                        "(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
3629                        ncr_name(np), np->rv_scntl3, np->rv_dmode, np->rv_dcntl,
3630                        np->rv_ctest3, np->rv_ctest4, np->rv_ctest5);
3631        }
3632
3633        if (bootverbose && np->paddr2)
3634                printk (KERN_INFO "%s: on-chip RAM at 0x%lx\n",
3635                        ncr_name(np), np->paddr2);
3636
3637        return 0;
3638}
3639
3640/*
3641**      Host attach and initialisations.
3642**
3643**      Allocate host data and ncb structure.
3644**      Request IO region and remap MMIO region.
3645**      Do chip initialization.
3646**      If all is OK, install interrupt handling and
3647**      start the timer daemon.
3648*/
3649
3650static int __init 
3651ncr_attach (Scsi_Host_Template *tpnt, int unit, ncr_device *device)
3652{
3653        struct host_data *host_data;
3654        ncb_p np = 0;
3655        struct Scsi_Host *instance = 0;
3656        u_long flags = 0;
3657        ncr_nvram *nvram = device->nvram;
3658        int i;
3659
3660#ifndef ENABLE_SCSI_ZALON
3661        printk(KERN_INFO "ncr53c%s-%d: rev 0x%x on pci bus %d device %d function %d "
3662#ifdef __sparc__
3663                "irq %s\n",
3664#else
3665                "irq %d\n",
3666#endif
3667                device->chip.name, unit, device->chip.revision_id,
3668                device->slot.bus, (device->slot.device_fn & 0xf8) >> 3,
3669                device->slot.device_fn & 7,
3670#ifdef __sparc__
3671                __irq_itoa(device->slot.irq));
3672#else
3673                device->slot.irq);
3674#endif
3675#endif
3676
3677        /*
3678        **      Allocate host_data structure
3679        */
3680        if (!(instance = scsi_register(tpnt, sizeof(*host_data))))
3681                goto attach_error;
3682        host_data = (struct host_data *) instance->hostdata;
3683
3684        /*
3685        **      Allocate the host control block.
3686        */
3687        np = __m_calloc_dma(device->dev, sizeof(struct ncb), "NCB");
3688        if (!np)
3689                goto attach_error;
3690        NCR_INIT_LOCK_NCB(np);
3691        np->dev  = device->dev;
3692        np->p_ncb = vtobus(np);
3693        host_data->ncb = np;
3694
3695        /*
3696        **      Allocate the default CCB.
3697        */
3698        np->ccb = (ccb_p) m_calloc_dma(sizeof(struct ccb), "CCB");
3699        if (!np->ccb)
3700                goto attach_error;
3701
3702        /*
3703        **      Store input informations in the host data structure.
3704        */
3705        strncpy(np->chip_name, device->chip.name, sizeof(np->chip_name) - 1);
3706        np->unit        = unit;
3707        np->verbose     = driver_setup.verbose;
3708        sprintf(np->inst_name, "ncr53c%s-%d", np->chip_name, np->unit);
3709        np->device_id   = device->chip.device_id;
3710        np->revision_id = device->chip.revision_id;
3711        np->bus         = device->slot.bus;
3712        np->device_fn   = device->slot.device_fn;
3713        np->features    = device->chip.features;
3714        np->clock_divn  = device->chip.nr_divisor;
3715        np->maxoffs     = device->chip.offset_max;
3716        np->maxburst    = device->chip.burst_max;
3717        np->myaddr      = device->host_id;
3718
3719        /*
3720        **      Allocate SCRIPTS areas.
3721        */
3722        np->script0  = (struct script *)
3723                        m_calloc_dma(sizeof(struct script), "SCRIPT");
3724        if (!np->script0)
3725                goto attach_error;
3726        np->scripth0  = (struct scripth *)
3727                        m_calloc_dma(sizeof(struct scripth), "SCRIPTH");
3728        if (!np->scripth0)
3729                goto attach_error;
3730
3731        /*
3732        **    Initialize timer structure
3733        **
3734        */
3735        init_timer(&np->timer);
3736        np->timer.data     = (unsigned long) np;
3737        np->timer.function = ncr53c8xx_timeout;
3738
3739        /*
3740        **      Try to map the controller chip to
3741        **      virtual and physical memory.
3742        */
3743
3744        np->paddr       = device->slot.base;
3745        np->paddr2      = (np->features & FE_RAM)? device->slot.base_2 : 0;
3746
3747#ifndef SCSI_NCR_IOMAPPED
3748        np->vaddr = remap_pci_mem(device->slot.base_c, (u_long) 128);
3749        if (!np->vaddr) {
3750                printk(KERN_ERR
3751                        "%s: can't map memory mapped IO region\n",ncr_name(np));
3752                goto attach_error;
3753        }
3754        else
3755                if (bootverbose > 1)
3756                        printk(KERN_INFO
3757                                "%s: using memory mapped IO at virtual address 0x%lx\n", ncr_name(np), (u_long) np->vaddr);
3758
3759        /*
3760        **      Make the controller's registers available.
3761        **      Now the INB INW INL OUTB OUTW OUTL macros
3762        **      can be used safely.
3763        */
3764
3765        np->reg = (struct ncr_reg*) np->vaddr;
3766
3767#endif /* !defined SCSI_NCR_IOMAPPED */
3768
3769        /*
3770        **      Try to map the controller chip into iospace.
3771        */
3772
3773#ifndef ENABLE_SCSI_ZALON
3774        request_region(device->slot.io_port, 128, "ncr53c8xx");
3775#endif
3776        np->base_io = device->slot.io_port;
3777
3778#ifdef SCSI_NCR_NVRAM_SUPPORT
3779        if (nvram) {
3780                switch(nvram->type) {
3781                case SCSI_NCR_SYMBIOS_NVRAM:
3782#ifdef SCSI_NCR_DEBUG_NVRAM
3783                        ncr_display_Symbios_nvram(&nvram->data.Symbios);
3784#endif
3785                        break;
3786                case SCSI_NCR_TEKRAM_NVRAM:
3787#ifdef SCSI_NCR_DEBUG_NVRAM
3788                        ncr_display_Tekram_nvram(&nvram->data.Tekram);
3789#endif
3790                        break;
3791                default:
3792                        nvram = 0;
3793#ifdef SCSI_NCR_DEBUG_NVRAM
3794                        printk(KERN_DEBUG "%s: NVRAM: None or invalid data.\n", ncr_name(np));
3795#endif
3796                }
3797        }
3798#endif
3799
3800        /*
3801        **      Do chip dependent initialization.
3802        */
3803        (void)ncr_prepare_setting(np, nvram);
3804
3805        if (np->paddr2 && sizeof(struct script) > 4096) {
3806                np->paddr2 = 0;
3807                printk(KERN_WARNING "%s: script too large, NOT using on chip RAM.\n",
3808                        ncr_name(np));
3809        }
3810
3811        /*
3812        **      Fill Linux host instance structure
3813        */
3814        instance->max_channel   = 0;
3815        instance->this_id       = np->myaddr;
3816        instance->max_id        = np->maxwide ? 16 : 8;
3817        instance->max_lun       = SCSI_NCR_MAX_LUN;
3818#ifndef SCSI_NCR_IOMAPPED
3819#if LINUX_VERSION_CODE >= LinuxVersionCode(2,3,29)
3820        instance->base          = (unsigned long) np->reg;
3821#else
3822        instance->base          = (char *) np->reg;
3823#endif
3824#endif
3825        instance->irq           = device->slot.irq;
3826        instance->unique_id     = device->slot.io_port;
3827        instance->io_port       = device->slot.io_port;
3828        instance->n_io_port     = 128;
3829        instance->dma_channel   = 0;
3830        instance->cmd_per_lun   = MAX_TAGS;
3831        instance->can_queue     = (MAX_START-4);
3832        scsi_set_device(instance, device->dev);
3833
3834#ifdef SCSI_NCR_INTEGRITY_CHECKING
3835        np->check_integrity       = 0;
3836        instance->check_integrity = 0;
3837
3838#ifdef SCSI_NCR_ENABLE_INTEGRITY_CHECK
3839        if ( !(driver_setup.bus_check & 0x04) ) {
3840                np->check_integrity       = 1;
3841                instance->check_integrity = 1;
3842        }
3843#endif
3844#endif
3845        /*
3846        **      Patch script to physical addresses
3847        */
3848        ncr_script_fill (&script0, &scripth0);
3849
3850        np->scripth     = np->scripth0;
3851        np->p_scripth   = vtobus(np->scripth);
3852
3853        np->p_script    = (np->paddr2) ?  np->paddr2 : vtobus(np->script0);
3854
3855        ncr_script_copy_and_bind (np, (ncrcmd *) &script0, (ncrcmd *) np->script0, sizeof(struct script));
3856        ncr_script_copy_and_bind (np, (ncrcmd *) &scripth0, (ncrcmd *) np->scripth0, sizeof(struct scripth));
3857        np->ccb->p_ccb          = vtobus (np->ccb);
3858
3859        /*
3860        **    Patch the script for LED support.
3861        */
3862
3863        if (np->features & FE_LED0) {
3864                np->script0->idle[0]  =
3865                                cpu_to_scr(SCR_REG_REG(gpreg, SCR_OR,  0x01));
3866                np->script0->reselected[0] =
3867                                cpu_to_scr(SCR_REG_REG(gpreg, SCR_AND, 0xfe));
3868                np->script0->start[0] =
3869                                cpu_to_scr(SCR_REG_REG(gpreg, SCR_AND, 0xfe));
3870        }
3871
3872        /*
3873        **      Look for the target control block of this nexus.
3874        **      For i = 0 to 3
3875        **              JUMP ^ IFTRUE (MASK (i, 3)), @(next_lcb)
3876        */
3877        for (i = 0 ; i < 4 ; i++) {
3878                np->jump_tcb[i].l_cmd   =
3879                                cpu_to_scr((SCR_JUMP ^ IFTRUE (MASK (i, 3))));
3880                np->jump_tcb[i].l_paddr =
3881                                cpu_to_scr(NCB_SCRIPTH_PHYS (np, bad_target));
3882        }
3883
3884        /*
3885        **      Reset chip.
3886        */
3887        ncr_chip_reset(np, 100);
3888
3889        /*
3890        **      Now check the cache handling of the pci chipset.
3891        */
3892
3893        if (ncr_snooptest (np)) {
3894                printk (KERN_ERR "CACHE INCORRECTLY CONFIGURED.\n");
3895                goto attach_error;
3896        };
3897
3898        /*
3899        **      Install the interrupt handler.
3900        */
3901
3902        if (request_irq(device->slot.irq, ncr53c8xx_intr,
3903                        ((driver_setup.irqm & 0x10) ? 0 : SA_SHIRQ) |
3904#if LINUX_VERSION_CODE < LinuxVersionCode(2,2,0)
3905                        ((driver_setup.irqm & 0x20) ? 0 : SA_INTERRUPT),
3906#else
3907                        0,
3908#endif
3909                        "ncr53c8xx", np)) {
3910#ifdef __sparc__
3911                printk(KERN_ERR "%s: request irq %s failure\n",
3912                        ncr_name(np), __irq_itoa(device->slot.irq));
3913#else
3914                printk(KERN_ERR "%s: request irq %d failure\n",
3915                        ncr_name(np), device->slot.irq);
3916#endif
3917                goto attach_error;
3918        }
3919
3920        np->irq = device->slot.irq;
3921
3922        /*
3923        **      Initialize the fixed part of the default ccb.
3924        */
3925        ncr_init_ccb(np, np->ccb);
3926
3927        /*
3928        **      After SCSI devices have been opened, we cannot
3929        **      reset the bus safely, so we do it here.
3930        **      Interrupt handler does the real work.
3931        **      Process the reset exception,
3932        **      if interrupts are not enabled yet.
3933        **      Then enable disconnects.
3934        */
3935        NCR_LOCK_NCB(np, flags);
3936        if (ncr_reset_scsi_bus(np, 0, driver_setup.settle_delay) != 0) {
3937                printk(KERN_ERR "%s: FATAL ERROR: CHECK SCSI BUS - CABLES, TERMINATION, DEVICE POWER etc.!\n", ncr_name(np));
3938
3939                NCR_UNLOCK_NCB(np, flags);
3940                goto attach_error;
3941        }
3942        ncr_exception (np);
3943
3944        np->disc = 1;
3945
3946        /*
3947        **      The middle-level SCSI driver does not
3948        **      wait for devices to settle.
3949        **      Wait synchronously if more than 2 seconds.
3950        */
3951        if (driver_setup.settle_delay > 2) {
3952                printk(KERN_INFO "%s: waiting %d seconds for scsi devices to settle...\n",
3953                        ncr_name(np), driver_setup.settle_delay);
3954                MDELAY (1000 * driver_setup.settle_delay);
3955        }
3956
3957        /*
3958        **      Now let the generic SCSI driver
3959        **      look for the SCSI devices on the bus ..
3960        */
3961
3962        /*
3963        **      start the timeout daemon
3964        */
3965        np->lasttime=0;
3966        ncr_timeout (np);
3967
3968        /*
3969        **  use SIMPLE TAG messages by default
3970        */
3971#ifdef SCSI_NCR_ALWAYS_SIMPLE_TAG
3972        np->order = M_SIMPLE_TAG;
3973#endif
3974
3975        /*
3976        **  Done.
3977        */
3978        if (!the_template) {
3979                the_template = instance->hostt;
3980                first_host = instance;
3981        }
3982
3983        NCR_UNLOCK_NCB(np, flags);
3984
3985        return 0;
3986
3987attach_error:
3988        if (!instance) return -1;
3989        printk(KERN_INFO "%s: detaching...\n", ncr_name(np));
3990        if (!np)
3991                goto unregister;
3992#ifndef SCSI_NCR_IOMAPPED
3993        if (np->vaddr) {
3994#ifdef DEBUG_NCR53C8XX
3995                printk(KERN_DEBUG "%s: releasing memory mapped IO region %lx[%d]\n", ncr_name(np), (u_long) np->vaddr, 128);
3996#endif
3997                unmap_pci_mem((vm_offset_t) np->vaddr, (u_long) 128);
3998        }
3999#endif /* !SCSI_NCR_IOMAPPED */
4000        if (np->base_io) {
4001#ifdef DEBUG_NCR53C8XX
4002                printk(KERN_DEBUG "%s: releasing IO region %x[%d]\n", ncr_name(np), np->base_io, 128);
4003#endif
4004#ifndef ENABLE_SCSI_ZALON
4005                release_region(np->base_io, 128);
4006#endif
4007        }
4008        if (np->irq) {
4009#ifdef DEBUG_NCR53C8XX
4010#ifdef __sparc__
4011        printk(KERN_INFO "%s: freeing irq %s\n", ncr_name(np),
4012               __irq_itoa(np->irq));
4013#else
4014        printk(KERN_INFO "%s: freeing irq %d\n", ncr_name(np), np->irq);
4015#endif
4016#endif
4017                free_irq(np->irq, np);
4018        }
4019        if (np->scripth0)
4020                m_free_dma(np->scripth0, sizeof(struct scripth), "SCRIPTH");
4021        if (np->script0)
4022                m_free_dma(np->script0, sizeof(struct script), "SCRIPT");
4023        if (np->ccb)
4024                m_free_dma(np->ccb, sizeof(struct ccb), "CCB");
4025        m_free_dma(np, sizeof(struct ncb), "NCB");
4026
4027unregister:
4028        scsi_unregister(instance);
4029
4030        return -1;
4031}
4032
4033
4034/*==========================================================
4035**
4036**
4037**      Done SCSI commands list management.
4038**
4039**      We donnot enter the scsi_done() callback immediately 
4040**      after a command has been seen as completed but we 
4041**      insert it into a list which is flushed outside any kind 
4042**      of driver critical section.
4043**      This allows to do minimal stuff under interrupt and 
4044**      inside critical sections and to also avoid locking up 
4045**      on recursive calls to driver entry points under SMP.
4046**      In fact, the only kernel point which is entered by the 
4047**      driver with a driver lock set is kmalloc(GFP_ATOMIC) 
4048**      that shall not reenter the driver under any circumstances,
4049**      AFAIK.
4050**
4051**==========================================================
4052*/
4053static inline void ncr_queue_done_cmd(ncb_p np, Scsi_Cmnd *cmd)
4054{
4055        unmap_scsi_data(np, cmd);
4056        cmd->host_scribble = (char *) np->done_list;
4057        np->done_list = cmd;
4058}
4059
4060static inline void ncr_flush_done_cmds(Scsi_Cmnd *lcmd)
4061{
4062        Scsi_Cmnd *cmd;
4063
4064        while (lcmd) {
4065                cmd = lcmd;
4066                lcmd = (Scsi_Cmnd *) cmd->host_scribble;
4067                cmd->scsi_done(cmd);
4068        }
4069}
4070
4071/*==========================================================
4072**
4073**
4074**      Prepare the next negotiation message for integrity check,
4075**      if needed.
4076**
4077**      Fill in the part of message buffer that contains the 
4078**      negotiation and the nego_status field of the CCB.
4079**      Returns the size of the message in bytes.
4080**
4081**
4082**==========================================================
4083*/
4084
4085#ifdef SCSI_NCR_INTEGRITY_CHECKING
4086static int ncr_ic_nego(ncb_p np, ccb_p cp, Scsi_Cmnd *cmd, u_char *msgptr)
4087{
4088        tcb_p tp = &np->target[cp->target];
4089        int msglen = 0;
4090        int nego = 0;
4091        u_char no_increase;
4092
4093        if (tp->inq_done) {
4094
4095                if (!tp->ic_maximums_set) {
4096                        tp->ic_maximums_set = 1;
4097
4098                        /* check target and host adapter capabilities */
4099                        if ( (tp->inq_byte7 & INQ7_WIDE16) && 
4100                                        np->maxwide && tp->usrwide ) 
4101                                tp->ic_max_width = 1;
4102                        else
4103                                tp->ic_max_width = 0;
4104
4105                        if ((tp->inq_byte7 & INQ7_SYNC) && tp->maxoffs) {
4106                                tp->ic_min_sync   = (tp->minsync < np->minsync) ?
4107                                                        np->minsync : tp->minsync;
4108                        }
4109                        else 
4110                                tp->ic_min_sync   = 255;
4111                        
4112                        tp->period   = 1;
4113                        tp->widedone = 1;
4114                }
4115
4116                if (DEBUG_FLAGS & DEBUG_IC) {
4117                        printk("%s: cmd->ic_nego %d, 1st byte 0x%2X\n",
4118                                ncr_name(np), cmd->ic_nego, cmd->cmnd[0]);
4119                }
4120
4121                /* First command from integrity check routine will request
4122                 * a PPR message.  Disable.
4123                 */
4124                if ((cmd->ic_nego & NS_PPR) == NS_PPR)
4125                        cmd->ic_nego &= ~NS_PPR;
4126                /* Previous command recorded a parity or an initiator
4127                 * detected error condition. Force bus to narrow for this
4128                 * target. Clear flag. Negotation on request sense.
4129                 * Note: kernel forces 2 bus resets :o( but clears itself out.
4130                 * Minor bug? in scsi_obsolete.c (ugly)
4131                 */
4132                if (np->check_integ_par) {
4133                        printk("%s: Parity Error. Target set to narrow.\n",
4134                                ncr_name(np));
4135                        tp->ic_max_width = 0;
4136                        tp->widedone = tp->period = 0;
4137                }
4138                
4139                /* In case of a bus reset, ncr_negotiate will reset 
4140                 * the flags tp->widedone and tp->period to 0, forcing
4141                 * a new negotiation. 
4142                 */
4143                no_increase = 0;
4144                if (tp->widedone == 0) {
4145                        cmd->ic_nego = NS_WIDE;
4146                        tp->widedone = 1;
4147                        no_increase = 1;
4148                }
4149                else if (tp->period == 0) {
4150                        cmd->ic_nego = NS_SYNC;
4151                        tp->period = 1;
4152                        no_increase = 1;
4153                }
4154                        
4155                switch (cmd->ic_nego) {
4156                case NS_WIDE:
4157                        /*
4158                        **      negotiate wide transfers ?
4159                        **      Do NOT negotiate if device only supports
4160                        **      narrow. 
4161                        */
4162                        if (tp->ic_max_width | np->check_integ_par) {
4163                                nego = NS_WIDE;
4164
4165                                msgptr[msglen++] = M_EXTENDED;
4166                                msgptr[msglen++] = 2;
4167                                msgptr[msglen++] = M_X_WIDE_REQ;
4168                                msgptr[msglen++] = cmd->ic_nego_width & tp->ic_max_width;
4169                        }
4170                        else
4171                                cmd->ic_nego_width &= tp->ic_max_width;
4172              
4173                        break;
4174
4175                case NS_SYNC:
4176                        /*
4177                        **      negotiate synchronous transfers?
4178                        **      Target must support sync transfers.
4179                        **
4180                        **      If period becomes longer than max, reset to async
4181                        */
4182
4183                        if (tp->inq_byte7 & INQ7_SYNC) {
4184
4185                                nego = NS_SYNC;
4186
4187                                msgptr[msglen++] = M_EXTENDED;
4188                                msgptr[msglen++] = 3;
4189                                msgptr[msglen++] = M_X_SYNC_REQ;
4190
4191                                switch (cmd->ic_nego_sync) {
4192                                case 2: /* increase the period */
4193                                        if (!no_increase) {
4194                                          if (tp->ic_min_sync <= 0x0A)
4195                                              tp->ic_min_sync = 0x0C;
4196                                          else if (tp->ic_min_sync <= 0x0C)
4197                                              tp->ic_min_sync = 0x19;
4198                                          else if (tp->ic_min_sync <= 0x19)
4199                                              tp->ic_min_sync *= 2;
4200                                          else {
4201                                                tp->ic_min_sync = 255;
4202                                                cmd->ic_nego_sync = 0;
4203                                                tp->maxoffs = 0;
4204                                           }
4205                                        }
4206                                        msgptr[msglen++] = tp->maxoffs?tp->ic_min_sync:0;
4207                                        msgptr[msglen++] = tp->maxoffs;
4208                                        break;
4209
4210                                case 1: /* nego. to maximum */
4211                                        msgptr[msglen++] = tp->maxoffs?tp->ic_min_sync:0;
4212                                        msgptr[msglen++] = tp->maxoffs;
4213                                        break;
4214
4215                                case 0: /* nego to async */
4216                                default:
4217                                        msgptr[msglen++] = 0;
4218                                        msgptr[msglen++] = 0;
4219                                        break;
4220                                };
4221                        }
4222                        else
4223                                cmd->ic_nego_sync = 0;
4224                        break;
4225
4226                case NS_NOCHANGE:
4227                default:
4228                        break;
4229                };
4230        };
4231
4232        cp->nego_status = nego;
4233        np->check_integ_par = 0;
4234
4235        if (nego) {
4236                tp->nego_cp = cp;
4237                if (DEBUG_FLAGS & DEBUG_NEGO) {
4238                        ncr_print_msg(cp, nego == NS_WIDE ?
4239                          "wide/narrow msgout": "sync/async msgout", msgptr);
4240                };
4241        };
4242
4243        return msglen;
4244}
4245#endif /* SCSI_NCR_INTEGRITY_CHECKING */
4246
4247/*==========================================================
4248**
4249**
4250**      Prepare the next negotiation message if needed.
4251**
4252**      Fill in the part of message buffer that contains the 
4253**      negotiation and the nego_status field of the CCB.
4254**      Returns the size of the message in bytes.
4255**
4256**
4257**==========================================================
4258*/
4259
4260
4261static int ncr_prepare_nego(ncb_p np, ccb_p cp, u_char *msgptr)
4262{
4263        tcb_p tp = &np->target[cp->target];
4264        int msglen = 0;
4265        int nego = 0;
4266
4267        if (tp->inq_done) {
4268
4269                /*
4270                **      negotiate wide transfers ?
4271                */
4272
4273                if (!tp->widedone) {
4274                        if (tp->inq_byte7 & INQ7_WIDE16) {
4275                                nego = NS_WIDE;
4276#ifdef SCSI_NCR_INTEGRITY_CHECKING
4277                                if (tp->ic_done)
4278                                         tp->usrwide &= tp->ic_max_width;
4279#endif
4280                        } else
4281                                tp->widedone=1;
4282
4283                };
4284
4285                /*
4286                **      negotiate synchronous transfers?
4287                */
4288
4289                if (!nego && !tp->period) {
4290                        if (tp->inq_byte7 & INQ7_SYNC) {
4291                                nego = NS_SYNC;
4292#ifdef SCSI_NCR_INTEGRITY_CHECKING
4293                                if ((tp->ic_done) &&
4294                                              (tp->minsync < tp->ic_min_sync))
4295                                         tp->minsync = tp->ic_min_sync;
4296#endif
4297                        } else {
4298                                tp->period  =0xffff;
4299                                PRINT_TARGET(np, cp->target);
4300                                printk ("target did not report SYNC.\n");
4301                        };
4302                };
4303        };
4304
4305        switch (nego) {
4306        case NS_SYNC:
4307                msgptr[msglen++] = M_EXTENDED;
4308                msgptr[msglen++] = 3;
4309                msgptr[msglen++] = M_X_SYNC_REQ;
4310                msgptr[msglen++] = tp->maxoffs ? tp->minsync : 0;
4311                msgptr[msglen++] = tp->maxoffs;
4312                break;
4313        case NS_WIDE:
4314                msgptr[msglen++] = M_EXTENDED;
4315                msgptr[msglen++] = 2;
4316                msgptr[msglen++] = M_X_WIDE_REQ;
4317                msgptr[msglen++] = tp->usrwide;
4318                break;
4319        };
4320
4321        cp->nego_status = nego;
4322
4323        if (nego) {
4324                tp->nego_cp = cp;
4325                if (DEBUG_FLAGS & DEBUG_NEGO) {
4326                        ncr_print_msg(cp, nego == NS_WIDE ?
4327                                          "wide msgout":"sync_msgout", msgptr);
4328                };
4329        };
4330
4331        return msglen;
4332}
4333
4334
4335
4336/*==========================================================
4337**
4338**
4339**      Start execution of a SCSI command.
4340**      This is called from the generic SCSI driver.
4341**
4342**
4343**==========================================================
4344*/
4345static int ncr_queue_command (ncb_p np, Scsi_Cmnd *cmd)
4346{
4347/*      Scsi_Device        *device    = cmd->device; */
4348        tcb_p tp                      = &np->target[cmd->target];
4349        lcb_p lp                      = tp->lp[cmd->lun];
4350        ccb_p cp;
4351
4352        int     segments;
4353        u_char  idmsg, *msgptr;
4354        u_int  msglen;
4355        int     direction;
4356        u_int32 lastp, goalp;
4357
4358        /*---------------------------------------------
4359        **
4360        **      Some shortcuts ...
4361        **
4362        **---------------------------------------------
4363        */
4364        if ((cmd->target == np->myaddr    ) ||
4365                (cmd->target >= MAX_TARGET) ||
4366                (cmd->lun    >= MAX_LUN   )) {
4367                return(DID_BAD_TARGET);
4368        }
4369
4370        /*---------------------------------------------
4371        **
4372        **      Complete the 1st TEST UNIT READY command
4373        **      with error condition if the device is 
4374        **      flagged NOSCAN, in order to speed up 
4375        **      the boot.
4376        **
4377        **---------------------------------------------
4378        */
4379        if ((cmd->cmnd[0] == 0 || cmd->cmnd[0] == 0x12) && 
4380            (tp->usrflag & UF_NOSCAN)) {
4381                tp->usrflag &= ~UF_NOSCAN;
4382                return DID_BAD_TARGET;
4383        }
4384
4385        if (DEBUG_FLAGS & DEBUG_TINY) {
4386                PRINT_ADDR(cmd);
4387                printk ("CMD=%x ", cmd->cmnd[0]);
4388        }
4389
4390        /*---------------------------------------------------
4391        **
4392        **      Assign a ccb / bind cmd.
4393        **      If resetting, shorten settle_time if necessary
4394        **      in order to avoid spurious timeouts.
4395        **      If resetting or no free ccb,
4396        **      insert cmd into the waiting list.
4397        **
4398        **----------------------------------------------------
4399        */
4400        if (np->settle_time && cmd->timeout_per_command >= HZ) {
4401                u_long tlimit = ktime_get(cmd->timeout_per_command - HZ);
4402                if (ktime_dif(np->settle_time, tlimit) > 0)
4403                        np->settle_time = tlimit;
4404        }
4405
4406        if (np->settle_time || !(cp=ncr_get_ccb (np, cmd->target, cmd->lun))) {
4407                insert_into_waiting_list(np, cmd);
4408                return(DID_OK);
4409        }
4410        cp->cmd = cmd;
4411
4412        /*---------------------------------------------------
4413        **
4414        **      Enable tagged queue if asked by scsi ioctl
4415        **
4416        **----------------------------------------------------
4417        */
4418#if 0   /* This stuff was only useful for linux-1.2.13 */
4419        if (lp && !lp->numtags && cmd->device && cmd->device->tagged_queue) {
4420                lp->numtags = tp->usrtags;
4421                ncr_setup_tags (np, cmd->target, cmd->lun);
4422        }
4423#endif
4424
4425        /*----------------------------------------------------
4426        **
4427        **      Build the identify / tag / sdtr message
4428        **
4429        **----------------------------------------------------
4430        */
4431
4432        idmsg = M_IDENTIFY | cmd->lun;
4433
4434        if (cp ->tag != NO_TAG ||
4435                (cp != np->ccb && np->disc && !(tp->usrflag & UF_NODISC)))
4436                idmsg |= 0x40;
4437
4438        msgptr = cp->scsi_smsg;
4439        msglen = 0;
4440        msgptr[msglen++] = idmsg;
4441
4442        if (cp->tag != NO_TAG) {
4443                char order = np->order;
4444
4445                /*
4446                **      Force ordered tag if necessary to avoid timeouts 
4447                **      and to preserve interactivity.
4448                */
4449                if (lp && ktime_exp(lp->tags_stime)) {
4450                        if (lp->tags_smap) {
4451                                order = M_ORDERED_TAG;
4452                                if ((DEBUG_FLAGS & DEBUG_TAGS)||bootverbose>2){ 
4453                                        PRINT_ADDR(cmd);
4454                                        printk("ordered tag forced.\n");
4455                                }
4456                        }
4457                        lp->tags_stime = ktime_get(3*HZ);
4458                        lp->tags_smap = lp->tags_umap;
4459                }
4460
4461                if (order == 0) {
4462                        /*
4463                        **      Ordered write ops, unordered read ops.
4464                        */
4465                        switch (cmd->cmnd[0]) {
4466                        case 0x08:  /* READ_SMALL (6) */
4467                        case 0x28:  /* READ_BIG  (10) */
4468                        case 0xa8:  /* READ_HUGE (12) */
4469                                order = M_SIMPLE_TAG;
4470                                break;
4471                        default:
4472                                order = M_ORDERED_TAG;
4473                        }
4474                }
4475                msgptr[msglen++] = order;
4476                /*
4477                **      Actual tags are numbered 1,3,5,..2*MAXTAGS+1,
4478                **      since we may have to deal with devices that have 
4479                **      problems with #TAG 0 or too great #TAG numbers.
4480                */
4481                msgptr[msglen++] = (cp->tag << 1) + 1;
4482        }
4483
4484        /*----------------------------------------------------
4485        **
4486        **      Build the data descriptors
4487        **
4488        **----------------------------------------------------
4489        */
4490
4491        direction = scsi_data_direction(cmd);
4492        if (direction != SCSI_DATA_NONE) {
4493                segments = ncr_scatter (np, cp, cp->cmd);
4494                if (segments < 0) {
4495                        ncr_free_ccb(np, cp);
4496                        return(DID_ERROR);
4497                }
4498        }
4499        else {
4500                cp->data_len = 0;
4501                segments = 0;
4502        }
4503
4504        /*---------------------------------------------------
4505        **
4506        **      negotiation required?
4507        **
4508        **      (nego_status is filled by ncr_prepare_nego())
4509        **
4510        **---------------------------------------------------
4511        */
4512
4513        cp->nego_status = 0;
4514
4515#ifdef SCSI_NCR_INTEGRITY_CHECKING
4516        if ((np->check_integrity && tp->ic_done) || !np->check_integrity) {
4517                 if ((!tp->widedone || !tp->period) && !tp->nego_cp && lp) {
4518                        msglen += ncr_prepare_nego (np, cp, msgptr + msglen);
4519                 }
4520        }
4521        else if (np->check_integrity && (cmd->ic_in_progress)) { 
4522                msglen += ncr_ic_nego (np, cp, cmd, msgptr + msglen);
4523        }
4524        else if (np->check_integrity && cmd->ic_complete) {
4525                /*
4526                 * Midlayer signal to the driver that all of the scsi commands
4527                 * for the integrity check have completed. Save the negotiated
4528                 * parameters (extracted from sval and wval). 
4529                 */ 
4530
4531                {
4532                        u_char idiv;
4533                        idiv = (tp->wval>>4) & 0x07;
4534                        if ((tp->sval&0x1f) && idiv )
4535                                tp->period = (((tp->sval>>5)+4)  
4536                                                *div_10M[idiv-1])/np->clock_khz;
4537                        else
4538                                tp->period = 0xffff;
4539                }
4540                /*
4541                 * tp->period contains 10 times the transfer period, 
4542                 * which itself is 4 * the requested negotiation rate.
4543                 */
4544                if      (tp->period <= 250)     tp->ic_min_sync = 10;
4545                else if (tp->period <= 303)     tp->ic_min_sync = 11;
4546                else if (tp->period <= 500)     tp->ic_min_sync = 12;
4547                else                            
4548                                tp->ic_min_sync = (tp->period + 40 - 1) / 40;
4549
4550
4551                /*
4552                 * Negotiation for this target it complete.
4553                 */
4554                tp->ic_max_width =  (tp->wval & EWS) ? 1: 0;
4555                tp->ic_done = 1;
4556                tp->widedone = 1;
4557
4558                printk("%s: Integrity Check Complete: \n", ncr_name(np)); 
4559
4560                printk("%s: %s %s SCSI", ncr_name(np), 
4561                                (tp->sval&0x1f)?"SYNC":"ASYNC",
4562                                tp->ic_max_width?"WIDE":"NARROW");
4563
4564                if (tp->sval&0x1f) {
4565                        u_long mbs = 10000 * (tp->ic_max_width + 1);
4566
4567                        printk(" %d.%d  MB/s", 
4568                                (int) (mbs / tp->period), (int) (mbs % tp->period));
4569
4570                        printk(" (%d ns, %d offset)\n", 
4571                                  tp->period/10, tp->sval&0x1f);
4572                }
4573                else
4574                        printk(" %d MB/s. \n ", (tp->ic_max_width+1)*5);
4575        }
4576#else
4577        if ((!tp->widedone || !tp->period) && !tp->nego_cp && lp) {
4578                msglen += ncr_prepare_nego (np, cp, msgptr + msglen);
4579        }
4580#endif /* SCSI_NCR_INTEGRITY_CHECKING */
4581
4582        /*----------------------------------------------------
4583        **
4584        **      Determine xfer direction.
4585        **
4586        **----------------------------------------------------
4587        */
4588        if (!cp->data_len)
4589                direction = SCSI_DATA_NONE;
4590
4591        /*
4592        **      If data direction is UNKNOWN, speculate DATA_READ 
4593        **      but prepare alternate pointers for WRITE in case 
4594        **      of our speculation will be just wrong.
4595        **      SCRIPTS will swap values if needed.
4596        */
4597        switch(direction) {
4598        case SCSI_DATA_UNKNOWN:
4599        case SCSI_DATA_WRITE:
4600                goalp = NCB_SCRIPT_PHYS (np, data_out2) + 8;
4601                if (segments <= MAX_SCATTERL)
4602                        lastp = goalp - 8 - (segments * 16);
4603                else {
4604                        lastp = NCB_SCRIPTH_PHYS (np, hdata_out2);
4605                        lastp -= (segments - MAX_SCATTERL) * 16;
4606                }
4607                if (direction != SCSI_DATA_UNKNOWN)
4608                        break;
4609                cp->phys.header.wgoalp  = cpu_to_scr(goalp);
4610                cp->phys.header.wlastp  = cpu_to_scr(lastp);
4611                /* fall through */
4612        case SCSI_DATA_READ:
4613                goalp = NCB_SCRIPT_PHYS (np, data_in2) + 8;
4614                if (segments <= MAX_SCATTERL)
4615                        lastp = goalp - 8 - (segments * 16);
4616                else {
4617                        lastp = NCB_SCRIPTH_PHYS (np, hdata_in2);
4618                        lastp -= (segments - MAX_SCATTERL) * 16;
4619                }
4620                break;
4621        default:
4622        case SCSI_DATA_NONE:
4623                lastp = goalp = NCB_SCRIPT_PHYS (np, no_data);
4624                break;
4625        }
4626
4627        /*
4628        **      Set all pointers values needed by SCRIPTS.
4629        **      If direction is unknown, start at data_io.
4630        */
4631        cp->phys.header.lastp = cpu_to_scr(lastp);
4632        cp->phys.header.goalp = cpu_to_scr(goalp);
4633
4634        if (direction == SCSI_DATA_UNKNOWN)
4635                cp->phys.header.savep = 
4636                        cpu_to_scr(NCB_SCRIPTH_PHYS (np, data_io));
4637        else
4638                cp->phys.header.savep= cpu_to_scr(lastp);
4639
4640        /*
4641        **      Save the initial data pointer in order to be able 
4642        **      to redo the command.
4643        */
4644        cp->startp = cp->phys.header.savep;
4645
4646        /*----------------------------------------------------
4647        **
4648        **      fill in ccb
4649        **
4650        **----------------------------------------------------
4651        **
4652        **
4653        **      physical -> virtual backlink
4654        **      Generic SCSI command
4655        */
4656
4657        /*
4658        **      Startqueue
4659        */
4660        cp->start.schedule.l_paddr   = cpu_to_scr(NCB_SCRIPT_PHYS (np, select));
4661        cp->restart.schedule.l_paddr = cpu_to_scr(NCB_SCRIPT_PHYS (np, resel_dsa));
4662        /*
4663        **      select
4664        */
4665        cp->phys.select.sel_id          = cmd->target;
4666        cp->phys.select.sel_scntl3      = tp->wval;
4667        cp->phys.select.sel_sxfer       = tp->sval;
4668        /*
4669        **      message
4670        */
4671        cp->phys.smsg.addr              = cpu_to_scr(CCB_PHYS (cp, scsi_smsg));
4672        cp->phys.smsg.size              = cpu_to_scr(msglen);
4673
4674        /*
4675        **      command
4676        */
4677        memcpy(cp->cdb_buf, cmd->cmnd, MIN(cmd->cmd_len, sizeof(cp->cdb_buf)));
4678        cp->phys.cmd.addr               = cpu_to_scr(CCB_PHYS (cp, cdb_buf[0]));
4679        cp->phys.cmd.size               = cpu_to_scr(cmd->cmd_len);
4680
4681        /*
4682        **      status
4683        */
4684        cp->actualquirks                = tp->quirks;
4685        cp->host_status                 = cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
4686        cp->scsi_status                 = S_ILLEGAL;
4687        cp->parity_status               = 0;
4688
4689        cp->xerr_status                 = XE_OK;
4690#if 0
4691        cp->sync_status                 = tp->sval;
4692        cp->wide_status                 = tp->wval;
4693#endif
4694
4695        /*----------------------------------------------------
4696        **
4697        **      Critical region: start this job.
4698        **
4699        **----------------------------------------------------
4700        */
4701
4702        /*
4703        **      activate this job.
4704        */
4705        cp->magic               = CCB_MAGIC;
4706
4707        /*
4708        **      insert next CCBs into start queue.
4709        **      2 max at a time is enough to flush the CCB wait queue.
4710        */
4711        cp->auto_sense = 0;
4712        if (lp)
4713                ncr_start_next_ccb(np, lp, 2);
4714        else
4715                ncr_put_start_queue(np, cp);
4716
4717        /*
4718        **      Command is successfully queued.
4719        */
4720
4721        return(DID_OK);
4722}
4723
4724
4725/*==========================================================
4726**
4727**
4728**      Insert a CCB into the start queue and wake up the 
4729**      SCRIPTS processor.
4730**
4731**
4732**==========================================================
4733*/
4734
4735static void ncr_start_next_ccb(ncb_p np, lcb_p lp, int maxn)
4736{
4737        XPT_QUEHEAD *qp;
4738        ccb_p cp;
4739
4740        if (lp->held_ccb)
4741                return;
4742
4743        while (maxn-- && lp->queuedccbs < lp->queuedepth) {
4744                qp = xpt_remque_head(&lp->wait_ccbq);
4745                if (!qp)
4746                        break;
4747                ++lp->queuedccbs;
4748                cp = xpt_que_entry(qp, struct ccb, link_ccbq);
4749                xpt_insque_tail(qp, &lp->busy_ccbq);
4750                lp->jump_ccb[cp->tag == NO_TAG ? 0 : cp->tag] =
4751                        cpu_to_scr(CCB_PHYS (cp, restart));
4752                ncr_put_start_queue(np, cp);
4753        }
4754}
4755
4756static void ncr_put_start_queue(ncb_p np, ccb_p cp)
4757{
4758        u_short qidx;
4759
4760        /*
4761        **      insert into start queue.
4762        */
4763        if (!np->squeueput) np->squeueput = 1;
4764        qidx = np->squeueput + 2;
4765        if (qidx >= MAX_START + MAX_START) qidx = 1;
4766
4767        np->scripth->tryloop [qidx] = cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
4768        MEMORY_BARRIER();
4769        np->scripth->tryloop [np->squeueput] = cpu_to_scr(CCB_PHYS (cp, start));
4770
4771        np->squeueput = qidx;
4772        ++np->queuedccbs;
4773        cp->queued = 1;
4774
4775        if (DEBUG_FLAGS & DEBUG_QUEUE)
4776                printk ("%s: queuepos=%d.\n", ncr_name (np), np->squeueput);
4777
4778        /*
4779        **      Script processor may be waiting for reselect.
4780        **      Wake it up.
4781        */
4782        MEMORY_BARRIER();
4783        OUTB (nc_istat, SIGP);
4784}
4785
4786
4787/*==========================================================
4788**
4789**
4790**      Start reset process.
4791**      If reset in progress do nothing.
4792**      The interrupt handler will reinitialize the chip.
4793**      The timeout handler will wait for settle_time before 
4794**      clearing it and so resuming command processing.
4795**
4796**
4797**==========================================================
4798*/
4799static void ncr_start_reset(ncb_p np)
4800{
4801        if (!np->settle_time) {
4802                (void) ncr_reset_scsi_bus(np, 1, driver_setup.settle_delay);
4803        }
4804 }
4805 
4806static int ncr_reset_scsi_bus(ncb_p np, int enab_int, int settle_delay)
4807{
4808        u_int32 term;
4809        int retv = 0;
4810
4811        np->settle_time = ktime_get(settle_delay * HZ);
4812
4813        if (bootverbose > 1)
4814                printk("%s: resetting, "
4815                        "command processing suspended for %d seconds\n",
4816                        ncr_name(np), settle_delay);
4817
4818        ncr_chip_reset(np, 100);
4819        UDELAY (2000);  /* The 895 needs time for the bus mode to settle */
4820        if (enab_int)
4821                OUTW (nc_sien, RST);
4822        /*
4823        **      Enable Tolerant, reset IRQD if present and 
4824        **      properly set IRQ mode, prior to resetting the bus.
4825        */
4826        OUTB (nc_stest3, TE);
4827        if (np->device_id != PSEUDO_ZALON_720_ID)
4828                OUTB (nc_dcntl, (np->rv_dcntl & IRQM));
4829        OUTB (nc_scntl1, CRST);
4830        UDELAY (200);
4831
4832        if (!driver_setup.bus_check)
4833                goto out;
4834        /*
4835        **      Check for no terminators or SCSI bus shorts to ground.
4836        **      Read SCSI data bus, data parity bits and control signals.
4837        **      We are expecting RESET to be TRUE and other signals to be 
4838        **      FALSE.
4839        */
4840
4841        term =  INB(nc_sstat0);
4842        term =  ((term & 2) << 7) + ((term & 1) << 17); /* rst sdp0 */
4843        term |= ((INB(nc_sstat2) & 0x01) << 26) |       /* sdp1     */
4844                ((INW(nc_sbdl) & 0xff)   << 9)  |       /* d7-0     */
4845                ((INW(nc_sbdl) & 0xff00) << 10) |       /* d15-8    */
4846                INB(nc_sbcl);   /* req ack bsy sel atn msg cd io    */
4847
4848        if (!(np->features & FE_WIDE))
4849                term &= 0x3ffff;
4850
4851        if (term != (2<<7)) {
4852                printk("%s: suspicious SCSI data while resetting the BUS.\n",
4853                        ncr_name(np));
4854                printk("%s: %sdp0,d7-0,rst,req,ack,bsy,sel,atn,msg,c/d,i/o = "
4855                        "0x%lx, expecting 0x%lx\n",
4856                        ncr_name(np),
4857                        (np->features & FE_WIDE) ? "dp1,d15-8," : "",
4858                        (u_long)term, (u_long)(2<<7));
4859                if (driver_setup.bus_check == 1)
4860                        retv = 1;
4861        }
4862out:
4863        OUTB (nc_scntl1, 0);
4864        return retv;
4865}
4866
4867/*==========================================================
4868**
4869**
4870**      Reset the SCSI BUS.
4871**      This is called from the generic SCSI driver.
4872**
4873**
4874**==========================================================
4875*/
4876static int ncr_reset_bus (ncb_p np, Scsi_Cmnd *cmd, int sync_reset)
4877{
4878/*      Scsi_Device        *device    = cmd->device; */
4879        ccb_p cp;
4880        int found;
4881
4882/*
4883 * Return immediately if reset is in progress.
4884 */
4885        if (np->settle_time) {
4886                return SCSI_RESET_PUNT;
4887        }
4888/*
4889 * Start the reset process.
4890 * The script processor is then assumed to be stopped.
4891 * Commands will now be queued in the waiting list until a settle 
4892 * delay of 2 seconds will be completed.
4893 */
4894        ncr_start_reset(np);
4895/*
4896 * First, look in the wakeup list
4897 */
4898        for (found=0, cp=np->ccb; cp; cp=cp->link_ccb) {
4899                /*
4900                **      look for the ccb of this command.
4901                */
4902                if (cp->host_status == HS_IDLE) continue;
4903                if (cp->cmd == cmd) {
4904                        found = 1;
4905                        break;
4906                }
4907        }
4908/*
4909 * Then, look in the waiting list
4910 */
4911        if (!found && retrieve_from_waiting_list(0, np, cmd))
4912                found = 1;
4913/*
4914 * Wake-up all awaiting commands with DID_RESET.
4915 */
4916        reset_waiting_list(np);
4917/*
4918 * Wake-up all pending commands with HS_RESET -> DID_RESET.
4919 */
4920        ncr_wakeup(np, HS_RESET);
4921/*
4922 * If the involved command was not in a driver queue, and the 
4923 * scsi driver told us reset is synchronous, and the command is not 
4924 * currently in the waiting list, complete it with DID_RESET status,
4925 * in order to keep it alive.
4926 */
4927        if (!found && sync_reset && !retrieve_from_waiting_list(0, np, cmd)) {
4928                cmd->result = ScsiResult(DID_RESET, 0);
4929                ncr_queue_done_cmd(np, cmd);
4930        }
4931
4932        return SCSI_RESET_SUCCESS;
4933}
4934
4935/*==========================================================
4936**
4937**
4938**      Abort an SCSI command.
4939**      This is called from the generic SCSI driver.
4940**
4941**
4942**==========================================================
4943*/
4944static int ncr_abort_command (ncb_p np, Scsi_Cmnd *cmd)
4945{
4946/*      Scsi_Device        *device    = cmd->device; */
4947        ccb_p cp;
4948        int found;
4949        int retv;
4950
4951/*
4952 * First, look for the scsi command in the waiting list
4953 */
4954        if (remove_from_waiting_list(np, cmd)) {
4955                cmd->result = ScsiResult(DID_ABORT, 0);
4956                ncr_queue_done_cmd(np, cmd);
4957                return SCSI_ABORT_SUCCESS;
4958        }
4959
4960/*
4961 * Then, look in the wakeup list
4962 */
4963        for (found=0, cp=np->ccb; cp; cp=cp->link_ccb) {
4964                /*
4965                **      look for the ccb of this command.
4966                */
4967                if (cp->host_status == HS_IDLE) continue;
4968                if (cp->cmd == cmd) {
4969                        found = 1;
4970                        break;
4971                }
4972        }
4973
4974        if (!found) {
4975                return SCSI_ABORT_NOT_RUNNING;
4976        }
4977
4978        if (np->settle_time) {
4979                return SCSI_ABORT_SNOOZE;
4980        }
4981
4982        /*
4983        **      If the CCB is active, patch schedule jumps for the 
4984        **      script to abort the command.
4985        */
4986
4987        switch(cp->host_status) {
4988        case HS_BUSY:
4989        case HS_NEGOTIATE:
4990                printk ("%s: abort ccb=%p (cancel)\n", ncr_name (np), cp);
4991                        cp->start.schedule.l_paddr =
4992                                cpu_to_scr(NCB_SCRIPTH_PHYS (np, cancel));
4993                retv = SCSI_ABORT_PENDING;
4994                break;
4995        case HS_DISCONNECT:
4996                cp->restart.schedule.l_paddr =
4997                                cpu_to_scr(NCB_SCRIPTH_PHYS (np, abort));
4998                retv = SCSI_ABORT_PENDING;
4999                break;
5000        default:
5001                retv = SCSI_ABORT_NOT_RUNNING;
5002                break;
5003
5004        }
5005
5006        /*
5007        **      If there are no requests, the script
5008        **      processor will sleep on SEL_WAIT_RESEL.
5009        **      Let's wake it up, since it may have to work.
5010        */
5011        OUTB (nc_istat, SIGP);
5012
5013        return retv;
5014}
5015
5016/*==========================================================
5017**
5018**      Linux release module stuff.
5019**
5020**      Called before unloading the module
5021**      Detach the host.
5022**      We have to free resources and halt the NCR chip
5023**
5024**==========================================================
5025*/
5026
5027#ifdef MODULE
5028static int ncr_detach(ncb_p np)
5029{
5030        ccb_p cp;
5031        tcb_p tp;
5032        lcb_p lp;
5033        int target, lun;
5034        int i;
5035        char inst_name[16];
5036
5037        /* Local copy so we don't access np after freeing it! */
5038        strncpy(inst_name, ncr_name(np), 16);
5039
5040        printk("%s: releasing host resources\n", ncr_name(np));
5041
5042/*
5043**      Stop the ncr_timeout process
5044**      Set release_stage to 1 and wait that ncr_timeout() set it to 2.
5045*/
5046
5047#ifdef DEBUG_NCR53C8XX
5048        printk("%s: stopping the timer\n", ncr_name(np));
5049#endif
5050        np->release_stage = 1;
5051        for (i = 50 ; i && np->release_stage != 2 ; i--) MDELAY (100);
5052        if (np->release_stage != 2)
5053                printk("%s: the timer seems to be already stopped\n", ncr_name(np));
5054        else np->release_stage = 2;
5055
5056/*
5057**      Disable chip interrupts
5058*/
5059
5060#ifdef DEBUG_NCR53C8XX
5061        printk("%s: disabling chip interrupts\n", ncr_name(np));
5062#endif
5063        OUTW (nc_sien , 0);
5064        OUTB (nc_dien , 0);
5065
5066/*
5067**      Free irq
5068*/
5069
5070#ifdef DEBUG_NCR53C8XX
5071#ifdef __sparc__
5072        printk("%s: freeing irq %s\n", ncr_name(np), __irq_itoa(np->irq));
5073#else
5074        printk("%s: freeing irq %d\n", ncr_name(np), np->irq);
5075#endif
5076#endif
5077        free_irq(np->irq, np);
5078
5079        /*
5080        **      Reset NCR chip
5081        **      Restore bios setting for automatic clock detection.
5082        */
5083
5084        printk("%s: resetting chip\n", ncr_name(np));
5085        ncr_chip_reset(np, 100);
5086
5087        OUTB(nc_dmode,  np->sv_dmode);
5088        OUTB(nc_dcntl,  np->sv_dcntl);
5089        OUTB(nc_ctest0, np->sv_ctest0);
5090        OUTB(nc_ctest3, np->sv_ctest3);
5091        OUTB(nc_ctest4, np->sv_ctest4);
5092        OUTB(nc_ctest5, np->sv_ctest5);
5093        OUTB(nc_gpcntl, np->sv_gpcntl);
5094        OUTB(nc_stest2, np->sv_stest2);
5095
5096        ncr_selectclock(np, np->sv_scntl3);
5097
5098        /*
5099        **      Release Memory mapped IO region and IO mapped region
5100        */
5101
5102#ifndef SCSI_NCR_IOMAPPED
5103#ifdef DEBUG_NCR53C8XX
5104        printk("%s: releasing memory mapped IO region %lx[%d]\n", ncr_name(np), (u_long) np->vaddr, 128);
5105#endif
5106        unmap_pci_mem((vm_offset_t) np->vaddr, (u_long) 128);
5107#endif /* !SCSI_NCR_IOMAPPED */
5108
5109#ifdef DEBUG_NCR53C8XX
5110        printk("%s: releasing IO region %x[%d]\n", ncr_name(np), np->base_io, 128);
5111#endif
5112#ifndef ENABLE_SCSI_ZALON
5113        release_region(np->base_io, 128);
5114#endif
5115
5116        /*
5117        **      Free allocated ccb(s)
5118        */
5119
5120        while ((cp=np->ccb->link_ccb) != NULL) {
5121                np->ccb->link_ccb = cp->link_ccb;
5122                if (cp->host_status) {
5123                printk("%s: shall free an active ccb (host_status=%d)\n",
5124                        ncr_name(np), cp->host_status);
5125                }
5126#ifdef DEBUG_NCR53C8XX
5127        printk("%s: freeing ccb (%lx)\n", ncr_name(np), (u_long) cp);
5128#endif
5129                m_free_dma(cp, sizeof(*cp), "CCB");
5130        }
5131
5132        /*
5133        **      Free allocated tp(s)
5134        */
5135
5136        for (target = 0; target < MAX_TARGET ; target++) {
5137                tp=&np->target[target];
5138                for (lun = 0 ; lun < MAX_LUN ; lun++) {
5139                        lp = tp->lp[lun];
5140                        if (lp) {
5141#ifdef DEBUG_NCR53C8XX
5142        printk("%s: freeing lp (%lx)\n", ncr_name(np), (u_long) lp);
5143#endif
5144                                if (lp->jump_ccb != &lp->jump_ccb_0)
5145                                        m_free_dma(lp->jump_ccb,256,"JUMP_CCB");
5146                                m_free_dma(lp, sizeof(*lp), "LCB");
5147                        }
5148                }
5149        }
5150
5151        if (np->scripth0)
5152                m_free_dma(np->scripth0, sizeof(struct scripth), "SCRIPTH");
5153        if (np->script0)
5154                m_free_dma(np->script0, sizeof(struct script), "SCRIPT");
5155        if (np->ccb)
5156                m_free_dma(np->ccb, sizeof(struct ccb), "CCB");
5157        m_free_dma(np, sizeof(struct ncb), "NCB");
5158
5159        printk("%s: host resources successfully released\n", inst_name);
5160
5161        return 1;
5162}
5163#endif
5164
5165/*==========================================================
5166**
5167**
5168**      Complete execution of a SCSI command.
5169**      Signal completion to the generic SCSI driver.
5170**
5171**
5172**==========================================================
5173*/
5174
5175void ncr_complete (ncb_p np, ccb_p cp)
5176{
5177        Scsi_Cmnd *cmd;
5178        tcb_p tp;
5179        lcb_p lp;
5180
5181        /*
5182        **      Sanity check
5183        */
5184
5185        if (!cp || cp->magic != CCB_MAGIC || !cp->cmd)
5186                return;
5187
5188        /*
5189        **      Print minimal debug information.
5190        */
5191
5192        if (DEBUG_FLAGS & DEBUG_TINY)
5193                printk ("CCB=%lx STAT=%x/%x\n", (unsigned long)cp,
5194                        cp->host_status,cp->scsi_status);
5195
5196        /*
5197        **      Get command, target and lun pointers.
5198        */
5199
5200        cmd = cp->cmd;
5201        cp->cmd = NULL;
5202        tp = &np->target[cmd->target];
5203        lp = tp->lp[cmd->lun];
5204
5205        /*
5206        **      We donnot queue more than 1 ccb per target 
5207        **      with negotiation at any time. If this ccb was 
5208        **      used for negotiation, clear this info in the tcb.
5209        */
5210
5211        if (cp == tp->nego_cp)
5212                tp->nego_cp = 0;
5213
5214        /*
5215        **      If auto-sense performed, change scsi status.
5216        */
5217        if (cp->auto_sense) {
5218                cp->scsi_status = cp->auto_sense;
5219        }
5220
5221        /*
5222        **      If we were recovering from queue full or performing 
5223        **      auto-sense, requeue skipped CCBs to the wait queue.
5224        */
5225
5226        if (lp && lp->held_ccb) {
5227                if (cp == lp->held_ccb) {
5228                        xpt_que_splice(&lp->skip_ccbq, &lp->wait_ccbq);
5229                        xpt_que_init(&lp->skip_ccbq);
5230                        lp->held_ccb = 0;
5231                }
5232        }
5233
5234        /*
5235        **      Check for parity errors.
5236        */
5237
5238        if (cp->parity_status > 1) {
5239                PRINT_ADDR(cmd);
5240                printk ("%d parity error(s).\n",cp->parity_status);
5241        }
5242
5243        /*
5244        **      Check for extended errors.
5245        */
5246
5247        if (cp->xerr_status != XE_OK) {
5248                PRINT_ADDR(cmd);
5249                switch (cp->xerr_status) {
5250                case XE_EXTRA_DATA:
5251                        printk ("extraneous data discarded.\n");
5252                        break;
5253                case XE_BAD_PHASE:
5254                        printk ("illegal scsi phase (4/5).\n");
5255                        break;
5256                default:
5257                        printk ("extended error %d.\n", cp->xerr_status);
5258                        break;
5259                }
5260                if (cp->host_status==HS_COMPLETE)
5261                        cp->host_status = HS_FAIL;
5262        }
5263
5264        /*
5265        **      Print out any error for debugging purpose.
5266        */
5267        if (DEBUG_FLAGS & (DEBUG_RESULT|DEBUG_TINY)) {
5268                if (cp->host_status!=HS_COMPLETE || cp->scsi_status!=S_GOOD) {
5269                        PRINT_ADDR(cmd);
5270                        printk ("ERROR: cmd=%x host_status=%x scsi_status=%x\n",
5271                                cmd->cmnd[0], cp->host_status, cp->scsi_status);
5272                }
5273        }
5274
5275        /*
5276        **      Check the status.
5277        */
5278        if (   (cp->host_status == HS_COMPLETE)
5279                && (cp->scsi_status == S_GOOD ||
5280                    cp->scsi_status == S_COND_MET)) {
5281                /*
5282                **      All went well (GOOD status).
5283                **      CONDITION MET status is returned on 
5284                **      `Pre-Fetch' or `Search data' success.
5285                */
5286                cmd->result = ScsiResult(DID_OK, cp->scsi_status);
5287
5288                /*
5289                **      @RESID@
5290                **      Could dig out the correct value for resid,
5291                **      but it would be quite complicated.
5292                */
5293                /* if (cp->phys.header.lastp != cp->phys.header.goalp) */
5294
5295                /*
5296                **      Allocate the lcb if not yet.
5297                */
5298                if (!lp)
5299                        ncr_alloc_lcb (np, cmd->target, cmd->lun);
5300
5301                /*
5302                **      On standard INQUIRY response (EVPD and CmDt 
5303                **      not set), setup logical unit according to 
5304                **      announced capabilities (we need the 1rst 7 bytes).
5305                */
5306                if (cmd->cmnd[0] == 0x12 && !(cmd->cmnd[1] & 0x3) &&
5307                    cmd->cmnd[4] >= 7 && !cmd->use_sg) {
5308                        sync_scsi_data(np, cmd);        /* SYNC the data */
5309                        ncr_setup_lcb (np, cmd->target, cmd->lun,
5310                                       (char *) cmd->request_buffer);
5311                }
5312
5313                tp->bytes     += cp->data_len;
5314                tp->transfers ++;
5315
5316                /*
5317                **      If tags was reduced due to queue full,
5318                **      increase tags if 1000 good status received.
5319                */
5320                if (lp && lp->usetags && lp->numtags < lp->maxtags) {
5321                        ++lp->num_good;
5322                        if (lp->num_good >= 1000) {
5323                                lp->num_good = 0;
5324                                ++lp->numtags;
5325                                ncr_setup_tags (np, cmd->target, cmd->lun);
5326                        }
5327                }
5328        } else if ((cp->host_status == HS_COMPLETE)
5329                && (cp->scsi_status == S_CHECK_COND)) {
5330                /*
5331                **   Check condition code
5332                */
5333                cmd->result = ScsiResult(DID_OK, S_CHECK_COND);
5334
5335                /*
5336                **      Copy back sense data to caller's buffer.
5337                */
5338                memcpy(cmd->sense_buffer, cp->sense_buf,
5339                       MIN(sizeof(cmd->sense_buffer), sizeof(cp->sense_buf)));
5340
5341                if (DEBUG_FLAGS & (DEBUG_RESULT|DEBUG_TINY)) {
5342                        u_char * p = (u_char*) & cmd->sense_buffer;
5343                        int i;
5344                        PRINT_ADDR(cmd);
5345                        printk ("sense data:");
5346                        for (i=0; i<14; i++) printk (" %x", *p++);
5347                        printk (".\n");
5348                }
5349        } else if ((cp->host_status == HS_COMPLETE)
5350                && (cp->scsi_status == S_CONFLICT)) {
5351                /*
5352                **   Reservation Conflict condition code
5353                */
5354                cmd->result = ScsiResult(DID_OK, S_CONFLICT);
5355        
5356        } else if ((cp->host_status == HS_COMPLETE)
5357                && (cp->scsi_status == S_BUSY ||
5358                    cp->scsi_status == S_QUEUE_FULL)) {
5359
5360                /*
5361                **   Target is busy.
5362                */
5363                cmd->result = ScsiResult(DID_OK, cp->scsi_status);
5364
5365        } else if ((cp->host_status == HS_SEL_TIMEOUT)
5366                || (cp->host_status == HS_TIMEOUT)) {
5367
5368                /*
5369                **   No response
5370                */
5371                cmd->result = ScsiResult(DID_TIME_OUT, cp->scsi_status);
5372
5373        } else if (cp->host_status == HS_RESET) {
5374
5375                /*
5376                **   SCSI bus reset
5377                */
5378                cmd->result = ScsiResult(DID_RESET, cp->scsi_status);
5379
5380        } else if (cp->host_status == HS_ABORTED) {
5381
5382                /*
5383                **   Transfer aborted
5384                */
5385                cmd->result = ScsiResult(DID_ABORT, cp->scsi_status);
5386
5387        } else {
5388
5389                /*
5390                **  Other protocol messes
5391                */
5392                PRINT_ADDR(cmd);
5393                printk ("COMMAND FAILED (%x %x) @%p.\n",
5394                        cp->host_status, cp->scsi_status, cp);
5395
5396                cmd->result = ScsiResult(DID_ERROR, cp->scsi_status);
5397        }
5398
5399        /*
5400        **      trace output
5401        */
5402
5403        if (tp->usrflag & UF_TRACE) {
5404                u_char * p;
5405                int i;
5406                PRINT_ADDR(cmd);
5407                printk (" CMD:");
5408                p = (u_char*) &cmd->cmnd[0];
5409                for (i=0; i<cmd->cmd_len; i++) printk (" %x", *p++);
5410
5411                if (cp->host_status==HS_COMPLETE) {
5412                        switch (cp->scsi_status) {
5413                        case S_GOOD:
5414                                printk ("  GOOD");
5415                                break;
5416                        case S_CHECK_COND:
5417                                printk ("  SENSE:");
5418                                p = (u_char*) &cmd->sense_buffer;
5419                                for (i=0; i<14; i++)
5420                                        printk (" %x", *p++);
5421                                break;
5422                        default:
5423                                printk ("  STAT: %x\n", cp->scsi_status);
5424                                break;
5425                        }
5426                } else printk ("  HOSTERROR: %x", cp->host_status);
5427                printk ("\n");
5428        }
5429
5430        /*
5431        **      Free this ccb
5432        */
5433        ncr_free_ccb (np, cp);
5434
5435        /*
5436        **      requeue awaiting scsi commands for this lun.
5437        */
5438        if (lp && lp->queuedccbs < lp->queuedepth &&
5439            !xpt_que_empty(&lp->wait_ccbq))
5440                ncr_start_next_ccb(np, lp, 2);
5441
5442        /*
5443        **      requeue awaiting scsi commands for this controller.
5444        */
5445        if (np->waiting_list)
5446                requeue_waiting_list(np);
5447
5448        /*
5449        **      signal completion to generic driver.
5450        */
5451        ncr_queue_done_cmd(np, cmd);
5452}
5453
5454/*==========================================================
5455**
5456**
5457**      Signal all (or one) control block done.
5458**
5459**
5460**==========================================================
5461*/
5462
5463/*
5464**      This CCB has been skipped by the NCR.
5465**      Queue it in the correponding unit queue.
5466*/
5467static void ncr_ccb_skipped(ncb_p np, ccb_p cp)
5468{
5469        tcb_p tp = &np->target[cp->target];
5470        lcb_p lp = tp->lp[cp->lun];
5471
5472        if (lp && cp != np->ccb) {
5473                cp->host_status &= ~HS_SKIPMASK;
5474                cp->start.schedule.l_paddr = 
5475                        cpu_to_scr(NCB_SCRIPT_PHYS (np, select));
5476                xpt_remque(&cp->link_ccbq);
5477                xpt_insque_tail(&cp->link_ccbq, &lp->skip_ccbq);
5478                if (cp->queued) {
5479                        --lp->queuedccbs;
5480                }
5481        }
5482        if (cp->queued) {
5483                --np->queuedccbs;
5484                cp->queued = 0;
5485        }
5486}
5487
5488/*
5489**      The NCR has completed CCBs.
5490**      Look at the DONE QUEUE if enabled, otherwise scan all CCBs
5491*/
5492void ncr_wakeup_done (ncb_p np)
5493{
5494        ccb_p cp;
5495#ifdef SCSI_NCR_CCB_DONE_SUPPORT
5496        int i, j;
5497
5498        i = np->ccb_done_ic;
5499        while (1) {
5500                j = i+1;
5501                if (j >= MAX_DONE)
5502                        j = 0;
5503
5504                cp = np->ccb_done[j];
5505                if (!CCB_DONE_VALID(cp))
5506                        break;
5507
5508                np->ccb_done[j] = (ccb_p) CCB_DONE_EMPTY;
5509                np->scripth->done_queue[5*j + 4] =
5510                                cpu_to_scr(NCB_SCRIPT_PHYS (np, done_plug));
5511                MEMORY_BARRIER();
5512                np->scripth->done_queue[5*i + 4] =
5513                                cpu_to_scr(NCB_SCRIPT_PHYS (np, done_end));
5514
5515                if (cp->host_status & HS_DONEMASK)
5516                        ncr_complete (np, cp);
5517                else if (cp->host_status & HS_SKIPMASK)
5518                        ncr_ccb_skipped (np, cp);
5519
5520                i = j;
5521        }
5522        np->ccb_done_ic = i;
5523#else
5524        cp = np->ccb;
5525        while (cp) {
5526                if (cp->host_status & HS_DONEMASK)
5527                        ncr_complete (np, cp);
5528                else if (cp->host_status & HS_SKIPMASK)
5529                        ncr_ccb_skipped (np, cp);
5530                cp = cp->link_ccb;
5531        }
5532#endif
5533}
5534
5535/*
5536**      Complete all active CCBs.
5537*/
5538void ncr_wakeup (ncb_p np, u_long code)
5539{
5540        ccb_p cp = np->ccb;
5541
5542        while (cp) {
5543                if (cp->host_status != HS_IDLE) {
5544                        cp->host_status = code;
5545                        ncr_complete (np, cp);
5546                }
5547                cp = cp->link_ccb;
5548        }
5549}
5550
5551/*
5552** Reset ncr chip.
5553*/
5554
5555/* Some initialisation must be done immediately following reset, for 53c720,
5556 * at least.  EA (dcntl bit 5) isn't set here as it is set once only in
5557 * the _detect function.
5558 */
5559static void ncr_chip_reset(ncb_p np, int delay)
5560{
5561        OUTB (nc_istat,  SRST);
5562        UDELAY (delay);
5563        OUTB (nc_istat,  0   );
5564
5565        if (np->features & FE_EHP)
5566                OUTB (nc_ctest0, EHP);
5567        if (np->features & FE_MUX)
5568                OUTB (nc_ctest4, MUX);
5569}
5570
5571
5572/*==========================================================
5573**
5574**
5575**      Start NCR chip.
5576**
5577**
5578**==========================================================
5579*/
5580
5581void ncr_init (ncb_p np, int reset, char * msg, u_long code)
5582{
5583        int     i;
5584
5585        /*
5586        **      Reset chip if asked, otherwise just clear fifos.
5587        */
5588
5589        if (reset) {
5590                OUTB (nc_istat,  SRST);
5591                UDELAY (100);
5592        }
5593        else {
5594                OUTB (nc_stest3, TE|CSF);
5595                OUTONB (nc_ctest3, CLF);
5596        }
5597 
5598        /*
5599        **      Message.
5600        */
5601
5602        if (msg) printk (KERN_INFO "%s: restart (%s).\n", ncr_name (np), msg);
5603
5604        /*
5605        **      Clear Start Queue
5606        */
5607        np->queuedepth = MAX_START - 1; /* 1 entry needed as end marker */
5608        for (i = 1; i < MAX_START + MAX_START; i += 2)
5609                np->scripth0->tryloop[i] =
5610                                cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
5611
5612        /*
5613        **      Start at first entry.
5614        */
5615        np->squeueput = 0;
5616        np->script0->startpos[0] = cpu_to_scr(NCB_SCRIPTH_PHYS (np, tryloop));
5617
5618#ifdef SCSI_NCR_CCB_DONE_SUPPORT
5619        /*
5620        **      Clear Done Queue
5621        */
5622        for (i = 0; i < MAX_DONE; i++) {
5623                np->ccb_done[i] = (ccb_p) CCB_DONE_EMPTY;
5624                np->scripth0->done_queue[5*i + 4] =
5625                        cpu_to_scr(NCB_SCRIPT_PHYS (np, done_end));
5626        }
5627#endif
5628
5629        /*
5630        **      Start at first entry.
5631        */
5632        np->script0->done_pos[0] = cpu_to_scr(NCB_SCRIPTH_PHYS (np,done_queue));
5633        np->ccb_done_ic = MAX_DONE-1;
5634        np->scripth0->done_queue[5*(MAX_DONE-1) + 4] =
5635                        cpu_to_scr(NCB_SCRIPT_PHYS (np, done_plug));
5636
5637        /*
5638        **      Wakeup all pending jobs.
5639        */
5640        ncr_wakeup (np, code);
5641
5642        /*
5643        **      Init chip.
5644        */
5645
5646        /*
5647        ** Remove reset; big delay because the 895 needs time for the
5648        ** bus mode to settle
5649        */
5650        ncr_chip_reset(np, 2000);
5651
5652        OUTB (nc_scntl0, np->rv_scntl0 | 0xc0);
5653                                        /*  full arb., ena parity, par->ATN  */
5654        OUTB (nc_scntl1, 0x00);         /*  odd parity, and remove CRST!! */
5655
5656        ncr_selectclock(np, np->rv_scntl3);     /* Select SCSI clock */
5657
5658        OUTB (nc_scid  , RRE|np->myaddr);       /* Adapter SCSI address */
5659        OUTW (nc_respid, 1ul<<np->myaddr);      /* Id to respond to */
5660        OUTB (nc_istat , SIGP   );              /*  Signal Process */
5661        OUTB (nc_dmode , np->rv_dmode);         /* Burst length, dma mode */
5662        OUTB (nc_ctest5, np->rv_ctest5);        /* Large fifo + large burst */
5663
5664        OUTB (nc_dcntl , NOCOM|np->rv_dcntl);   /* Protect SFBR */
5665        OUTB (nc_ctest0, np->rv_ctest0);        /* 720: CDIS and EHP */
5666        OUTB (nc_ctest3, np->rv_ctest3);        /* Write and invalidate */
5667        OUTB (nc_ctest4, np->rv_ctest4);        /* Master parity checking */
5668
5669        OUTB (nc_stest2, EXT|np->rv_stest2);    /* Extended Sreq/Sack filtering */
5670        OUTB (nc_stest3, TE);                   /* TolerANT enable */
5671        OUTB (nc_stime0, 0x0c   );              /* HTH disabled  STO 0.25 sec */
5672
5673        /*
5674        **      Disable disconnects.
5675        */
5676
5677        np->disc = 0;
5678
5679        /*
5680        **    Enable GPIO0 pin for writing if LED support.
5681        */
5682
5683        if (np->features & FE_LED0) {
5684                OUTOFFB (nc_gpcntl, 0x01);
5685        }
5686
5687        /*
5688        **      enable ints
5689        */
5690
5691        OUTW (nc_sien , STO|HTH|MA|SGE|UDC|RST|PAR);
5692        OUTB (nc_dien , MDPE|BF|ABRT|SSI|SIR|IID);
5693
5694        /*
5695        **      For 895/6 enable SBMC interrupt and save current SCSI bus mode.
5696        */
5697        if (np->features & FE_ULTRA2) {
5698                OUTONW (nc_sien, SBMC);
5699                np->scsi_mode = INB (nc_stest4) & SMODE;
5700        }
5701
5702        /*
5703        **      DEL 441 - 53C876 Rev 5 - Part Number 609-0392787/2788 - ITEM 2.
5704        **      Disable overlapped arbitration.
5705        **      All 896 chips are also affected by this errata.
5706        */
5707        if (np->device_id == PCI_DEVICE_ID_NCR_53C875)
5708                OUTB (nc_ctest0, (1<<5));
5709        else if (np->device_id == PCI_DEVICE_ID_NCR_53C896)
5710                OUTB (nc_ccntl0, DPR);
5711
5712        /*
5713        **      Fill in target structure.
5714        **      Reinitialize usrsync.
5715        **      Reinitialize usrwide.
5716        **      Prepare sync negotiation according to actual SCSI bus mode.
5717        */
5718
5719        for (i=0;i<MAX_TARGET;i++) {
5720                tcb_p tp = &np->target[i];
5721
5722                tp->sval    = 0;
5723                tp->wval    = np->rv_scntl3;
5724
5725                if (tp->usrsync != 255) {
5726                        if (tp->usrsync <= np->maxsync) {
5727                                if (tp->usrsync < np->minsync) {
5728                                        tp->usrsync = np->minsync;
5729                                }
5730                        }
5731                        else
5732                                tp->usrsync = 255;
5733                };
5734
5735                if (tp->usrwide > np->maxwide)
5736                        tp->usrwide = np->maxwide;
5737
5738                ncr_negotiate (np, tp);
5739        }
5740
5741        /*
5742        **    Start script processor.
5743        */
5744        if (np->paddr2) {
5745                if (bootverbose)
5746                        printk ("%s: Downloading SCSI SCRIPTS.\n",
5747                                ncr_name(np));
5748                OUTL (nc_scratcha, vtobus(np->script0));
5749                OUTL_DSP (NCB_SCRIPTH_PHYS (np, start_ram));
5750        }
5751        else
5752                OUTL_DSP (NCB_SCRIPT_PHYS (np, start));
5753}
5754
5755/*==========================================================
5756**
5757**      Prepare the negotiation values for wide and
5758**      synchronous transfers.
5759**
5760**==========================================================
5761*/
5762
5763static void ncr_negotiate (struct ncb* np, struct tcb* tp)
5764{
5765        /*
5766        **      minsync unit is 4ns !
5767        */
5768
5769        u_long minsync = tp->usrsync;
5770
5771        /*
5772        **      SCSI bus mode limit
5773        */
5774
5775        if (np->scsi_mode && np->scsi_mode == SMODE_SE) {
5776                if (minsync < 12) minsync = 12;
5777        }
5778
5779        /*
5780        **      our limit ..
5781        */
5782
5783        if (minsync < np->minsync)
5784                minsync = np->minsync;
5785
5786        /*
5787        **      divider limit
5788        */
5789
5790        if (minsync > np->maxsync)
5791                minsync = 255;
5792
5793        tp->minsync = minsync;
5794        tp->maxoffs = (minsync<255 ? np->maxoffs : 0);
5795
5796        /*
5797        **      period=0: has to negotiate sync transfer
5798        */
5799
5800        tp->period=0;
5801
5802        /*
5803        **      widedone=0: has to negotiate wide transfer
5804        */
5805        tp->widedone=0;
5806}
5807
5808/*==========================================================
5809**
5810**      Get clock factor and sync divisor for a given 
5811**      synchronous factor period.
5812**      Returns the clock factor (in sxfer) and scntl3 
5813**      synchronous divisor field.
5814**
5815**==========================================================
5816*/
5817
5818static void ncr_getsync(ncb_p np, u_char sfac, u_char *fakp, u_char *scntl3p)
5819{
5820        u_long  clk = np->clock_khz;    /* SCSI clock frequency in kHz  */
5821        int     div = np->clock_divn;   /* Number of divisors supported */
5822        u_long  fak;                    /* Sync factor in sxfer         */
5823        u_long  per;                    /* Period in tenths of ns       */
5824        u_long  kpc;                    /* (per * clk)                  */
5825
5826        /*
5827        **      Compute the synchronous period in tenths of nano-seconds
5828        */
5829        if      (sfac <= 10)    per = 250;
5830        else if (sfac == 11)    per = 303;
5831        else if (sfac == 12)    per = 500;
5832        else                    per = 40 * sfac;
5833
5834        /*
5835        **      Look for the greatest clock divisor that allows an 
5836        **      input speed faster than the period.
5837        */
5838        kpc = per * clk;
5839        while (--div >= 0)
5840                if (kpc >= (div_10M[div] << 2)) break;
5841
5842        /*
5843        **      Calculate the lowest clock factor that allows an output 
5844        **      speed not faster than the period.
5845        */
5846        fak = (kpc - 1) / div_10M[div] + 1;
5847
5848#if 0   /* This optimization does not seem very useful */
5849
5850        per = (fak * div_10M[div]) / clk;
5851
5852        /*
5853        **      Why not to try the immediate lower divisor and to choose 
5854        **      the one that allows the fastest output speed ?
5855        **      We dont want input speed too much greater than output speed.
5856        */
5857        if (div >= 1 && fak < 8) {
5858                u_long fak2, per2;
5859                fak2 = (kpc - 1) / div_10M[div-1] + 1;
5860                per2 = (fak2 * div_10M[div-1]) / clk;
5861                if (per2 < per && fak2 <= 8) {
5862                        fak = fak2;
5863                        per = per2;
5864                        --div;
5865                }
5866        }
5867#endif
5868
5869        if (fak < 4) fak = 4;   /* Should never happen, too bad ... */
5870
5871        /*
5872        **      Compute and return sync parameters for the ncr
5873        */
5874        *fakp           = fak - 4;
5875        *scntl3p        = ((div+1) << 4) + (sfac < 25 ? 0x80 : 0);
5876}
5877
5878
5879/*==========================================================
5880**
5881**      Set actual values, sync status and patch all ccbs of 
5882**      a target according to new sync/wide agreement.
5883**
5884**==========================================================
5885*/
5886
5887static void ncr_set_sync_wide_status (ncb_p np, u_char target)
5888{
5889        ccb_p cp;
5890        tcb_p tp = &np->target[target];
5891
5892        /*
5893        **      set actual value and sync_status
5894        */
5895        OUTB (nc_sxfer, tp->sval);
5896        np->sync_st = tp->sval;
5897        OUTB (nc_scntl3, tp->wval);
5898        np->wide_st = tp->wval;
5899
5900        /*
5901        **      patch ALL ccbs of this target.
5902        */
5903        for (cp = np->ccb; cp; cp = cp->link_ccb) {
5904                if (!cp->cmd) continue;
5905                if (cp->cmd->target != target) continue;
5906#if 0
5907                cp->sync_status = tp->sval;
5908                cp->wide_status = tp->wval;
5909#endif
5910                cp->phys.select.sel_scntl3 = tp->wval;
5911                cp->phys.select.sel_sxfer  = tp->sval;
5912        };
5913}
5914
5915/*==========================================================
5916**
5917**      Switch sync mode for current job and it's target
5918**
5919**==========================================================
5920*/
5921
5922static void ncr_setsync (ncb_p np, ccb_p cp, u_char scntl3, u_char sxfer)
5923{
5924        Scsi_Cmnd *cmd;
5925        tcb_p tp;
5926        u_char target = INB (nc_sdid) & 0x0f;
5927        u_char idiv;
5928
5929        assert (cp && cp->cmd);
5930        if (!cp) return;
5931
5932        cmd = cp->cmd;
5933        if (!cmd) return;
5934
5935        assert (target == (cmd->target & 0xf));
5936
5937        tp = &np->target[target];
5938
5939        if (!scntl3 || !(sxfer & 0x1f))
5940                scntl3 = np->rv_scntl3;
5941        scntl3 = (scntl3 & 0xf0) | (tp->wval & EWS) | (np->rv_scntl3 & 0x07);
5942
5943        /*
5944        **      Deduce the value of controller sync period from scntl3.
5945        **      period is in tenths of nano-seconds.
5946        */
5947
5948        idiv = ((scntl3 >> 4) & 0x7);
5949        if ((sxfer & 0x1f) && idiv)
5950                tp->period = (((sxfer>>5)+4)*div_10M[idiv-1])/np->clock_khz;
5951        else
5952                tp->period = 0xffff;
5953
5954        /*
5955        **       Stop there if sync parameters are unchanged
5956        */
5957        if (tp->sval == sxfer && tp->wval == scntl3) return;
5958        tp->sval = sxfer;
5959        tp->wval = scntl3;
5960
5961        /*
5962        **      Bells and whistles   ;-)
5963        */
5964        PRINT_TARGET(np, target);
5965        if (sxfer & 0x01f) {
5966                unsigned f10 = 100000 << (tp->widedone ? tp->widedone -1 : 0);
5967                unsigned mb10 = (f10 + tp->period/2) / tp->period;
5968                char *scsi;
5969
5970                /*
5971                **  Disable extended Sreq/Sack filtering
5972                */
5973                if (tp->period <= 2000) OUTOFFB (nc_stest2, EXT);
5974
5975                /*
5976                **      Bells and whistles   ;-)
5977                */
5978                if      (tp->period < 500)      scsi = "FAST-40";
5979                else if (tp->period < 1000)     scsi = "FAST-20";
5980                else if (tp->period < 2000)     scsi = "FAST-10";
5981                else                            scsi = "FAST-5";
5982
5983                printk ("%s %sSCSI %d.%d MB/s (%d ns, offset %d)\n", scsi,
5984                        tp->widedone > 1 ? "WIDE " : "",
5985                        mb10 / 10, mb10 % 10, tp->period / 10, sxfer & 0x1f);
5986        } else
5987                printk ("%sasynchronous.\n", tp->widedone > 1 ? "wide " : "");
5988
5989        /*
5990        **      set actual value and sync_status
5991        **      patch ALL ccbs of this target.
5992        */
5993        ncr_set_sync_wide_status(np, target);
5994}
5995
5996/*==========================================================
5997**
5998**      Switch wide mode for current job and it's target
5999**      SCSI specs say: a SCSI device that accepts a WDTR 
6000**      message shall reset the synchronous agreement to 
6001**      asynchronous mode.
6002**
6003**==========================================================
6004*/
6005
6006static void ncr_setwide (ncb_p np, ccb_p cp, u_char wide, u_char ack)
6007{
6008        Scsi_Cmnd *cmd;
6009        u_short target = INB (nc_sdid) & 0x0f;
6010        tcb_p tp;
6011        u_char  scntl3;
6012        u_char  sxfer;
6013
6014        assert (cp && cp->cmd);
6015        if (!cp) return;
6016
6017        cmd = cp->cmd;
6018        if (!cmd) return;
6019
6020        assert (target == (cmd->target & 0xf));
6021
6022        tp = &np->target[target];
6023        tp->widedone  =  wide+1;
6024        scntl3 = (tp->wval & (~EWS)) | (wide ? EWS : 0);
6025
6026        sxfer = ack ? 0 : tp->sval;
6027
6028        /*
6029        **       Stop there if sync/wide parameters are unchanged
6030        */
6031        if (tp->sval == sxfer && tp->wval == scntl3) return;
6032        tp->sval = sxfer;
6033        tp->wval = scntl3;
6034
6035        /*
6036        **      Bells and whistles   ;-)
6037        */
6038        if (bootverbose >= 2) {
6039                PRINT_TARGET(np, target);
6040                if (scntl3 & EWS)
6041                        printk ("WIDE SCSI (16 bit) enabled.\n");
6042                else
6043                        printk ("WIDE SCSI disabled.\n");
6044        }
6045
6046        /*
6047        **      set actual value and sync_status
6048        **      patch ALL ccbs of this target.
6049        */
6050        ncr_set_sync_wide_status(np, target);
6051}
6052
6053/*==========================================================
6054**
6055**      Switch tagged mode for a target.
6056**
6057**==========================================================
6058*/
6059
6060static void ncr_setup_tags (ncb_p np, u_char tn, u_char ln)
6061{
6062        tcb_p tp = &np->target[tn];
6063        lcb_p lp = tp->lp[ln];
6064        u_char   reqtags, maxdepth;
6065
6066        /*
6067        **      Just in case ...
6068        */
6069        if ((!tp) || (!lp))
6070                return;
6071
6072        /*
6073        **      If SCSI device queue depth is not yet set, leave here.
6074        */
6075        if (!lp->scdev_depth)
6076                return;
6077
6078        /*
6079        **      Donnot allow more tags than the SCSI driver can queue 
6080        **      for this device.
6081        **      Donnot allow more tags than we can handle.
6082        */
6083        maxdepth = lp->scdev_depth;
6084        if (maxdepth > lp->maxnxs)      maxdepth    = lp->maxnxs;
6085        if (lp->maxtags > maxdepth)     lp->maxtags = maxdepth;
6086        if (lp->numtags > maxdepth)     lp->numtags = maxdepth;
6087
6088        /*
6089        **      only devices conformant to ANSI Version >= 2
6090        **      only devices capable of tagged commands
6091        **      only if enabled by user ..
6092        */
6093        if ((lp->inq_byte7 & INQ7_QUEUE) && lp->numtags > 1) {
6094                reqtags = lp->numtags;
6095        } else {
6096                reqtags = 1;
6097        };
6098
6099        /*
6100        **      Update max number of tags
6101        */
6102        lp->numtags = reqtags;
6103        if (lp->numtags > lp->maxtags)
6104                lp->maxtags = lp->numtags;
6105
6106        /*
6107        **      If we want to switch tag mode, we must wait 
6108        **      for no CCB to be active.
6109        */
6110        if      (reqtags > 1 && lp->usetags) {   /* Stay in tagged mode    */
6111                if (lp->queuedepth == reqtags)   /* Already announced      */
6112                        return;
6113                lp->queuedepth  = reqtags;
6114        }
6115        else if (reqtags <= 1 && !lp->usetags) { /* Stay in untagged mode  */
6116                lp->queuedepth  = reqtags;
6117                return;
6118        }
6119        else {                                   /* Want to switch tag mode */
6120                if (lp->busyccbs)                /* If not yet safe, return */
6121                        return;
6122                lp->queuedepth  = reqtags;
6123                lp->usetags     = reqtags > 1 ? 1 : 0;
6124        }
6125
6126        /*
6127        **      Patch the lun mini-script, according to tag mode.
6128        */
6129        lp->jump_tag.l_paddr = lp->usetags?
6130                        cpu_to_scr(NCB_SCRIPT_PHYS(np, resel_tag)) :
6131                        cpu_to_scr(NCB_SCRIPT_PHYS(np, resel_notag));
6132
6133        /*
6134        **      Announce change to user.
6135        */
6136        if (bootverbose) {
6137                PRINT_LUN(np, tn, ln);
6138                if (lp->usetags) {
6139                        printk("tagged command queue depth set to %d\n", reqtags);
6140                }
6141                else {
6142                        printk("tagged command queueing disabled\n");
6143                }
6144        }
6145}
6146
6147/*----------------------------------------------------
6148**
6149**      handle user commands
6150**
6151**----------------------------------------------------
6152*/
6153
6154#ifdef SCSI_NCR_USER_COMMAND_SUPPORT
6155
6156static void ncr_usercmd (ncb_p np)
6157{
6158        u_char t;
6159        tcb_p tp;
6160
6161        switch (np->user.cmd) {
6162
6163        case 0: return;
6164
6165        case UC_SETSYNC:
6166                for (t=0; t<MAX_TARGET; t++) {
6167                        if (!((np->user.target>>t)&1)) continue;
6168                        tp = &np->target[t];
6169                        tp->usrsync = np->user.data;
6170                        ncr_negotiate (np, tp);
6171                };
6172                break;
6173
6174        case UC_SETTAGS:
6175                for (t=0; t<MAX_TARGET; t++) {
6176                        int ln;
6177                        if (!((np->user.target>>t)&1)) continue;
6178                        np->target[t].usrtags = np->user.data;
6179                        for (ln = 0; ln < MAX_LUN; ln++) {
6180                                lcb_p lp = np->target[t].lp[ln];
6181                                if (!lp)
6182                                        continue;
6183                                lp->maxtags = lp->numtags = np->user.data;
6184                                ncr_setup_tags (np, t, ln);
6185                        }
6186                };
6187                break;
6188
6189        case UC_SETDEBUG:
6190#ifdef SCSI_NCR_DEBUG_INFO_SUPPORT
6191                ncr_debug = np->user.data;
6192#endif
6193                break;
6194
6195        case UC_SETORDER:
6196                np->order = np->user.data;
6197                break;
6198
6199        case UC_SETVERBOSE:
6200                np->verbose = np->user.data;
6201                break;
6202
6203        case UC_SETWIDE:
6204                for (t=0; t<MAX_TARGET; t++) {
6205                        u_long size;
6206                        if (!((np->user.target>>t)&1)) continue;
6207                        tp = &np->target[t];
6208                        size = np->user.data;
6209                        if (size > np->maxwide) size=np->maxwide;
6210                        tp->usrwide = size;
6211                        ncr_negotiate (np, tp);
6212                };
6213                break;
6214
6215        case UC_SETFLAG:
6216                for (t=0; t<MAX_TARGET; t++) {
6217                        if (!((np->user.target>>t)&1)) continue;
6218                        tp = &np->target[t];
6219                        tp->usrflag = np->user.data;
6220                };
6221                break;
6222        }
6223        np->user.cmd=0;
6224}
6225#endif
6226
6227/*==========================================================
6228**
6229**
6230**      ncr timeout handler.
6231**
6232**
6233**==========================================================
6234**
6235**      Misused to keep the driver running when
6236**      interrupts are not configured correctly.
6237**
6238**----------------------------------------------------------
6239*/
6240
6241static void ncr_timeout (ncb_p np)
6242{
6243        u_long  thistime = ktime_get(0);
6244
6245        /*
6246        **      If release process in progress, let's go
6247        **      Set the release stage from 1 to 2 to synchronize
6248        **      with the release process.
6249        */
6250
6251        if (np->release_stage) {
6252                if (np->release_stage == 1) np->release_stage = 2;
6253                return;
6254        }
6255
6256        np->timer.expires = ktime_get(SCSI_NCR_TIMER_INTERVAL);
6257        add_timer(&np->timer);
6258
6259        /*
6260        **      If we are resetting the ncr, wait for settle_time before 
6261        **      clearing it. Then command processing will be resumed.
6262        */
6263        if (np->settle_time) {
6264                if (np->settle_time <= thistime) {
6265                        if (bootverbose > 1)
6266                                printk("%s: command processing resumed\n", ncr_name(np));
6267                        np->settle_time = 0;
6268                        np->disc        = 1;
6269                        requeue_waiting_list(np);
6270                }
6271                return;
6272        }
6273
6274        /*
6275        **      Since the generic scsi driver only allows us 0.5 second 
6276        **      to perform abort of a command, we must look at ccbs about 
6277        **      every 0.25 second.
6278        */
6279        if (np->lasttime + 4*HZ < thistime) {
6280                /*
6281                **      block ncr interrupts
6282                */
6283                np->lasttime = thistime;
6284        }
6285
6286#ifdef SCSI_NCR_BROKEN_INTR
6287        if (INB(nc_istat) & (INTF|SIP|DIP)) {
6288
6289                /*
6290                **      Process pending interrupts.
6291                */
6292                if (DEBUG_FLAGS & DEBUG_TINY) printk ("{");
6293                ncr_exception (np);
6294                if (DEBUG_FLAGS & DEBUG_TINY) printk ("}");
6295        }
6296#endif /* SCSI_NCR_BROKEN_INTR */
6297}
6298
6299/*==========================================================
6300**
6301**      log message for real hard errors
6302**
6303**      "ncr0 targ 0?: ERROR (ds:si) (so-si-sd) (sxfer/scntl3) @ name (dsp:dbc)."
6304**      "             reg: r0 r1 r2 r3 r4 r5 r6 ..... rf."
6305**
6306**      exception register:
6307**              ds:     dstat
6308**              si:     sist
6309**
6310**      SCSI bus lines:
6311**              so:     control lines as driver by NCR.
6312**              si:     control lines as seen by NCR.
6313**              sd:     scsi data lines as seen by NCR.
6314**
6315**      wide/fastmode:
6316**              sxfer:  (see the manual)
6317**              scntl3: (see the manual)
6318**
6319**      current script command:
6320**              dsp:    script address (relative to start of script).
6321**              dbc:    first word of script command.
6322**
6323**      First 16 register of the chip:
6324**              r0..rf
6325**
6326**==========================================================
6327*/
6328
6329static void ncr_log_hard_error(ncb_p np, u_short sist, u_char dstat)
6330{
6331        u_int32 dsp;
6332        int     script_ofs;
6333        int     script_size;
6334        char    *script_name;
6335        u_char  *script_base;
6336        int     i;
6337
6338        dsp     = INL (nc_dsp);
6339
6340        if (dsp > np->p_script && dsp <= np->p_script + sizeof(struct script)) {
6341                script_ofs      = dsp - np->p_script;
6342                script_size     = sizeof(struct script);
6343                script_base     = (u_char *) np->script0;
6344                script_name     = "script";
6345        }
6346        else if (np->p_scripth < dsp && 
6347                 dsp <= np->p_scripth + sizeof(struct scripth)) {
6348                script_ofs      = dsp - np->p_scripth;
6349                script_size     = sizeof(struct scripth);
6350                script_base     = (u_char *) np->scripth0;
6351                script_name     = "scripth";
6352        } else {
6353                script_ofs      = dsp;
6354                script_size     = 0;
6355                script_base     = 0;
6356                script_name     = "mem";
6357        }
6358
6359        printk ("%s:%d: ERROR (%x:%x) (%x-%x-%x) (%x/%x) @ (%s %x:%08x).\n",
6360                ncr_name (np), (unsigned)INB (nc_sdid)&0x0f, dstat, sist,
6361                (unsigned)INB (nc_socl), (unsigned)INB (nc_sbcl), (unsigned)INB (nc_sbdl),
6362                (unsigned)INB (nc_sxfer),(unsigned)INB (nc_scntl3), script_name, script_ofs,
6363                (unsigned)INL (nc_dbc));
6364
6365        if (((script_ofs & 3) == 0) &&
6366            (unsigned)script_ofs < script_size) {
6367                printk ("%s: script cmd = %08x\n", ncr_name(np),
6368                        scr_to_cpu((int) *(ncrcmd *)(script_base + script_ofs)));
6369        }
6370
6371        printk ("%s: regdump:", ncr_name(np));
6372        for (i=0; i<16;i++)
6373            printk (" %02x", (unsigned)INB_OFF(i));
6374        printk (".\n");
6375}
6376
6377/*============================================================
6378**
6379**      ncr chip exception handler.
6380**
6381**============================================================
6382**
6383**      In normal cases, interrupt conditions occur one at a 
6384**      time. The ncr is able to stack in some extra registers 
6385**      other interrupts that will occurs after the first one.
6386**      But severall interrupts may occur at the same time.
6387**
6388**      We probably should only try to deal with the normal 
6389**      case, but it seems that multiple interrupts occur in 
6390**      some cases that are not abnormal at all.
6391**
6392**      The most frequent interrupt condition is Phase Mismatch.
6393**      We should want to service this interrupt quickly.
6394**      A SCSI parity error may be delivered at the same time.
6395**      The SIR interrupt is not very frequent in this driver, 
6396**      since the INTFLY is likely used for command completion 
6397**      signaling.
6398**      The Selection Timeout interrupt may be triggered with 
6399**      IID and/or UDC.
6400**      The SBMC interrupt (SCSI Bus Mode Change) may probably 
6401**      occur at any time.
6402**
6403**      This handler try to deal as cleverly as possible with all
6404**      the above.
6405**
6406**============================================================
6407*/
6408
6409void ncr_exception (ncb_p np)
6410{
6411        u_char  istat, dstat;
6412        u_short sist;
6413        int     i;
6414
6415        /*
6416        **      interrupt on the fly ?
6417        **      Since the global header may be copied back to a CCB 
6418        **      using a posted PCI memory write, the last operation on 
6419        **      the istat register is a READ in order to flush posted 
6420        **      PCI write commands.
6421        */
6422        istat = INB (nc_istat);
6423        if (istat & INTF) {
6424                OUTB (nc_istat, (istat & SIGP) | INTF);
6425                istat = INB (nc_istat);
6426                if (DEBUG_FLAGS & DEBUG_TINY) printk ("F ");
6427                ncr_wakeup_done (np);
6428        };
6429
6430        if (!(istat & (SIP|DIP)))
6431                return;
6432
6433        if (istat & CABRT)
6434                OUTB (nc_istat, CABRT);
6435
6436        /*
6437        **      Steinbach's Guideline for Systems Programming:
6438        **      Never test for an error condition you don't know how to handle.
6439        */
6440
6441        sist  = (istat & SIP) ? INW (nc_sist)  : 0;
6442        dstat = (istat & DIP) ? INB (nc_dstat) : 0;
6443
6444        if (DEBUG_FLAGS & DEBUG_TINY)
6445                printk ("<%d|%x:%x|%x:%x>",
6446                        (int)INB(nc_scr0),
6447                        dstat,sist,
6448                        (unsigned)INL(nc_dsp),
6449                        (unsigned)INL(nc_dbc));
6450
6451        /*========================================================
6452        **      First, interrupts we want to service cleanly.
6453        **
6454        **      Phase mismatch is the most frequent interrupt, and 
6455        **      so we have to service it as quickly and as cleanly 
6456        **      as possible.
6457        **      Programmed interrupts are rarely used in this driver,
6458        **      but we must handle them cleanly anyway.
6459        **      We try to deal with PAR and SBMC combined with 
6460        **      some other interrupt(s).
6461        **=========================================================
6462        */
6463
6464        if (!(sist  & (STO|GEN|HTH|SGE|UDC|RST)) &&
6465            !(dstat & (MDPE|BF|ABRT|IID))) {
6466                if ((sist & SBMC) && ncr_int_sbmc (np))
6467                        return;
6468                if ((sist & PAR)  && ncr_int_par  (np))
6469                        return;
6470                if (sist & MA) {
6471                        ncr_int_ma (np);
6472                        return;
6473                }
6474                if (dstat & SIR) {
6475                        ncr_int_sir (np);
6476                        return;
6477                }
6478                /*
6479                **  DEL 397 - 53C875 Rev 3 - Part Number 609-0392410 - ITEM 2.
6480                */
6481                if (!(sist & (SBMC|PAR)) && !(dstat & SSI)) {
6482                        printk( "%s: unknown interrupt(s) ignored, "
6483                                "ISTAT=%x DSTAT=%x SIST=%x\n",
6484                                ncr_name(np), istat, dstat, sist);
6485                        return;
6486                }
6487                OUTONB_STD ();
6488                return;
6489        };
6490
6491        /*========================================================
6492        **      Now, interrupts that need some fixing up.
6493        **      Order and multiple interrupts is so less important.
6494        **
6495        **      If SRST has been asserted, we just reset the chip.
6496        **
6497        **      Selection is intirely handled by the chip. If the 
6498        **      chip says STO, we trust it. Seems some other 
6499        **      interrupts may occur at the same time (UDC, IID), so 
6500        **      we ignore them. In any case we do enough fix-up 
6501        **      in the service routine.
6502        **      We just exclude some fatal dma errors.
6503        **=========================================================
6504        */
6505
6506        if (sist & RST) {
6507                ncr_init (np, 1, bootverbose ? "scsi reset" : NULL, HS_RESET);
6508                return;
6509        };
6510
6511        if ((sist & STO) &&
6512                !(dstat & (MDPE|BF|ABRT))) {
6513        /*
6514        **      DEL 397 - 53C875 Rev 3 - Part Number 609-0392410 - ITEM 1.
6515        */
6516                OUTONB (nc_ctest3, CLF);
6517
6518                ncr_int_sto (np);
6519                return;
6520        };
6521
6522        /*=========================================================
6523        **      Now, interrupts we are not able to recover cleanly.
6524        **      (At least for the moment).
6525        **
6526        **      Do the register dump.
6527        **      Log message for real hard errors.
6528        **      Clear all fifos.
6529        **      For MDPE, BF, ABORT, IID, SGE and HTH we reset the 
6530        **      BUS and the chip.
6531        **      We are more soft for UDC.
6532        **=========================================================
6533        */
6534
6535        if (ktime_exp(np->regtime)) {
6536                np->regtime = ktime_get(10*HZ);
6537                for (i = 0; i<sizeof(np->regdump); i++)
6538                        ((char*)&np->regdump)[i] = INB_OFF(i);
6539                np->regdump.nc_dstat = dstat;
6540                np->regdump.nc_sist  = sist;
6541        };
6542
6543        ncr_log_hard_error(np, sist, dstat);
6544
6545        printk ("%s: have to clear fifos.\n", ncr_name (np));
6546        OUTB (nc_stest3, TE|CSF);
6547        OUTONB (nc_ctest3, CLF);
6548
6549        if ((sist & (SGE)) ||
6550                (dstat & (MDPE|BF|ABRT|IID))) {
6551                ncr_start_reset(np);
6552                return;
6553        };
6554
6555        if (sist & HTH) {
6556                printk ("%s: handshake timeout\n", ncr_name(np));
6557                ncr_start_reset(np);
6558                return;
6559        };
6560
6561        if (sist & UDC) {
6562                printk ("%s: unexpected disconnect\n", ncr_name(np));
6563                OUTB (HS_PRT, HS_UNEXPECTED);
6564                OUTL_DSP (NCB_SCRIPT_PHYS (np, cleanup));
6565                return;
6566        };
6567
6568        /*=========================================================
6569        **      We just miss the cause of the interrupt. :(
6570        **      Print a message. The timeout will do the real work.
6571        **=========================================================
6572        */
6573        printk ("%s: unknown interrupt\n", ncr_name(np));
6574}
6575
6576/*==========================================================
6577**
6578**      ncr chip exception handler for selection timeout
6579**
6580**==========================================================
6581**
6582**      There seems to be a bug in the 53c810.
6583**      Although a STO-Interrupt is pending,
6584**      it continues executing script commands.
6585**      But it will fail and interrupt (IID) on
6586**      the next instruction where it's looking
6587**      for a valid phase.
6588**
6589**----------------------------------------------------------
6590*/
6591
6592void ncr_int_sto (ncb_p np)
6593{
6594        u_long dsa;
6595        ccb_p cp;
6596        if (DEBUG_FLAGS & DEBUG_TINY) printk ("T");
6597
6598        /*
6599        **      look for ccb and set the status.
6600        */
6601
6602        dsa = INL (nc_dsa);
6603        cp = np->ccb;
6604        while (cp && (CCB_PHYS (cp, phys) != dsa))
6605                cp = cp->link_ccb;
6606
6607        if (cp) {
6608                cp-> host_status = HS_SEL_TIMEOUT;
6609                ncr_complete (np, cp);
6610        };
6611
6612        /*
6613        **      repair start queue and jump to start point.
6614        */
6615
6616        OUTL_DSP (NCB_SCRIPTH_PHYS (np, sto_restart));
6617        return;
6618}
6619
6620/*==========================================================
6621**
6622**      ncr chip exception handler for SCSI bus mode change
6623**
6624**==========================================================
6625**
6626**      spi2-r12 11.2.3 says a transceiver mode change must 
6627**      generate a reset event and a device that detects a reset 
6628**      event shall initiate a hard reset. It says also that a
6629**      device that detects a mode change shall set data transfer 
6630**      mode to eight bit asynchronous, etc...
6631**      So, just resetting should be enough.
6632**       
6633**
6634**----------------------------------------------------------
6635*/
6636
6637static int ncr_int_sbmc (ncb_p np)
6638{
6639        u_char scsi_mode = INB (nc_stest4) & SMODE;
6640
6641        if (scsi_mode != np->scsi_mode) {
6642                printk("%s: SCSI bus mode change from %x to %x.\n",
6643                        ncr_name(np), np->scsi_mode, scsi_mode);
6644
6645                np->scsi_mode = scsi_mode;
6646
6647
6648                /*
6649                **      Suspend command processing for 1 second and 
6650                **      reinitialize all except the chip.
6651                */
6652                np->settle_time = ktime_get(1*HZ);
6653                ncr_init (np, 0, bootverbose ? "scsi mode change" : NULL, HS_RESET);
6654                return 1;
6655        }
6656        return 0;
6657}
6658
6659/*==========================================================
6660**
6661**      ncr chip exception handler for SCSI parity error.
6662**
6663**==========================================================
6664**
6665**
6666**----------------------------------------------------------
6667*/
6668
6669static int ncr_int_par (ncb_p np)
6670{
6671        u_char  hsts    = INB (HS_PRT);
6672        u_int32 dbc     = INL (nc_dbc);
6673        u_char  sstat1  = INB (nc_sstat1);
6674        int phase       = -1;
6675        int msg         = -1;
6676        u_int32 jmp;
6677
6678        printk("%s: SCSI parity error detected: SCR1=%d DBC=%x SSTAT1=%x\n",
6679                ncr_name(np), hsts, dbc, sstat1);
6680
6681        /*
6682         *      Ignore the interrupt if the NCR is not connected 
6683         *      to the SCSI bus, since the right work should have  
6684         *      been done on unexpected disconnection handling.
6685         */
6686        if (!(INB (nc_scntl1) & ISCON))
6687                return 0;
6688
6689        /*
6690         *      If the nexus is not clearly identified, reset the bus.
6691         *      We will try to do better later.
6692         */
6693        if (hsts & HS_INVALMASK)
6694                goto reset_all;
6695
6696        /*
6697         *      If the SCSI parity error occurs in MSG IN phase, prepare a 
6698         *      MSG PARITY message. Otherwise, prepare a INITIATOR DETECTED 
6699         *      ERROR message and let the device decide to retry the command 
6700         *      or to terminate with check condition. If we were in MSG IN 
6701         *      phase waiting for the response of a negotiation, we will 
6702         *      get SIR_NEGO_FAILED at dispatch.
6703         */
6704        if (!(dbc & 0xc0000000))
6705                phase = (dbc >> 24) & 7;
6706        if (phase == 7)
6707                msg = M_PARITY;
6708        else
6709                msg = M_ID_ERROR;
6710
6711#ifdef SCSI_NCR_INTEGRITY_CHECKING
6712        /*
6713        **      Save error message. For integrity check use only.
6714        */
6715        if (np->check_integrity)
6716                np->check_integ_par = msg;
6717#endif
6718
6719        /*
6720         *      If the NCR stopped on a MOVE ^ DATA_IN, we jump to a 
6721         *      script that will ignore all data in bytes until phase 
6722         *      change, since we are not sure the chip will wait the phase 
6723         *      change prior to delivering the interrupt.
6724         */
6725        if (phase == 1)
6726                jmp = NCB_SCRIPTH_PHYS (np, par_err_data_in);
6727        else
6728                jmp = NCB_SCRIPTH_PHYS (np, par_err_other);
6729
6730        OUTONB (nc_ctest3, CLF );       /* clear dma fifo  */
6731        OUTB (nc_stest3, TE|CSF);       /* clear scsi fifo */
6732
6733        np->msgout[0] = msg;
6734        OUTL_DSP (jmp);
6735        return 1;
6736
6737reset_all:
6738        ncr_start_reset(np);
6739        return 1;
6740}
6741
6742/*==========================================================
6743**
6744**
6745**      ncr chip exception handler for phase errors.
6746**
6747**
6748**==========================================================
6749**
6750**      We have to construct a new transfer descriptor,
6751**      to transfer the rest of the current block.
6752**
6753**----------------------------------------------------------
6754*/
6755
6756static void ncr_int_ma (ncb_p np)
6757{
6758        u_int32 dbc;
6759        u_int32 rest;
6760        u_int32 dsp;
6761        u_int32 dsa;
6762        u_int32 nxtdsp;
6763        u_int32 newtmp;
6764        u_int32 *vdsp;
6765        u_int32 oadr, olen;
6766        u_int32 *tblp;
6767        ncrcmd *newcmd;
6768        u_char  cmd, sbcl;
6769        ccb_p   cp;
6770
6771        dsp     = INL (nc_dsp);
6772        dbc     = INL (nc_dbc);
6773        sbcl    = INB (nc_sbcl);
6774
6775        cmd     = dbc >> 24;
6776        rest    = dbc & 0xffffff;
6777
6778        /*
6779        **      Take into account dma fifo and various buffers and latches,
6780        **      only if the interrupted phase is an OUTPUT phase.
6781        */
6782
6783        if ((cmd & 1) == 0) {
6784                u_char  ctest5, ss0, ss2;
6785                u_short delta;
6786
6787                ctest5 = (np->rv_ctest5 & DFS) ? INB (nc_ctest5) : 0;
6788                if (ctest5 & DFS)
6789                        delta=(((ctest5 << 8) | (INB (nc_dfifo) & 0xff)) - rest) & 0x3ff;
6790                else
6791                        delta=(INB (nc_dfifo) - rest) & 0x7f;
6792
6793                /*
6794                **      The data in the dma fifo has not been transferred to
6795                **      the target -> add the amount to the rest
6796                **      and clear the data.
6797                **      Check the sstat2 register in case of wide transfer.
6798                */
6799
6800                rest += delta;
6801                ss0  = INB (nc_sstat0);
6802                if (ss0 & OLF) rest++;
6803                if (ss0 & ORF) rest++;
6804                if (INB(nc_scntl3) & EWS) {
6805                        ss2 = INB (nc_sstat2);
6806                        if (ss2 & OLF1) rest++;
6807                        if (ss2 & ORF1) rest++;
6808                };
6809
6810                if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE))
6811                        printk ("P%x%x RL=%d D=%d SS0=%x ", cmd&7, sbcl&7,
6812                                (unsigned) rest, (unsigned) delta, ss0);
6813
6814        } else  {
6815                if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE))
6816                        printk ("P%x%x RL=%d ", cmd&7, sbcl&7, rest);
6817        }
6818
6819        /*
6820        **      Clear fifos.
6821        */
6822        OUTONB (nc_ctest3, CLF );       /* clear dma fifo  */
6823        OUTB (nc_stest3, TE|CSF);       /* clear scsi fifo */
6824
6825        /*
6826        **      locate matching cp.
6827        **      if the interrupted phase is DATA IN or DATA OUT,
6828        **      trust the global header.
6829        */
6830        dsa = INL (nc_dsa);
6831        if (!(cmd & 6)) {
6832                cp = np->header.cp;
6833                if (CCB_PHYS(cp, phys) != dsa)
6834                        cp = 0;
6835        } else {
6836                cp  = np->ccb;
6837                while (cp && (CCB_PHYS (cp, phys) != dsa))
6838                        cp = cp->link_ccb;
6839        }
6840
6841        /*
6842        **      try to find the interrupted script command,
6843        **      and the address at which to continue.
6844        */
6845        vdsp    = 0;
6846        nxtdsp  = 0;
6847        if      (dsp >  np->p_script &&
6848                 dsp <= np->p_script + sizeof(struct script)) {
6849                vdsp = (u_int32 *)((char*)np->script0 + (dsp-np->p_script-8));
6850                nxtdsp = dsp;
6851        }
6852        else if (dsp >  np->p_scripth &&
6853                 dsp <= np->p_scripth + sizeof(struct scripth)) {
6854                vdsp = (u_int32 *)((char*)np->scripth0 + (dsp-np->p_scripth-8));
6855                nxtdsp = dsp;
6856        }
6857        else if (cp) {
6858                if      (dsp == CCB_PHYS (cp, patch[2])) {
6859                        vdsp = &cp->patch[0];
6860                        nxtdsp = scr_to_cpu(vdsp[3]);
6861                }
6862                else if (dsp == CCB_PHYS (cp, patch[6])) {
6863                        vdsp = &cp->patch[4];
6864                        nxtdsp = scr_to_cpu(vdsp[3]);
6865                }
6866        }
6867
6868        /*
6869        **      log the information
6870        */
6871
6872        if (DEBUG_FLAGS & DEBUG_PHASE) {
6873                printk ("\nCP=%p CP2=%p DSP=%x NXT=%x VDSP=%p CMD=%x ",
6874                        cp, np->header.cp,
6875                        (unsigned)dsp,
6876                        (unsigned)nxtdsp, vdsp, cmd);
6877        };
6878
6879        /*
6880        **      cp=0 means that the DSA does not point to a valid control 
6881        **      block. This should not happen since we donnot use multi-byte 
6882        **      move while we are being reselected ot after command complete.
6883        **      We are not able to recover from such a phase error.
6884        */
6885        if (!cp) {
6886                printk ("%s: SCSI phase error fixup: "
6887                        "CCB already dequeued (0x%08lx)\n", 
6888                        ncr_name (np), (u_long) np->header.cp);
6889                goto reset_all;
6890        }
6891
6892        /*
6893        **      get old startaddress and old length.
6894        */
6895
6896        oadr = scr_to_cpu(vdsp[1]);
6897
6898        if (cmd & 0x10) {       /* Table indirect */
6899                tblp = (u_int32 *) ((char*) &cp->phys + oadr);
6900                olen = scr_to_cpu(tblp[0]);
6901                oadr = scr_to_cpu(tblp[1]);
6902        } else {
6903                tblp = (u_int32 *) 0;
6904                olen = scr_to_cpu(vdsp[0]) & 0xffffff;
6905        };
6906
6907        if (DEBUG_FLAGS & DEBUG_PHASE) {
6908                printk ("OCMD=%x\nTBLP=%p OLEN=%x OADR=%x\n",
6909                        (unsigned) (scr_to_cpu(vdsp[0]) >> 24),
6910                        tblp,
6911                        (unsigned) olen,
6912                        (unsigned) oadr);
6913        };
6914
6915        /*
6916        **      check cmd against assumed interrupted script command.
6917        */
6918
6919        if (cmd != (scr_to_cpu(vdsp[0]) >> 24)) {
6920                PRINT_ADDR(cp->cmd);
6921                printk ("internal error: cmd=%02x != %02x=(vdsp[0] >> 24)\n",
6922                        (unsigned)cmd, (unsigned)scr_to_cpu(vdsp[0]) >> 24);
6923
6924                goto reset_all;
6925        }
6926
6927        /*
6928        **      cp != np->header.cp means that the header of the CCB 
6929        **      currently being processed has not yet been copied to 
6930        **      the global header area. That may happen if the device did 
6931        **      not accept all our messages after having been selected.
6932        */
6933        if (cp != np->header.cp) {
6934                printk ("%s: SCSI phase error fixup: "
6935                        "CCB address mismatch (0x%08lx != 0x%08lx)\n", 
6936                        ncr_name (np), (u_long) cp, (u_long) np->header.cp);
6937        }
6938
6939        /*
6940        **      if old phase not dataphase, leave here.
6941        */
6942
6943        if (cmd & 0x06) {
6944                PRINT_ADDR(cp->cmd);
6945                printk ("phase change %x-%x %d@%08x resid=%d.\n",
6946                        cmd&7, sbcl&7, (unsigned)olen,
6947                        (unsigned)oadr, (unsigned)rest);
6948                goto unexpected_phase;
6949        };
6950
6951        /*
6952        **      choose the correct patch area.
6953        **      if savep points to one, choose the other.
6954        */
6955
6956        newcmd = cp->patch;
6957        newtmp = CCB_PHYS (cp, patch);
6958        if (newtmp == scr_to_cpu(cp->phys.header.savep)) {
6959                newcmd = &cp->patch[4];
6960                newtmp = CCB_PHYS (cp, patch[4]);
6961        }
6962
6963        /*
6964        **      fillin the commands
6965        */
6966
6967        newcmd[0] = cpu_to_scr(((cmd & 0x0f) << 24) | rest);
6968        newcmd[1] = cpu_to_scr(oadr + olen - rest);
6969        newcmd[2] = cpu_to_scr(SCR_JUMP);
6970        newcmd[3] = cpu_to_scr(nxtdsp);
6971
6972        if (DEBUG_FLAGS & DEBUG_PHASE) {
6973                PRINT_ADDR(cp->cmd);
6974                printk ("newcmd[%d] %x %x %x %x.\n",
6975                        (int) (newcmd - cp->patch),
6976                        (unsigned)scr_to_cpu(newcmd[0]),
6977                        (unsigned)scr_to_cpu(newcmd[1]),
6978                        (unsigned)scr_to_cpu(newcmd[2]),
6979                        (unsigned)scr_to_cpu(newcmd[3]));
6980        }
6981        /*
6982        **      fake the return address (to the patch).
6983        **      and restart script processor at dispatcher.
6984        */
6985        OUTL (nc_temp, newtmp);
6986        OUTL_DSP (NCB_SCRIPT_PHYS (np, dispatch));
6987        return;
6988
6989        /*
6990        **      Unexpected phase changes that occurs when the current phase 
6991        **      is not a DATA IN or DATA OUT phase are due to error conditions.
6992        **      Such event may only happen when the SCRIPTS is using a 
6993        **      multibyte SCSI MOVE.
6994        **
6995        **      Phase change            Some possible cause
6996        **
6997        **      COMMAND  --> MSG IN     SCSI parity error detected by target.
6998        **      COMMAND  --> STATUS     Bad command or refused by target.
6999        **      MSG OUT  --> MSG IN     Message rejected by target.
7000        **      MSG OUT  --> COMMAND    Bogus target that discards extended
7001        **                              negotiation messages.
7002        **
7003        **      The code below does not care of the new phase and so 
7004        **      trusts the target. Why to annoy it ?
7005        **      If the interrupted phase is COMMAND phase, we restart at
7006        **      dispatcher.
7007        **      If a target does not get all the messages after selection, 
7008        **      the code assumes blindly that the target discards extended 
7009        **      messages and clears the negotiation status.
7010        **      If the target does not want all our response to negotiation,
7011        **      we force a SIR_NEGO_PROTO interrupt (it is a hack that avoids 
7012        **      bloat for such a should_not_happen situation).
7013        **      In all other situation, we reset the BUS.
7014        **      Are these assumptions reasonnable ? (Wait and see ...)
7015        */
7016unexpected_phase:
7017        dsp -= 8;
7018        nxtdsp = 0;
7019
7020        switch (cmd & 7) {
7021        case 2: /* COMMAND phase */
7022                nxtdsp = NCB_SCRIPT_PHYS (np, dispatch);
7023                break;
7024#if 0
7025        case 3: /* STATUS  phase */
7026                nxtdsp = NCB_SCRIPT_PHYS (np, dispatch);
7027                break;
7028#endif
7029        case 6: /* MSG OUT phase */
7030                np->scripth->nxtdsp_go_on[0] = cpu_to_scr(dsp + 8);
7031                if      (dsp == NCB_SCRIPT_PHYS (np, send_ident)) {
7032                        cp->host_status = HS_BUSY;
7033                        nxtdsp = NCB_SCRIPTH_PHYS (np, clratn_go_on);
7034                }
7035                else if (dsp == NCB_SCRIPTH_PHYS (np, send_wdtr) ||
7036                         dsp == NCB_SCRIPTH_PHYS (np, send_sdtr)) {
7037                        nxtdsp = NCB_SCRIPTH_PHYS (np, nego_bad_phase);
7038                }
7039                break;
7040#if 0
7041        case 7: /* MSG IN  phase */
7042                nxtdsp = NCB_SCRIPT_PHYS (np, clrack);
7043                break;
7044#endif
7045        }
7046
7047        if (nxtdsp) {
7048                OUTL_DSP (nxtdsp);
7049                return;
7050        }
7051
7052reset_all:
7053        ncr_start_reset(np);
7054}
7055
7056
7057static void ncr_sir_to_redo(ncb_p np, int num, ccb_p cp)
7058{
7059        Scsi_Cmnd *cmd  = cp->cmd;
7060        tcb_p tp        = &np->target[cmd->target];
7061        lcb_p lp        = tp->lp[cmd->lun];
7062        XPT_QUEHEAD     *qp;
7063        ccb_p           cp2;
7064        int             disc_cnt = 0;
7065        int             busy_cnt = 0;
7066        u_int32         startp;
7067        u_char          s_status = INB (SS_PRT);
7068
7069        /*
7070        **      Let the SCRIPTS processor skip all not yet started CCBs,
7071        **      and count disconnected CCBs. Since the busy queue is in 
7072        **      the same order as the chip start queue, disconnected CCBs 
7073        **      are before cp and busy ones after.
7074        */
7075        if (lp) {
7076                qp = lp->busy_ccbq.blink;
7077                while (qp != &lp->busy_ccbq) {
7078                        cp2 = xpt_que_entry(qp, struct ccb, link_ccbq);
7079                        qp  = qp->blink;
7080                        ++busy_cnt;
7081                        if (cp2 == cp)
7082                                break;
7083                        cp2->start.schedule.l_paddr =
7084                        cpu_to_scr(NCB_SCRIPTH_PHYS (np, skip));
7085                }
7086                lp->held_ccb = cp;      /* Requeue when this one completes */
7087                disc_cnt = lp->queuedccbs - busy_cnt;
7088        }
7089
7090        switch(s_status) {
7091        default:        /* Just for safety, should never happen */
7092        case S_QUEUE_FULL:
7093                /*
7094                **      Decrease number of tags to the number of 
7095                **      disconnected commands.
7096                */
7097                if (!lp)
7098                        goto out;
7099                if (bootverbose >= 1) {
7100                        PRINT_ADDR(cmd);
7101                        printk ("QUEUE FULL! %d busy, %d disconnected CCBs\n",
7102                                busy_cnt, disc_cnt);
7103                }
7104                if (disc_cnt < lp->numtags) {
7105                        lp->numtags     = disc_cnt > 2 ? disc_cnt : 2;
7106                        lp->num_good    = 0;
7107                        ncr_setup_tags (np, cmd->target, cmd->lun);
7108                }
7109                /*
7110                **      Requeue the command to the start queue.
7111                **      If any disconnected commands,
7112                **              Clear SIGP.
7113                **              Jump to reselect.
7114                */
7115                cp->phys.header.savep = cp->startp;
7116                cp->host_status = HS_BUSY;
7117                cp->scsi_status = S_ILLEGAL;
7118
7119                ncr_put_start_queue(np, cp);
7120                if (disc_cnt)
7121                        INB (nc_ctest2);                /* Clear SIGP */
7122                OUTL_DSP (NCB_SCRIPT_PHYS (np, reselect));
7123                return;
7124        case S_TERMINATED:
7125        case S_CHECK_COND:
7126                /*
7127                **      If we were requesting sense, give up.
7128                */
7129                if (cp->auto_sense)
7130                        goto out;
7131
7132                /*
7133                **      Device returned CHECK CONDITION status.
7134                **      Prepare all needed data strutures for getting 
7135                **      sense data.
7136                **
7137                **      identify message
7138                */
7139                cp->scsi_smsg2[0]       = M_IDENTIFY | cmd->lun;
7140                cp->phys.smsg.addr      = cpu_to_scr(CCB_PHYS (cp, scsi_smsg2));
7141                cp->phys.smsg.size      = cpu_to_scr(1);
7142
7143                /*
7144                **      sense command
7145                */
7146                cp->phys.cmd.addr       = cpu_to_scr(CCB_PHYS (cp, sensecmd));
7147                cp->phys.cmd.size       = cpu_to_scr(6);
7148
7149                /*
7150                **      patch requested size into sense command
7151                */
7152                cp->sensecmd[0]         = 0x03;
7153                cp->sensecmd[1]         = cmd->lun << 5;
7154                cp->sensecmd[4]         = sizeof(cp->sense_buf);
7155
7156                /*
7157                **      sense data
7158                */
7159                bzero(cp->sense_buf, sizeof(cp->sense_buf));
7160                cp->phys.sense.addr     = cpu_to_scr(CCB_PHYS(cp,sense_buf[0]));
7161                cp->phys.sense.size     = cpu_to_scr(sizeof(cp->sense_buf));
7162
7163                /*
7164                **      requeue the command.
7165                */
7166                startp = cpu_to_scr(NCB_SCRIPTH_PHYS (np, sdata_in));
7167
7168                cp->phys.header.savep   = startp;
7169                cp->phys.header.goalp   = startp + 24;
7170                cp->phys.header.lastp   = startp;
7171                cp->phys.header.wgoalp  = startp + 24;
7172                cp->phys.header.wlastp  = startp;
7173
7174                cp->host_status = HS_BUSY;
7175                cp->scsi_status = S_ILLEGAL;
7176                cp->auto_sense  = s_status;
7177
7178                cp->start.schedule.l_paddr =
7179                        cpu_to_scr(NCB_SCRIPT_PHYS (np, select));
7180
7181                /*
7182                **      Select without ATN for quirky devices.
7183                */
7184                if (tp->quirks & QUIRK_NOMSG)
7185                        cp->start.schedule.l_paddr =
7186                        cpu_to_scr(NCB_SCRIPTH_PHYS (np, select_no_atn));
7187
7188                ncr_put_start_queue(np, cp);
7189
7190                OUTL_DSP (NCB_SCRIPT_PHYS (np, start));
7191                return;
7192        }
7193
7194out:
7195        OUTONB_STD ();
7196        return;
7197}
7198
7199
7200/*==========================================================
7201**
7202**
7203**      ncr chip exception handler for programmed interrupts.
7204**
7205**
7206**==========================================================
7207*/
7208
7209static int ncr_show_msg (u_char * msg)
7210{
7211        u_char i;
7212        printk ("%x",*msg);
7213        if (*msg==M_EXTENDED) {
7214                for (i=1;i<8;i++) {
7215                        if (i-1>msg[1]) break;
7216                        printk ("-%x",msg[i]);
7217                };
7218                return (i+1);
7219        } else if ((*msg & 0xf0) == 0x20) {
7220                printk ("-%x",msg[1]);
7221                return (2);
7222        };
7223        return (1);
7224}
7225
7226static void ncr_print_msg ( ccb_p cp, char *label, u_char *msg)
7227{
7228        if (cp)
7229                PRINT_ADDR(cp->cmd);
7230        if (label)
7231                printk("%s: ", label);
7232        
7233        (void) ncr_show_msg (msg);
7234        printk(".\n");
7235}
7236
7237void ncr_int_sir (ncb_p np)
7238{
7239        u_char scntl3;
7240        u_char chg, ofs, per, fak, wide;
7241        u_char num = INB (nc_dsps);
7242        ccb_p   cp=0;
7243        u_long  dsa    = INL (nc_dsa);
7244        u_char  target = INB (nc_sdid) & 0x0f;
7245        tcb_p   tp     = &np->target[target];
7246
7247        if (DEBUG_FLAGS & DEBUG_TINY) printk ("I#%d", num);
7248
7249        switch (num) {
7250        case SIR_INTFLY:
7251                /*
7252                **      This is used for HP Zalon/53c720 where INTFLY
7253                **      operation is currently broken.
7254                */
7255                ncr_wakeup_done(np);
7256#ifdef SCSI_NCR_CCB_DONE_SUPPORT
7257                OUTL(nc_dsp, NCB_SCRIPT_PHYS (np, done_end) + 8);
7258#else
7259                OUTL(nc_dsp, NCB_SCRIPT_PHYS (np, start));
7260#endif
7261                return;
7262        case SIR_RESEL_NO_MSG_IN:
7263        case SIR_RESEL_NO_IDENTIFY:
7264                /*
7265                **      If devices reselecting without sending an IDENTIFY 
7266                **      message still exist, this should help.
7267                **      We just assume lun=0, 1 CCB, no tag.
7268                */
7269                if (tp->lp[0]) { 
7270                        OUTL_DSP (scr_to_cpu(tp->lp[0]->jump_ccb[0]));
7271                        return;
7272                }
7273        case SIR_RESEL_BAD_TARGET:      /* Will send a TARGET RESET message */
7274        case SIR_RESEL_BAD_LUN:         /* Will send a TARGET RESET message */
7275        case SIR_RESEL_BAD_I_T_L_Q:     /* Will send an ABORT TAG message   */
7276        case SIR_RESEL_BAD_I_T_L:       /* Will send an ABORT message       */
7277                printk ("%s:%d: SIR %d, "
7278                        "incorrect nexus identification on reselection\n",
7279                        ncr_name (np), target, num);
7280                goto out;
7281        case SIR_DONE_OVERFLOW:
7282                printk ("%s:%d: SIR %d, "
7283                        "CCB done queue overflow\n",
7284                        ncr_name (np), target, num);
7285                goto out;
7286        case SIR_BAD_STATUS:
7287                cp = np->header.cp;
7288                if (!cp || CCB_PHYS (cp, phys) != dsa)
7289                        goto out;
7290                ncr_sir_to_redo(np, num, cp);
7291                return;
7292        default:
7293                /*
7294                **      lookup the ccb
7295                */
7296                cp = np->ccb;
7297                while (cp && (CCB_PHYS (cp, phys) != dsa))
7298                        cp = cp->link_ccb;
7299
7300                assert (cp && cp == np->header.cp);
7301
7302                if (!cp || cp != np->header.cp)
7303                        goto out;
7304        }
7305
7306        switch (num) {
7307/*-----------------------------------------------------------------------------
7308**
7309**      Was Sie schon immer ueber transfermode negotiation wissen wollten ...
7310**
7311**      We try to negotiate sync and wide transfer only after
7312**      a successful inquire command. We look at byte 7 of the
7313**      inquire data to determine the capabilities of the target.
7314**
7315**      When we try to negotiate, we append the negotiation message
7316**      to the identify and (maybe) simple tag message.
7317**      The host status field is set to HS_NEGOTIATE to mark this
7318**      situation.
7319**
7320**      If the target doesn't answer this message immidiately
7321**      (as required by the standard), the SIR_NEGO_FAIL interrupt
7322**      will be raised eventually.
7323**      The handler removes the HS_NEGOTIATE status, and sets the
7324**      negotiated value to the default (async / nowide).
7325**
7326**      If we receive a matching answer immediately, we check it
7327**      for validity, and set the values.
7328**
7329**      If we receive a Reject message immediately, we assume the
7330**      negotiation has failed, and fall back to standard values.
7331**
7332**      If we receive a negotiation message while not in HS_NEGOTIATE
7333**      state, it's a target initiated negotiation. We prepare a
7334**      (hopefully) valid answer, set our parameters, and send back 
7335**      this answer to the target.
7336**
7337**      If the target doesn't fetch the answer (no message out phase),
7338**      we assume the negotiation has failed, and fall back to default
7339**      settings.
7340**
7341**      When we set the values, we adjust them in all ccbs belonging 
7342**      to this target, in the controller's register, and in the "phys"
7343**      field of the controller's struct ncb.
7344**
7345**      Possible cases:            hs  sir   msg_in value  send   goto
7346**      We try to negotiate:
7347**      -> target doesn't msgin    NEG FAIL  noop   defa.  -      dispatch
7348**      -> target rejected our msg NEG FAIL  reject defa.  -      dispatch
7349**      -> target answered  (ok)   NEG SYNC  sdtr   set    -      clrack
7350**      -> target answered (!ok)   NEG SYNC  sdtr   defa.  REJ--->msg_bad
7351**      -> target answered  (ok)   NEG WIDE  wdtr   set    -      clrack
7352**      -> target answered (!ok)   NEG WIDE  wdtr   defa.  REJ--->msg_bad
7353**      -> any other msgin         NEG FAIL  noop   defa.  -      dispatch
7354**
7355**      Target tries to negotiate:
7356**      -> incoming message        --- SYNC  sdtr   set    SDTR   -
7357**      -> incoming message        --- WIDE  wdtr   set    WDTR   -
7358**      We sent our answer:
7359**      -> target doesn't msgout   --- PROTO ?      defa.  -      dispatch
7360**
7361**-----------------------------------------------------------------------------
7362*/
7363
7364        case SIR_NEGO_FAILED:
7365                /*-------------------------------------------------------
7366                **
7367                **      Negotiation failed.
7368                **      Target doesn't send an answer message,
7369                **      or target rejected our message.
7370                **
7371                **      Remove negotiation request.
7372                **
7373                **-------------------------------------------------------
7374                */
7375                OUTB (HS_PRT, HS_BUSY);
7376
7377                /* fall through */
7378
7379        case SIR_NEGO_PROTO:
7380                /*-------------------------------------------------------
7381                **
7382                **      Negotiation failed.
7383                **      Target doesn't fetch the answer message.
7384                **
7385                **-------------------------------------------------------
7386                */
7387
7388                if (DEBUG_FLAGS & DEBUG_NEGO) {
7389                        PRINT_ADDR(cp->cmd);
7390                        printk ("negotiation failed sir=%x status=%x.\n",
7391                                num, cp->nego_status);
7392                };
7393
7394                /*
7395                **      any error in negotiation:
7396                **      fall back to default mode.
7397                */
7398                switch (cp->nego_status) {
7399
7400                case NS_SYNC:
7401                        ncr_setsync (np, cp, 0, 0xe0);
7402                        break;
7403
7404                case NS_WIDE:
7405                        ncr_setwide (np, cp, 0, 0);
7406                        break;
7407
7408                };
7409                np->msgin [0] = M_NOOP;
7410                np->msgout[0] = M_NOOP;
7411                cp->nego_status = 0;
7412                break;
7413
7414        case SIR_NEGO_SYNC:
7415                /*
7416                **      Synchronous request message received.
7417                */
7418
7419                if (DEBUG_FLAGS & DEBUG_NEGO) {
7420                        PRINT_ADDR(cp->cmd);
7421                        printk ("sync msgin: ");
7422                        (void) ncr_show_msg (np->msgin);
7423                        printk (".\n");
7424                };
7425
7426                /*
7427                **      get requested values.
7428                */
7429
7430                chg = 0;
7431                per = np->msgin[3];
7432                ofs = np->msgin[4];
7433                if (ofs==0) per=255;
7434
7435                /*
7436                **      if target sends SDTR message,
7437                **            it CAN transfer synch.
7438                */
7439
7440                if (ofs)
7441                        tp->inq_byte7 |= INQ7_SYNC;
7442
7443                /*
7444                **      check values against driver limits.
7445                */
7446
7447                if (per < np->minsync)
7448                        {chg = 1; per = np->minsync;}
7449                if (per < tp->minsync)
7450                        {chg = 1; per = tp->minsync;}
7451                if (ofs > tp->maxoffs)
7452                        {chg = 1; ofs = tp->maxoffs;}
7453
7454                /*
7455                **      Check against controller limits.
7456                */
7457                fak     = 7;
7458                scntl3  = 0;
7459                if (ofs != 0) {
7460                        ncr_getsync(np, per, &fak, &scntl3);
7461                        if (fak > 7) {
7462                                chg = 1;
7463                                ofs = 0;
7464                        }
7465                }
7466                if (ofs == 0) {
7467                        fak     = 7;
7468                        per     = 0;
7469                        scntl3  = 0;
7470                        tp->minsync = 0;
7471                }
7472
7473                if (DEBUG_FLAGS & DEBUG_NEGO) {
7474                        PRINT_ADDR(cp->cmd);
7475                        printk ("sync: per=%d scntl3=0x%x ofs=%d fak=%d chg=%d.\n",
7476                                per, scntl3, ofs, fak, chg);
7477                }
7478
7479                if (INB (HS_PRT) == HS_NEGOTIATE) {
7480                        OUTB (HS_PRT, HS_BUSY);
7481                        switch (cp->nego_status) {
7482
7483                        case NS_SYNC:
7484                                /*
7485                                **      This was an answer message
7486                                */
7487                                if (chg) {
7488                                        /*
7489                                        **      Answer wasn't acceptable.
7490                                        */
7491                                        ncr_setsync (np, cp, 0, 0xe0);
7492                                        OUTL_DSP (NCB_SCRIPT_PHYS (np, msg_bad));
7493                                } else {
7494                                        /*
7495                                        **      Answer is ok.
7496                                        */
7497                                        ncr_setsync (np, cp, scntl3, (fak<<5)|ofs);
7498                                        OUTL_DSP (NCB_SCRIPT_PHYS (np, clrack));
7499                                };
7500                                return;
7501
7502                        case NS_WIDE:
7503                                ncr_setwide (np, cp, 0, 0);
7504                                break;
7505                        };
7506                };
7507
7508                /*
7509                **      It was a request. Set value and
7510                **      prepare an answer message
7511                */
7512
7513                ncr_setsync (np, cp, scntl3, (fak<<5)|ofs);
7514
7515                np->msgout[0] = M_EXTENDED;
7516                np->msgout[1] = 3;
7517                np->msgout[2] = M_X_SYNC_REQ;
7518                np->msgout[3] = per;
7519                np->msgout[4] = ofs;
7520
7521                cp->nego_status = NS_SYNC;
7522
7523                if (DEBUG_FLAGS & DEBUG_NEGO) {
7524                        PRINT_ADDR(cp->cmd);
7525                        printk ("sync msgout: ");
7526                        (void) ncr_show_msg (np->msgout);
7527                        printk (".\n");
7528                }
7529
7530                if (!ofs) {
7531                        OUTL_DSP (NCB_SCRIPT_PHYS (np, msg_bad));
7532                        return;
7533                }
7534                np->msgin [0] = M_NOOP;
7535
7536                break;
7537
7538        case SIR_NEGO_WIDE:
7539                /*
7540                **      Wide request message received.
7541                */
7542                if (DEBUG_FLAGS & DEBUG_NEGO) {
7543                        PRINT_ADDR(cp->cmd);
7544                        printk ("wide msgin: ");
7545                        (void) ncr_show_msg (np->msgin);
7546                        printk (".\n");
7547                };
7548
7549                /*
7550                **      get requested values.
7551                */
7552
7553                chg  = 0;
7554                wide = np->msgin[3];
7555
7556                /*
7557                **      if target sends WDTR message,
7558                **            it CAN transfer wide.
7559                */
7560
7561                if (wide)
7562                        tp->inq_byte7 |= INQ7_WIDE16;
7563
7564                /*
7565                **      check values against driver limits.
7566                */
7567
7568                if (wide > tp->usrwide)
7569                        {chg = 1; wide = tp->usrwide;}
7570
7571                if (DEBUG_FLAGS & DEBUG_NEGO) {
7572                        PRINT_ADDR(cp->cmd);
7573                        printk ("wide: wide=%d chg=%d.\n", wide, chg);
7574                }
7575
7576                if (INB (HS_PRT) == HS_NEGOTIATE) {
7577                        OUTB (HS_PRT, HS_BUSY);
7578                        switch (cp->nego_status) {
7579
7580                        case NS_WIDE:
7581                                /*
7582                                **      This was an answer message
7583                                */
7584                                if (chg) {
7585                                        /*
7586                                        **      Answer wasn't acceptable.
7587                                        */
7588                                        ncr_setwide (np, cp, 0, 1);
7589                                        OUTL_DSP (NCB_SCRIPT_PHYS (np, msg_bad));
7590                                } else {
7591                                        /*
7592                                        **      Answer is ok.
7593                                        */
7594                                        ncr_setwide (np, cp, wide, 1);
7595                                        OUTL_DSP (NCB_SCRIPT_PHYS (np, clrack));
7596                                };
7597                                return;
7598
7599                        case NS_SYNC:
7600                                ncr_setsync (np, cp, 0, 0xe0);
7601                                break;
7602                        };
7603                };
7604
7605                /*
7606                **      It was a request, set value and
7607                **      prepare an answer message
7608                */
7609
7610                ncr_setwide (np, cp, wide, 1);
7611
7612                np->msgout[0] = M_EXTENDED;
7613                np->msgout[1] = 2;
7614                np->msgout[2] = M_X_WIDE_REQ;
7615                np->msgout[3] = wide;
7616
7617                np->msgin [0] = M_NOOP;
7618
7619                cp->nego_status = NS_WIDE;
7620
7621                if (DEBUG_FLAGS & DEBUG_NEGO) {
7622                        PRINT_ADDR(cp->cmd);
7623                        printk ("wide msgout: ");
7624                        (void) ncr_show_msg (np->msgin);
7625                        printk (".\n");
7626                }
7627                break;
7628
7629/*--------------------------------------------------------------------
7630**
7631**      Processing of special messages
7632**
7633**--------------------------------------------------------------------
7634*/
7635
7636        case SIR_REJECT_RECEIVED:
7637                /*-----------------------------------------------
7638                **
7639                **      We received a M_REJECT message.
7640                **
7641                **-----------------------------------------------
7642                */
7643
7644                PRINT_ADDR(cp->cmd);
7645                printk ("M_REJECT received (%x:%x).\n",
7646                        (unsigned)scr_to_cpu(np->lastmsg), np->msgout[0]);
7647                break;
7648
7649        case SIR_REJECT_SENT:
7650                /*-----------------------------------------------
7651                **
7652                **      We received an unknown message
7653                **
7654                **-----------------------------------------------
7655                */
7656
7657                PRINT_ADDR(cp->cmd);
7658                printk ("M_REJECT sent for ");
7659                (void) ncr_show_msg (np->msgin);
7660                printk (".\n");
7661                break;
7662
7663/*--------------------------------------------------------------------
7664**
7665**      Processing of special messages
7666**
7667**--------------------------------------------------------------------
7668*/
7669
7670        case SIR_IGN_RESIDUE:
7671                /*-----------------------------------------------
7672                **
7673                **      We received an IGNORE RESIDUE message,
7674                **      which couldn't be handled by the script.
7675                **
7676                **-----------------------------------------------
7677                */
7678
7679                PRINT_ADDR(cp->cmd);
7680                printk ("M_IGN_RESIDUE received, but not yet implemented.\n");
7681                break;
7682#if 0
7683        case SIR_MISSING_SAVE:
7684                /*-----------------------------------------------
7685                **
7686                **      We received an DISCONNECT message,
7687                **      but the datapointer wasn't saved before.
7688                **
7689                **-----------------------------------------------
7690                */
7691
7692                PRINT_ADDR(cp->cmd);
7693                printk ("M_DISCONNECT received, but datapointer not saved: "
7694                        "data=%x save=%x goal=%x.\n",
7695                        (unsigned) INL (nc_temp),
7696                        (unsigned) scr_to_cpu(np->header.savep),
7697                        (unsigned) scr_to_cpu(np->header.goalp));
7698                break;
7699#endif
7700        };
7701
7702out:
7703        OUTONB_STD ();
7704}
7705
7706/*==========================================================
7707**
7708**
7709**      Acquire a control block
7710**
7711**
7712**==========================================================
7713*/
7714
7715static  ccb_p ncr_get_ccb (ncb_p np, u_char tn, u_char ln)
7716{
7717        tcb_p tp = &np->target[tn];
7718        lcb_p lp = tp->lp[ln];
7719        u_char tag = NO_TAG;
7720        ccb_p cp = (ccb_p) 0;
7721
7722        /*
7723        **      Lun structure available ?
7724        */
7725        if (lp) {
7726                XPT_QUEHEAD *qp;
7727                /*
7728                **      Keep from using more tags than we can handle.
7729                */
7730                if (lp->usetags && lp->busyccbs >= lp->maxnxs)
7731                        return (ccb_p) 0;
7732
7733                /*
7734                **      Allocate a new CCB if needed.
7735                */
7736                if (xpt_que_empty(&lp->free_ccbq))
7737                        ncr_alloc_ccb(np, tn, ln);
7738
7739                /*
7740                **      Tune tag mode if asked by user.
7741                */
7742                if (lp->queuedepth != lp->numtags) {
7743                        ncr_setup_tags(np, tn, ln);
7744                }
7745                        
7746                /*
7747                **      Look for free CCB
7748                */
7749                qp = xpt_remque_head(&lp->free_ccbq);
7750                if (qp) {
7751                        cp = xpt_que_entry(qp, struct ccb, link_ccbq);
7752                        if (cp->magic) {
7753                                PRINT_LUN(np, tn, ln);
7754                                printk ("ccb free list corrupted (@%p)\n", cp);
7755                                cp = 0;
7756                        }
7757                        else {
7758                                xpt_insque_tail(qp, &lp->wait_ccbq);
7759                                ++lp->busyccbs;
7760                        }
7761                }
7762
7763                /*
7764                **      If a CCB is available,
7765                **      Get a tag for this nexus if required.
7766                */
7767                if (cp) {
7768                        if (lp->usetags)
7769                                tag = lp->cb_tags[lp->ia_tag];
7770                }
7771                else if (lp->actccbs > 0)
7772                        return (ccb_p) 0;
7773        }
7774
7775        /*
7776        **      if nothing available, take the default.
7777        */
7778        if (!cp)
7779                cp = np->ccb;
7780
7781        /*
7782        **      Wait until available.
7783        */
7784#if 0
7785        while (cp->magic) {
7786                if (flags & SCSI_NOSLEEP) break;
7787                if (tsleep ((caddr_t)cp, PRIBIO|PCATCH, "ncr", 0))
7788                        break;
7789        };
7790#endif
7791
7792        if (cp->magic)
7793                return ((ccb_p) 0);
7794
7795        cp->magic = 1;
7796
7797        /*
7798        **      Move to next available tag if tag used.
7799        */
7800        if (lp) {
7801                if (tag != NO_TAG) {
7802                        ++lp->ia_tag;
7803                        if (lp->ia_tag == MAX_TAGS)
7804                                lp->ia_tag = 0;
7805                        lp->tags_umap |= (((tagmap_t) 1) << tag);
7806                }
7807        }
7808
7809        /*
7810        **      Remember all informations needed to free this CCB.
7811        */
7812        cp->tag    = tag;
7813        cp->target = tn;
7814        cp->lun    = ln;
7815
7816        if (DEBUG_FLAGS & DEBUG_TAGS) {
7817                PRINT_LUN(np, tn, ln);
7818                printk ("ccb @%p using tag %d.\n", cp, tag);
7819        }
7820
7821        return cp;
7822}
7823
7824/*==========================================================
7825**
7826**
7827**      Release one control block
7828**
7829**
7830**==========================================================
7831*/
7832
7833static void ncr_free_ccb (ncb_p np, ccb_p cp)
7834{
7835        tcb_p tp = &np->target[cp->target];
7836        lcb_p lp = tp->lp[cp->lun];
7837
7838        if (DEBUG_FLAGS & DEBUG_TAGS) {
7839                PRINT_LUN(np, cp->target, cp->lun);
7840                printk ("ccb @%p freeing tag %d.\n", cp, cp->tag);
7841        }
7842
7843        /*
7844        **      If lun control block available,
7845        **      decrement active commands and increment credit, 
7846        **      free the tag if any and remove the JUMP for reselect.
7847        */
7848        if (lp) {
7849                if (cp->tag != NO_TAG) {
7850                        lp->cb_tags[lp->if_tag++] = cp->tag;
7851                        if (lp->if_tag == MAX_TAGS)
7852                                lp->if_tag = 0;
7853                        lp->tags_umap &= ~(((tagmap_t) 1) << cp->tag);
7854                        lp->tags_smap &= lp->tags_umap;
7855                        lp->jump_ccb[cp->tag] =
7856                                cpu_to_scr(NCB_SCRIPTH_PHYS(np, bad_i_t_l_q));
7857                } else {
7858                        lp->jump_ccb[0] =
7859                                cpu_to_scr(NCB_SCRIPTH_PHYS(np, bad_i_t_l));
7860                }
7861        }
7862
7863        /*
7864        **      Make this CCB available.
7865        */
7866
7867        if (lp) {
7868                if (cp != np->ccb) {
7869                        xpt_remque(&cp->link_ccbq);
7870                        xpt_insque_head(&cp->link_ccbq, &lp->free_ccbq);
7871                }
7872                --lp->busyccbs;
7873                if (cp->queued) {
7874                        --lp->queuedccbs;
7875                }
7876        }
7877        cp -> host_status = HS_IDLE;
7878        cp -> magic = 0;
7879        if (cp->queued) {
7880                --np->queuedccbs;
7881                cp->queued = 0;
7882        }
7883
7884#if 0
7885        if (cp == np->ccb)
7886                wakeup ((caddr_t) cp);
7887#endif
7888}
7889
7890
7891#define ncr_reg_bus_addr(r) (np->paddr + offsetof (struct ncr_reg, r))
7892
7893/*------------------------------------------------------------------------
7894**      Initialize the fixed part of a CCB structure.
7895**------------------------------------------------------------------------
7896**------------------------------------------------------------------------
7897*/
7898static void ncr_init_ccb(ncb_p np, ccb_p cp)
7899{
7900        ncrcmd copy_4 = np->features & FE_PFEN ? SCR_COPY(4) : SCR_COPY_F(4);
7901
7902        /*
7903        **      Remember virtual and bus address of this ccb.
7904        */
7905        cp->p_ccb          = vtobus(cp);
7906        cp->phys.header.cp = cp;
7907
7908        /*
7909        **      This allows xpt_remque to work for the default ccb.
7910        */
7911        xpt_que_init(&cp->link_ccbq);
7912
7913        /*
7914        **      Initialyze the start and restart launch script.
7915        **
7916        **      COPY(4) @(...p_phys), @(dsa)
7917        **      JUMP @(sched_point)
7918        */
7919        cp->start.setup_dsa[0]   = cpu_to_scr(copy_4);
7920        cp->start.setup_dsa[1]   = cpu_to_scr(CCB_PHYS(cp, start.p_phys));
7921        cp->start.setup_dsa[2]   = cpu_to_scr(ncr_reg_bus_addr(nc_dsa));
7922        cp->start.schedule.l_cmd = cpu_to_scr(SCR_JUMP);
7923        cp->start.p_phys         = cpu_to_scr(CCB_PHYS(cp, phys));
7924
7925        bcopy(&cp->start, &cp->restart, sizeof(cp->restart));
7926
7927        cp->start.schedule.l_paddr   = cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
7928        cp->restart.schedule.l_paddr = cpu_to_scr(NCB_SCRIPTH_PHYS (np, abort));
7929}
7930
7931
7932/*------------------------------------------------------------------------
7933**      Allocate a CCB and initialize its fixed part.
7934**------------------------------------------------------------------------
7935**------------------------------------------------------------------------
7936*/
7937static void ncr_alloc_ccb(ncb_p np, u_char tn, u_char ln)
7938{
7939        tcb_p tp = &np->target[tn];
7940        lcb_p lp = tp->lp[ln];
7941        ccb_p cp = 0;
7942
7943        /*
7944        **      Allocate memory for this CCB.
7945        */
7946        cp = m_calloc_dma(sizeof(struct ccb), "CCB");
7947        if (!cp)
7948                return;
7949
7950        /*
7951        **      Count it and initialyze it.
7952        */
7953        lp->actccbs++;
7954        np->actccbs++;
7955        bzero (cp, sizeof (*cp));
7956        ncr_init_ccb(np, cp);
7957
7958        /*
7959        **      Chain into wakeup list and free ccb queue and take it 
7960        **      into account for tagged commands.
7961        */
7962        cp->link_ccb      = np->ccb->link_ccb;
7963        np->ccb->link_ccb = cp;
7964
7965        xpt_insque_head(&cp->link_ccbq, &lp->free_ccbq);
7966        ncr_setup_tags (np, tn, ln);
7967}
7968
7969/*==========================================================
7970**
7971**
7972**      Allocation of resources for Targets/Luns/Tags.
7973**
7974**
7975**==========================================================
7976*/
7977
7978
7979/*------------------------------------------------------------------------
7980**      Target control block initialisation.
7981**------------------------------------------------------------------------
7982**      This data structure is fully initialized after a SCSI command 
7983**      has been successfully completed for this target.
7984**      It contains a SCRIPT that is called on target reselection.
7985**------------------------------------------------------------------------
7986*/
7987static void ncr_init_tcb (ncb_p np, u_char tn)
7988{
7989        tcb_p tp = &np->target[tn];
7990        ncrcmd copy_1 = np->features & FE_PFEN ? SCR_COPY(1) : SCR_COPY_F(1);
7991        int th = tn & 3;
7992        int i;
7993
7994        /*
7995        **      Jump to next tcb if SFBR does not match this target.
7996        **      JUMP  IF (SFBR != #target#), @(next tcb)
7997        */
7998        tp->jump_tcb.l_cmd   =
7999                cpu_to_scr((SCR_JUMP ^ IFFALSE (DATA (0x80 + tn))));
8000        tp->jump_tcb.l_paddr = np->jump_tcb[th].l_paddr;
8001
8002        /*
8003        **      Load the synchronous transfer register.
8004        **      COPY @(tp->sval), @(sxfer)
8005        */
8006        tp->getscr[0] = cpu_to_scr(copy_1);
8007        tp->getscr[1] = cpu_to_scr(vtobus (&tp->sval));
8008#ifdef SCSI_NCR_BIG_ENDIAN
8009        tp->getscr[2] = cpu_to_scr(ncr_reg_bus_addr(nc_sxfer) ^ 3);
8010#else
8011        tp->getscr[2] = cpu_to_scr(ncr_reg_bus_addr(nc_sxfer));
8012#endif
8013
8014        /*
8015        **      Load the timing register.
8016        **      COPY @(tp->wval), @(scntl3)
8017        */
8018        tp->getscr[3] = cpu_to_scr(copy_1);
8019        tp->getscr[4] = cpu_to_scr(vtobus (&tp->wval));
8020#ifdef SCSI_NCR_BIG_ENDIAN
8021        tp->getscr[5] = cpu_to_scr(ncr_reg_bus_addr(nc_scntl3) ^ 3);
8022#else
8023        tp->getscr[5] = cpu_to_scr(ncr_reg_bus_addr(nc_scntl3));
8024#endif
8025
8026        /*
8027        **      Get the IDENTIFY message and the lun.
8028        **      CALL @script(resel_lun)
8029        */
8030        tp->call_lun.l_cmd   = cpu_to_scr(SCR_CALL);
8031        tp->call_lun.l_paddr = cpu_to_scr(NCB_SCRIPT_PHYS (np, resel_lun));
8032
8033        /*
8034        **      Look for the lun control block of this nexus.
8035        **      For i = 0 to 3
8036        **              JUMP ^ IFTRUE (MASK (i, 3)), @(next_lcb)
8037        */
8038        for (i = 0 ; i < 4 ; i++) {
8039                tp->jump_lcb[i].l_cmd   =
8040                                cpu_to_scr((SCR_JUMP ^ IFTRUE (MASK (i, 3))));
8041                tp->jump_lcb[i].l_paddr =
8042                                cpu_to_scr(NCB_SCRIPTH_PHYS (np, bad_identify));
8043        }
8044
8045        /*
8046        **      Link this target control block to the JUMP chain.
8047        */
8048        np->jump_tcb[th].l_paddr = cpu_to_scr(vtobus (&tp->jump_tcb));
8049
8050        /*
8051        **      These assert's should be moved at driver initialisations.
8052        */
8053#ifdef SCSI_NCR_BIG_ENDIAN
8054        assert (( (offsetof(struct ncr_reg, nc_sxfer) ^
8055                offsetof(struct tcb    , sval    )) &3) == 3);
8056        assert (( (offsetof(struct ncr_reg, nc_scntl3) ^
8057                offsetof(struct tcb    , wval    )) &3) == 3);
8058#else
8059        assert (( (offsetof(struct ncr_reg, nc_sxfer) ^
8060                offsetof(struct tcb    , sval    )) &3) == 0);
8061        assert (( (offsetof(struct ncr_reg, nc_scntl3) ^
8062                offsetof(struct tcb    , wval    )) &3) == 0);
8063#endif
8064}
8065
8066
8067/*------------------------------------------------------------------------
8068**      Lun control block allocation and initialization.
8069**------------------------------------------------------------------------
8070**      This data structure is allocated and initialized after a SCSI 
8071**      command has been successfully completed for this target/lun.
8072**------------------------------------------------------------------------
8073*/
8074static lcb_p ncr_alloc_lcb (ncb_p np, u_char tn, u_char ln)
8075{
8076        tcb_p tp = &np->target[tn];
8077        lcb_p lp = tp->lp[ln];
8078        ncrcmd copy_4 = np->features & FE_PFEN ? SCR_COPY(4) : SCR_COPY_F(4);
8079        int lh = ln & 3;
8080
8081        /*
8082        **      Already done, return.
8083        */
8084        if (lp)
8085                return lp;
8086
8087        /*
8088        **      Allocate the lcb.
8089        */
8090        lp = m_calloc_dma(sizeof(struct lcb), "LCB");
8091        if (!lp)
8092                goto fail;
8093        bzero(lp, sizeof(*lp));
8094        tp->lp[ln] = lp;
8095
8096        /*
8097        **      Initialize the target control block if not yet.
8098        */
8099        if (!tp->jump_tcb.l_cmd)
8100                ncr_init_tcb(np, tn);
8101
8102        /*
8103        **      Initialize the CCB queue headers.
8104        */
8105        xpt_que_init(&lp->free_ccbq);
8106        xpt_que_init(&lp->busy_ccbq);
8107        xpt_que_init(&lp->wait_ccbq);
8108        xpt_que_init(&lp->skip_ccbq);
8109
8110        /*
8111        **      Set max CCBs to 1 and use the default 1 entry 
8112        **      jump table by default.
8113        */
8114        lp->maxnxs      = 1;
8115        lp->jump_ccb    = &lp->jump_ccb_0;
8116        lp->p_jump_ccb  = cpu_to_scr(vtobus(lp->jump_ccb));
8117
8118        /*
8119        **      Initilialyze the reselect script:
8120        **
8121        **      Jump to next lcb if SFBR does not match this lun.
8122        **      Load TEMP with the CCB direct jump table bus address.
8123        **      Get the SIMPLE TAG message and the tag.
8124        **
8125        **      JUMP  IF (SFBR != #lun#), @(next lcb)
8126        **      COPY @(lp->p_jump_ccb),   @(temp)
8127        **      JUMP @script(resel_notag)
8128        */
8129        lp->jump_lcb.l_cmd   =
8130                cpu_to_scr((SCR_JUMP ^ IFFALSE (MASK (0x80+ln, 0xff))));
8131        lp->jump_lcb.l_paddr = tp->jump_lcb[lh].l_paddr;
8132
8133        lp->load_jump_ccb[0] = cpu_to_scr(copy_4);
8134        lp->load_jump_ccb[1] = cpu_to_scr(vtobus (&lp->p_jump_ccb));
8135        lp->load_jump_ccb[2] = cpu_to_scr(ncr_reg_bus_addr(nc_temp));
8136
8137        lp->jump_tag.l_cmd   = cpu_to_scr(SCR_JUMP);
8138        lp->jump_tag.l_paddr = cpu_to_scr(NCB_SCRIPT_PHYS (np, resel_notag));
8139
8140        /*
8141        **      Link this lun control block to the JUMP chain.
8142        */
8143        tp->jump_lcb[lh].l_paddr = cpu_to_scr(vtobus (&lp->jump_lcb));
8144
8145        /*
8146        **      Initialize command queuing control.
8147        */
8148        lp->busyccbs    = 1;
8149        lp->queuedccbs  = 1;
8150        lp->queuedepth  = 1;
8151fail:
8152        return lp;
8153}
8154
8155
8156/*------------------------------------------------------------------------
8157**      Lun control block setup on INQUIRY data received.
8158**------------------------------------------------------------------------
8159**      We only support WIDE, SYNC for targets and CMDQ for logical units.
8160**      This setup is done on each INQUIRY since we are expecting user 
8161**      will play with CHANGE DEFINITION commands. :-)
8162**------------------------------------------------------------------------
8163*/
8164static lcb_p ncr_setup_lcb (ncb_p np, u_char tn, u_char ln, u_char *inq_data)
8165{
8166        tcb_p tp = &np->target[tn];
8167        lcb_p lp = tp->lp[ln];
8168        u_char inq_byte7;
8169
8170        /*
8171        **      If no lcb, try to allocate it.
8172        */
8173        if (!lp && !(lp = ncr_alloc_lcb(np, tn, ln)))
8174                goto fail;
8175
8176        /*
8177        **      Get device quirks from a speciality table.
8178        */
8179        tp->quirks = ncr_lookup (inq_data);
8180        if (tp->quirks && bootverbose) {
8181                PRINT_LUN(np, tn, ln);
8182                printk ("quirks=%x.\n", tp->quirks);
8183        }
8184
8185        /*
8186        **      Evaluate trustable target/unit capabilities.
8187        **      We only believe device version >= SCSI-2 that 
8188        **      use appropriate response data format (2).
8189        **      But it seems that some CCS devices also 
8190        **      support SYNC and I donnot want to frustrate 
8191        **      anybody. ;-)
8192        */
8193        inq_byte7 = 0;
8194        if      ((inq_data[2] & 0x7) >= 2 && (inq_data[3] & 0xf) == 2)
8195                inq_byte7 = inq_data[7];
8196        else if ((inq_data[2] & 0x7) == 1 && (inq_data[3] & 0xf) == 1)
8197                inq_byte7 = INQ7_SYNC;
8198
8199        /*
8200        **      Throw away announced LUN capabilities if we are told 
8201        **      that there is no real device supported by the logical unit.
8202        */
8203        if ((inq_data[0] & 0xe0) > 0x20 || (inq_data[0] & 0x1f) == 0x1f)
8204                inq_byte7 &= (INQ7_SYNC | INQ7_WIDE16);
8205
8206        /*
8207        **      If user is wanting SYNC, force this feature.
8208        */
8209        if (driver_setup.force_sync_nego)
8210                inq_byte7 |= INQ7_SYNC;
8211
8212        /*
8213        **      Prepare negotiation if SIP capabilities have changed.
8214        */
8215        tp->inq_done = 1;
8216        if ((inq_byte7 ^ tp->inq_byte7) & (INQ7_SYNC | INQ7_WIDE16)) {
8217                tp->inq_byte7 = inq_byte7;
8218                ncr_negotiate(np, tp);
8219        }
8220
8221        /*
8222        **      If unit supports tagged commands, allocate the 
8223        **      CCB JUMP table if not yet.
8224        */
8225        if ((inq_byte7 & INQ7_QUEUE) && lp->jump_ccb == &lp->jump_ccb_0) {
8226                int i;
8227                lp->jump_ccb = m_calloc_dma(256, "JUMP_CCB");
8228                if (!lp->jump_ccb) {
8229                        lp->jump_ccb = &lp->jump_ccb_0;
8230                        goto fail;
8231                }
8232                lp->p_jump_ccb = cpu_to_scr(vtobus(lp->jump_ccb));
8233                for (i = 0 ; i < 64 ; i++)
8234                        lp->jump_ccb[i] =
8235                                cpu_to_scr(NCB_SCRIPTH_PHYS (np, bad_i_t_l_q));
8236                for (i = 0 ; i < MAX_TAGS ; i++)
8237                        lp->cb_tags[i] = i;
8238                lp->maxnxs = MAX_TAGS;
8239                lp->tags_stime = ktime_get(3*HZ);
8240        }
8241
8242        /*
8243        **      Adjust tagged queueing status if needed.
8244        */
8245        if ((inq_byte7 ^ lp->inq_byte7) & INQ7_QUEUE) {
8246                lp->inq_byte7 = inq_byte7;
8247                lp->numtags   = lp->maxtags;
8248                ncr_setup_tags (np, tn, ln);
8249        }
8250
8251fail:
8252        return lp;
8253}
8254
8255/*==========================================================
8256**
8257**
8258**      Build Scatter Gather Block
8259**
8260**
8261**==========================================================
8262**
8263**      The transfer area may be scattered among
8264**      several non adjacent physical pages.
8265**
8266**      We may use MAX_SCATTER blocks.
8267**
8268**----------------------------------------------------------
8269*/
8270
8271/*
8272**      We try to reduce the number of interrupts caused
8273**      by unexpected phase changes due to disconnects.
8274**      A typical harddisk may disconnect before ANY block.
8275**      If we wanted to avoid unexpected phase changes at all
8276**      we had to use a break point every 512 bytes.
8277**      Of course the number of scatter/gather blocks is
8278**      limited.
8279**      Under Linux, the scatter/gatter blocks are provided by 
8280**      the generic driver. We just have to copy addresses and 
8281**      sizes to the data segment array.
8282*/
8283
8284static  int     ncr_scatter(ncb_p np, ccb_p cp, Scsi_Cmnd *cmd)
8285{
8286        struct scr_tblmove *data;
8287        int segment     = 0;
8288        int use_sg      = (int) cmd->use_sg;
8289
8290        data            = cp->phys.data;
8291        cp->data_len    = 0;
8292
8293        if (!use_sg) {
8294                if (cmd->request_bufflen) {
8295                        u_long baddr = map_scsi_single_data(np, cmd);
8296
8297                        data = &data[MAX_SCATTER - 1];
8298                        data[0].addr = cpu_to_scr(baddr);
8299                        data[0].size = cpu_to_scr(cmd->request_bufflen);
8300                        cp->data_len = cmd->request_bufflen;
8301                        segment = 1;
8302                }
8303        }
8304        else if (use_sg <= MAX_SCATTER) {
8305                struct scatterlist *scatter = (struct scatterlist *)cmd->buffer;
8306
8307                use_sg = map_scsi_sg_data(np, cmd);
8308                data = &data[MAX_SCATTER - use_sg];
8309
8310                while (segment < use_sg) {
8311                        u_long baddr = scsi_sg_dma_address(&scatter[segment]);
8312                        unsigned int len = scsi_sg_dma_len(&scatter[segment]);
8313
8314                        data[segment].addr = cpu_to_scr(baddr);
8315                        data[segment].size = cpu_to_scr(len);
8316                        cp->data_len      += len;
8317                        ++segment;
8318                }
8319        }
8320        else {
8321                return -1;
8322        }
8323
8324        return segment;
8325}
8326
8327/*==========================================================
8328**
8329**
8330**      Test the pci bus snoop logic :-(
8331**
8332**      Has to be called with interrupts disabled.
8333**
8334**
8335**==========================================================
8336*/
8337
8338#ifndef SCSI_NCR_IOMAPPED
8339static int __init ncr_regtest (struct ncb* np)
8340{
8341        register volatile u_int32 data;
8342        /*
8343        **      ncr registers may NOT be cached.
8344        **      write 0xffffffff to a read only register area,
8345        **      and try to read it back.
8346        */
8347        data = 0xffffffff;
8348        OUTL_OFF(offsetof(struct ncr_reg, nc_dstat), data);
8349        data = INL_OFF(offsetof(struct ncr_reg, nc_dstat));
8350#if 1
8351        if (data == 0xffffffff) {
8352#else
8353        if ((data & 0xe2f0fffd) != 0x02000080) {
8354#endif
8355                printk ("CACHE TEST FAILED: reg dstat-sstat2 readback %x.\n",
8356                        (unsigned) data);
8357                return (0x10);
8358        };
8359        return (0);
8360}
8361#endif
8362
8363static int __init ncr_snooptest (struct ncb* np)
8364{
8365        u_int32 ncr_rd, ncr_wr, ncr_bk, host_rd, host_wr, pc;
8366        int     i, err=0;
8367#ifndef SCSI_NCR_IOMAPPED
8368        if (np->reg) {
8369            err |= ncr_regtest (np);
8370            if (err) return (err);
8371        }
8372#endif
8373        /*
8374        **      init
8375        */
8376        pc  = NCB_SCRIPTH_PHYS (np, snooptest);
8377        host_wr = 1;
8378        ncr_wr  = 2;
8379        /*
8380        **      Set memory and register.
8381        */
8382        np->ncr_cache = cpu_to_scr(host_wr);
8383        OUTL (nc_temp, ncr_wr);
8384        /*
8385        **      Start script (exchange values)
8386        */
8387        OUTL_DSP (pc);
8388        /*
8389        **      Wait 'til done (with timeout)
8390        */
8391        for (i=0; i<NCR_SNOOP_TIMEOUT; i++)
8392                if (INB(nc_istat) & (INTF|SIP|DIP))
8393                        break;
8394        /*
8395        **      Save termination position.
8396        */
8397        pc = INL (nc_dsp);
8398        /*
8399        **      Read memory and register.
8400        */
8401        host_rd = scr_to_cpu(np->ncr_cache);
8402        ncr_rd  = INL (nc_scratcha);
8403        ncr_bk  = INL (nc_temp);
8404        /*
8405        **      Reset ncr chip
8406        */
8407        ncr_chip_reset(np, 100);
8408        /*
8409        **      check for timeout
8410        */
8411        if (i>=NCR_SNOOP_TIMEOUT) {
8412                printk ("CACHE TEST FAILED: timeout.\n");
8413                return (0x20);
8414        };
8415        /*
8416        **      Check termination position.
8417        */
8418        if (pc != NCB_SCRIPTH_PHYS (np, snoopend)+8) {
8419                printk ("CACHE TEST FAILED: script execution failed.\n");
8420                printk ("start=%08lx, pc=%08lx, end=%08lx\n", 
8421                        (u_long) NCB_SCRIPTH_PHYS (np, snooptest), (u_long) pc,
8422                        (u_long) NCB_SCRIPTH_PHYS (np, snoopend) +8);
8423                return (0x40);
8424        };
8425        /*
8426        **      Show results.
8427        */
8428        if (host_wr != ncr_rd) {
8429                printk ("CACHE TEST FAILED: host wrote %d, ncr read %d.\n",
8430                        (int) host_wr, (int) ncr_rd);
8431                err |= 1;
8432        };
8433        if (host_rd != ncr_wr) {
8434                printk ("CACHE TEST FAILED: ncr wrote %d, host read %d.\n",
8435                        (int) ncr_wr, (int) host_rd);
8436                err |= 2;
8437        };
8438        if (ncr_bk != ncr_wr) {
8439                printk ("CACHE TEST FAILED: ncr wrote %d, read back %d.\n",
8440                        (int) ncr_wr, (int) ncr_bk);
8441                err |= 4;
8442        };
8443        return (err);
8444}
8445
8446/*==========================================================
8447**
8448**
8449**      Device lookup.
8450**
8451**      @GENSCSI@ should be integrated to scsiconf.c
8452**
8453**
8454**==========================================================
8455*/
8456
8457struct table_entry {
8458        char *  manufacturer;
8459        char *  model;
8460        char *  version;
8461        u_long  info;
8462};
8463
8464static struct table_entry device_tab[] =
8465{
8466#if 0
8467        {"", "", "", QUIRK_NOMSG},
8468#endif
8469        {"SONY", "SDT-5000", "3.17", QUIRK_NOMSG},
8470        {"WangDAT", "Model 2600", "01.7", QUIRK_NOMSG},
8471        {"WangDAT", "Model 3200", "02.2", QUIRK_NOMSG},
8472        {"WangDAT", "Model 1300", "02.4", QUIRK_NOMSG},
8473        {"", "", "", 0} /* catch all: must be last entry. */
8474};
8475
8476static u_long ncr_lookup(char * id)
8477{
8478        struct table_entry * p = device_tab;
8479        char *d, *r, c;
8480
8481        for (;;p++) {
8482
8483                d = id+8;
8484                r = p->manufacturer;
8485                while ((c=*r++)) if (c!=*d++) break;
8486                if (c) continue;
8487
8488                d = id+16;
8489                r = p->model;
8490                while ((c=*r++)) if (c!=*d++) break;
8491                if (c) continue;
8492
8493                d = id+32;
8494                r = p->version;
8495                while ((c=*r++)) if (c!=*d++) break;
8496                if (c) continue;
8497
8498                return (p->info);
8499        }
8500}
8501
8502/*==========================================================
8503**
8504**      Determine the ncr's clock frequency.
8505**      This is essential for the negotiation
8506**      of the synchronous transfer rate.
8507**
8508**==========================================================
8509**
8510**      Note: we have to return the correct value.
8511**      THERE IS NO SAVE DEFAULT VALUE.
8512**
8513**      Most NCR/SYMBIOS boards are delivered with a 40 Mhz clock.
8514**      53C860 and 53C875 rev. 1 support fast20 transfers but 
8515**      do not have a clock doubler and so are provided with a 
8516**      80 MHz clock. All other fast20 boards incorporate a doubler 
8517**      and so should be delivered with a 40 MHz clock.
8518**      The future fast40 chips (895/895) use a 40 Mhz base clock 
8519**      and provide a clock quadrupler (160 Mhz). The code below 
8520**      tries to deal as cleverly as possible with all this stuff.
8521**
8522**----------------------------------------------------------
8523*/
8524
8525/*
8526 *      Select NCR SCSI clock frequency
8527 */
8528static void ncr_selectclock(ncb_p np, u_char scntl3)
8529{
8530        if (np->multiplier < 2) {
8531                OUTB(nc_scntl3, scntl3);
8532                return;
8533        }
8534
8535        if (bootverbose >= 2)
8536                printk ("%s: enabling clock multiplier\n", ncr_name(np));
8537
8538        OUTB(nc_stest1, DBLEN);    /* Enable clock multiplier             */
8539        if (np->multiplier > 2) {  /* Poll bit 5 of stest4 for quadrupler */
8540                int i = 20;
8541                while (!(INB(nc_stest4) & LCKFRQ) && --i > 0)
8542                        UDELAY (20);
8543                if (!i)
8544                        printk("%s: the chip cannot lock the frequency\n", ncr_name(np));
8545        } else                  /* Wait 20 micro-seconds for doubler    */
8546                UDELAY (20);
8547        OUTB(nc_stest3, HSC);           /* Halt the scsi clock          */
8548        OUTB(nc_scntl3, scntl3);
8549        OUTB(nc_stest1, (DBLEN|DBLSEL));/* Select clock multiplier      */
8550        OUTB(nc_stest3, 0x00);          /* Restart scsi clock           */
8551}
8552
8553
8554/*
8555 *      calculate NCR SCSI clock frequency (in KHz)
8556 */
8557static unsigned __init ncrgetfreq (ncb_p np, int gen)
8558{
8559        unsigned ms = 0;
8560        char count = 0;
8561
8562        /*
8563         * Measure GEN timer delay in order 
8564         * to calculate SCSI clock frequency
8565         *
8566         * This code will never execute too
8567         * many loop iterations (if DELAY is 
8568         * reasonably correct). It could get
8569         * too low a delay (too high a freq.)
8570         * if the CPU is slow executing the 
8571         * loop for some reason (an NMI, for
8572         * example). For this reason we will
8573         * if multiple measurements are to be 
8574         * performed trust the higher delay 
8575         * (lower frequency returned).
8576         */
8577        OUTB (nc_stest1, 0);    /* make sure clock doubler is OFF */
8578        OUTW (nc_sien , 0);     /* mask all scsi interrupts */
8579        (void) INW (nc_sist);   /* clear pending scsi interrupt */
8580        OUTB (nc_dien , 0);     /* mask all dma interrupts */
8581        (void) INW (nc_sist);   /* another one, just to be sure :) */
8582        OUTB (nc_scntl3, 4);    /* set pre-scaler to divide by 3 */
8583        OUTB (nc_stime1, 0);    /* disable general purpose timer */
8584        OUTB (nc_stime1, gen);  /* set to nominal delay of 1<<gen * 125us */
8585        while (!(INW(nc_sist) & GEN) && ms++ < 100000) {
8586                for (count = 0; count < 10; count ++)
8587                        UDELAY (100);   /* count ms */
8588        }
8589        OUTB (nc_stime1, 0);    /* disable general purpose timer */
8590        /*
8591         * set prescaler to divide by whatever 0 means
8592         * 0 ought to choose divide by 2, but appears
8593         * to set divide by 3.5 mode in my 53c810 ...
8594         */
8595        OUTB (nc_scntl3, 0);
8596
8597        if (bootverbose >= 2)
8598                printk ("%s: Delay (GEN=%d): %u msec\n", ncr_name(np), gen, ms);
8599        /*
8600         * adjust for prescaler, and convert into KHz 
8601         */
8602        return ms ? ((1 << gen) * 4340) / ms : 0;
8603}
8604
8605/*
8606 *      Get/probe NCR SCSI clock frequency
8607 */
8608static void __init ncr_getclock (ncb_p np, int mult)
8609{
8610        unsigned char scntl3 = INB(nc_scntl3);
8611        unsigned char stest1 = INB(nc_stest1);
8612        unsigned f1;
8613
8614        np->multiplier = 1;
8615        f1 = 40000;
8616
8617        /*
8618        **      True with 875 or 895 with clock multiplier selected
8619        */
8620        if (mult > 1 && (stest1 & (DBLEN+DBLSEL)) == DBLEN+DBLSEL) {
8621                if (bootverbose >= 2)
8622                        printk ("%s: clock multiplier found\n", ncr_name(np));
8623                np->multiplier = mult;
8624        }
8625
8626        /*
8627        **      If multiplier not found or scntl3 not 7,5,3,
8628        **      reset chip and get frequency from general purpose timer.
8629        **      Otherwise trust scntl3 BIOS setting.
8630        */
8631        if (np->multiplier != mult || (scntl3 & 7) < 3 || !(scntl3 & 1)) {
8632                unsigned f2;
8633
8634                ncr_chip_reset(np, 5);
8635
8636                (void) ncrgetfreq (np, 11);     /* throw away first result */
8637                f1 = ncrgetfreq (np, 11);
8638                f2 = ncrgetfreq (np, 11);
8639
8640                if (bootverbose)
8641                        printk ("%s: NCR clock is %uKHz, %uKHz\n", ncr_name(np), f1, f2);
8642
8643                if (f1 > f2) f1 = f2;           /* trust lower result   */
8644
8645                if      (f1 <   45000)          f1 =  40000;
8646                else if (f1 <   55000)          f1 =  50000;
8647                else                            f1 =  80000;
8648
8649                if (f1 < 80000 && mult > 1) {
8650                        if (bootverbose >= 2)
8651                                printk ("%s: clock multiplier assumed\n", ncr_name(np));
8652                        np->multiplier  = mult;
8653                }
8654        } else {
8655                if      ((scntl3 & 7) == 3)     f1 =  40000;
8656                else if ((scntl3 & 7) == 5)     f1 =  80000;
8657                else                            f1 = 160000;
8658
8659                f1 /= np->multiplier;
8660        }
8661
8662        /*
8663        **      Compute controller synchronous parameters.
8664        */
8665        f1              *= np->multiplier;
8666        np->clock_khz   = f1;
8667}
8668
8669/*===================== LINUX ENTRY POINTS SECTION ==========================*/
8670
8671/*
8672**   Linux select queue depths function
8673*/
8674
8675int ncr53c8xx_slave_configure(Scsi_Device *device)
8676{
8677        struct Scsi_Host *host = device->host;
8678        ncb_p np;
8679        tcb_p tp;
8680        lcb_p lp;
8681        int numtags, depth_to_use;
8682
8683        np = ((struct host_data *) host->hostdata)->ncb;
8684        tp = &np->target[device->id];
8685        lp = tp->lp[device->lun];
8686
8687        /*
8688        **      Select queue depth from driver setup.
8689        **      Donnot use more than configured by user.
8690        **      Use at least 2.
8691        **      Donnot use more than our maximum.
8692        */
8693        numtags = device_queue_depth(np->unit, device->id, device->lun);
8694        if (numtags > tp->usrtags)
8695                numtags = tp->usrtags;
8696        if (!device->tagged_supported)
8697                numtags = 1;
8698        depth_to_use = numtags;
8699        if (depth_to_use < 2)
8700                depth_to_use = 2;
8701        if (depth_to_use > MAX_TAGS)
8702                depth_to_use = MAX_TAGS;
8703
8704        scsi_adjust_queue_depth(device,
8705                                (device->tagged_supported ?
8706                                 MSG_SIMPLE_TAG : 0),
8707                                depth_to_use);
8708
8709        /*
8710        **      Since the queue depth is not tunable under Linux,
8711        **      we need to know this value in order not to 
8712        **      announce stupid things to user.
8713        */
8714        if (lp) {
8715                lp->numtags = lp->maxtags = numtags;
8716                lp->scdev_depth = depth_to_use;
8717        }
8718        ncr_setup_tags (np, device->id, device->lun);
8719
8720#ifdef DEBUG_NCR53C8XX
8721        printk("ncr53c8xx_select_queue_depth: host=%d, id=%d, lun=%d, depth=%d\n",
8722               np->unit, device->id, device->lun, depth_to_use);
8723#endif
8724
8725        return 0;
8726}
8727
8728/*
8729**   Linux entry point of queuecommand() function
8730*/
8731
8732int ncr53c8xx_queue_command (Scsi_Cmnd *cmd, void (* done)(Scsi_Cmnd *))
8733{
8734     ncb_p np = ((struct host_data *) cmd->host->hostdata)->ncb;
8735     unsigned long flags;
8736     int sts;
8737
8738#ifdef DEBUG_NCR53C8XX
8739printk("ncr53c8xx_queue_command\n");
8740#endif
8741
8742     cmd->scsi_done     = done;
8743     cmd->host_scribble = NULL;
8744#ifdef SCSI_NCR_DYNAMIC_DMA_MAPPING
8745     cmd->__data_mapped = 0;
8746     cmd->__data_mapping = 0;
8747#endif
8748
8749     NCR_LOCK_NCB(np, flags);
8750
8751     if ((sts = ncr_queue_command(np, cmd)) != DID_OK) {
8752          cmd->result = ScsiResult(sts, 0);
8753#ifdef DEBUG_NCR53C8XX
8754printk("ncr53c8xx : command not queued - result=%d\n", sts);
8755#endif
8756     }
8757#ifdef DEBUG_NCR53C8XX
8758     else
8759printk("ncr53c8xx : command successfully queued\n");
8760#endif
8761
8762     NCR_UNLOCK_NCB(np, flags);
8763
8764     if (sts != DID_OK) {
8765          unmap_scsi_data(np, cmd);
8766          done(cmd);
8767     }
8768
8769     return sts;
8770}
8771
8772/*
8773**   Linux entry point of the interrupt handler.
8774**   Since linux versions > 1.3.70, we trust the kernel for 
8775**   passing the internal host descriptor as 'dev_id'.
8776**   Otherwise, we scan the host list and call the interrupt 
8777**   routine for each host that uses this IRQ.
8778*/
8779
8780static void ncr53c8xx_intr(int irq, void *dev_id, struct pt_regs * regs)
8781{
8782     unsigned long flags;
8783     ncb_p np = (ncb_p) dev_id;
8784     Scsi_Cmnd *done_list;
8785
8786#ifdef DEBUG_NCR53C8XX
8787     printk("ncr53c8xx : interrupt received\n");
8788#endif
8789
8790     if (DEBUG_FLAGS & DEBUG_TINY) printk ("[");
8791
8792     NCR_LOCK_NCB(np, flags);
8793     ncr_exception(np);
8794     done_list     = np->done_list;
8795     np->done_list = 0;
8796     NCR_UNLOCK_NCB(np, flags);
8797
8798     if (DEBUG_FLAGS & DEBUG_TINY) printk ("]\n");
8799
8800     if (done_list) {
8801          NCR_LOCK_SCSI_DONE(done_list->host, flags);
8802          ncr_flush_done_cmds(done_list);
8803          NCR_UNLOCK_SCSI_DONE(done_list->host, flags);
8804     }
8805}
8806
8807/*
8808**   Linux entry point of the timer handler
8809*/
8810
8811static void ncr53c8xx_timeout(unsigned long npref)
8812{
8813     ncb_p np = (ncb_p) npref;
8814     unsigned long flags;
8815     Scsi_Cmnd *done_list;
8816
8817     NCR_LOCK_NCB(np, flags);
8818     ncr_timeout((ncb_p) np);
8819     done_list     = np->done_list;
8820     np->done_list = 0;
8821     NCR_UNLOCK_NCB(np, flags);
8822
8823     if (done_list) {
8824          NCR_LOCK_SCSI_DONE(done_list->host, flags);
8825          ncr_flush_done_cmds(done_list);
8826          NCR_UNLOCK_SCSI_DONE(done_list->host, flags);
8827     }
8828}
8829
8830/*
8831**   Linux entry point of reset() function
8832*/
8833
8834#if defined SCSI_RESET_SYNCHRONOUS && defined SCSI_RESET_ASYNCHRONOUS
8835int ncr53c8xx_reset(Scsi_Cmnd *cmd, unsigned int reset_flags)
8836#else
8837int ncr53c8xx_reset(Scsi_Cmnd *cmd)
8838#endif
8839{
8840        ncb_p np = ((struct host_data *) cmd->host->hostdata)->ncb;
8841        int sts;
8842        unsigned long flags;
8843        Scsi_Cmnd *done_list;
8844
8845#if defined SCSI_RESET_SYNCHRONOUS && defined SCSI_RESET_ASYNCHRONOUS
8846        printk("ncr53c8xx_reset: pid=%lu reset_flags=%x serial_number=%ld serial_number_at_timeout=%ld\n",
8847                cmd->pid, reset_flags, cmd->serial_number, cmd->serial_number_at_timeout);
8848#else
8849        printk("ncr53c8xx_reset: command pid %lu\n", cmd->pid);
8850#endif
8851
8852        NCR_LOCK_NCB(np, flags);
8853
8854        /*
8855         * We have to just ignore reset requests in some situations.
8856         */
8857#if defined SCSI_RESET_NOT_RUNNING
8858        if (cmd->serial_number != cmd->serial_number_at_timeout) {
8859                sts = SCSI_RESET_NOT_RUNNING;
8860                goto out;
8861        }
8862#endif
8863        /*
8864         * If the mid-level driver told us reset is synchronous, it seems 
8865         * that we must call the done() callback for the involved command, 
8866         * even if this command was not queued to the low-level driver, 
8867         * before returning SCSI_RESET_SUCCESS.
8868         */
8869
8870#if defined SCSI_RESET_SYNCHRONOUS && defined SCSI_RESET_ASYNCHRONOUS
8871        sts = ncr_reset_bus(np, cmd,
8872        (reset_flags & (SCSI_RESET_SYNCHRONOUS | SCSI_RESET_ASYNCHRONOUS)) == SCSI_RESET_SYNCHRONOUS);
8873#else
8874        sts = ncr_reset_bus(np, cmd, 0);
8875#endif
8876
8877        /*
8878         * Since we always reset the controller, when we return success, 
8879         * we add this information to the return code.
8880         */
8881#if defined SCSI_RESET_HOST_RESET
8882        if (sts == SCSI_RESET_SUCCESS)
8883                sts |= SCSI_RESET_HOST_RESET;
8884#endif
8885
8886out:
8887        done_list     = np->done_list;
8888        np->done_list = 0;
8889        NCR_UNLOCK_NCB(np, flags);
8890
8891        ncr_flush_done_cmds(done_list);
8892
8893        return sts;
8894}
8895
8896/*
8897**   Linux entry point of abort() function
8898*/
8899
8900int ncr53c8xx_abort(Scsi_Cmnd *cmd)
8901{
8902        ncb_p np = ((struct host_data *) cmd->host->hostdata)->ncb;
8903        int sts;
8904        unsigned long flags;
8905        Scsi_Cmnd *done_list;
8906
8907#if defined SCSI_RESET_SYNCHRONOUS && defined SCSI_RESET_ASYNCHRONOUS
8908        printk("ncr53c8xx_abort: pid=%lu serial_number=%ld serial_number_at_timeout=%ld\n",
8909                cmd->pid, cmd->serial_number, cmd->serial_number_at_timeout);
8910#else
8911        printk("ncr53c8xx_abort: command pid %lu\n", cmd->pid);
8912#endif
8913
8914        NCR_LOCK_NCB(np, flags);
8915
8916#if defined SCSI_RESET_SYNCHRONOUS && defined SCSI_RESET_ASYNCHRONOUS
8917        /*
8918         * We have to just ignore abort requests in some situations.
8919         */
8920        if (cmd->serial_number != cmd->serial_number_at_timeout) {
8921                sts = SCSI_ABORT_NOT_RUNNING;
8922                goto out;
8923        }
8924#endif
8925
8926        sts = ncr_abort_command(np, cmd);
8927out:
8928        done_list     = np->done_list;
8929        np->done_list = 0;
8930        NCR_UNLOCK_NCB(np, flags);
8931
8932        ncr_flush_done_cmds(done_list);
8933
8934        return sts;
8935}
8936
8937
8938#ifdef MODULE
8939int ncr53c8xx_release(struct Scsi_Host *host)
8940{
8941#ifdef DEBUG_NCR53C8XX
8942printk("ncr53c8xx : release\n");
8943#endif
8944     ncr_detach(((struct host_data *) host->hostdata)->ncb);
8945
8946     return 1;
8947}
8948#endif
8949
8950
8951/*
8952**      Scsi command waiting list management.
8953**
8954**      It may happen that we cannot insert a scsi command into the start queue,
8955**      in the following circumstances.
8956**              Too few preallocated ccb(s), 
8957**              maxtags < cmd_per_lun of the Linux host control block,
8958**              etc...
8959**      Such scsi commands are inserted into a waiting list.
8960**      When a scsi command complete, we try to requeue the commands of the
8961**      waiting list.
8962*/
8963
8964#define next_wcmd host_scribble
8965
8966static void insert_into_waiting_list(ncb_p np, Scsi_Cmnd *cmd)
8967{
8968        Scsi_Cmnd *wcmd;
8969
8970#ifdef DEBUG_WAITING_LIST
8971        printk("%s: cmd %lx inserted into waiting list\n", ncr_name(np), (u_long) cmd);
8972#endif
8973        cmd->next_wcmd = 0;
8974        if (!(wcmd = np->waiting_list)) np->waiting_list = cmd;
8975        else {
8976                while ((wcmd->next_wcmd) != 0)
8977                        wcmd = (Scsi_Cmnd *) wcmd->next_wcmd;
8978                wcmd->next_wcmd = (char *) cmd;
8979        }
8980}
8981
8982static Scsi_Cmnd *retrieve_from_waiting_list(int to_remove, ncb_p np, Scsi_Cmnd *cmd)
8983{
8984        Scsi_Cmnd **pcmd = &np->waiting_list;
8985
8986        while (*pcmd) {
8987                if (cmd == *pcmd) {
8988                        if (to_remove) {
8989                                *pcmd = (Scsi_Cmnd *) cmd->next_wcmd;
8990                                cmd->next_wcmd = 0;
8991                        }
8992#ifdef DEBUG_WAITING_LIST
8993        printk("%s: cmd %lx retrieved from waiting list\n", ncr_name(np), (u_long) cmd);
8994#endif
8995                        return cmd;
8996                }
8997                pcmd = (Scsi_Cmnd **) &(*pcmd)->next_wcmd;
8998        }
8999        return 0;
9000}
9001
9002static void process_waiting_list(ncb_p np, int sts)
9003{
9004        Scsi_Cmnd *waiting_list, *wcmd;
9005
9006        waiting_list = np->waiting_list;
9007        np->waiting_list = 0;
9008
9009#ifdef DEBUG_WAITING_LIST
9010        if (waiting_list) printk("%s: waiting_list=%lx processing sts=%d\n", ncr_name(np), (u_long) waiting_list, sts);
9011#endif
9012        while ((wcmd = waiting_list) != 0) {
9013                waiting_list = (Scsi_Cmnd *) wcmd->next_wcmd;
9014                wcmd->next_wcmd = 0;
9015                if (sts == DID_OK) {
9016#ifdef DEBUG_WAITING_LIST
9017        printk("%s: cmd %lx trying to requeue\n", ncr_name(np), (u_long) wcmd);
9018#endif
9019                        sts = ncr_queue_command(np, wcmd);
9020                }
9021                if (sts != DID_OK) {
9022#ifdef DEBUG_WAITING_LIST
9023        printk("%s: cmd %lx done forced sts=%d\n", ncr_name(np), (u_long) wcmd, sts);
9024#endif
9025                        wcmd->result = ScsiResult(sts, 0);
9026                        ncr_queue_done_cmd(np, wcmd);
9027                }
9028        }
9029}
9030
9031#undef next_wcmd
9032
9033#ifdef SCSI_NCR_PROC_INFO_SUPPORT
9034
9035/*=========================================================================
9036**      Proc file system stuff
9037**
9038**      A read operation returns profile information.
9039**      A write operation is a control command.
9040**      The string is parsed in the driver code and the command is passed 
9041**      to the ncr_usercmd() function.
9042**=========================================================================
9043*/
9044
9045#ifdef SCSI_NCR_USER_COMMAND_SUPPORT
9046
9047#define is_digit(c)     ((c) >= '0' && (c) <= '9')
9048#define digit_to_bin(c) ((c) - '0')
9049#define is_space(c)     ((c) == ' ' || (c) == '\t')
9050
9051static int skip_spaces(char *ptr, int len)
9052{
9053        int cnt, c;
9054
9055        for (cnt = len; cnt > 0 && (c = *ptr++) && is_space(c); cnt--);
9056
9057        return (len - cnt);
9058}
9059
9060static int get_int_arg(char *ptr, int len, u_long *pv)
9061{
9062        int     cnt, c;
9063        u_long  v;
9064
9065        for (v = 0, cnt = len; cnt > 0 && (c = *ptr++) && is_digit(c); cnt--) {
9066                v = (v * 10) + digit_to_bin(c);
9067        }
9068
9069        if (pv)
9070                *pv = v;
9071
9072        return (len - cnt);
9073}
9074
9075static int is_keyword(char *ptr, int len, char *verb)
9076{
9077        int verb_len = strlen(verb);
9078
9079        if (len >= strlen(verb) && !memcmp(verb, ptr, verb_len))
9080                return verb_len;
9081        else
9082                return 0;
9083
9084}
9085
9086#define SKIP_SPACES(min_spaces)                                         \
9087        if ((arg_len = skip_spaces(ptr, len)) < (min_spaces))           \
9088                return -EINVAL;                                         \
9089        ptr += arg_len; len -= arg_len;
9090
9091#define GET_INT_ARG(v)                                                  \
9092        if (!(arg_len = get_int_arg(ptr, len, &(v))))                   \
9093                return -EINVAL;                                         \
9094        ptr += arg_len; len -= arg_len;
9095
9096
9097/*
9098**      Parse a control command
9099*/
9100
9101static int ncr_user_command(ncb_p np, char *buffer, int length)
9102{
9103        char *ptr       = buffer;
9104        int len         = length;
9105        struct usrcmd    *uc = &np->user;
9106        int             arg_len;
9107        u_long          target;
9108
9109        bzero(uc, sizeof(*uc));
9110
9111        if (len > 0 && ptr[len-1] == '\n')
9112                --len;
9113
9114        if      ((arg_len = is_keyword(ptr, len, "setsync")) != 0)
9115                uc->cmd = UC_SETSYNC;
9116        else if ((arg_len = is_keyword(ptr, len, "settags")) != 0)
9117                uc->cmd = UC_SETTAGS;
9118        else if ((arg_len = is_keyword(ptr, len, "setorder")) != 0)
9119                uc->cmd = UC_SETORDER;
9120        else if ((arg_len = is_keyword(ptr, len, "setverbose")) != 0)
9121                uc->cmd = UC_SETVERBOSE;
9122        else if ((arg_len = is_keyword(ptr, len, "setwide")) != 0)
9123                uc->cmd = UC_SETWIDE;
9124        else if ((arg_len = is_keyword(ptr, len, "setdebug")) != 0)
9125                uc->cmd = UC_SETDEBUG;
9126        else if ((arg_len = is_keyword(ptr, len, "setflag")) != 0)
9127                uc->cmd = UC_SETFLAG;
9128        else
9129                arg_len = 0;
9130
9131#ifdef DEBUG_PROC_INFO
9132printk("ncr_user_command: arg_len=%d, cmd=%ld\n", arg_len, uc->cmd);
9133#endif
9134
9135        if (!arg_len)
9136                return -EINVAL;
9137        ptr += arg_len; len -= arg_len;
9138
9139        switch(uc->cmd) {
9140        case UC_SETSYNC:
9141        case UC_SETTAGS:
9142        case UC_SETWIDE:
9143        case UC_SETFLAG:
9144                SKIP_SPACES(1);
9145                if ((arg_len = is_keyword(ptr, len, "all")) != 0) {
9146                        ptr += arg_len; len -= arg_len;
9147                        uc->target = ~0;
9148                } else {
9149                        GET_INT_ARG(target);
9150                        uc->target = (1<<target);
9151#ifdef DEBUG_PROC_INFO
9152printk("ncr_user_command: target=%ld\n", target);
9153#endif
9154                }
9155                break;
9156        }
9157
9158        switch(uc->cmd) {
9159        case UC_SETVERBOSE:
9160        case UC_SETSYNC:
9161        case UC_SETTAGS:
9162        case UC_SETWIDE:
9163                SKIP_SPACES(1);
9164                GET_INT_ARG(uc->data);
9165#ifdef DEBUG_PROC_INFO
9166printk("ncr_user_command: data=%ld\n", uc->data);
9167#endif
9168                break;
9169        case UC_SETORDER:
9170                SKIP_SPACES(1);
9171                if      ((arg_len = is_keyword(ptr, len, "simple")))
9172                        uc->data = M_SIMPLE_TAG;
9173                else if ((arg_len = is_keyword(ptr, len, "ordered")))
9174                        uc->data = M_ORDERED_TAG;
9175                else if ((arg_len = is_keyword(ptr, len, "default")))
9176                        uc->data = 0;
9177                else
9178                        return -EINVAL;
9179                break;
9180        case UC_SETDEBUG:
9181                while (len > 0) {
9182                        SKIP_SPACES(1);
9183                        if      ((arg_len = is_keyword(ptr, len, "alloc")))
9184                                uc->data |= DEBUG_ALLOC;
9185                        else if ((arg_len = is_keyword(ptr, len, "phase")))
9186                                uc->data |= DEBUG_PHASE;
9187                        else if ((arg_len = is_keyword(ptr, len, "queue")))
9188                                uc->data |= DEBUG_QUEUE;
9189                        else if ((arg_len = is_keyword(ptr, len, "result")))
9190                                uc->data |= DEBUG_RESULT;
9191                        else if ((arg_len = is_keyword(ptr, len, "scatter")))
9192                                uc->data |= DEBUG_SCATTER;
9193                        else if ((arg_len = is_keyword(ptr, len, "script")))
9194                                uc->data |= DEBUG_SCRIPT;
9195                        else if ((arg_len = is_keyword(ptr, len, "tiny")))
9196                                uc->data |= DEBUG_TINY;
9197                        else if ((arg_len = is_keyword(ptr, len, "timing")))
9198                                uc->data |= DEBUG_TIMING;
9199                        else if ((arg_len = is_keyword(ptr, len, "nego")))
9200                                uc->data |= DEBUG_NEGO;
9201                        else if ((arg_len = is_keyword(ptr, len, "tags")))
9202                                uc->data |= DEBUG_TAGS;
9203                        else
9204                                return -EINVAL;
9205                        ptr += arg_len; len -= arg_len;
9206                }
9207#ifdef DEBUG_PROC_INFO
9208printk("ncr_user_command: data=%ld\n", uc->data);
9209#endif
9210                break;
9211        case UC_SETFLAG:
9212                while (len > 0) {
9213                        SKIP_SPACES(1);
9214                        if      ((arg_len = is_keyword(ptr, len, "trace")))
9215                                uc->data |= UF_TRACE;
9216                        else if ((arg_len = is_keyword(ptr, len, "no_disc")))
9217                                uc->data |= UF_NODISC;
9218                        else
9219                                return -EINVAL;
9220                        ptr += arg_len; len -= arg_len;
9221                }
9222                break;
9223        default:
9224                break;
9225        }
9226
9227        if (len)
9228                return -EINVAL;
9229        else {
9230                long flags;
9231
9232                NCR_LOCK_NCB(np, flags);
9233                ncr_usercmd (np);
9234                NCR_UNLOCK_NCB(np, flags);
9235        }
9236        return length;
9237}
9238
9239#endif  /* SCSI_NCR_USER_COMMAND_SUPPORT */
9240
9241
9242#ifdef SCSI_NCR_USER_INFO_SUPPORT
9243/*
9244**      Copy formatted information into the input buffer.
9245*/
9246
9247static int ncr_host_info(ncb_p np, char *ptr, off_t offset, int len)
9248{
9249        struct info_str info;
9250
9251        info.buffer     = ptr;
9252        info.length     = len;
9253        info.offset     = offset;
9254        info.pos        = 0;
9255
9256        copy_info(&info, "  Chip NCR53C%s, device id 0x%x, "
9257                         "revision id 0x%x\n",
9258                         np->chip_name, np->device_id,  np->revision_id);
9259        copy_info(&info, "  On PCI bus %d, device %d, function %d, "
9260#ifdef __sparc__
9261                "IRQ %s\n",
9262#else
9263                "IRQ %d\n",
9264#endif
9265                np->bus, (np->device_fn & 0xf8) >> 3, np->device_fn & 7,
9266#ifdef __sparc__
9267                __irq_itoa(np->irq));
9268#else
9269                (int) np->irq);
9270#endif
9271        copy_info(&info, "  Synchronous period factor %d, "
9272                         "max commands per lun %d\n",
9273                         (int) np->minsync, MAX_TAGS);
9274
9275        if (driver_setup.debug || driver_setup.verbose > 1) {
9276                copy_info(&info, "  Debug flags 0x%x, verbosity level %d\n",
9277                          driver_setup.debug, driver_setup.verbose);
9278        }
9279
9280        return info.pos > info.offset? info.pos - info.offset : 0;
9281}
9282
9283#endif /* SCSI_NCR_USER_INFO_SUPPORT */
9284
9285/*
9286**      Entry point of the scsi proc fs of the driver.
9287**      - func = 0 means read  (returns profile data)
9288**      - func = 1 means write (parse user control command)
9289*/
9290
9291static int ncr53c8xx_proc_info(char *buffer, char **start, off_t offset,
9292                        int length, int hostno, int func)
9293{
9294        struct Scsi_Host *host;
9295        struct host_data *host_data;
9296        ncb_p ncb = 0;
9297        int retv;
9298
9299#ifdef DEBUG_PROC_INFO
9300printk("ncr53c8xx_proc_info: hostno=%d, func=%d\n", hostno, func);
9301#endif
9302
9303        if((host = scsi_host_hn_get(hostno))==NULL)
9304                return -EINVAL;
9305                
9306        host_data = (struct host_data *) host->hostdata;
9307        ncb = host_data->ncb;
9308
9309        if (func) {
9310#ifdef  SCSI_NCR_USER_COMMAND_SUPPORT
9311                retv = ncr_user_command(ncb, buffer, length);
9312#else
9313                retv = -EINVAL;
9314#endif
9315        }
9316        else {
9317                if (start)
9318                        *start = buffer;
9319#ifdef SCSI_NCR_USER_INFO_SUPPORT
9320                retv = ncr_host_info(ncb, buffer, offset, length);
9321#else
9322                retv = -EINVAL;
9323#endif
9324        }
9325
9326        return retv;
9327}
9328
9329/*=========================================================================
9330**      End of proc file system stuff
9331**=========================================================================
9332*/
9333#endif
9334
9335
9336/*==========================================================
9337**
9338**      /proc directory entry.
9339**
9340**==========================================================
9341*/
9342#if LINUX_VERSION_CODE < LinuxVersionCode(2,3,27)
9343static struct proc_dir_entry proc_scsi_ncr53c8xx = {
9344    PROC_SCSI_NCR53C8XX, 9, NAME53C8XX,
9345    S_IFDIR | S_IRUGO | S_IXUGO, 2
9346};
9347#endif
9348
9349/*==========================================================
9350**
9351**      Boot command line.
9352**
9353**==========================================================
9354*/
9355#ifdef  MODULE
9356char *ncr53c8xx = 0;    /* command line passed by insmod */
9357# if LINUX_VERSION_CODE >= LinuxVersionCode(2,1,30)
9358MODULE_PARM(ncr53c8xx, "s");
9359# endif
9360#endif
9361
9362int __init ncr53c8xx_setup(char *str)
9363{
9364        return sym53c8xx__setup(str);
9365}
9366
9367#if LINUX_VERSION_CODE >= LinuxVersionCode(2,3,13)
9368#ifndef MODULE
9369__setup("ncr53c8xx=", ncr53c8xx_setup);
9370#endif
9371#endif
9372
9373/*===================================================================
9374**
9375**   SYM53C8XX supported device list
9376**
9377**===================================================================
9378*/
9379
9380static u_short  ncr_chip_ids[]   __initdata = {
9381        PSEUDO_ZALON_720_ID,
9382        PCI_DEVICE_ID_NCR_53C810,
9383        PCI_DEVICE_ID_NCR_53C815,
9384        PCI_DEVICE_ID_NCR_53C820,
9385        PCI_DEVICE_ID_NCR_53C825,
9386        PCI_DEVICE_ID_NCR_53C860,
9387        PCI_DEVICE_ID_NCR_53C875,
9388        PCI_DEVICE_ID_NCR_53C875J,
9389        PCI_DEVICE_ID_NCR_53C885,
9390        PCI_DEVICE_ID_NCR_53C895,
9391        PCI_DEVICE_ID_NCR_53C896,
9392        PCI_DEVICE_ID_NCR_53C895A,
9393        PCI_DEVICE_ID_NCR_53C1510D
9394};
9395
9396#ifdef ENABLE_SCSI_ZALON
9397/* Attach a 53c720 interfaced via Zalon chip on HP boxes.  */
9398int zalon_attach(Scsi_Host_Template *tpnt, unsigned long io_port,
9399                struct parisc_device *dev, int irq, int unit)
9400{
9401        u_short device_id;
9402        u_char revision;
9403        int i;
9404        ncr_chip *chip;
9405        ncr_device device;
9406
9407        tpnt->proc_name = NAME53C8XX;
9408        tpnt->proc_info = ncr53c8xx_proc_info;
9409
9410#if     defined(SCSI_NCR_BOOT_COMMAND_LINE_SUPPORT) && defined(MODULE)
9411        if (ncr53c8xx)
9412                ncr53c8xx_setup(ncr53c8xx);
9413#endif
9414
9415#ifdef SCSI_NCR_DEBUG_INFO_SUPPORT
9416        ncr_debug = driver_setup.debug;
9417#endif
9418        if (initverbose >= 2)
9419                ncr_print_driver_setup();
9420
9421        memset(&device, 0, sizeof(ncr_device));
9422        chip = 0;
9423        device_id = PSEUDO_ZALON_720_ID;
9424        revision = 0;
9425        for (i = 0; i < sizeof(ncr_chip_table)/sizeof(ncr_chip_table[0]); i++) {                if (device_id != ncr_chip_table[i].device_id)
9426                        continue;
9427                chip = &device.chip;
9428                memcpy(chip, &ncr_chip_table[i], sizeof(*chip));
9429                chip->revision_id = revision;
9430                break;
9431        }
9432
9433        if (!chip) {
9434                printk(NAME53C8XX ": not initializing, device not supported\n");                return -1;
9435        }
9436
9437        /* Fix some features according to driver setup. */
9438        driver_setup.diff_support = 2;
9439
9440        /* The following three are needed before any other access. */
9441        writeb(0x20, io_port + 0x38); /* DCNTL_REG,  EA  */
9442        writeb(0x04, io_port + 0x1b); /* CTEST0_REG, EHP */
9443        writeb(0x80, io_port + 0x22); /* CTEST4_REG, MUX */
9444
9445        /* Initialise ncr_device structure with items required by ncr_attach. */
9446        device.host_id          = driver_setup.host_id;
9447        device.dev              = &dev->dev;
9448        device.slot.bus         = 0;
9449        device.slot.device_fn   = 0;
9450        device.slot.base        = (u_long)io_port;
9451        device.slot.base_c      = (u_long)io_port;
9452        device.slot.base_2      = 0;
9453        device.slot.base_2_c    = 0;
9454        device.slot.io_port     = io_port;
9455        device.slot.irq         = irq;
9456        device.attach_done      = 0;
9457
9458        printk(KERN_INFO NAME53C8XX ": 53c%s detected\n", device.chip.name);
9459
9460        return ncr_attach(tpnt, unit, &device);
9461}
9462#endif
9463
9464/*==========================================================
9465**
9466**      Chip detection entry point.
9467**
9468**==========================================================
9469*/
9470int __init ncr53c8xx_detect(Scsi_Host_Template *tpnt)
9471{
9472        /*
9473        **    Initialize driver general stuff.
9474        */
9475#ifdef SCSI_NCR_PROC_INFO_SUPPORT
9476#if LINUX_VERSION_CODE < LinuxVersionCode(2,3,27)
9477     tpnt->proc_dir  = &proc_scsi_ncr53c8xx;
9478#else
9479     tpnt->proc_name = NAME53C8XX;
9480#endif
9481     tpnt->proc_info = ncr53c8xx_proc_info;
9482#endif
9483
9484#if     defined(SCSI_NCR_BOOT_COMMAND_LINE_SUPPORT) && defined(MODULE)
9485if (ncr53c8xx)
9486        ncr53c8xx_setup(ncr53c8xx);
9487#endif
9488
9489        return sym53c8xx__detect(tpnt, ncr_chip_ids,
9490                                 sizeof(ncr_chip_ids)/sizeof(ncr_chip_ids[0]));
9491}
9492
9493/*==========================================================
9494**
9495**   Entry point for info() function
9496**
9497**==========================================================
9498*/
9499const char *ncr53c8xx_info (struct Scsi_Host *host)
9500{
9501        return SCSI_NCR_DRIVER_NAME;
9502}
9503
9504/*
9505**      Module stuff
9506*/
9507MODULE_LICENSE("GPL");
9508
9509#if LINUX_VERSION_CODE >= LinuxVersionCode(2,4,0)
9510static
9511#endif
9512#if LINUX_VERSION_CODE >= LinuxVersionCode(2,4,0) || defined(MODULE)
9513#ifdef ENABLE_SCSI_ZALON
9514Scsi_Host_Template driver_template =  {
9515        .proc_name =            "zalon720",
9516        .detect =               zalon7xx_detect,
9517        .release =              zalon7xx_release,
9518        .info =                 ncr53c8xx_info,
9519        .queuecommand =         ncr53c8xx_queue_command,
9520        .can_queue =            SCSI_NCR_CAN_QUEUE,
9521        .this_id =              7,
9522        .sg_tablesize =         SCSI_NCR_SG_TABLESIZE,
9523        .cmd_per_lun =          SCSI_NCR_CMD_PER_LUN,
9524        .use_clustering =       DISABLE_CLUSTERING,
9525};
9526
9527
9528#else
9529Scsi_Host_Template driver_template = NCR53C8XX;
9530#endif
9531#include "scsi_module.c"
9532#endif
9533
lxr.linux.no kindly hosted by Redpill Linpro AS, provider of Linux consulting and operations services since 1995.