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