root/drivers/scsi/NCR5380.c

/* [previous][next][first][last][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. initialize_SCp
  2. NCR5380_print
  3. NCR5380_print_phase
  4. run_main
  5. should_disconnect
  6. NCR5380_set_timer
  7. NCR5380_timer_fn
  8. NCR5380_all_init
  9. probe_intr
  10. NCR5380_probe_irq
  11. NCR5380_print_options
  12. NCR5380_print_status
  13. NCR5380_init
  14. NCR5380_queue_command
  15. NCR5380_main
  16. NCR5380_intr
  17. NCR5380_select
  18. NCR5380_transfer_pio
  19. NCR5380_transfer_dma
  20. NCR5380_information_transfer
  21. NCR5380_reselect
  22. NCR5380_dma_complete
  23. NCR5380_abort
  24. NCR5380_reset

   1 #define NDEBUG (NDEBUG_RESTART_SELECT)
   2 /* 
   3  * NCR 5380 generic driver routines.  These should make it *trivial*
   4  *      to implement 5380 SCSI drivers under Linux with a non-trantor
   5  *      architecture.
   6  *
   7  *      Note that these routines also work with NR53c400 family chips.
   8  *
   9  * Copyright 1993, Drew Eckhardt
  10  *      Visionary Computing 
  11  *      (Unix and Linux consulting and custom programming)
  12  *      drew@colorado.edu
  13  *      +1 (303) 666-5836
  14  *
  15  * DISTRIBUTION RELEASE 6. 
  16  *
  17  * For more information, please consult 
  18  *
  19  * NCR 5380 Family
  20  * SCSI Protocol Controller
  21  * Databook
  22  *
  23  * NCR Microelectronics
  24  * 1635 Aeroplaza Drive
  25  * Colorado Springs, CO 80916
  26  * 1+ (719) 578-3400
  27  * 1+ (800) 334-5454
  28  */
  29 
  30 /*
  31  * $Log: NCR5380.c,v $
  32  * Revision 1.5  1994/01/19  09:14:57  drew
  33  * Fixed udelay() hack that was being used on DATAOUT phases
  34  * instead of a proper wait for the final handshake.
  35  *
  36  * Revision 1.4  1994/01/19  06:44:25  drew
  37  * *** empty log message ***
  38  *
  39  * Revision 1.3  1994/01/19  05:24:40  drew
  40  * Added support for TCR LAST_BYTE_SENT bit.
  41  *
  42  * Revision 1.2  1994/01/15  06:14:11  drew
  43  * REAL DMA support, bug fixes.
  44  *
  45  * Revision 1.1  1994/01/15  06:00:54  drew
  46  * Initial revision
  47  *
  48  */
  49 
  50 /*
  51  * Further development / testing that should be done : 
  52  * 1.  Cleanup the NCR5380_transfer_dma function and DMA operation complete
  53  *     code so that everything does the same thing that's done at the 
  54  *     end of a pseudo-DMA read operation.
  55  *
  56  * 2.  Fix REAL_DMA (interrupt driven, polled works fine) -
  57  *     basically, transfer size needs to be reduced by one 
  58  *     and the last byte read as is done with PSEUDO_DMA.
  59  * 
  60  * 3.  Test USLEEP code 
  61  *
  62  * 4.  Test SCSI-II tagged queueing (I have no devices which support 
  63  *      tagged queueing)
  64  *
  65  * 5.  Test linked command handling code after Eric is ready with 
  66  *      the high level code.
  67  */
  68 
  69 #ifndef notyet
  70 #undef LINKED
  71 #undef USLEEP
  72 #undef REAL_DMA
  73 #endif
  74 
  75 #ifdef REAL_DMA_POLL
  76 #undef READ_OVERRUNS
  77 #define READ_OVERRUNS
  78 #endif
  79 
  80 /*
  81  * Design
  82  * Issues :
  83  *
  84  * The other Linux SCSI drivers were written when Linux was Intel PC-only,
  85  * and specifically for each board rather than each chip.  This makes their
  86  * adaptation to platforms like the Mac (Some of which use NCR5380's)
  87  * more difficult than it has to be.
  88  *
  89  * Also, many of the SCSI drivers were written before the command queuing
  90  * routines were implemented, meaning their implementations of queued 
  91  * commands were hacked on rather than designed in from the start.
  92  *
  93  * When I designed the Linux SCSI drivers I figured that 
  94  * while having two different SCSI boards in a system might be useful
  95  * for debugging things, two of the same type wouldn't be used.
  96  * Well, I was wrong and a number of users have mailed me about running
  97  * multiple high-performance SCSI boards in a server.
  98  *
  99  * Finally, when I get questions from users, I have no idea what 
 100  * revision of my driver they are running.
 101  *
 102  * This driver attempts to address these problems :
 103  * This is a generic 5380 driver.  To use it on a different platform, 
 104  * one simply writes appropriate system specific macros (ie, data
 105  * transfer - some PC's will use the I/O bus, 68K's must use 
 106  * memory mapped) and drops this file in their 'C' wrapper.
 107  *
 108  * As far as command queueing, two queues are maintained for 
 109  * each 5380 in the system - commands that haven't been issued yet,
 110  * and commands that are currently executing.  This means that an 
 111  * unlimited number of commands may be queued, letting 
 112  * more commands propagate from the higher driver levels giving higher 
 113  * throughput.  Note that both I_T_L and I_T_L_Q nexuses are supported, 
 114  * allowing multiple commands to propagate all the way to a SCSI-II device 
 115  * while a command is already executing.
 116  *
 117  * To solve the multiple-boards-in-the-same-system problem, 
 118  * there is a separate instance structure for each instance
 119  * of a 5380 in the system.  So, multiple NCR5380 drivers will
 120  * be able to coexist with appropriate changes to the high level
 121  * SCSI code.  
 122  *
 123  * A NCR5380_PUBLIC_REVISION macro is provided, with the release
 124  * number (updated for each public release) printed by the 
 125  * NCR5380_print_options command, which should be called from the 
 126  * wrapper detect function, so that I know what release of the driver
 127  * users are using.
 128  *
 129  * Issues specific to the NCR5380 : 
 130  *
 131  * When used in a PIO or pseudo-dma mode, the NCR5380 is a braindead 
 132  * piece of hardware that requires you to sit in a loop polling for 
 133  * the REQ signal as long as you are connected.  Some devices are 
 134  * brain dead (ie, many TEXEL CD ROM drives) and won't disconnect 
 135  * while doing long seek operations.
 136  * 
 137  * The workaround for this is to keep track of devices that have
 138  * disconnected.  If the device hasn't disconnected, for commands that
 139  * should disconnect, we do something like 
 140  *
 141  * while (!REQ is asserted) { sleep for N usecs; poll for M usecs }
 142  * 
 143  * Some tweaking of N and M needs to be done.  An algorithm based 
 144  * on "time to data" would give the best results as long as short time
 145  * to datas (ie, on the same track) were considered, however these 
 146  * broken devices are the exception rather than the rule and I'd rather
 147  * spend my time optimizing for the normal case.
 148  *
 149  * Architecture :
 150  *
 151  * At the heart of the design is a coroutine, NCR5380_main,
 152  * which is started when not running by the interrupt handler,
 153  * timer, and queue command function.  It attempts to establish
 154  * I_T_L or I_T_L_Q nexuses by removing the commands from the 
 155  * issue queue and calling NCR5380_select() if a nexus 
 156  * is not established. 
 157  *
 158  * Once a nexus is established, the NCR5380_information_transfer()
 159  * phase goes through the various phases as instructed by the target.
 160  * if the target goes into MSG IN and sends a DISCONNECT message,
 161  * the command structure is placed into the per instance disconnected
 162  * queue, and NCR5380_main tries to find more work.  If USLEEP
 163  * was defined, and the target is idle for too long, the system
 164  * will try to sleep.
 165  *
 166  * If a command has disconnected, eventually an interrupt will trigger,
 167  * calling NCR5380_intr()  which will in turn call NCR5380_reselect
 168  * to reestablish a nexus.  This will run main if necessary.
 169  *
 170  * On command termination, the done function will be called as 
 171  * appropriate.
 172  *
 173  * SCSI pointers are maintained in the SCp field of SCSI command 
 174  * structures, being initialized after the command is connected
 175  * in NCR5380_select, and set as appropriate in NCR5380_information_transfer.
 176  * Note that in violation of the standard, an implicit SAVE POINTERS operation
 177  * is done, since some BROKEN disks fail to issue an explicit SAVE POINTERS.
 178  */
 179 
 180 /*
 181  * Using this file :
 182  * This file a skeleton Linux SCSI driver for the NCR 5380 series
 183  * of chips.  To use it, you write a architecture specific functions 
 184  * and macros and include this file in your driver.
 185  *
 186  * These macros control options : 
 187  * AUTOPROBE_IRQ - if defined, the NCR5380_probe_irq() function will be 
 188  *      defined.
 189  * 
 190  * AUTOSENSE - if defined, REQUEST SENSE will be performed automatically
 191  *      for commands that return with a CHECK CONDITION status. 
 192  *
 193  * DIFFERENTIAL - if defined, NCR53c81 chips will use external differential
 194  *      transceivers. 
 195  *
 196  * LIMIT_TRANSFERSIZE - if defined, limit the pseudo-dma transfers to 512
 197  *      bytes at a time.  Since interrupts are disabled by default during
 198  *      these transfers, we might need this to give reasonable interrupt
 199  *      service time if the transfer size gets too large.
 200  *
 201  * LINKED - if defined, linked commands are supported.
 202  *
 203  * PSEUDO_DMA - if defined, PSEUDO DMA is used during the data transfer phases.
 204  *
 205  * REAL_DMA - if defined, REAL DMA is used during the data transfer phases.
 206  *
 207  * REAL_DMA_POLL - if defined, REAL DMA is used but the driver doesn't
 208  *      rely on phase mismatch and EOP interrupts to determine end 
 209  *      of phase.
 210  *
 211  * SCSI2 - if defined, SCSI-2 tagged queuing is used where possible
 212  *
 213  * UNSAFE - leave interrupts enabled during pseudo-DMA transfers.  You
 214  *          only really want to use this if you're having a problem with
 215  *          dropped characters during high speed communications, and even
 216  *          then, you're going to be better off twiddling with transfersize
 217  *          in the high level code.
 218  *
 219  * USLEEP - if defined, on devices that aren't disconnecting from the 
 220  *      bus, we will go to sleep so that the CPU can get real work done 
 221  *      when we run a command that won't complete immediately.
 222  *
 223  * Note that if USLEEP is defined, NCR5380_TIMER *must* also be
 224  * defined.
 225  *
 226  * Defaults for these will be provided if USLEEP is defined, although
 227  * the user may want to adjust these to allocate CPU resources to 
 228  * the SCSI driver or "real" code.
 229  * 
 230  * USLEEP_SLEEP - amount of time, in jiffies, to sleep
 231  *
 232  * USLEEP_POLL - amount of time, in jiffies, to poll
 233  *
 234  * These macros MUST be defined :
 235  * NCR5380_local_declare() - declare any local variables needed for your transfer
 236  *      routines.
 237  *
 238  * NCR5380_setup(instance) - initialize any local variables needed from a given
 239  *      instance of the host adapter for NCR5380_{read,write,pread,pwrite}
 240  * 
 241  * NCR5380_read(register)  - read from the specified register
 242  *
 243  * NCR5380_write(register, value) - write to the specific register 
 244  *
 245  * NCR5380_implementation_fields  - additional fields needed for this 
 246  *      specific implementation of the NCR5380
 247  *
 248  * Either real DMA *or* pseudo DMA may be implemented
 249  * REAL functions : 
 250  * NCR5380_REAL_DMA should be defined if real DMA is to be used.
 251  * Note that the DMA setup functions should return the number of bytes 
 252  *      that they were able to program the controller for.
 253  *
 254  * Also note that generic i386/PC versions of these macros are 
 255  *      available as NCR5380_i386_dma_write_setup,
 256  *      NCR5380_i386_dma_read_setup, and NCR5380_i386_dma_residual.
 257  *
 258  * NCR5380_dma_write_setup(instance, src, count) - initialize
 259  * NCR5380_dma_read_setup(instance, dst, count) - initialize
 260  * NCR5380_dma_residual(instance); - residual count
 261  *
 262  * PSEUDO functions :
 263  * NCR5380_pwrite(instance, src, count)
 264  * NCR5380_pread(instance, dst, count);
 265  *
 266  * If nothing specific to this implementation needs doing (ie, with external
 267  * hardware), you must also define 
 268  *  
 269  * NCR5380_queue_command
 270  * NCR5380_reset
 271  * NCR5380_abort
 272  *
 273  * to be the global entry points into the specific driver, ie 
 274  * #define NCR5380_queue_command t128_queue_command.
 275  *
 276  * If this is not done, the routines will be defined as static functions
 277  * with the NCR5380* names and the user must provide a globally
 278  * accessible wrapper function.
 279  *
 280  * The generic driver is initialized by calling NCR5380_init(instance),
 281  * after setting the appropriate host specific fields and ID.  If the 
 282  * driver wishes to autoprobe for an IRQ line, the NCR5380_probe_irq(instance,
 283  * possible) function may be used.  Before the specific driver initialization
 284  * code finishes, NCR5380_print_options should be called.
 285  */
 286 
 287 static struct Scsi_Host *first_instance = NULL;
 288 static Scsi_Host_Template *the_template = NULL;
 289 
 290 /*
 291  * Function : void initialize_SCp(Scsi_Cmnd *cmd)
 292  *
 293  * Purpose : initialize the saved data pointers for cmd to point to the 
 294  *      start of the buffer.
 295  *
 296  * Inputs : cmd - Scsi_Cmnd structure to have pointers reset.
 297  */
 298 
 299 static __inline__ void initialize_SCp(Scsi_Cmnd *cmd) {
     /* [previous][next][first][last][top][bottom][index][help] */
 300     /* 
 301      * Initialize the Scsi Pointer field so that all of the commands in the 
 302      * various queues are valid.
 303      */
 304 
 305     if (cmd->use_sg) {
 306         cmd->SCp.buffer = (struct scatterlist *) cmd->buffer;
 307         cmd->SCp.buffers_residual = cmd->use_sg - 1;
 308         cmd->SCp.ptr = (char *) cmd->SCp.buffer->address;
 309         cmd->SCp.this_residual = cmd->SCp.buffer->length;
 310     } else {
 311         cmd->SCp.buffer = NULL;
 312         cmd->SCp.buffers_residual = 0;
 313         cmd->SCp.ptr = (char *) cmd->request_buffer;
 314         cmd->SCp.this_residual = cmd->request_bufflen;
 315     }
 316 }
 317 
 318 #include <linux/delay.h>
 319 
 320 #ifdef NDEBUG
 321 static struct {
 322     unsigned char mask;
 323     const char * name;} 
 324 signals[] = {{ SR_DBP, "PARITY"}, { SR_RST, "RST" }, { SR_BSY, "BSY" }, 
 325     { SR_REQ, "REQ" }, { SR_MSG, "MSG" }, { SR_CD,  "CD" }, { SR_IO, "IO" }, 
 326     { SR_SEL, "SEL" }, {0, NULL}}, 
 327 basrs[] = {{BASR_ATN, "ATN"}, {BASR_ACK, "ACK"}, {0, NULL}},
 328 icrs[] = {{ICR_ASSERT_RST, "ASSERT RST"},{ICR_ASSERT_ACK, "ASSERT ACK"},
 329     {ICR_ASSERT_BSY, "ASSERT BSY"}, {ICR_ASSERT_SEL, "ASSERT SEL"}, 
 330     {ICR_ASSERT_ATN, "ASSERT ATN"}, {ICR_ASSERT_DATA, "ASSERT DATA"}, 
 331     {0, NULL}},
 332 mrs[] = {{MR_BLOCK_DMA_MODE, "MODE BLOCK DMA"}, {MR_TARGET, "MODE TARGET"}, 
 333     {MR_ENABLE_PAR_CHECK, "MODE PARITY CHECK"}, {MR_ENABLE_PAR_INTR, 
 334     "MODE PARITY INTR"}, {MR_MONITOR_BSY, "MODE MONITOR BSY"},
 335     {MR_DMA_MODE, "MODE DMA"}, {MR_ARBITRATE, "MODE ARBITRATION"}, 
 336     {0, NULL}};
 337 
 338 /*
 339  * Function : void NCR5380_print(struct Scsi_Host *instance)
 340  *
 341  * Purpose : print the SCSI bus signals for debugging purposes
 342  *
 343  * Input : instance - which NCR5380
 344  */
 345 
 346 static void NCR5380_print(struct Scsi_Host *instance) {
     /* [previous][next][first][last][top][bottom][index][help] */
 347     NCR5380_local_declare();
 348     unsigned char status, data, basr, mr, icr, i;
 349     NCR5380_setup(instance);
 350     cli();
 351     data = NCR5380_read(CURRENT_SCSI_DATA_REG);
 352     status = NCR5380_read(STATUS_REG);
 353     mr = NCR5380_read(MODE_REG);
 354     icr = NCR5380_read(INITIATOR_COMMAND_REG);
 355     basr = NCR5380_read(BUS_AND_STATUS_REG);
 356     sti();
 357     for (i = 0; signals[i].mask ; ++i) 
 358         if (status & signals[i].mask)
 359             printk(" %s", signals[i].name);
 360     for (i = 0; basrs[i].mask ; ++i) 
 361         if (basr & basrs[i].mask)
 362             printk(" %s", basrs[i].name);
 363     for (i = 0; icrs[i].mask; ++i) 
 364         if (icr & icrs[i].mask)
 365             printk(" %s", icrs[i].name);
 366     for (i = 0; mrs[i].mask; ++i) 
 367         if (mr & mrs[i].mask)
 368             printk(" %s", mrs[i].name);
 369     printk("\n");
 370 }
 371 
 372 static struct {
 373     unsigned char value;
 374     const char *name;
 375 } phases[] = {
 376 {PHASE_DATAOUT, "DATAOUT"}, {PHASE_DATAIN, "DATAIN"}, {PHASE_CMDOUT, "CMDOUT"},
 377 {PHASE_STATIN, "STATIN"}, {PHASE_MSGOUT, "MSGOUT"}, {PHASE_MSGIN, "MSGIN"},
 378 {PHASE_UNKNOWN, "UNKNOWN"}};
 379 
 380 /* 
 381  * Function : void NCR5380_print_phase(struct Scsi_Host *instance)
 382  *
 383  * Purpose : print the current SCSI phase for debugging purposes
 384  *
 385  * Input : instance - which NCR5380
 386  */
 387 
 388 static void NCR5380_print_phase(struct Scsi_Host *instance) {
     /* [previous][next][first][last][top][bottom][index][help] */
 389     NCR5380_local_declare();
 390     unsigned char status;
 391     int i;
 392     NCR5380_setup(instance);
 393 
 394     status = NCR5380_read(STATUS_REG);
 395     if (!(status & SR_REQ)) 
 396         printk("scsi%d : REQ not asserted, phase unknown.\n", 
 397             instance->host_no);
 398     else {
 399         for (i = 0; (phases[i].value != PHASE_UNKNOWN) && 
 400             (phases[i].value != (status & PHASE_MASK)); ++i); 
 401         printk("scsi%d : phase %s\n", instance->host_no, phases[i].name);
 402     }
 403 }
 404 #endif
 405 
 406 /*
 407  * We need to have our coroutine active given these constraints : 
 408  * 1.  The mutex flag, main_running, can only be set when the main 
 409  *     routine can actually process data, otherwise SCSI commands
 410  *     will never get issued.
 411  *
 412  * 2.  NCR5380_main() shouldn't be called before it has exited, because
 413  *     other drivers have had kernel stack overflows in similar
 414  *     situations.
 415  *
 416  * 3.  We don't want to inline NCR5380_main() because of space concerns,
 417  *     even though it is only called in two places.
 418  *
 419  * So, the solution is to set the mutex in an inline wrapper for the 
 420  * main coroutine, and have the main coroutine exit with interrupts 
 421  * disabled after the final search through the queues so that no race 
 422  * conditions are possible.
 423  */
 424 
 425 static volatile int main_running = 0;
 426 
 427 /* 
 428  * Function : run_main(void)
 429  * 
 430  * Purpose : insure that the coroutine is running and will process our 
 431  *      request.  main_running is checked/set here (in an inline function)
 432  *      rather than in NCR5380_main itself to reduce the chances of stack
 433  *      overflow.
 434  *
 435  */
 436 
 437 static __inline__ void run_main(void) {
     /* [previous][next][first][last][top][bottom][index][help] */
 438     cli();
 439     if (!main_running) {
 440         main_running = 1;
 441         NCR5380_main();
 442         /* 
 443          * main_running is cleared in NCR5380_main once it can't do 
 444          * more work, and NCR5380_main exits with interrupts disabled.
 445          */
 446         sti();
 447     } else 
 448         sti();
 449 }
 450 
 451 #ifdef USLEEP
 452 #ifndef NCR5380_TIMER
 453 #error "NCR5380_TIMER must be defined so that this type of NCR5380 driver gets a unique timer."
 454 #endif
 455 
 456 /*
 457  * These need tweaking, and would probably work best as per-device 
 458  * flags initialized differently for disk, tape, cd, etc devices.
 459  * People with broken devices are free to experiment as to what gives
 460  * the best results for them.
 461  *
 462  * USLEEP_SLEEP should be a minimum seek time.
 463  *
 464  * USLEEP_POLL should be a maximum rotational latency.
 465  */
 466 #ifndef USLEEP_SLEEP
 467 /* 20 ms (reasonable hard disk speed) */
 468 #define USLEEP_SLEEP 2
 469 #endif
 470 /* 300 RPM (floppy speed) */
 471 #ifndef USLEEP_POLL
 472 #define USLEEP_POLL 20
 473 #endif
 474 
 475 static struct Scsi_Host * expires_first = NULL;
 476 
 477 /* 
 478  * Function : int should_disconnect (unsigned char cmd)
 479  *
 480  * Purpose : decide weather a command would normally disconnect or 
 481  *      not, since if it won't disconnect we should go to sleep.
 482  *
 483  * Input : cmd - opcode of SCSI command
 484  *
 485  * Returns : DISCONNECT_LONG if we should disconnect for a really long 
 486  *      time (ie always, sleep, look for REQ active, sleep), 
 487  *      DISCONNECT_TIME_TO_DATA if we would only disconnect for a normal
 488  *      time-to-data delay, DISCONNECT_NONE if this command would return
 489  *      immediately.
 490  *
 491  *      Future sleep algorithms based on time to data can exploit 
 492  *      something like this so they can differentiate between "normal" 
 493  *      (ie, read, write, seek) and unusual commands (ie, * format).
 494  *
 495  * Note : We don't deal with commands that handle an immediate disconnect,
 496  *        
 497  */
 498 
 499 static int should_disconnect (unsigned char cmd) {
     /* [previous][next][first][last][top][bottom][index][help] */
 500     switch (cmd) {
 501     case READ_6:
 502     case WRITE_6:
 503     case SEEK_6:
 504     case READ_10:
 505     case WRITE_10:
 506     case SEEK_10:
 507         return DISCONNECT_TIME_TO_DATA;
 508     case FORMAT_UNIT:
 509     case SEARCH_HIGH:
 510     case SEARCH_LOW:
 511     case SEARCH_EQUAL:
 512         return DISCONNECT_LONG;
 513     default:
 514         return DISCONNECT_NONE;
 515     }
 516 }
 517 
 518 /*
 519  * Assumes instance->time_expires has been set in higher level code.
 520  */
 521 
 522 static int NCR5380_set_timer (struct Scsi_Host *instance) {
     /* [previous][next][first][last][top][bottom][index][help] */
 523     struct Scsi_Host *tmp, **prev;
 524     
 525     cli();
 526     if (((struct NCR5380_hostdata *) (instance->host_data))->next_timer) {
 527         sti();
 528         return -1;
 529     }
 530 
 531     for (prev = &expires_first, tmp = expires_first; tmp; 
 532         prev = &(((struct NCR5380_hostdata *) tmp->host_data)->next_timer), 
 533         tmp = ((struct NCR5380_hostdata *) tmp->host_data)->next_timer)
 534         if (instance->time_expires < tmp->time_expires) 
 535             break;
 536            
 537     instance->next_timer = tmp;
 538     *prev = instance;
 539     timer_table[NCR5380_TIMER].expires = expires_first->time_expires;
 540     timer_active |= 1 << NCR5380_TIMER;
 541     sti();
 542     return 0;
 543 }    
 544 
 545 /* Doing something about unwanted reentrancy here might be useful */
 546 void NCR5380_timer_fn(void) {
     /* [previous][next][first][last][top][bottom][index][help] */
 547     struct Scsi_Host *instance;
 548     cli();
 549     for (; expires_first && expires_first->time_expires >= jiffies; ) {
 550         instance = ((NCR5380_hostdata *) expires_first->host_data)->
 551             expires_next;
 552         ((NCR5380_hostdata *) expires_first->host_data)->expires_next = 
 553             NULL;
 554         ((NCR5380_hostdata *) expires_first->host_data)->time_expires = 
 555             0;
 556         expires_first = instance;
 557     }
 558 
 559     if (expires_first) {
 560         timer_table[NCR5380_TIMER].expires = ((NCR5380_hostdata *) 
 561             expires_first->host_data)->time_expires;
 562         timer_active |= (1 << NCR5380_TIMER);
 563     } else {
 564         timer_table[NCR5380_TIMER].expires = 0;
 565         timer_active &= ~(1 << MCR5380_TIMER);
 566     }
 567     sti();
 568 
 569     run_main();
 570 }
 571 #endif /* def USLEEP */
 572 
 573 static void NCR5380_all_init (void) {
     /* [previous][next][first][last][top][bottom][index][help] */
 574     static int done = 0;
 575     if (!done) {
 576 #if (NDEBUG & NDEBUG_INIT)
 577         printk("scsi : NCR5380_all_init()\n");
 578 #endif
 579         done = 1;
 580 #ifdef USLEEP
 581         timer_table[NCR5380_TIMER].expires = 0;
 582         timer_table[NCR5380_TIMER].fn = NCR5380_timer_fn;
 583 #endif
 584     }
 585 }
 586 
 587 #ifdef AUTOPROBE_IRQ
 588 /*
 589  * Function : int NCR5380_probe_irq (struct Scsi_Host *instance, int possible)
 590  * 
 591  * Purpose : autoprobe for the IRQ line used by the NCR5380.  
 592  *
 593  * Inputs : instance - pointer to this instance of the NCR5380 driver,
 594  *          possible - bitmask of permissible interrupts.
 595  *
 596  * Returns : number of the IRQ selected, IRQ_NONE if no interrupt fired.
 597  * 
 598  * XXX no effort is made to deal with spurious interrupts. 
 599  */
 600 
 601 
 602 static int probe_irq;
 603 static void probe_intr (int irq, struct pt_regs * regs) {
     /* [previous][next][first][last][top][bottom][index][help] */
 604     probe_irq = irq;
 605 };
 606 
 607 static int NCR5380_probe_irq (struct Scsi_Host *instance, int possible) {
     /* [previous][next][first][last][top][bottom][index][help] */
 608     NCR5380_local_declare();
 609     struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *)
 610          instance->hostdata;
 611     unsigned long timeout;
 612     int trying_irqs, i, mask;
 613     NCR5380_setup(instance);
 614 
 615     for (trying_irqs = i = 0, mask = 1; i < 16; ++i, mask <<= 1) 
 616         if ((mask & possible) &&  (request_irq(i, &probe_intr, SA_INTERRUPT, "NCR-probe") 
 617             == 0)) 
 618             trying_irqs |= mask;
 619 
 620     timeout = jiffies + 25;
 621     probe_irq = IRQ_NONE;
 622 
 623 /*
 624  * A interrupt is triggered whenever BSY = false, SEL = true
 625  * and a bit set in the SELECT_ENABLE_REG is asserted on the 
 626  * SCSI bus.
 627  *
 628  * Note that the bus is only driven when the phase control signals
 629  * (I/O, C/D, and MSG) match those in the TCR, so we must reset that
 630  * to zero.
 631  */
 632 
 633     NCR5380_write(TARGET_COMMAND_REG, 0);
 634     NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
 635     NCR5380_write(OUTPUT_DATA_REG, hostdata->id_mask);
 636     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA | 
 637         ICR_ASSERT_SEL);
 638 
 639     while (probe_irq == IRQ_NONE && jiffies < timeout)
 640         barrier();
 641 
 642     NCR5380_write(SELECT_ENABLE_REG, 0);
 643     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
 644 
 645     for (i = 0, mask = 1; i < 16; ++i, mask <<= 1)
 646         if (trying_irqs & mask) 
 647             free_irq(i);
 648 
 649     return probe_irq;
 650 }
 651 #endif /* AUTOPROBE_IRQ */
 652  
 653 /*
 654  * Function : void NCR58380_print_options (struct Scsi_Host *instance)
 655  *
 656  * Purpose : called by probe code indicating the NCR5380 driver
 657  *           options that were selected.
 658  *
 659  * Inputs : instance, pointer to this instance.  Unused.
 660  */
 661 
 662 static void NCR5380_print_options (struct Scsi_Host *instance) {
     /* [previous][next][first][last][top][bottom][index][help] */
 663     printk(" generic options"
 664 #ifdef AUTOPROBE_IRQ
 665     " AUTOPROBE_IRQ"
 666 #endif
 667 #ifdef AUTOSENSE 
 668     " AUTOSENSE"
 669 #endif
 670 #ifdef DIFFERENTIAL
 671     " DIFFERENTIAL"
 672 #endif
 673 #ifdef REAL_DMA
 674     " REAL DMA"
 675 #endif
 676 #ifdef REAL_DMA_POLL
 677     " REAL DMA POLL"
 678 #endif
 679 #ifdef PARITY
 680     " PARITY"
 681 #endif
 682 #ifdef PSEUDO_DMA
 683     " PSEUDO DMA"
 684 #endif
 685 #ifdef SCSI2
 686     " SCSI-2"
 687 #endif
 688 #ifdef UNSAFE
 689     " UNSAFE "
 690 #endif
 691     );
 692 #ifdef USLEEP
 693     printk(" USLEEP, USLEEP_POLL=%d USLEEP_SLEEP=%d", USLEEP_POLL, USLEEP_SLEEP);
 694 #endif
 695     printk(" generic release=%d", NCR5380_PUBLIC_RELEASE);
 696 #ifdef NCR53C400
 697     if (hostdata->flags & FLAG_NCR53C400) {
 698         printk(" ncr53c400 release=%d", NCR53C400_PUBLIC_RELEASE);
 699     }
 700 #endif
 701 }
 702 
 703 /*
 704  * Function : void NCR5380_print_status (struct Scsi_Host *instance)
 705  *
 706  * Purpose : print commands in the various queues, called from
 707  *      NCR5380_abort and NCR5380_debug to aid debugging.
 708  *
 709  * Inputs : instance, pointer to this instance.  
 710  */
 711 
 712 static void NCR5380_print_status (struct Scsi_Host *instance) {
     /* [previous][next][first][last][top][bottom][index][help] */
 713     struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *) 
 714         instance->hostdata;
 715     Scsi_Cmnd *ptr;
 716 
 717 
 718     printk("NCR5380 : coroutine is%s running.\n",
 719         main_running ? "" : "n't");
 720     
 721 #ifdef NDEBUG
 722     NCR5380_print (instance);
 723     NCR5380_print_phase (instance);
 724 #endif
 725 
 726     cli();
 727     if (!hostdata->connected) {
 728         printk ("scsi%d: no currently connected command\n",
 729             instance->host_no);
 730     } else {
 731         print_Scsi_Cmnd ((Scsi_Cmnd *) hostdata->connected);
 732     }
 733 
 734     printk ("scsi%d: issue_queue\n", instance->host_no);
 735 
 736     for (ptr = (Scsi_Cmnd *) hostdata->issue_queue; ptr; 
 737         ptr = (Scsi_Cmnd *) ptr->host_scribble) 
 738         print_Scsi_Cmnd (ptr);
 739 
 740     printk ("scsi%d: disconnected_queue\n", instance->host_no);
 741 
 742     for (ptr = (Scsi_Cmnd *) hostdata->disconnected_queue; ptr; 
 743         ptr = (Scsi_Cmnd *) ptr->host_scribble) 
 744         print_Scsi_Cmnd (ptr);
 745     
 746     sti();
 747 }
 748 
 749 
 750 /* 
 751  * Function : void NCR5380_init (struct Scsi_Host *instance, flags)
 752  *
 753  * Purpose : initializes *instance and corresponding 5380 chip,
 754  *      with flags OR'd into the initial flags value.
 755  *
 756  * Inputs : instance - instantiation of the 5380 driver.  
 757  *
 758  * Notes : I assume that the host, hostno, and id bits have been
 759  *      set correctly.  I don't care about the irq and other fields. 
 760  * 
 761  */
 762 
 763 static void NCR5380_init (struct Scsi_Host *instance, int flags) {
     /* [previous][next][first][last][top][bottom][index][help] */
 764     NCR5380_local_declare();
 765     int i;
 766     struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *) 
 767         instance->hostdata;
 768 
 769     /* 
 770      * On NCR53C400 boards, NCR5380 registers are mapped 8 past 
 771      * the base address.
 772      */
 773 
 774     if (flags & FLAG_NCR53C400)
 775         instance->io_port += 8;
 776 
 777     NCR5380_setup(instance);
 778 
 779     NCR5380_all_init();
 780 
 781     hostdata->aborted = 0;
 782     hostdata->id_mask = 1 << instance->this_id;
 783     for (i = hostdata->id_mask; i <= 0x80; i <<= 1)
 784         if (i > hostdata->id_mask)
 785             hostdata->id_higher_mask |= i;
 786     for (i = 0; i < 8; ++i)
 787         hostdata->busy[i] = 0;
 788 #ifdef REAL_DMA
 789     hostdata->dmalen = 0;
 790 #endif
 791     hostdata->targets_present = 0;
 792     hostdata->connected = NULL;
 793     hostdata->issue_queue = NULL;
 794     hostdata->disconnected_queue = NULL;
 795     hostdata->flags = FLAG_CHECK_LAST_BYTE_SENT | flags;
 796 
 797     if (!the_template) {
 798         the_template = instance->hostt;
 799         first_instance = instance;
 800     }
 801         
 802 
 803 #ifdef USLEEP
 804     hostdata->time_expires = 0;
 805     hostdata->next_timer = NULL;
 806 #endif
 807 
 808 #ifndef AUTOSENSE
 809     if ((instance->cmd_per_lun > 1) || instance->can_queue > 1)) 
 810          printk("scsi%d : WARNING : support for multiple outstanding commands enabled\n"
 811                 "         without AUTOSENSE option, contingent allegiance conditions may\n"
 812                 "         be incorrectly cleared.\n", instance->host_no);
 813 #endif /* def AUTOSENSE */
 814 
 815     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
 816     NCR5380_write(MODE_REG, MR_BASE);
 817     NCR5380_write(TARGET_COMMAND_REG, 0);
 818     NCR5380_write(SELECT_ENABLE_REG, 0);
 819 #ifdef NCR53C400
 820     if (hostdata->flags & FLAG_NCR53C400) {
 821         NCR5380_write(C400_CONTROL_STATUS_REG, CSR_BASE);
 822     }
 823 #endif
 824 }
 825 
 826 /* 
 827  * Function : int NCR5380_queue_command (Scsi_Cmnd *cmd, 
 828  *      void (*done)(Scsi_Cmnd *)) 
 829  *
 830  * Purpose :  enqueues a SCSI command
 831  *
 832  * Inputs : cmd - SCSI command, done - function called on completion, with
 833  *      a pointer to the command descriptor.
 834  * 
 835  * Returns : 0
 836  *
 837  * Side effects : 
 838  *      cmd is added to the per instance issue_queue, with minor 
 839  *      twiddling done to the host specific fields of cmd.  If the 
 840  *      main coroutine is not running, it is restarted.
 841  *
 842  */
 843 
 844 /* Only make static if a wrapper function is used */
 845 #ifndef NCR5380_queue_command
 846 static
 847 #endif
 848 int NCR5380_queue_command (Scsi_Cmnd *cmd, void (*done)(Scsi_Cmnd *)) {
     /* [previous][next][first][last][top][bottom][index][help] */
 849     struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *)
 850         cmd->host->hostdata;
 851     Scsi_Cmnd *tmp;
 852 
 853 #if (NDEBUG & NDEBUG_NO_WRITE)
 854     switch (cmd->cmnd[0]) {
 855     case WRITE:
 856     case WRITE_10:
 857         printk("scsi%d : WRITE attempted with NO_WRITE debugging flag set\n",
 858             instance->host_no);
 859         cmd->result = (DID_ERROR << 16);
 860         done(cmd);
 861         return 0;
 862     }
 863 #endif /* (NDEBUG & NDEBUG_NO_WRITE) */
 864 
 865 
 866     /* 
 867      * We use the host_scribble field as a pointer to the next command  
 868      * in a queue 
 869      */
 870 
 871     cmd->host_scribble = NULL;
 872     cmd->scsi_done = done;
 873 
 874     cmd->result = 0;
 875 
 876 
 877     /* 
 878      * Insert the cmd into the issue queue. Note that REQUEST SENSE 
 879      * commands are added to the head of the queue since any command will
 880      * clear the contingent allegiance condition that exists and the 
 881      * sense data is only guaranteed to be valid while the condition exists.
 882      */
 883 
 884     cli();
 885     if (!(hostdata->issue_queue) || (cmd->cmnd[0] == REQUEST_SENSE)) {
 886         cmd->host_scribble = (unsigned char *) hostdata->issue_queue;
 887         hostdata->issue_queue = cmd;
 888     } else {
 889         for (tmp = (Scsi_Cmnd *) hostdata->issue_queue; tmp->host_scribble; 
 890                 tmp = (Scsi_Cmnd *) tmp->host_scribble);
 891         tmp->host_scribble = (unsigned char *) cmd;
 892     }
 893 #if (NDEBUG & NDEBUG_QUEUES)
 894     printk("scsi%d : command added to %s of queue\n", instance->host_no,
 895         (cmd->cmnd[0] == REQUEST_SENSE) ? "head" : "tail");
 896 #endif
 897 
 898 /* Run the coroutine if it isn't already running. */
 899     run_main();
 900     return 0;
 901 }
 902 
 903 /*
 904  * Function : NCR5380_main (void) 
 905  *
 906  * Purpose : NCR5380_main is a coroutine that runs as long as more work can 
 907  *      be done on the NCR5380 host adapters in a system.  Both 
 908  *      NCR5380_queue_command() and NCR5380_intr() will try to start it 
 909  *      in case it is not running.
 910  * 
 911  * NOTE : NCR5380_main exits with interrupts *disabled*, the caller should 
 912  *  reenable them.  This prevents reentrancy and kernel stack overflow.
 913  */     
 914     
 915 static void NCR5380_main (void) {
     /* [previous][next][first][last][top][bottom][index][help] */
 916     Scsi_Cmnd *tmp, *prev;
 917     struct Scsi_Host *instance;
 918     struct NCR5380_hostdata *hostdata;
 919     int done;
 920 
 921     /*
 922      * We run (with interrupts disabled) until we're sure that none of 
 923      * the host adapters have anything that can be done, at which point 
 924      * we set main_running to 0 and exit.
 925      *
 926      * Interrupts are enabled before doing various other internal 
 927      * instructions, after we've decided that we need to run through
 928      * the loop again.
 929      *
 930      * this should prevent any race conditions.
 931      */
 932 
 933     do {
 934         cli(); /* Freeze request queues */
 935         done = 1;
 936         for (instance = first_instance; instance && 
 937             instance->hostt == the_template; instance=instance->next) {
 938             hostdata = (struct NCR5380_hostdata *) instance->hostdata;
 939             cli();
 940             if (!hostdata->connected) {
 941 #if (NDEBUG & NDEBUG_MAIN)
 942                 printk("scsi%d : not connected\n", instance->host_no);
 943 #endif
 944                 /*
 945                  * Search through the issue_queue for a command destined
 946                  * for a target that's not busy.
 947                  */
 948                 for (tmp = (Scsi_Cmnd *) hostdata->issue_queue, 
 949                     prev = NULL; tmp; prev = tmp, tmp = (Scsi_Cmnd *) 
 950                     tmp->host_scribble) 
 951 
 952                     /*  When we find one, remove it from the issue queue. */
 953                     if (!(hostdata->busy[tmp->target] & (1 << tmp->lun))) {
 954                             if (prev)
 955                                 prev->host_scribble = tmp->host_scribble;
 956                             else
 957                                 hostdata->issue_queue = (Scsi_Cmnd *) tmp->host_scribble;
 958                         tmp->host_scribble = NULL;
 959 
 960                         /* reenable interrupts after finding one */
 961                         sti();
 962 
 963                         /* 
 964                          * Attempt to establish an I_T_L nexus here. 
 965                          * On success, instance->hostdata->connected is set.
 966                          * On failure, we must add the command back to the
 967                          *   issue queue so we can keep trying. 
 968                          */
 969 #if (NDEBUG & (NDEBUG_MAIN | NDEBUG_QUEUES))
 970                         printk("scsi%d : main() : command for target %d lun %d removed from issue_queue\n",
 971                             instance->host_no, tmp->target, tmp->lun);
 972 #endif
 973                         /* 
 974                          * REQUEST SENSE commands are issued without tagged
 975                          * queueing, even on SCSI-II devices because the 
 976                          * contingent allegiance condition exists for the 
 977                          * entire unit.
 978                          */
 979                         
 980                         if (!NCR5380_select(instance, tmp, 
 981                             (tmp->cmnd[0] == REQUEST_SENSE) ? TAG_NONE : 
 982                             TAG_NEXT)) {
 983                             break;
 984                         } else {
 985                             cli();
 986                             tmp->host_scribble = (unsigned char *) 
 987                                 hostdata->issue_queue;
 988                             hostdata->issue_queue = tmp;
 989                             sti();
 990 #if (NDEBUG & (NDEBUG_MAIN | NDEBUG_QUEUES))
 991                         printk("scsi%d : main(): select() failed, returned to issue_queue\n",
 992                             instance->host_no);
 993 #endif
 994                         }
 995                     } /* if target/lun is not busy */
 996             } /* if (!hostdata->connected) */
 997                 
 998             if (hostdata->connected 
 999 #ifdef REAL_DMA
1000                 && !hostdata->dmalen
1001 #endif
1002 #ifdef USLEEP
1003                 && (!hostdata->time_expires || hostdata->time_expires >= jiffies)
1004 #endif
1005                 ) {
1006                 sti();
1007 #if (NDEBUG & NDEBUG_MAIN)
1008                 printk("scsi%d : main() : performing information transfer\n",
1009                         instance->host_no);
1010 #endif
1011                 NCR5380_information_transfer(instance);
1012 #if (NDEBUG & NDEBUG_MAIN)
1013                 printk("scsi%d : main() : done set false\n", instance->host_no);
1014 #endif
1015                 done = 0;
1016             } else 
1017                 break;
1018         } /* for instance */
1019     } while (!done);
1020     main_running = 0;
1021 }
1022 
1023 /*
1024  * Function : void NCR5380_intr (int irq)
1025  * 
1026  * Purpose : handle interrupts, reestablishing I_T_L or I_T_L_Q nexuses
1027  *      from the disconnected queue, and restarting NCR5380_main() 
1028  *      as required.
1029  *
1030  * Inputs : int irq, irq that caused this interrupt.
1031  *
1032  */
1033 
1034 static void NCR5380_intr (int irq, struct pt_regs * regs) {
     /* [previous][next][first][last][top][bottom][index][help] */
1035     NCR5380_local_declare(); 
1036     struct Scsi_Host *instance;
1037     int done;
1038     unsigned char basr;
1039 #if (NDEBUG & NDEBUG_INTR)
1040     printk("scsi : NCR5380 irq %d triggered\n", irq);
1041 #endif
1042     do {
1043         done = 1;
1044         for (instance = first_instance; instance && (instance->hostt == 
1045             the_template); instance = instance->next)
1046             if (instance->irq == irq) {
1047                 
1048                 /* Look for pending interrupts */
1049                 NCR5380_setup(instance);
1050                 basr = NCR5380_read(BUS_AND_STATUS_REG);
1051                 /* XXX dispatch to appropriate routine if found and done=0 */
1052                 if (basr & BASR_IRQ) {
1053 #if (NDEBUG & NDEBUG_INTR)
1054                     NCR5380_print(instance);
1055 #endif
1056                     if ((NCR5380_read(STATUS_REG) & (SR_SEL | SR_IO)) == 
1057                         (SR_SEL | SR_IO)) {
1058                         done = 0;
1059                         sti();
1060 #if (NDEBUG & NDEBUG_INTR)
1061                         printk("scsi%d : SEL interrupt\n", instance->host_no);
1062 #endif
1063                         NCR5380_reselect(instance);
1064                         (void) NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1065                     } else if (basr & BASR_PARITY_ERROR) {
1066 #if (NDEBUG & NDEBUG_INTR)
1067                         printk("scsi%d : PARITY interrupt\n", instance->host_no);
1068 #endif
1069                         (void) NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1070                     } else if ((NCR5380_read(STATUS_REG) & SR_RST) == SR_RST) {
1071 #if (NDEBUG & NDEBUG_INTR)
1072                         printk("scsi%d : RESET interrupt\n", instance->host_no);
1073 #endif
1074                         (void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1075                     } else {
1076 /*  
1077  * XXX the rest of the interrupt conditions should *only* occur during a 
1078  * DMA transfer, which I haven't gotten around to fixing yet.
1079  */
1080 
1081 #if defined(REAL_DMA)
1082                     /*
1083                      * We should only get PHASE MISMATCH and EOP interrupts
1084                      * if we have DMA enabled, so do a sanity check based on
1085                      * the current setting of the MODE register.
1086                      */
1087 
1088                         if ((NCR5380_read(MODE_REG) & MR_DMA) && ((basr & 
1089                             BASR_END_DMA_TRANSFER) || 
1090                             !(basr & BASR_PHASE_MATCH))) {
1091                             int transfered;
1092 
1093                             if (!hostdata->connected) 
1094                                 panic("scsi%d : received end of DMA interrupt with no connected cmd\n",
1095                                     instance->hostno);
1096 
1097                             transfered = (hostdata->dmalen - NCR5380_dma_residual(instance));
1098                             hostdata->connected->SCp.this_residual -= transferred;
1099                             hostdata->connected->SCp.ptr += transferred;
1100                             hostdata->dmalen = 0;
1101 
1102                             (void) NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1103 #if NCR_TIMEOUT
1104                             {
1105                               unsigned long timeout = jiffies + NCR_TIMEOUT;
1106 
1107                               while (NCR5380_read(BUS_AND_STATUS_REG) & BASR_ACK
1108                                      && jiffies < timeout)
1109                                 ;
1110                               if (jiffies >= timeout)
1111                                 printk("scsi: timeout at %d\n", __LINE__);
1112                             }
1113 #else /* NCR_TIMEOUT */
1114                             while (NCR5380_read(BUS_AND_STATUS_REG) & BASR_ACK);
1115 #endif
1116 
1117                             NCR5380_write(MODE_REG, MR_BASE);
1118                             NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1119                         }
1120 #else
1121 #if (NDEBUG & NDEBUG_INTR)
1122                     printk("scsi : unknown interrupt, BASR 0x%X, MR 0x%X, SR 0x%x\n", basr, NCR5380_read(MODE_REG), NCR5380_read(STATUS_REG));
1123 #endif
1124                     (void) NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1125 #endif
1126                     } 
1127                 } /* if BASR_IRQ */
1128                 if (!done) 
1129                     run_main();
1130             } /* if (instance->irq == irq) */
1131     } while (!done);
1132 }
1133 
1134 /* 
1135  * Function : int NCR5380_select (struct Scsi_Host *instance, Scsi_Cmnd *cmd, 
1136  *      int tag);
1137  *
1138  * Purpose : establishes I_T_L or I_T_L_Q nexus for new or existing command,
1139  *      including ARBITRATION, SELECTION, and initial message out for 
1140  *      IDENTIFY and queue messages. 
1141  *
1142  * Inputs : instance - instantiation of the 5380 driver on which this 
1143  *      target lives, cmd - SCSI command to execute, tag - set to TAG_NEXT for 
1144  *      new tag, TAG_NONE for untagged queueing, otherwise set to the tag for 
1145  *      the command that is presently connected.
1146  * 
1147  * Returns : -1 if selection could not execute for some reason,
1148  *      0 if selection succeeded or failed because the target 
1149  *      did not respond.
1150  *
1151  * Side effects : 
1152  *      If bus busy, arbitration failed, etc, NCR5380_select() will exit 
1153  *              with registers as they should have been on entry - ie
1154  *              SELECT_ENABLE will be set appropriately, the NCR5380
1155  *              will cease to drive any SCSI bus signals.
1156  *
1157  *      If successful : I_T_L or I_T_L_Q nexus will be established, 
1158  *              instance->connected will be set to cmd.  
1159  *              SELECT interrupt will be disabled.
1160  *
1161  *      If failed (no target) : cmd->scsi_done() will be called, and the 
1162  *              cmd->result host byte set to DID_BAD_TARGET.
1163  */
1164 
1165 static int NCR5380_select (struct Scsi_Host *instance, Scsi_Cmnd *cmd,
     /* [previous][next][first][last][top][bottom][index][help] */
1166     int tag) {
1167     NCR5380_local_declare();
1168     struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata*) 
1169         instance->hostdata;
1170     unsigned char tmp[3], phase;
1171     unsigned char *data;
1172     int len;
1173     unsigned long timeout;
1174     NCR5380_setup(instance);
1175 
1176     hostdata->restart_select = 0;
1177 #if defined (NDEBUG) && (NDEBUG & NDEBUG_ARBITRATION) 
1178     NCR5380_print(instance);
1179     printk("scsi%d : starting arbitration, id = %d\n", instance->host_no,
1180         instance->this_id);
1181 #endif
1182     cli(); 
1183 
1184     /* 
1185      * Set the phase bits to 0, otherwise the NCR5380 won't drive the 
1186      * data bus during SELECTION.
1187      */
1188 
1189     NCR5380_write(TARGET_COMMAND_REG, 0);
1190 
1191 
1192     /* 
1193      * Start arbitration.
1194      */
1195     
1196     NCR5380_write(OUTPUT_DATA_REG, hostdata->id_mask);
1197     NCR5380_write(MODE_REG, MR_ARBITRATE);
1198 
1199     sti();
1200 
1201     /* Wait for arbitration logic to complete */
1202 #if NCR_TIMEOUT
1203     {
1204       unsigned long timeout = jiffies + 2*NCR_TIMEOUT;
1205 
1206       while (!(NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_PROGRESS)
1207            && jiffies < timeout)
1208         ;
1209       if (jiffies >= timeout)
1210       {
1211         printk("scsi: arbitration timeout at %d\n", __LINE__);
1212         NCR5380_write(MODE_REG, MR_BASE);
1213         NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1214         return -1;
1215       }
1216     }
1217 #else /* NCR_TIMEOUT */
1218     while (!(NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_PROGRESS));
1219 #endif
1220 
1221 #if (NDEBUG & NDEBUG_ARBITRATION) 
1222     printk("scsi%d : arbitration complete\n", instance->host_no);
1223 /* Avoid GCC 2.4.5 asm needs to many reloads error */
1224     __asm__("nop");
1225 #endif
1226 
1227     /* 
1228      * The arbitration delay is 2.2us, but this is a minimum and there is 
1229      * no maximum so we can safely sleep for ceil(2.2) usecs to accommodate
1230      * the integral nature of udelay().
1231      *
1232      */
1233 
1234     udelay(3);
1235 
1236     /* Check for lost arbitration */
1237     if ((NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST) ||
1238         (NCR5380_read(CURRENT_SCSI_DATA_REG) & hostdata->id_higher_mask) ||
1239         (NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST)) {
1240         NCR5380_write(MODE_REG, MR_BASE); 
1241 #if (NDEBUG & NDEBUG_ARBITRATION)
1242     printk("scsi%d : lost arbitration, deasserting MR_ARBITRATE\n", 
1243         instance->host_no);
1244 #endif
1245         return -1;
1246     }
1247 
1248 
1249 
1250     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_SEL);
1251     
1252     if (NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST) {
1253         NCR5380_write(MODE_REG, MR_BASE);
1254         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1255 #if (NDEBUG & NDEBUG_ARBITRATION)
1256     printk("scsi%d : lost arbitration, deasserting ICR_ASSERT_SEL\n", 
1257         instance->host_no);
1258 #endif
1259         return -1;
1260     }
1261 
1262     /* 
1263      * Again, bus clear + bus settle time is 1.2us, however, this is 
1264      * a minimum so we'll udelay ceil(1.2)
1265      */
1266 
1267     udelay(2);  
1268 
1269 #if (NDEBUG & NDEBUG_ARBITRATION)
1270     printk("scsi%d : won arbitration\n", instance->host_no);
1271 #endif
1272 
1273 
1274     /* 
1275      * Now that we have won arbitration, start Selection process, asserting 
1276      * the host and target ID's on the SCSI bus.
1277      */
1278 
1279     NCR5380_write(OUTPUT_DATA_REG, (hostdata->id_mask | (1 << cmd->target)));
1280 
1281     /* 
1282      * Raise ATN while SEL is true before BSY goes false from arbitration,
1283      * since this is the only way to guarantee that we'll get a MESSAGE OUT
1284      * phase immediately after selection.
1285      */
1286 
1287     NCR5380_write(INITIATOR_COMMAND_REG, (ICR_BASE | ICR_ASSERT_BSY | 
1288         ICR_ASSERT_DATA | ICR_ASSERT_ATN | ICR_ASSERT_SEL ));
1289     NCR5380_write(MODE_REG, MR_BASE);
1290 
1291     /* 
1292      * Reselect interrupts must be turned off prior to the dropping of BSY,
1293      * otherwise we will trigger an interrupt.
1294      */
1295     NCR5380_write(SELECT_ENABLE_REG, 0);
1296 
1297     /* Reset BSY */
1298     NCR5380_write(INITIATOR_COMMAND_REG, (ICR_BASE | ICR_ASSERT_DATA | 
1299         ICR_ASSERT_ATN | ICR_ASSERT_SEL));
1300 
1301     /* 
1302      * Something weird happens when we cease to drive BSY - looks
1303      * like the board/chip is letting us do another read before the 
1304      * appropriate propagation delay has expired, and we're confusing
1305      * a BSY signal from ourselves as the target's response to SELECTION.
1306      *
1307      * A small delay (the 'C++' frontend breaks the pipeline with an
1308      * unnecessary jump, making it work on my 386-33/Trantor T128, the
1309      * tighter 'C' code breaks and requires this) solves the problem - 
1310      * the 1 us delay is arbitrary, and only used because this delay will 
1311      * be the same on other platforms and since it works here, it should 
1312      * work there.
1313      */
1314 
1315     udelay(1);
1316 
1317 #if (NDEBUG & NDEBUG_SELECTION)
1318     printk("scsi%d : selecting target %d\n", instance->host_no, cmd->target);
1319 #endif
1320 
1321     /* 
1322      * The SCSI specification calls for a 250 ms timeout for the actual 
1323      * selection.
1324      */
1325 
1326     timeout = jiffies + 25; 
1327 
1328     /* 
1329      * XXX very interesting - we're seeing a bounce where the BSY we 
1330      * asserted is being reflected / still asserted (propagation delay?)
1331      * and it's detecting as true.  Sigh.
1332      */
1333 
1334     while ((jiffies < timeout) && !(NCR5380_read(STATUS_REG) & 
1335         (SR_BSY | SR_IO)));
1336 
1337     if ((NCR5380_read(STATUS_REG) & (SR_SEL | SR_IO)) == 
1338             (SR_SEL | SR_IO)) {
1339             NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1340             NCR5380_reselect(instance);
1341             printk ("scsi%d : reselection after won arbitration?\n",
1342                 instance->host_no);
1343             NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1344             return -1;
1345     }
1346 
1347     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1348 
1349     if (!(NCR5380_read(STATUS_REG) & SR_BSY)) {
1350         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1351         if (hostdata->targets_present & (1 << cmd->target)) {
1352             printk("scsi%d : weirdness\n", instance->host_no);
1353             if (hostdata->restart_select)
1354                 printk("\trestart select\n");
1355 #ifdef NDEBUG
1356             NCR5380_print (instance);
1357 #endif
1358             NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1359             return -1;
1360         }
1361         cmd->result = DID_BAD_TARGET << 16;
1362         cmd->scsi_done(cmd);
1363         NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1364 #if (NDEBUG & NDEBUG_SELECTION)
1365         printk("scsi%d : target did not respond within 250ms\n", 
1366             instance->host_no);
1367 #endif
1368         NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1369         return 0;
1370     } 
1371 
1372     hostdata->targets_present |= (1 << cmd->target);
1373 
1374     /*
1375      * Since we followed the SCSI spec, and raised ATN while SEL 
1376      * was true but before BSY was false during selection, the information
1377      * transfer phase should be a MESSAGE OUT phase so that we can send the
1378      * IDENTIFY message.
1379      * 
1380      * If SCSI-II tagged queuing is enabled, we also send a SIMPLE_QUEUE_TAG
1381      * message (2 bytes) with a tag ID that we increment with every command
1382      * until it wraps back to 0.
1383      *
1384      * XXX - it turns out that there are some broken SCSI-II devices,
1385      *       which claim to support tagged queuing but fail when more than
1386      *       some number of commands are issued at once.
1387      */
1388 
1389     /* Wait for start of REQ/ACK handshake */
1390     while (!(NCR5380_read(STATUS_REG) & SR_REQ));
1391 
1392 #if (NDEBUG & NDEBUG_SELECTION)
1393     printk("scsi%d : target %d selected, going into MESSAGE OUT phase.\n",
1394         instance->host_no, cmd->target);
1395 #endif
1396     tmp[0] = IDENTIFY(((instance->irq == IRQ_NONE) ? 0 : 1), cmd->lun);
1397 #ifdef SCSI2
1398     if (cmd->device->tagged_queue && (tag != TAG_NONE)) {
1399         tmp[1] = SIMPLE_QUEUE_TAG;
1400         if (tag == TAG_NEXT) {
1401             /* 0 is TAG_NONE, used to imply no tag for this command */
1402             if (cmd->device->current_tag == 0)
1403                 cmd->device->current_tag = 1;
1404 
1405             cmd->tag = cmd->device->current_tag;
1406             cmd->device->current_tag++;
1407         } else  
1408             cmd->tag = (unsigned char) tag;
1409 
1410         tmp[2] = cmd->tag;
1411         hostdata->last_message = SIMPLE_QUEUE_TAG;
1412         len = 3;
1413     } else 
1414 #endif /* def SCSI2 */
1415     {
1416         len = 1;
1417         cmd->tag=0;
1418     }
1419 
1420     /* Send message(s) */
1421     data = tmp;
1422     phase = PHASE_MSGOUT;
1423     NCR5380_transfer_pio(instance, &phase, &len, &data);
1424 #if (NDEBUG & NDEBUG_SELECTION)
1425     printk("scsi%d : nexus established.\n", instance->host_no);
1426 #endif
1427     /* XXX need to handle errors here */
1428     hostdata->connected = cmd;
1429 #ifdef SCSI2
1430     if (!cmd->device->tagged_queue)
1431 #endif    
1432         hostdata->busy[cmd->target] |= (1 << cmd->lun);
1433 
1434     initialize_SCp(cmd);
1435 
1436 
1437     return 0;
1438 }
1439 
1440 /* 
1441  * Function : int NCR5380_transfer_pio (struct Scsi_Host *instance, 
1442  *      unsigned char *phase, int *count, unsigned char **data)
1443  *
1444  * Purpose : transfers data in given phase using polled I/O
1445  *
1446  * Inputs : instance - instance of driver, *phase - pointer to 
1447  *      what phase is expected, *count - pointer to number of 
1448  *      bytes to transfer, **data - pointer to data pointer.
1449  * 
1450  * Returns : -1 when different phase is entered without transferring
1451  *      maximum number of bytes, 0 if all bytes or transfered or exit
1452  *      is in same phase.
1453  *
1454  *      Also, *phase, *count, *data are modified in place.
1455  *
1456  * XXX Note : handling for bus free may be useful.
1457  */
1458 
1459 /*
1460  * Note : this code is not as quick as it could be, however it 
1461  * IS 100% reliable, and for the actual data transfer where speed
1462  * counts, we will always do a pseudo DMA or DMA transfer.
1463  */
1464 
1465 static int NCR5380_transfer_pio (struct Scsi_Host *instance, 
     /* [previous][next][first][last][top][bottom][index][help] */
1466         unsigned char *phase, int *count, unsigned char **data) {
1467     NCR5380_local_declare();
1468     register unsigned char p = *phase, tmp;
1469     register int c = *count;
1470     register unsigned char *d = *data;
1471     NCR5380_setup(instance);
1472 
1473     /* 
1474      * The NCR5380 chip will only drive the SCSI bus when the 
1475      * phase specified in the appropriate bits of the TARGET COMMAND
1476      * REGISTER match the STATUS REGISTER
1477      */
1478 
1479     NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(p));
1480 
1481     do {
1482         /* 
1483          * Wait for assertion of REQ, after which the phase bits will be 
1484          * valid 
1485          */
1486         while (!((tmp = NCR5380_read(STATUS_REG)) & SR_REQ));
1487 
1488 #if (NDEBUG & NDEBUG_HANDSHAKE)
1489         printk("scsi%d : REQ detected\n", instance->host_no);
1490 #endif
1491 
1492         /* Check for phase mismatch */  
1493         if ((tmp & PHASE_MASK) != p) {
1494 #if (NDEBUG & NDEBUG_PIO)
1495             printk("scsi%d : phase mismatch\n", instance->host_no);
1496             NCR5380_print_phase(instance);
1497 #endif
1498             break;
1499         }
1500 
1501         /* Do actual transfer from SCSI bus to / from memory */
1502         if (!(p & SR_IO)) 
1503             NCR5380_write(OUTPUT_DATA_REG, *d);
1504         else 
1505             *d = NCR5380_read(CURRENT_SCSI_DATA_REG);
1506 
1507         ++d;
1508 
1509         /* 
1510          * The SCSI standard suggests that in MSGOUT phase, the initiator
1511          * should drop ATN on the last byte of the message phase
1512          * after REQ has been asserted for the handshake but before
1513          * the initiator raises ACK.
1514          */
1515 
1516         if (!(p & SR_IO)) {
1517             if (!((p & SR_MSG) && c > 1)) {
1518                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | 
1519                     ICR_ASSERT_DATA);
1520 #if (NDEBUG & NDEBUG_PIO)
1521         NCR5380_print(instance);
1522 #endif
1523                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | 
1524                         ICR_ASSERT_DATA | ICR_ASSERT_ACK);
1525             } else {
1526                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE |
1527                     ICR_ASSERT_DATA | ICR_ASSERT_ATN);
1528 #if (NDEBUG & NDEBUG_PIO)
1529         NCR5380_print(instance);
1530 #endif
1531                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | 
1532                     ICR_ASSERT_DATA | ICR_ASSERT_ATN | ICR_ASSERT_ACK);
1533             }
1534         } else {
1535 #if (NDEBUG & NDEBUG_PIO)
1536         NCR5380_print(instance);
1537 #endif
1538         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ACK);
1539         }
1540 
1541         while (NCR5380_read(STATUS_REG) & SR_REQ);
1542 
1543 #if (NDEBUG & NDEBUG_HANDSHAKE)
1544             printk("scsi%d : req false, handshake complete\n", instance->host_no);
1545 #endif
1546 
1547 /*
1548  * We have several special cases to consider during REQ/ACK handshaking : 
1549  * 1.  We were in MSGOUT phase, and we are on the last byte of the 
1550  *      message.  ATN must be dropped as ACK is dropped.
1551  *
1552  * 2.  We are in a MSGIN phase, and we are on the last byte of the  
1553  *      message.  We must exit with ACK asserted, so that the calling
1554  *      code may raise ATN before dropping ACK to reject the message.
1555  *
1556  * 3.  ACK and ATN are clear and the target may proceed as normal.
1557  */
1558         if (!(p == PHASE_MSGIN && c == 1)) {  
1559             if (p == PHASE_MSGOUT && c > 1)
1560                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1561             else
1562                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1563         } 
1564     } while (--c);
1565 
1566 #if (NDEBUG & NDEBUG_PIO) 
1567     printk("scsi%d : residual %d\n", instance->host_no, c);
1568 #endif
1569 
1570     *count = c;
1571     *data = d;
1572     tmp = NCR5380_read(STATUS_REG);
1573     if (tmp & SR_REQ)
1574         *phase = tmp & PHASE_MASK;
1575     else 
1576         *phase = PHASE_UNKNOWN;
1577 
1578     if (!c || (*phase == p))
1579         return 0;
1580     else 
1581         return -1;
1582 }
1583 
1584 #if defined(REAL_DMA) || defined(PSEUDO_DMA) || defined (REAL_DMA_POLL)
1585 /* 
1586  * Function : int NCR5380_transfer_dma (struct Scsi_Host *instance, 
1587  *      unsigned char *phase, int *count, unsigned char **data)
1588  *
1589  * Purpose : transfers data in given phase using either real
1590  *      or pseudo DMA.
1591  *
1592  * Inputs : instance - instance of driver, *phase - pointer to 
1593  *      what phase is expected, *count - pointer to number of 
1594  *      bytes to transfer, **data - pointer to data pointer.
1595  * 
1596  * Returns : -1 when different phase is entered without transferring
1597  *      maximum number of bytes, 0 if all bytes or transfered or exit
1598  *      is in same phase.
1599  *
1600  *      Also, *phase, *count, *data are modified in place.
1601  *
1602  */
1603 
1604 
1605 static int NCR5380_transfer_dma (struct Scsi_Host *instance, 
     /* [previous][next][first][last][top][bottom][index][help] */
1606     unsigned char *phase, int *count, unsigned char **data) {
1607     NCR5380_local_declare();
1608     register int c = *count;
1609     register unsigned char p = *phase;
1610     register unsigned char *d = *data;
1611     unsigned char tmp;
1612     int foo;
1613 #if defined(REAL_DMA_POLL)
1614     int cnt, toPIO;
1615     unsigned char saved_data = 0, overrun = 0, residue;
1616 #endif
1617 
1618     struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *) 
1619         instance->hostdata;
1620 
1621     NCR5380_setup(instance);
1622 
1623     if ((tmp = (NCR5380_read(STATUS_REG) & PHASE_MASK)) != p) {
1624         *phase = tmp;
1625         return -1;
1626     }
1627 #if defined(REAL_DMA) || defined(REAL_DMA_POLL) 
1628 #ifdef READ_OVERRUNS
1629      if (p & SR_IO) {
1630        c -= 2;
1631      }
1632 #endif
1633 #if (NDEBUG & NDEBUG_DMA)
1634     printk("scsi%d : initializing DMA channel %d for %s, %d bytes %s %0x\n",
1635         instance->host_no, instance->dma_channel, (p & SR_IO) ? "reading" :
1636         "writing", c, (p & SR_IO) ? "to" : "from", (unsigned) d);
1637 #endif
1638     hostdata->dma_len = (p & SR_IO) ?
1639         NCR5380_dma_read_setup(instance, d, c) : 
1640         NCR5380_dma_write_setup(instance, d, c);
1641 #endif
1642 
1643     NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(p));
1644 
1645 #ifdef REAL_DMA
1646     NCR5380_write(MODE_REG, MR_BASE | MR_DMA_MODE | MR_ENABLE_EOP_INTR | MR_MONITOR_BSY);
1647 #elif defined(REAL_DMA_POLL)
1648     NCR5380_write(MODE_REG, MR_BASE | MR_DMA_MODE);
1649 #else
1650     /*
1651      * Note : on my sample board, watch-dog timeouts occurred when interrupts
1652      * were not disabled for the duration of a single DMA transfer, from 
1653      * before the setting of DMA mode to after transfer of the last byte.
1654      */
1655 
1656 #if defined(PSEUDO_DMA) && !defined(UNSAFE)
1657     cli();
1658 #endif
1659     NCR5380_write(MODE_REG, MR_BASE | MR_DMA_MODE);
1660 #endif /* def REAL_DMA */
1661 
1662 #if (NDEBUG & NDEBUG_DMA) & 0
1663     printk("scsi%d : mode reg = 0x%X\n", instance->host_no, NCR5380_read(MODE_REG));
1664 #endif
1665 
1666 /* 
1667  * FOO stuff. For some UNAPPARENT reason, I'm getting 
1668  * watchdog timers fired on bootup for NO APPARENT REASON, meaning it's
1669  * probably a timing problem.
1670  *
1671  * Since this is the only place I have back-to-back writes, perhaps this 
1672  * is the problem?
1673  */
1674 
1675     if (p & SR_IO) {
1676 #ifndef FOO
1677         udelay(1);
1678 #endif
1679         NCR5380_write(START_DMA_INITIATOR_RECEIVE_REG, 0);
1680     } else {
1681 #ifndef FOO
1682         udelay(1);
1683 #endif
1684         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA);
1685 #ifndef FOO
1686         udelay(1);
1687 #endif
1688         NCR5380_write(START_DMA_SEND_REG, 0);
1689 #ifndef FOO
1690         udelay(1);
1691 #endif
1692     }
1693 
1694 #if defined(REAL_DMA_POLL)
1695     do {
1696         tmp = NCR5380_read(BUS_AND_STATUS_REG);
1697     } while ((tmp & BASR_PHASE_MATCH) && !(tmp & (BASR_BUSY_ERROR | 
1698         BASR_END_DMA_TRANSFER)));
1699 
1700 /*
1701   At this point, either we've completed DMA, or we have a phase mismatch,
1702   or we've unexpectedly lost BUSY (which is a real error).
1703 
1704   For write DMAs, we want to wait until the last byte has been
1705   transferred out over the bus before we turn off DMA mode.  Alas, there
1706   seems to be no terribly good way of doing this on a 5380 under all
1707   conditions.  For non-scatter-gather operations, we can wait until REQ
1708   and ACK both go false, or until a phase mismatch occurs.  Gather-writes
1709   are nastier, since the device will be expecting more data than we
1710   are prepared to send it, and REQ will remain asserted.  On a 53C8[01] we
1711   could test LAST BIT SENT to assure transfer (I imagine this is precisely
1712   why this signal was added to the newer chips) but on the older 538[01]
1713   this signal does not exist.  The workaround for this lack is a watchdog;
1714   we bail out of the wait-loop after a modest amount of wait-time if
1715   the usual exit conditions are not met.  Not a terribly clean or
1716   correct solution :-%
1717 
1718   Reads are equally tricky due to a nasty characteristic of the NCR5380.
1719   If the chip is in DMA mode for an READ, it will respond to a target's
1720   REQ by latching the SCSI data into the INPUT DATA register and asserting
1721   ACK, even if it has _already_ been notified by the DMA controller that
1722   the current DMA transfer has completed!  If the NCR5380 is then taken
1723   out of DMA mode, this already-acknowledged byte is lost.
1724 
1725   This is not a problem for "one DMA transfer per command" reads, because
1726   the situation will never arise... either all of the data is DMA'ed
1727   properly, or the target switches to MESSAGE IN phase to signal a
1728   disconnection (either operation bringing the DMA to a clean halt).
1729   However, in order to handle scatter-reads, we must work around the
1730   problem.  The chosen fix is to DMA N-2 bytes, then check for the
1731   condition before taking the NCR5380 out of DMA mode.  One or two extra
1732   bytes are transferred via PIO as necessary to fill out the original
1733   request.
1734 */
1735 
1736     if (p & SR_IO) {
1737 #ifdef READ_OVERRUNS
1738       udelay(10);
1739       if (((NCR5380_read(BUS_AND_STATUS_REG) & (BASR_PHASE_MATCH|BASR_ACK)) ==
1740            (BASR_PHASE_MATCH | BASR_ACK))) {
1741         saved_data = NCR5380_read(INPUT_DATA_REGISTER);
1742         overrun = 1;
1743       }
1744 #endif
1745     } else {
1746       int limit = 100;
1747       while (((tmp = NCR5380_read(BUS_AND_STATUS_REG)) & BASR_ACK) ||
1748             (NCR5380_read(STATUS_REG) & SR_REQ)) {
1749         if (!(tmp & BASR_PHASE_MATCH)) break;
1750         if (--limit < 0) break;
1751       }
1752     }
1753 
1754 
1755 #if (NDEBUG & NDEBUG_DMA)
1756     printk("scsi%d : polled DMA transfer complete, basr 0x%X, sr 0x%X\n",
1757            instance->host_no, tmp, NCR5380_read(STATUS_REG));
1758 #endif
1759 
1760     NCR5380_write(MODE_REG, MR_BASE);
1761     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1762 
1763     residue = NCR5380_dma_residual(instance);
1764     c -= residue;
1765     *count -= c;
1766     *data += c;
1767     *phase = NCR5380_read(STATUS_REG) & PHASE_MASK;
1768 
1769 #ifdef READ_OVERRUNS
1770     if (*phase == p && (p & SR_IO) && residue == 0) {
1771       if (overrun) {
1772 #if (NDEBUG & NDEBUG_DMA)
1773         printk("Got an input overrun, using saved byte\n");
1774 #endif
1775         **data = saved_data;
1776         *data += 1;
1777         *count -= 1;
1778         cnt = toPIO = 1;
1779       } else {
1780         printk("No overrun??\n");
1781         cnt = toPIO = 2;
1782       }
1783 #if (NDEBUG & NDEBUG_DMA)
1784       printk("Doing %d-byte PIO to 0x%X\n", cnt, *data);
1785 #endif
1786       NCR5380_transfer_pio(instance, phase, &cnt, data);
1787       *count -= toPIO - cnt;
1788     }
1789 #endif        
1790 
1791 #if (NDEBUG & NDEBUG_DMA)
1792      printk("Return with data ptr = 0x%X, count %d, last 0x%X, next 0x%X\n",
1793             *data, *count, *(*data+*count-1), *(*data+*count));
1794 #endif
1795      return 0;
1796      
1797 #elif defined(REAL_DMA)
1798     return 0;
1799 #else /* defined(REAL_DMA_POLL) */
1800     if (p & SR_IO) {
1801         if (!(foo = NCR5380_pread(instance, d, c - 1))) {
1802             /*
1803              * We can't disable DMA mode after successfully transferring 
1804              * what we plan to be the last byte, since that would open up
1805              * a race condition where if the target asserted REQ before 
1806              * we got the DMA mode reset, the NCR5380 would have latched
1807              * an additional byte into the INPUT DATA register and we'd
1808              * have dropped it.
1809              * 
1810              * The workaround was to transfer one fewer bytes than we 
1811              * intended to with the pseudo-DMA read function, wait for 
1812              * the chip to latch the last byte, read it, and then disable
1813              * pseudo-DMA mode.
1814              * 
1815              * After REQ is asserted, the NCR5380 asserts DRQ and ACK.
1816              * REQ is deasserted when ACK is asserted, and not reasserted
1817              * until ACK goes false.  Since the NCR5380 won't lower ACK
1818              * until DACK is asserted, which won't happen unless we twiddle
1819              * the DMA port or we take the NCR5380 out of DMA mode, we 
1820              * can guarantee that we won't handshake another extra 
1821              * byte.
1822              */
1823 
1824             while (!(NCR5380_read(BUS_AND_STATUS_REG) & BASR_DRQ));
1825             /* Wait for clean handshake */
1826             while (NCR5380_read(STATUS_REG) & SR_REQ);
1827             d[c - 1] = NCR5380_read(INPUT_DATA_REG);
1828         }
1829     } else {
1830         int timeout;
1831         if (!(foo = NCR5380_pwrite(instance, d, c))) {
1832             /*
1833              * Wait for the last byte to be sent.  If REQ is being asserted for 
1834              * the byte we're interested, we'll ACK it and it will go false.  
1835              */
1836             if (!(hostdata->flags & FLAG_HAS_LAST_BYTE_SENT)) {
1837                 timeout = 20000;
1838 #if 1
1839 #if 1
1840                 while (!(NCR5380_read(BUS_AND_STATUS_REG) & 
1841                         BASR_DRQ) && (NCR5380_read(BUS_AND_STATUS_REG) &
1842                         BASR_PHASE_MATCH));
1843 #else
1844                 if (NCR5380_read(STATUS_REG) & SR_REQ) {
1845                     for (; timeout && 
1846                         !(NCR5380_read(BUS_AND_STATUS_REG) & BASR_ACK); 
1847                         --timeout);
1848                     for (; timeout && (NCR5380_read(STATUS_REG) & SR_REQ);
1849                         --timeout);
1850                 } 
1851 #endif
1852         
1853 
1854 #if (NDEBUG & NDEBUG_LAST_BYTE_SENT)
1855                 if (!timeout) 
1856                     printk("scsi%d : timed out on last byte\n",
1857                             instance->host_no);
1858 #endif
1859 
1860 
1861                 if (hostdata->flags & FLAG_CHECK_LAST_BYTE_SENT) {
1862                     hostdata->flags &= ~FLAG_CHECK_LAST_BYTE_SENT;
1863                     if (NCR5380_read(TARGET_COMMAND_REG) & TCR_LAST_BYTE_SENT) {
1864                         hostdata->flags |= FLAG_HAS_LAST_BYTE_SENT;
1865 #if (NDEBUG & NDEBUG_LAST_BYTE_SENT)
1866                         printk("scsi%d : last bit sent works\n", 
1867                             instance->host_no);
1868 #endif
1869                     }
1870                 }
1871             } else 
1872                 while (!(NCR5380_read(TARGET_COMMAND_REG) & TCR_LAST_BYTE_SENT));
1873 #else
1874             udelay (5);
1875 #endif
1876         }
1877     }
1878 
1879     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1880     NCR5380_write(MODE_REG, MR_BASE);
1881 
1882     *data = d + c;
1883     *count = 0;
1884     *phase = (NCR5380_read(STATUS_REG & PHASE_MASK));
1885 #if defined(PSEUDO_DMA) && !defined(UNSAFE)
1886     sti();
1887 #endif /* defined(REAL_DMA_POLL) */
1888     return foo;
1889 #endif /* def REAL_DMA */
1890 }
1891 #endif /* defined(REAL_DMA) | defined(PSEUDO_DMA) */
1892 
1893 /*
1894  * Function : NCR5380_information_transfer (struct Scsi_Host *instance)
1895  *
1896  * Purpose : run through the various SCSI phases and do as the target 
1897  *      directs us to.  Operates on the currently connected command, 
1898  *      instance->connected.
1899  *
1900  * Inputs : instance, instance for which we are doing commands
1901  *
1902  * Side effects : SCSI things happen, the disconnected queue will be 
1903  *      modified if a command disconnects, *instance->connected will
1904  *      change.
1905  *
1906  * XXX Note : we need to watch for bus free or a reset condition here 
1907  *      to recover from an unexpected bus free condition.
1908  */
1909  
1910 static void NCR5380_information_transfer (struct Scsi_Host *instance) {
     /* [previous][next][first][last][top][bottom][index][help] */
1911     NCR5380_local_declare();
1912     struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *) 
1913         instance->hostdata;
1914     unsigned char msgout = NOP;
1915     int sink = 0;
1916     int len;
1917 #if defined(PSEUDO_DMA) || defined(REAL_DMA_POLL)
1918     int transfersize;
1919 #endif
1920     unsigned char *data;
1921     unsigned char phase, tmp, extended_msg[10], old_phase=0xff;
1922     Scsi_Cmnd *cmd = (Scsi_Cmnd *) hostdata->connected;
1923     NCR5380_setup(instance);
1924 
1925     while (1) {
1926         tmp = NCR5380_read(STATUS_REG);
1927         /* We only have a valid SCSI phase when REQ is asserted */
1928         if (tmp & SR_REQ) {
1929             phase = (tmp & PHASE_MASK); 
1930             if (phase != old_phase) {
1931                 old_phase = phase;
1932 #if (NDEBUG & NDEBUG_INFORMATION)
1933                 NCR5380_print_phase(instance);
1934 #endif
1935             }
1936             
1937             if (sink && (phase != PHASE_MSGOUT)) {
1938                 NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(tmp));
1939 
1940                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN | 
1941                     ICR_ASSERT_ACK);
1942                 while (NCR5380_read(STATUS_REG) & SR_REQ);
1943                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | 
1944                     ICR_ASSERT_ATN);
1945                 sink = 0;
1946                 continue;
1947             }
1948 
1949             switch (phase) {
1950             case PHASE_DATAIN:
1951             case PHASE_DATAOUT:
1952 #if (NDEBUG & NDEBUG_NO_DATAOUT)
1953                 printk("scsi%d : NDEBUG_NO_DATAOUT set, attempted DATAOUT aborted\n",
1954                     instance->host_no);
1955                 sink = 1;
1956                 msgout = ABORT;
1957                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1958                 break;
1959 #endif
1960                 /* 
1961                  * If there is no room left in the current buffer in the
1962                  * scatter-gather list, move onto the next one.
1963                  */
1964 
1965                 if (!cmd->SCp.this_residual && cmd->SCp.buffers_residual) {
1966                     ++cmd->SCp.buffer;
1967                     --cmd->SCp.buffers_residual;
1968                     cmd->SCp.this_residual = cmd->SCp.buffer->length;
1969                     cmd->SCp.ptr = cmd->SCp.buffer->address;
1970 #if (NDEBUG & NDEBUG_INFORMATION)
1971                     printk("scsi%d : %d bytes and %d buffers left\n",
1972                         instance->host_no, cmd->SCp.this_residual,
1973                         cmd->SCp.buffers_residual);
1974 #endif
1975                 }
1976 
1977                 /*
1978                  * The preferred transfer method is going to be 
1979                  * PSEUDO-DMA for systems that are strictly PIO,
1980                  * since we can let the hardware do the handshaking.
1981                  *
1982                  * For this to work, we need to know the transfersize
1983                  * ahead of time, since the pseudo-DMA code will sit
1984                  * in an unconditional loop.
1985                  */
1986 
1987 #if defined(PSEUDO_DMA) || defined(REAL_DMA_POLL)
1988 #ifdef NCR5380_dma_xfer_len
1989                 if (!cmd->device->borken &&
1990                     (transfersize = NCR5380_dma_xfer_len(instance, cmd)) != 0) {
1991 #else
1992                 transfersize = cmd->transfersize;
1993 
1994 #ifdef LIMIT_TRANSFERSIZE  /* If we have problems with interrupt service */
1995                 if( transfersize > 512 )
1996                     transfersize = 512;
1997 #endif  /* LIMIT_TRANSFERSIZE */
1998 
1999                 if (!cmd->device->borken && transfersize && 
2000                     cmd->SCp.this_residual && !(cmd->SCp.this_residual % 
2001                     transfersize)) {
2002 #endif
2003                     len = transfersize;
2004                     if (NCR5380_transfer_dma(instance, &phase,
2005                         &len, (unsigned char **) &cmd->SCp.ptr)) {
2006                         /*
2007                          * If the watchdog timer fires, all future accesses to this
2008                          * device will use the polled-IO.
2009                          */ 
2010                         printk("scsi%d : switching target %d lun %d to slow handshake\n",
2011                             instance->host_no, cmd->target, cmd->lun);
2012                         cmd->device->borken = 1;
2013                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | 
2014                             ICR_ASSERT_ATN);
2015                         sink = 1;
2016                         msgout = ABORT;
2017                         /* XXX - need to source or sink data here, as appropriate */
2018                     } else
2019                         cmd->SCp.this_residual -= transfersize - len;
2020                 } else
2021 #endif /* defined(PSEUDO_DMA) || defined(REAL_DMA_POLL) */
2022                   NCR5380_transfer_pio(instance, &phase, 
2023                     (int *) &cmd->SCp.this_residual, (unsigned char **)
2024                     &cmd->SCp.ptr);
2025                 break;
2026             case PHASE_MSGIN:
2027                 len = 1;
2028                 data = &tmp;
2029                 NCR5380_transfer_pio(instance, &phase, &len, &data);
2030                 cmd->SCp.Message = tmp;
2031 
2032                 switch (tmp) {
2033                 /*
2034                  * Linking lets us reduce the time required to get the 
2035                  * next command out to the device, hopefully this will
2036                  * mean we don't waste another revolution due to the delays
2037                  * required by ARBITRATION and another SELECTION.
2038                  *
2039                  * In the current implementation proposal, low level drivers
2040                  * merely have to start the next command, pointed to by 
2041                  * next_link, done() is called as with unlinked commands.
2042                  */
2043 #ifdef LINKED
2044                 case LINKED_CMD_COMPLETE:
2045                 case LINKED_FLG_CMD_COMPLETE:
2046                     /* Accept message by clearing ACK */
2047                     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2048                     
2049 #if (NDEBUG & NDEBUG_LINKED) 
2050                     printk("scsi%d : target %d lun %d linked command complete.\n",
2051                         instance->host_no, cmd->target, cmd->lun);
2052 #endif
2053                     /* 
2054                      * Sanity check : A linked command should only terminate with
2055                      * one of these messages if there are more linked commands
2056                      * available.
2057                      */
2058 
2059                     if (!cmd->next_link) {
2060                          printk("scsi%d : target %d lun %d linked command complete, no next_link\n"
2061                             instance->host_no, cmd->target, cmd->lun);
2062                             sink = 1;
2063                             msgout = ABORT;
2064                             NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE |
2065                                 ICR_ASSERT_ATN);
2066                             break;
2067                     }
2068 
2069                     initialize_SCp(cmd->next_link);
2070                     /* The next command is still part of this process */
2071                     cmd->next_link->tag = cmd->tag;
2072                     cmd->result = cmd->SCp.Status | (cmd->SCp.Message << 8); 
2073 #if (NDEBUG & NDEBUG_LINKED) 
2074                     printk("scsi%d : target %d lun %d linked request done, calling scsi_done().\n",
2075                         instance->host_no, cmd->target, cmd->lun);
2076 #endif
2077                     cmd->scsi_done(cmd);
2078                     cmd = hostdata->connected;
2079                     break;
2080 #endif /* def LINKED */
2081                 case ABORT:
2082                 case COMMAND_COMPLETE: 
2083                     /* Accept message by clearing ACK */
2084                     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2085                     hostdata->connected = NULL;
2086 #if (NDEBUG & NDEBUG_QUEUES)
2087                     printk("scsi%d : command for target %d, lun %d completed\n",
2088                         instance->host_no, cmd->target, cmd->lun);
2089 #endif
2090                     hostdata->busy[cmd->target] &= ~(1 << cmd->lun);
2091 
2092                     /* 
2093                      * I'm not sure what the correct thing to do here is : 
2094                      * 
2095                      * If the command that just executed is NOT a request 
2096                      * sense, the obvious thing to do is to set the result
2097                      * code to the values of the stored parameters.
2098                      * 
2099                      * If it was a REQUEST SENSE command, we need some way 
2100                      * to differentiate between the failure code of the original
2101                      * and the failure code of the REQUEST sense - the obvious
2102                      * case is success, where we fall through and leave the result
2103                      * code unchanged.
2104                      * 
2105                      * The non-obvious place is where the REQUEST SENSE failed 
2106                      */
2107 
2108                     if (cmd->cmnd[0] != REQUEST_SENSE) 
2109                         cmd->result = cmd->SCp.Status | (cmd->SCp.Message << 8); 
2110                     else if (cmd->SCp.Status != GOOD)
2111                         cmd->result = (cmd->result & 0x00ffff) | (DID_ERROR << 16);
2112                     
2113 #ifdef AUTOSENSE
2114                     if ((cmd->cmnd[0] != REQUEST_SENSE) && 
2115                         (cmd->SCp.Status == CHECK_CONDITION)) {
2116 #if (NDEBUG & NDEBUG_AUTOSENSE) 
2117                         printk("scsi%d : performing request sense\n", 
2118                             instance->host_no);
2119 #endif
2120                         cmd->cmnd[0] = REQUEST_SENSE;
2121                         cmd->cmnd[1] &= 0xe0;
2122                         cmd->cmnd[2] = 0;
2123                         cmd->cmnd[3] = 0;
2124                         cmd->cmnd[4] = sizeof(cmd->sense_buffer);
2125                         cmd->cmnd[5] = 0;
2126 
2127                         cmd->SCp.buffer = NULL;
2128                         cmd->SCp.buffers_residual = 0;
2129                         cmd->SCp.ptr = (char *) cmd->sense_buffer;
2130                         cmd->SCp.this_residual = sizeof(cmd->sense_buffer);
2131 
2132                         cli();
2133                         cmd->host_scribble = (unsigned char *) 
2134                             hostdata->issue_queue;
2135                         hostdata->issue_queue = (Scsi_Cmnd *) cmd;
2136                         sti();
2137 #if (NDEBUG & NDEBUG_QUEUES)
2138                         printk("scsi%d : REQUEST SENSE added to head of issue queue\n");
2139 #endif
2140                    } else
2141 #endif /* def AUTOSENSE */
2142                         cmd->scsi_done(cmd);
2143 
2144                     NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
2145                     /* 
2146                      * Restore phase bits to 0 so an interrupted selection, 
2147                      * arbitration can resume.
2148                      */
2149                     NCR5380_write(TARGET_COMMAND_REG, 0);
2150                     
2151                     while ((NCR5380_read(STATUS_REG) & SR_BSY) && !hostdata->connected)
2152                         barrier();
2153                     return;
2154                 case MESSAGE_REJECT:
2155                     /* Accept message by clearing ACK */
2156                     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2157                     switch (hostdata->last_message) {
2158                     case HEAD_OF_QUEUE_TAG:
2159                     case ORDERED_QUEUE_TAG:
2160                     case SIMPLE_QUEUE_TAG:
2161                         cmd->device->tagged_queue = 0;
2162                         hostdata->busy[cmd->target] |= (1 << cmd->lun);
2163                         break;
2164                     default:
2165                         break;
2166                     }
2167                 case DISCONNECT:
2168                     /* Accept message by clearing ACK */
2169                     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2170                     cmd->device->disconnect = 1;
2171                     cli();
2172                     cmd->host_scribble = (unsigned char *) 
2173                         hostdata->disconnected_queue;
2174                     hostdata->connected = NULL;
2175                     hostdata->disconnected_queue = cmd;
2176                     sti();
2177 #if (NDEBUG & NDEBUG_QUEUES)
2178                     printk("scsi%d : command for target %d lun %d was moved from connected to"
2179                            "  the disconnected_queue\n", instance->host_no, 
2180                             cmd->target, cmd->lun);
2181 #endif
2182                     /* 
2183                      * Restore phase bits to 0 so an interrupted selection, 
2184                      * arbitration can resume.
2185                      */
2186                     NCR5380_write(TARGET_COMMAND_REG, 0);
2187  
2188                     /* Enable reselect interrupts */
2189                     NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
2190                     /* Wait for bus free to avoid nasty timeouts */
2191                     while ((NCR5380_read(STATUS_REG) & SR_BSY) && !hostdata->connected)
2192                         barrier();
2193                     return;
2194                 /* 
2195                  * The SCSI data pointer is *IMPLICITLY* saved on a disconnect
2196                  * operation, in violation of the SCSI spec so we can safely 
2197                  * ignore SAVE/RESTORE pointers calls.
2198                  *
2199                  * Unfortunately, some disks violate the SCSI spec and 
2200                  * don't issue the required SAVE_POINTERS message before
2201                  * disconnecting, and we have to break spec to remain 
2202                  * compatible.
2203                  */
2204                 case SAVE_POINTERS:
2205                 case RESTORE_POINTERS:
2206                     /* Accept message by clearing ACK */
2207                     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2208                     break;
2209                 case EXTENDED_MESSAGE:
2210 /* 
2211  * Extended messages are sent in the following format :
2212  * Byte         
2213  * 0            EXTENDED_MESSAGE == 1
2214  * 1            length (includes one byte for code, doesn't 
2215  *              include first two bytes)
2216  * 2            code
2217  * 3..length+1  arguments
2218  *
2219  * Start the extended message buffer with the EXTENDED_MESSAGE
2220  * byte, since print_msg() wants the whole thing.  
2221  */
2222                     extended_msg[0] = EXTENDED_MESSAGE;
2223                     /* Accept first byte by clearing ACK */
2224                     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2225 
2226 #if (NDEBUG & NDEBUG_EXTENDED)
2227                     printk("scsi%d : receiving extended message\n",
2228                         instance->host_no);
2229 #endif
2230 
2231                     len = 2;
2232                     data = extended_msg + 1;
2233                     phase = PHASE_MSGIN;
2234                     NCR5380_transfer_pio(instance, &phase, &len, &data);
2235 
2236 #if (NDEBUG & NDEBUG_EXTENDED)
2237                     printk("scsi%d : length=%d, code=0x%02x\n", 
2238                         instance->host_no, (int) extended_msg[1],
2239                         (int) extended_msg[2]);
2240 #endif
2241 
2242                     if (!len && extended_msg[1] <= 
2243                         (sizeof (extended_msg) - 1)) {
2244                         /* Accept third byte by clearing ACK */
2245                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2246                         len = extended_msg[1] - 1;
2247                         data = extended_msg + 3;
2248                         phase = PHASE_MSGIN;
2249 
2250                         NCR5380_transfer_pio(instance, &phase, &len, &data);
2251 
2252 #if (NDEBUG & NDEBUG_EXTENDED)
2253                     printk("scsi%d : message received, residual %d\n",
2254                         instance->host_no, len);
2255 #endif
2256 
2257                         switch (extended_msg[2]) {
2258                         case EXTENDED_SDTR:
2259                         case EXTENDED_WDTR:
2260                         case EXTENDED_MODIFY_DATA_POINTER:
2261                         case EXTENDED_EXTENDED_IDENTIFY:
2262                             tmp = 0;
2263                         }
2264                     } else if (len) {
2265                         printk("scsi%d: error receiving extended message\n",
2266                             instance->host_no);
2267                         tmp = 0;
2268                     } else {
2269                         printk("scsi%d: extended message code %02x length %d is too long\n",
2270                             instance->host_no, extended_msg[2], extended_msg[1]);
2271                         tmp = 0;
2272                     }
2273                 /* Fall through to reject message */
2274                     
2275                 /* 
2276                  * If we get something weird that we aren't expecting, 
2277                  * reject it.
2278                  */
2279                 default:
2280                     if (!tmp) {
2281                         printk("scsi%d: rejecting message ", instance->host_no);
2282                         print_msg (extended_msg);
2283                         printk("\n");
2284                     } else if (tmp != EXTENDED_MESSAGE)
2285                         printk("scsi%d: rejecting unknown message %02x from target %d, lun %d\n",
2286                             instance->host_no, tmp, cmd->target, cmd->lun);
2287                     else
2288                         printk("scsi%d: rejecting unknown extended message code %02x, length %d from target %d, lun %d\n",
2289                             instance->host_no, extended_msg[1], extended_msg[0], cmd->target, cmd->lun);
2290    
2291                     msgout = MESSAGE_REJECT;
2292                     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | 
2293                         ICR_ASSERT_ATN);
2294                     break;
2295                 } /* switch (tmp) */
2296                 break;
2297             case PHASE_MSGOUT:
2298                 len = 1;
2299                 data = &msgout;
2300                 hostdata->last_message = msgout;
2301                 NCR5380_transfer_pio(instance, &phase, &len, &data);
2302                 if (msgout == ABORT) {
2303                     hostdata->busy[cmd->target] &= ~(1 << cmd->lun);
2304                     hostdata->connected = NULL;
2305                     cmd->result = DID_ERROR << 16;
2306                     cmd->scsi_done(cmd);
2307                     NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
2308                     return;
2309                 }
2310                 msgout = NOP;
2311                 break;
2312             case PHASE_CMDOUT:
2313                 len = cmd->cmd_len;
2314                 data = cmd->cmnd;
2315                 /* 
2316                  * XXX for performance reasons, on machines with a 
2317                  * PSEUDO-DMA architecture we should probably 
2318                  * use the dma transfer function.  
2319                  */
2320                 NCR5380_transfer_pio(instance, &phase, &len, 
2321                     &data);
2322 #ifdef USLEEP
2323                 if (!disconnect && should_disconnect(cmd->cmnd[0])) {
2324                     hostdata->time_expires = jiffies + USLEEP_SLEEP;
2325 #if (NDEBUG & NDEBUG_USLEEP)
2326                 printk("scsi%d : issued command, sleeping until %ul\n", instance->host_no,
2327                     hostdata->time_expires);
2328 #endif
2329                     NCR5380_set_timer (instance);
2330                     return;
2331                 }
2332 #endif /* def USLEEP */
2333                 break;
2334             case PHASE_STATIN:
2335                 len = 1;
2336                 data = &tmp;
2337                 NCR5380_transfer_pio(instance, &phase, &len, &data);
2338                 cmd->SCp.Status = tmp;
2339                 break;
2340             default:
2341                 printk("scsi%d : unknown phase\n", instance->host_no);
2342 #ifdef NDEBUG
2343                 NCR5380_print(instance);
2344 #endif
2345             } /* switch(phase) */
2346         } /* if (tmp * SR_REQ) */ 
2347 #ifdef USLEEP
2348         else {
2349             if (!disconnect && hostdata->time_expires && jiffies > 
2350                 hostdata->time_expires) {
2351                 hostdata->time_expires = jiffies + USLEEP_SLEEP;
2352 #if (NDEBUG & NDEBUG_USLEEP)
2353                 printk("scsi%d : poll timed out, sleeping until %ul\n", instance->host_no,
2354                     hostdata->time_expires);
2355 #endif
2356                 NCR5380_set_timer (instance);
2357                 return;
2358             }
2359         }
2360 #endif
2361     } /* while (1) */
2362 }
2363 
2364 /*
2365  * Function : void NCR5380_reselect (struct Scsi_Host *instance)
2366  *
2367  * Purpose : does reselection, initializing the instance->connected 
2368  *      field to point to the Scsi_Cmnd for which the I_T_L or I_T_L_Q 
2369  *      nexus has been reestablished,
2370  *      
2371  * Inputs : instance - this instance of the NCR5380.
2372  *
2373  */
2374 
2375 
2376 static void NCR5380_reselect (struct Scsi_Host *instance) {
     /* [previous][next][first][last][top][bottom][index][help] */
2377     NCR5380_local_declare();
2378     struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *)
2379         instance->hostdata;
2380     unsigned char target_mask;
2381     unsigned char lun, phase;
2382     int len;
2383 #ifdef SCSI2
2384     unsigned char tag;
2385 #endif
2386     unsigned char msg[3];
2387     unsigned char *data;
2388     Scsi_Cmnd *tmp = NULL, *prev;
2389     int abort = 0;
2390     NCR5380_setup(instance);
2391 
2392     /*
2393      * Disable arbitration, etc. since the host adapter obviously
2394      * lost, and tell an interrupted NCR5380_select() to restart.
2395      */
2396 
2397     NCR5380_write(MODE_REG, MR_BASE);
2398     hostdata->restart_select = 1;
2399 
2400     target_mask = NCR5380_read(CURRENT_SCSI_DATA_REG) & ~(hostdata->id_mask);
2401 
2402 #if (NDEBUG & NDEBUG_RESELECTION)
2403     printk("scsi%d : reselect\n", instance->host_no);
2404 #endif
2405 
2406     /* 
2407      * At this point, we have detected that our SCSI ID is on the bus,
2408      * SEL is true and BSY was false for at least one bus settle delay
2409      * (400 ns).
2410      *
2411      * We must assert BSY ourselves, until the target drops the SEL
2412      * signal.
2413      */
2414 
2415     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_BSY);
2416     
2417     while (NCR5380_read(STATUS_REG) & SR_SEL);
2418     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2419 
2420     /*
2421      * Wait for target to go into MSGIN.
2422      */
2423 
2424     while (!(NCR5380_read(STATUS_REG) & SR_REQ));
2425 
2426     len = 1;
2427     data = msg;
2428     phase = PHASE_MSGIN;
2429     NCR5380_transfer_pio(instance, &phase, &len, &data);
2430 
2431 
2432     if (!msg[0] & 0x80) {
2433         printk("scsi%d : expecting IDENTIFY message, got ",
2434             instance->host_no);
2435         print_msg(msg);
2436         abort = 1;
2437     } else {
2438         /* Accept message by clearing ACK */
2439         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2440         lun = (msg[0] & 0x07);
2441 
2442         /* 
2443          * We need to add code for SCSI-II to track which devices have
2444          * I_T_L_Q nexuses established, and which have simple I_T_L
2445          * nexuses so we can chose to do additional data transfer.
2446          */
2447 
2448 #ifdef SCSI2
2449 #error "SCSI-II tagged queueing is not supported yet"
2450 #endif
2451 
2452         /* 
2453          * Find the command corresponding to the I_T_L or I_T_L_Q  nexus we 
2454          * just reestablished, and remove it from the disconnected queue.
2455          */
2456 
2457 
2458         for (tmp = (Scsi_Cmnd *) hostdata->disconnected_queue, prev = NULL; 
2459             tmp; prev = tmp, tmp = (Scsi_Cmnd *) tmp->host_scribble) 
2460             if ((target_mask == (1 << tmp->target)) && (lun == tmp->lun)
2461 #ifdef SCSI2
2462             && (tag == tmp->tag) 
2463 #endif
2464 ) {
2465             if (prev)
2466                 prev->host_scribble = tmp->host_scribble;
2467             else
2468                 hostdata->disconnected_queue = (Scsi_Cmnd *) tmp->host_scribble;
2469             tmp->host_scribble = NULL;
2470             break;
2471         }
2472 
2473         if (!tmp) {
2474 #ifdef SCSI2
2475             printk("scsi%d : warning : target bitmask %02x lun %d tag %d not in disconnect_queue.\n",
2476                     instance->host_no, target_mask, lun, tag);
2477 #else
2478             printk("scsi%d : warning : target bitmask %02x lun %d not in disconnect_queue.\n",
2479                     instance->host_no, target_mask, lun);
2480 #endif
2481         /* 
2482          * Since we have an established nexus that we can't do anything with,
2483          * we must abort it.  
2484          */
2485         abort = 1;
2486         }
2487     }
2488 
2489     if (abort) {
2490         msg[0] = ABORT;
2491         len = 1;
2492         data = msg;
2493         phase = PHASE_MSGOUT;
2494         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
2495         NCR5380_transfer_pio(instance, &phase, &len, &data);
2496     } else {
2497         hostdata->connected = tmp;
2498 #if (NDEBUG & NDEBUG_RESELECTION)
2499         printk"scsi%d : nexus established, target = %d, lun = %d, tag = %d\n",
2500             instance->host_no, tmp->target, tmp->lun, tmp->tag);
2501 #endif
2502     }
2503 }
2504 
2505 /*
2506  * Function : void NCR5380_dma_complete (struct Scsi_Host *instance)
2507  *
2508  * Purpose : called by interrupt handler when DMA finishes or a phase
2509  *      mismatch occurs (which would finish the DMA transfer).  
2510  *
2511  * Inputs : instance - this instance of the NCR5380.
2512  *
2513  * Returns : pointer to the Scsi_Cmnd structure for which the I_T_L
2514  *      nexus has been reestablished, on failure NULL is returned.
2515  */
2516 
2517 #ifdef REAL_DMA
2518 static void NCR5380_dma_complete (NCR5380_instance *instance) {
     /* [previous][next][first][last][top][bottom][index][help] */
2519     NCR5380_local_declare();
2520     struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *
2521         instance->hostdata);
2522     int transferred;
2523     NCR5380_setup(instance);
2524     
2525     /*
2526      * XXX this might not be right.
2527      *
2528      * Wait for final byte to transfer, ie wait for ACK to go false.
2529      *
2530      * We should use the Last Byte Sent bit, unfortunately this is 
2531      * not available on the 5380/5381 (only the various CMOS chips)
2532      */
2533 
2534     while (NCR5380_read(BUS_AND_STATUS_REG) & BASR_ACK);
2535 
2536     NCR5380_write(MODE_REG, MR_BASE);
2537     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2538 
2539     /*
2540      * The only places we should see a phase mismatch and have to send
2541      * data from the same set of pointers will be the data transfer
2542      * phases.  So, residual, requested length are only important here.
2543      */
2544 
2545     if (!(hostdata->connected->SCp.phase & SR_CD)) {
2546         transferred = instance->dmalen - NCR5380_dma_residual();
2547         hostdata->connected->SCp.this_residual -= transferred;
2548         hostdata->connected->SCp.ptr += transferred;
2549     }
2550 }
2551 #endif /* def REAL_DMA */
2552 
2553 /*
2554  * Function : int NCR5380_abort (Scsi_Cmnd *cmd)
2555  *
2556  * Purpose : abort a command
2557  *
2558  * Inputs : cmd - the Scsi_Cmnd to abort, code - code to set the 
2559  *      host byte of the result field to, if zero DID_ABORTED is 
2560  *      used.
2561  *
2562  * Returns : 0 - success, -1 on failure.
2563  *
2564  * XXX - there is no way to abort the command that is currently 
2565  *       connected, you have to wait for it to complete.  If this is 
2566  *       a problem, we could implement longjmp() / setjmp(), setjmp()
2567  *       called where the loop started in NCR5380_main().
2568  */
2569 
2570 #ifndef NCR5380_abort
2571 static
2572 #endif
2573 int NCR5380_abort (Scsi_Cmnd *cmd) {
     /* [previous][next][first][last][top][bottom][index][help] */
2574     NCR5380_local_declare();
2575     struct Scsi_Host *instance = cmd->host;
2576     struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *)
2577         instance->hostdata;
2578     Scsi_Cmnd *tmp, **prev;
2579     unsigned char msg, phase, *msgptr;
2580     int len;
2581 
2582     printk("scsi%d : aborting command\n", instance->host_no);
2583     print_Scsi_Cmnd (cmd);
2584 
2585     NCR5380_print_status (instance);
2586 
2587     cli();
2588     NCR5380_setup(instance);
2589     
2590 #if (NDEBUG & NDEBUG_ABORT)
2591     printk("scsi%d : abort called\n", instance->host_no);
2592     printk("        basr 0x%X, sr 0x%X\n", 
2593            NCR5380_read(BUS_AND_STATUS_REG), NCR5380_read(STATUS_REG));
2594 #endif
2595 
2596 #if 0
2597 /*
2598  * Case 1 : If the command is the currently executing command, 
2599  * we'll set the aborted flag and return control so that 
2600  * information transfer routine can exit cleanly.
2601  */
2602 
2603     if (hostdata->connected == cmd) {
2604 #if (NDEBUG & NDEBUG_ABORT)
2605         printk("scsi%d : aborting connected command\n", instance->host_no);
2606 #endif
2607         hostdata->aborted = 1;
2608 /*
2609  * We should perform BSY checking, and make sure we haven't slipped
2610  * into BUS FREE.
2611  */
2612 
2613         NCR5380_write(INITIATOR_COMMAND_REG, ICR_ASSERT_ATN);
2614 /* 
2615  * Since we can't change phases until we've completed the current 
2616  * handshake, we have to source or sink a byte of data if the current
2617  * phase is not MSGOUT.
2618  */
2619 
2620 /* 
2621  * Return control to the executing NCR drive so we can clear the
2622  * aborted flag and get back into our main loop.
2623  */ 
2624  
2625         return 0;
2626     }
2627 #endif
2628 
2629 /* 
2630  * Case 2 : If the command hasn't been issued yet, we simply remove it 
2631  *          from the issue queue.
2632  */
2633     for (prev = (Scsi_Cmnd **) &(hostdata->issue_queue), 
2634         tmp = (Scsi_Cmnd *) hostdata->issue_queue;
2635         tmp; prev = (Scsi_Cmnd **) &(tmp->host_scribble), tmp = 
2636         (Scsi_Cmnd *) tmp->host_scribble) 
2637         if (cmd == tmp) {
2638             (*prev) = (Scsi_Cmnd *) tmp->host_scribble;
2639             tmp->host_scribble = NULL;
2640             tmp->result = DID_ABORT << 16;
2641             sti();
2642 #if (NDEBUG & NDEBUG_ABORT)
2643     printk("scsi%d : abort removed command from issue queue.\n", 
2644         instance->host_no);
2645 #endif
2646             tmp->done(tmp);
2647             return SCSI_ABORT_SUCCESS;
2648         }
2649 
2650 /* 
2651  * Case 3 : If any commands are connected, we're going to fail the abort
2652  *          and let the high level SCSI driver retry at a later time or 
2653  *          issue a reset.
2654  *
2655  *          Timeouts, and therefore aborted commands, will be highly unlikely
2656  *          and handling them cleanly in this situation would make the common
2657  *          case of noresets less efficient, and would pollute our code.  So,
2658  *          we fail.
2659  */
2660 
2661     if (hostdata->connected) {
2662         sti();
2663 #if (NDEBUG & NDEBUG_ABORT)
2664     printk("scsi%d : abort failed, command connected.\n", instance->host_no);
2665 #endif
2666         return SCSI_ABORT_NOT_RUNNING;
2667     }
2668 
2669 /*
2670  * Case 4: If the command is currently disconnected from the bus, and 
2671  *      there are no connected commands, we reconnect the I_T_L or 
2672  *      I_T_L_Q nexus associated with it, go into message out, and send 
2673  *      an abort message.
2674  *
2675  * This case is especially ugly. In order to reestablish the nexus, we
2676  * need to call NCR5380_select().  The easiest way to implement this 
2677  * function was to abort if the bus was busy, and let the interrupt
2678  * handler triggered on the SEL for reselect take care of lost arbitrations
2679  * where necessary, meaning interrupts need to be enabled.
2680  *
2681  * When interrupts are enabled, the queues may change - so we 
2682  * can't remove it from the disconnected queue before selecting it
2683  * because that could cause a failure in hashing the nexus if that 
2684  * device reselected.
2685  * 
2686  * Since the queues may change, we can't use the pointers from when we
2687  * first locate it.
2688  *
2689  * So, we must first locate the command, and if NCR5380_select()
2690  * succeeds, then issue the abort, relocate the command and remove
2691  * it from the disconnected queue.
2692  */
2693 
2694     for (tmp = (Scsi_Cmnd *) hostdata->disconnected_queue; tmp; 
2695         tmp = (Scsi_Cmnd *) tmp->host_scribble) 
2696         if (cmd == tmp) {
2697             sti(); 
2698 #if (NDEBUG & NDEBUG_ABORT)
2699     printk("scsi%d : aborting disconnected command.\n", instance->host_no);
2700 #endif
2701   
2702             if (NCR5380_select (instance, cmd, (int) cmd->tag)) 
2703                 return SCSI_ABORT_BUSY;
2704 
2705 #if (NDEBUG & NDEBUG_ABORT)
2706     printk("scsi%d : nexus reestablished.\n", instance->host_no);
2707 #endif
2708 
2709             msg = ABORT;
2710             msgptr = &msg;
2711             len = 1;
2712             phase = PHASE_MSGOUT;
2713             NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
2714             NCR5380_transfer_pio (instance, &phase, &len, &msgptr);
2715 
2716             cli();
2717             for (prev = (Scsi_Cmnd **) &(hostdata->disconnected_queue), 
2718                 tmp = (Scsi_Cmnd *) hostdata->disconnected_queue;
2719                 tmp; prev = (Scsi_Cmnd **) &(tmp->host_scribble), tmp = 
2720                 (Scsi_Cmnd *) tmp->host_scribble) 
2721                     if (cmd == tmp) {
2722                     *prev = (Scsi_Cmnd *) tmp->host_scribble;
2723                     tmp->host_scribble = NULL;
2724                     tmp->result = DID_ABORT << 16;
2725                     sti();
2726                     tmp->done(tmp);
2727                     return SCSI_ABORT_SUCCESS;
2728                 }
2729         }
2730 
2731 /*
2732  * Case 5 : If we reached this point, the command was not found in any of 
2733  *          the queues.
2734  *
2735  * We probably reached this point because of an unlikely race condition
2736  * between the command completing successfully and the abortion code,
2737  * so we won't panic, but we will notify the user in case something really
2738  * broke.
2739  */
2740 
2741     sti();
2742     printk("scsi%d : warning : SCSI command probably completed successfully\n"
2743            "         before abortion\n", instance->host_no); 
2744     return SCSI_ABORT_NOT_RUNNING;
2745 }
2746 
2747 
2748 /* 
2749  * Function : int NCR5380_reset (Scsi_Cmnd *cmd)
2750  * 
2751  * Purpose : reset the SCSI bus.
2752  *
2753  * Returns : SCSI_RESET_WAKEUP
2754  *
2755  */ 
2756 
2757 #ifndef NCR5380_reset
2758 static
2759 #endif
2760 int NCR5380_reset (Scsi_Cmnd *cmd) {
     /* [previous][next][first][last][top][bottom][index][help] */
2761     NCR5380_local_declare();
2762     NCR5380_setup(cmd->host);
2763 
2764     NCR5380_print_status (cmd->host);
2765 
2766     cli();
2767     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_RST);
2768     udelay(25);
2769     NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2770     sti();
2771 
2772     return SCSI_RESET_WAKEUP;
2773 }
2774 

/* [previous][next][first][last][top][bottom][index][help] */