]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/scsi/NCR5380.c
ncr5380: Remove LIST and REMOVE macros
[karo-tx-linux.git] / drivers / scsi / NCR5380.c
1 /* 
2  * NCR 5380 generic driver routines.  These should make it *trivial*
3  *      to implement 5380 SCSI drivers under Linux with a non-trantor
4  *      architecture.
5  *
6  *      Note that these routines also work with NR53c400 family chips.
7  *
8  * Copyright 1993, Drew Eckhardt
9  *      Visionary Computing 
10  *      (Unix and Linux consulting and custom programming)
11  *      drew@colorado.edu
12  *      +1 (303) 666-5836
13  *
14  * For more information, please consult 
15  *
16  * NCR 5380 Family
17  * SCSI Protocol Controller
18  * Databook
19  *
20  * NCR Microelectronics
21  * 1635 Aeroplaza Drive
22  * Colorado Springs, CO 80916
23  * 1+ (719) 578-3400
24  * 1+ (800) 334-5454
25  */
26
27 /*
28  * Revision 1.10 1998/9/2       Alan Cox
29  *                              (alan@lxorguk.ukuu.org.uk)
30  * Fixed up the timer lockups reported so far. Things still suck. Looking 
31  * forward to 2.3 and per device request queues. Then it'll be possible to
32  * SMP thread this beast and improve life no end.
33  
34  * Revision 1.9  1997/7/27      Ronald van Cuijlenborg
35  *                              (ronald.van.cuijlenborg@tip.nl or nutty@dds.nl)
36  * (hopefully) fixed and enhanced USLEEP
37  * added support for DTC3181E card (for Mustek scanner)
38  *
39
40  * Revision 1.8                 Ingmar Baumgart
41  *                              (ingmar@gonzo.schwaben.de)
42  * added support for NCR53C400a card
43  *
44
45  * Revision 1.7  1996/3/2       Ray Van Tassle (rayvt@comm.mot.com)
46  * added proc_info
47  * added support needed for DTC 3180/3280
48  * fixed a couple of bugs
49  *
50
51  * Revision 1.5  1994/01/19  09:14:57  drew
52  * Fixed udelay() hack that was being used on DATAOUT phases
53  * instead of a proper wait for the final handshake.
54  *
55  * Revision 1.4  1994/01/19  06:44:25  drew
56  * *** empty log message ***
57  *
58  * Revision 1.3  1994/01/19  05:24:40  drew
59  * Added support for TCR LAST_BYTE_SENT bit.
60  *
61  * Revision 1.2  1994/01/15  06:14:11  drew
62  * REAL DMA support, bug fixes.
63  *
64  * Revision 1.1  1994/01/15  06:00:54  drew
65  * Initial revision
66  *
67  */
68
69 /*
70  * Further development / testing that should be done : 
71  * 1.  Cleanup the NCR5380_transfer_dma function and DMA operation complete
72  *     code so that everything does the same thing that's done at the 
73  *     end of a pseudo-DMA read operation.
74  *
75  * 2.  Fix REAL_DMA (interrupt driven, polled works fine) -
76  *     basically, transfer size needs to be reduced by one 
77  *     and the last byte read as is done with PSEUDO_DMA.
78  * 
79  * 4.  Test SCSI-II tagged queueing (I have no devices which support 
80  *      tagged queueing)
81  */
82
83 #ifndef notyet
84 #undef REAL_DMA
85 #endif
86
87 #ifdef BOARD_REQUIRES_NO_DELAY
88 #define io_recovery_delay(x)
89 #else
90 #define io_recovery_delay(x)    udelay(x)
91 #endif
92
93 /*
94  * Design
95  *
96  * This is a generic 5380 driver.  To use it on a different platform, 
97  * one simply writes appropriate system specific macros (ie, data
98  * transfer - some PC's will use the I/O bus, 68K's must use 
99  * memory mapped) and drops this file in their 'C' wrapper.
100  *
101  * (Note from hch:  unfortunately it was not enough for the different
102  * m68k folks and instead of improving this driver they copied it
103  * and hacked it up for their needs.  As a consequence they lost
104  * most updates to this driver.  Maybe someone will fix all these
105  * drivers to use a common core one day..)
106  *
107  * As far as command queueing, two queues are maintained for 
108  * each 5380 in the system - commands that haven't been issued yet,
109  * and commands that are currently executing.  This means that an 
110  * unlimited number of commands may be queued, letting 
111  * more commands propagate from the higher driver levels giving higher 
112  * throughput.  Note that both I_T_L and I_T_L_Q nexuses are supported, 
113  * allowing multiple commands to propagate all the way to a SCSI-II device 
114  * while a command is already executing.
115  *
116  *
117  * Issues specific to the NCR5380 : 
118  *
119  * When used in a PIO or pseudo-dma mode, the NCR5380 is a braindead 
120  * piece of hardware that requires you to sit in a loop polling for 
121  * the REQ signal as long as you are connected.  Some devices are 
122  * brain dead (ie, many TEXEL CD ROM drives) and won't disconnect 
123  * while doing long seek operations. [...] These
124  * broken devices are the exception rather than the rule and I'd rather
125  * spend my time optimizing for the normal case.
126  *
127  * Architecture :
128  *
129  * At the heart of the design is a coroutine, NCR5380_main,
130  * which is started from a workqueue for each NCR5380 host in the
131  * system.  It attempts to establish I_T_L or I_T_L_Q nexuses by
132  * removing the commands from the issue queue and calling
133  * NCR5380_select() if a nexus is not established. 
134  *
135  * Once a nexus is established, the NCR5380_information_transfer()
136  * phase goes through the various phases as instructed by the target.
137  * if the target goes into MSG IN and sends a DISCONNECT message,
138  * the command structure is placed into the per instance disconnected
139  * queue, and NCR5380_main tries to find more work.  If the target is 
140  * idle for too long, the system will try to sleep.
141  *
142  * If a command has disconnected, eventually an interrupt will trigger,
143  * calling NCR5380_intr()  which will in turn call NCR5380_reselect
144  * to reestablish a nexus.  This will run main if necessary.
145  *
146  * On command termination, the done function will be called as 
147  * appropriate.
148  *
149  * SCSI pointers are maintained in the SCp field of SCSI command 
150  * structures, being initialized after the command is connected
151  * in NCR5380_select, and set as appropriate in NCR5380_information_transfer.
152  * Note that in violation of the standard, an implicit SAVE POINTERS operation
153  * is done, since some BROKEN disks fail to issue an explicit SAVE POINTERS.
154  */
155
156 /*
157  * Using this file :
158  * This file a skeleton Linux SCSI driver for the NCR 5380 series
159  * of chips.  To use it, you write an architecture specific functions 
160  * and macros and include this file in your driver.
161  *
162  * These macros control options : 
163  * AUTOPROBE_IRQ - if defined, the NCR5380_probe_irq() function will be 
164  *      defined.
165  * 
166  * AUTOSENSE - if defined, REQUEST SENSE will be performed automatically
167  *      for commands that return with a CHECK CONDITION status. 
168  *
169  * DIFFERENTIAL - if defined, NCR53c81 chips will use external differential
170  *      transceivers. 
171  *
172  * DONT_USE_INTR - if defined, never use interrupts, even if we probe or
173  *      override-configure an IRQ.
174  *
175  * PSEUDO_DMA - if defined, PSEUDO DMA is used during the data transfer phases.
176  *
177  * REAL_DMA - if defined, REAL DMA is used during the data transfer phases.
178  *
179  * REAL_DMA_POLL - if defined, REAL DMA is used but the driver doesn't
180  *      rely on phase mismatch and EOP interrupts to determine end 
181  *      of phase.
182  *
183  * Defaults for these will be provided although the user may want to adjust 
184  * these to allocate CPU resources to the SCSI driver or "real" code.
185  * 
186  * These macros MUST be defined :
187  * 
188  * NCR5380_read(register)  - read from the specified register
189  *
190  * NCR5380_write(register, value) - write to the specific register 
191  *
192  * NCR5380_implementation_fields  - additional fields needed for this 
193  *      specific implementation of the NCR5380
194  *
195  * Either real DMA *or* pseudo DMA may be implemented
196  * REAL functions : 
197  * NCR5380_REAL_DMA should be defined if real DMA is to be used.
198  * Note that the DMA setup functions should return the number of bytes 
199  *      that they were able to program the controller for.
200  *
201  * Also note that generic i386/PC versions of these macros are 
202  *      available as NCR5380_i386_dma_write_setup,
203  *      NCR5380_i386_dma_read_setup, and NCR5380_i386_dma_residual.
204  *
205  * NCR5380_dma_write_setup(instance, src, count) - initialize
206  * NCR5380_dma_read_setup(instance, dst, count) - initialize
207  * NCR5380_dma_residual(instance); - residual count
208  *
209  * PSEUDO functions :
210  * NCR5380_pwrite(instance, src, count)
211  * NCR5380_pread(instance, dst, count);
212  *
213  * The generic driver is initialized by calling NCR5380_init(instance),
214  * after setting the appropriate host specific fields and ID.  If the 
215  * driver wishes to autoprobe for an IRQ line, the NCR5380_probe_irq(instance,
216  * possible) function may be used.
217  */
218
219 static int do_abort(struct Scsi_Host *);
220 static void do_reset(struct Scsi_Host *);
221
222 /*
223  *      initialize_SCp          -       init the scsi pointer field
224  *      @cmd: command block to set up
225  *
226  *      Set up the internal fields in the SCSI command.
227  */
228
229 static inline void initialize_SCp(struct scsi_cmnd *cmd)
230 {
231         /* 
232          * Initialize the Scsi Pointer field so that all of the commands in the 
233          * various queues are valid.
234          */
235
236         if (scsi_bufflen(cmd)) {
237                 cmd->SCp.buffer = scsi_sglist(cmd);
238                 cmd->SCp.buffers_residual = scsi_sg_count(cmd) - 1;
239                 cmd->SCp.ptr = sg_virt(cmd->SCp.buffer);
240                 cmd->SCp.this_residual = cmd->SCp.buffer->length;
241         } else {
242                 cmd->SCp.buffer = NULL;
243                 cmd->SCp.buffers_residual = 0;
244                 cmd->SCp.ptr = NULL;
245                 cmd->SCp.this_residual = 0;
246         }
247 }
248
249 /**
250  * NCR5380_poll_politely2 - wait for two chip register values
251  * @instance: controller to poll
252  * @reg1: 5380 register to poll
253  * @bit1: Bitmask to check
254  * @val1: Expected value
255  * @reg2: Second 5380 register to poll
256  * @bit2: Second bitmask to check
257  * @val2: Second expected value
258  * @wait: Time-out in jiffies
259  *
260  * Polls the chip in a reasonably efficient manner waiting for an
261  * event to occur. After a short quick poll we begin to yield the CPU
262  * (if possible). In irq contexts the time-out is arbitrarily limited.
263  * Callers may hold locks as long as they are held in irq mode.
264  *
265  * Returns 0 if either or both event(s) occurred otherwise -ETIMEDOUT.
266  */
267
268 static int NCR5380_poll_politely2(struct Scsi_Host *instance,
269                                   int reg1, int bit1, int val1,
270                                   int reg2, int bit2, int val2, int wait)
271 {
272         struct NCR5380_hostdata *hostdata = shost_priv(instance);
273         unsigned long deadline = jiffies + wait;
274         unsigned long n;
275
276         /* Busy-wait for up to 10 ms */
277         n = min(10000U, jiffies_to_usecs(wait));
278         n *= hostdata->accesses_per_ms;
279         n /= 2000;
280         do {
281                 if ((NCR5380_read(reg1) & bit1) == val1)
282                         return 0;
283                 if ((NCR5380_read(reg2) & bit2) == val2)
284                         return 0;
285                 cpu_relax();
286         } while (n--);
287
288         if (irqs_disabled() || in_interrupt())
289                 return -ETIMEDOUT;
290
291         /* Repeatedly sleep for 1 ms until deadline */
292         while (time_is_after_jiffies(deadline)) {
293                 schedule_timeout_uninterruptible(1);
294                 if ((NCR5380_read(reg1) & bit1) == val1)
295                         return 0;
296                 if ((NCR5380_read(reg2) & bit2) == val2)
297                         return 0;
298         }
299
300         return -ETIMEDOUT;
301 }
302
303 static inline int NCR5380_poll_politely(struct Scsi_Host *instance,
304                                         int reg, int bit, int val, int wait)
305 {
306         return NCR5380_poll_politely2(instance, reg, bit, val,
307                                                 reg, bit, val, wait);
308 }
309
310 static struct {
311         unsigned char value;
312         const char *name;
313 } phases[] __maybe_unused = {
314         {PHASE_DATAOUT, "DATAOUT"}, 
315         {PHASE_DATAIN, "DATAIN"}, 
316         {PHASE_CMDOUT, "CMDOUT"}, 
317         {PHASE_STATIN, "STATIN"}, 
318         {PHASE_MSGOUT, "MSGOUT"}, 
319         {PHASE_MSGIN, "MSGIN"}, 
320         {PHASE_UNKNOWN, "UNKNOWN"}
321 };
322
323 #if NDEBUG
324 static struct {
325         unsigned char mask;
326         const char *name;
327 } signals[] = { 
328         {SR_DBP, "PARITY"}, 
329         {SR_RST, "RST"}, 
330         {SR_BSY, "BSY"}, 
331         {SR_REQ, "REQ"}, 
332         {SR_MSG, "MSG"}, 
333         {SR_CD, "CD"}, 
334         {SR_IO, "IO"}, 
335         {SR_SEL, "SEL"}, 
336         {0, NULL}
337 }, 
338 basrs[] = {
339         {BASR_ATN, "ATN"}, 
340         {BASR_ACK, "ACK"}, 
341         {0, NULL}
342 }, 
343 icrs[] = { 
344         {ICR_ASSERT_RST, "ASSERT RST"}, 
345         {ICR_ASSERT_ACK, "ASSERT ACK"}, 
346         {ICR_ASSERT_BSY, "ASSERT BSY"}, 
347         {ICR_ASSERT_SEL, "ASSERT SEL"}, 
348         {ICR_ASSERT_ATN, "ASSERT ATN"}, 
349         {ICR_ASSERT_DATA, "ASSERT DATA"}, 
350         {0, NULL}
351 }, 
352 mrs[] = { 
353         {MR_BLOCK_DMA_MODE, "MODE BLOCK DMA"}, 
354         {MR_TARGET, "MODE TARGET"}, 
355         {MR_ENABLE_PAR_CHECK, "MODE PARITY CHECK"}, 
356         {MR_ENABLE_PAR_INTR, "MODE PARITY INTR"}, 
357         {MR_MONITOR_BSY, "MODE MONITOR BSY"}, 
358         {MR_DMA_MODE, "MODE DMA"}, 
359         {MR_ARBITRATE, "MODE ARBITRATION"}, 
360         {0, NULL}
361 };
362
363 /**
364  *      NCR5380_print   -       print scsi bus signals
365  *      @instance:      adapter state to dump
366  *
367  *      Print the SCSI bus signals for debugging purposes
368  *
369  *      Locks: caller holds hostdata lock (not essential)
370  */
371
372 static void NCR5380_print(struct Scsi_Host *instance)
373 {
374         unsigned char status, data, basr, mr, icr, i;
375
376         data = NCR5380_read(CURRENT_SCSI_DATA_REG);
377         status = NCR5380_read(STATUS_REG);
378         mr = NCR5380_read(MODE_REG);
379         icr = NCR5380_read(INITIATOR_COMMAND_REG);
380         basr = NCR5380_read(BUS_AND_STATUS_REG);
381
382         printk("STATUS_REG: %02x ", status);
383         for (i = 0; signals[i].mask; ++i)
384                 if (status & signals[i].mask)
385                         printk(",%s", signals[i].name);
386         printk("\nBASR: %02x ", basr);
387         for (i = 0; basrs[i].mask; ++i)
388                 if (basr & basrs[i].mask)
389                         printk(",%s", basrs[i].name);
390         printk("\nICR: %02x ", icr);
391         for (i = 0; icrs[i].mask; ++i)
392                 if (icr & icrs[i].mask)
393                         printk(",%s", icrs[i].name);
394         printk("\nMODE: %02x ", mr);
395         for (i = 0; mrs[i].mask; ++i)
396                 if (mr & mrs[i].mask)
397                         printk(",%s", mrs[i].name);
398         printk("\n");
399 }
400
401
402 /* 
403  *      NCR5380_print_phase     -       show SCSI phase
404  *      @instance: adapter to dump
405  *
406  *      Print the current SCSI phase for debugging purposes
407  *
408  *      Locks: none
409  */
410
411 static void NCR5380_print_phase(struct Scsi_Host *instance)
412 {
413         unsigned char status;
414         int i;
415
416         status = NCR5380_read(STATUS_REG);
417         if (!(status & SR_REQ))
418                 printk("scsi%d : REQ not asserted, phase unknown.\n", instance->host_no);
419         else {
420                 for (i = 0; (phases[i].value != PHASE_UNKNOWN) && (phases[i].value != (status & PHASE_MASK)); ++i);
421                 printk("scsi%d : phase %s\n", instance->host_no, phases[i].name);
422         }
423 }
424 #endif
425
426
427 static int probe_irq __initdata;
428
429 /**
430  *      probe_intr      -       helper for IRQ autoprobe
431  *      @irq: interrupt number
432  *      @dev_id: unused
433  *      @regs: unused
434  *
435  *      Set a flag to indicate the IRQ in question was received. This is
436  *      used by the IRQ probe code.
437  */
438  
439 static irqreturn_t __init probe_intr(int irq, void *dev_id)
440 {
441         probe_irq = irq;
442         return IRQ_HANDLED;
443 }
444
445 /**
446  *      NCR5380_probe_irq       -       find the IRQ of an NCR5380
447  *      @instance: NCR5380 controller
448  *      @possible: bitmask of ISA IRQ lines
449  *
450  *      Autoprobe for the IRQ line used by the NCR5380 by triggering an IRQ
451  *      and then looking to see what interrupt actually turned up.
452  *
453  *      Locks: none, irqs must be enabled on entry
454  */
455
456 static int __init __maybe_unused NCR5380_probe_irq(struct Scsi_Host *instance,
457                                                 int possible)
458 {
459         struct NCR5380_hostdata *hostdata = shost_priv(instance);
460         unsigned long timeout;
461         int trying_irqs, i, mask;
462
463         for (trying_irqs = 0, i = 1, mask = 2; i < 16; ++i, mask <<= 1)
464                 if ((mask & possible) && (request_irq(i, &probe_intr, 0, "NCR-probe", NULL) == 0))
465                         trying_irqs |= mask;
466
467         timeout = jiffies + msecs_to_jiffies(250);
468         probe_irq = NO_IRQ;
469
470         /*
471          * A interrupt is triggered whenever BSY = false, SEL = true
472          * and a bit set in the SELECT_ENABLE_REG is asserted on the 
473          * SCSI bus.
474          *
475          * Note that the bus is only driven when the phase control signals
476          * (I/O, C/D, and MSG) match those in the TCR, so we must reset that
477          * to zero.
478          */
479
480         NCR5380_write(TARGET_COMMAND_REG, 0);
481         NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
482         NCR5380_write(OUTPUT_DATA_REG, hostdata->id_mask);
483         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA | ICR_ASSERT_SEL);
484
485         while (probe_irq == NO_IRQ && time_before(jiffies, timeout))
486                 schedule_timeout_uninterruptible(1);
487         
488         NCR5380_write(SELECT_ENABLE_REG, 0);
489         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
490
491         for (i = 1, mask = 2; i < 16; ++i, mask <<= 1)
492                 if (trying_irqs & mask)
493                         free_irq(i, NULL);
494
495         return probe_irq;
496 }
497
498 /**
499  *      NCR58380_info - report driver and host information
500  *      @instance: relevant scsi host instance
501  *
502  *      For use as the host template info() handler.
503  *
504  *      Locks: none
505  */
506
507 static const char *NCR5380_info(struct Scsi_Host *instance)
508 {
509         struct NCR5380_hostdata *hostdata = shost_priv(instance);
510
511         return hostdata->info;
512 }
513
514 static void prepare_info(struct Scsi_Host *instance)
515 {
516         struct NCR5380_hostdata *hostdata = shost_priv(instance);
517
518         snprintf(hostdata->info, sizeof(hostdata->info),
519                  "%s, io_port 0x%lx, n_io_port %d, "
520                  "base 0x%lx, irq %d, "
521                  "can_queue %d, cmd_per_lun %d, "
522                  "sg_tablesize %d, this_id %d, "
523                  "flags { %s%s%s}, "
524                  "options { %s} ",
525                  instance->hostt->name, instance->io_port, instance->n_io_port,
526                  instance->base, instance->irq,
527                  instance->can_queue, instance->cmd_per_lun,
528                  instance->sg_tablesize, instance->this_id,
529                  hostdata->flags & FLAG_NO_DMA_FIXUP  ? "NO_DMA_FIXUP "  : "",
530                  hostdata->flags & FLAG_NO_PSEUDO_DMA ? "NO_PSEUDO_DMA " : "",
531                  hostdata->flags & FLAG_TOSHIBA_DELAY ? "TOSHIBA_DELAY "  : "",
532 #ifdef AUTOPROBE_IRQ
533                  "AUTOPROBE_IRQ "
534 #endif
535 #ifdef DIFFERENTIAL
536                  "DIFFERENTIAL "
537 #endif
538 #ifdef REAL_DMA
539                  "REAL_DMA "
540 #endif
541 #ifdef REAL_DMA_POLL
542                  "REAL_DMA_POLL "
543 #endif
544 #ifdef PARITY
545                  "PARITY "
546 #endif
547 #ifdef PSEUDO_DMA
548                  "PSEUDO_DMA "
549 #endif
550                  "");
551 }
552
553 #ifdef PSEUDO_DMA
554 /******************************************/
555 /*
556  * /proc/scsi/[dtc pas16 t128 generic]/[0-ASC_NUM_BOARD_SUPPORTED]
557  *
558  * *buffer: I/O buffer
559  * **start: if inout == FALSE pointer into buffer where user read should start
560  * offset: current offset
561  * length: length of buffer
562  * hostno: Scsi_Host host_no
563  * inout: TRUE - user is writing; FALSE - user is reading
564  *
565  * Return the number of bytes read from or written
566  */
567
568 static int __maybe_unused NCR5380_write_info(struct Scsi_Host *instance,
569         char *buffer, int length)
570 {
571         struct NCR5380_hostdata *hostdata = shost_priv(instance);
572
573         hostdata->spin_max_r = 0;
574         hostdata->spin_max_w = 0;
575         return 0;
576 }
577
578 static int __maybe_unused NCR5380_show_info(struct seq_file *m,
579         struct Scsi_Host *instance)
580 {
581         struct NCR5380_hostdata *hostdata = shost_priv(instance);
582
583         seq_printf(m, "Highwater I/O busy spin counts: write %d, read %d\n",
584                 hostdata->spin_max_w, hostdata->spin_max_r);
585         return 0;
586 }
587 #endif
588
589 /**
590  *      NCR5380_init    -       initialise an NCR5380
591  *      @instance: adapter to configure
592  *      @flags: control flags
593  *
594  *      Initializes *instance and corresponding 5380 chip,
595  *      with flags OR'd into the initial flags value.
596  *
597  *      Notes : I assume that the host, hostno, and id bits have been
598  *      set correctly.  I don't care about the irq and other fields. 
599  *
600  *      Returns 0 for success
601  *
602  *      Locks: interrupts must be enabled when we are called 
603  */
604
605 static int NCR5380_init(struct Scsi_Host *instance, int flags)
606 {
607         struct NCR5380_hostdata *hostdata = shost_priv(instance);
608         int i;
609         unsigned long deadline;
610
611         if(in_interrupt())
612                 printk(KERN_ERR "NCR5380_init called with interrupts off!\n");
613
614         hostdata->id_mask = 1 << instance->this_id;
615         for (i = hostdata->id_mask; i <= 0x80; i <<= 1)
616                 if (i > hostdata->id_mask)
617                         hostdata->id_higher_mask |= i;
618         for (i = 0; i < 8; ++i)
619                 hostdata->busy[i] = 0;
620 #ifdef REAL_DMA
621         hostdata->dmalen = 0;
622 #endif
623         spin_lock_init(&hostdata->lock);
624         hostdata->connected = NULL;
625         hostdata->issue_queue = NULL;
626         hostdata->disconnected_queue = NULL;
627         hostdata->flags = flags;
628         
629         INIT_WORK(&hostdata->main_task, NCR5380_main);
630         hostdata->work_q = alloc_workqueue("ncr5380_%d",
631                                 WQ_UNBOUND | WQ_MEM_RECLAIM,
632                                 1, instance->host_no);
633         if (!hostdata->work_q)
634                 return -ENOMEM;
635
636         hostdata->host = instance;
637
638         prepare_info(instance);
639
640         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
641         NCR5380_write(MODE_REG, MR_BASE);
642         NCR5380_write(TARGET_COMMAND_REG, 0);
643         NCR5380_write(SELECT_ENABLE_REG, 0);
644
645         /* Calibrate register polling loop */
646         i = 0;
647         deadline = jiffies + 1;
648         do {
649                 cpu_relax();
650         } while (time_is_after_jiffies(deadline));
651         deadline += msecs_to_jiffies(256);
652         do {
653                 NCR5380_read(STATUS_REG);
654                 ++i;
655                 cpu_relax();
656         } while (time_is_after_jiffies(deadline));
657         hostdata->accesses_per_ms = i / 256;
658
659         return 0;
660 }
661
662 /**
663  * NCR5380_maybe_reset_bus - Detect and correct bus wedge problems.
664  * @instance: adapter to check
665  *
666  * If the system crashed, it may have crashed with a connected target and
667  * the SCSI bus busy. Check for BUS FREE phase. If not, try to abort the
668  * currently established nexus, which we know nothing about. Failing that
669  * do a bus reset.
670  *
671  * Note that a bus reset will cause the chip to assert IRQ.
672  *
673  * Returns 0 if successful, otherwise -ENXIO.
674  */
675
676 static int NCR5380_maybe_reset_bus(struct Scsi_Host *instance)
677 {
678         struct NCR5380_hostdata *hostdata = shost_priv(instance);
679         int pass;
680
681         for (pass = 1; (NCR5380_read(STATUS_REG) & SR_BSY) && pass <= 6; ++pass) {
682                 switch (pass) {
683                 case 1:
684                 case 3:
685                 case 5:
686                         shost_printk(KERN_ERR, instance, "SCSI bus busy, waiting up to five seconds\n");
687                         NCR5380_poll_politely(instance,
688                                               STATUS_REG, SR_BSY, 0, 5 * HZ);
689                         break;
690                 case 2:
691                         shost_printk(KERN_ERR, instance, "bus busy, attempting abort\n");
692                         do_abort(instance);
693                         break;
694                 case 4:
695                         shost_printk(KERN_ERR, instance, "bus busy, attempting reset\n");
696                         do_reset(instance);
697                         /* Wait after a reset; the SCSI standard calls for
698                          * 250ms, we wait 500ms to be on the safe side.
699                          * But some Toshiba CD-ROMs need ten times that.
700                          */
701                         if (hostdata->flags & FLAG_TOSHIBA_DELAY)
702                                 msleep(2500);
703                         else
704                                 msleep(500);
705                         break;
706                 case 6:
707                         shost_printk(KERN_ERR, instance, "bus locked solid\n");
708                         return -ENXIO;
709                 }
710         }
711         return 0;
712 }
713
714 /**
715  *      NCR5380_exit    -       remove an NCR5380
716  *      @instance: adapter to remove
717  */
718
719 static void NCR5380_exit(struct Scsi_Host *instance)
720 {
721         struct NCR5380_hostdata *hostdata = shost_priv(instance);
722
723         cancel_work_sync(&hostdata->main_task);
724         destroy_workqueue(hostdata->work_q);
725 }
726
727 /**
728  * NCR5380_queue_command - queue a command
729  * @instance: the relevant SCSI adapter
730  * @cmd: SCSI command
731  *
732  * cmd is added to the per-instance issue queue, with minor
733  * twiddling done to the host specific fields of cmd.  If the
734  * main coroutine is not running, it is restarted.
735  */
736
737 static int NCR5380_queue_command(struct Scsi_Host *instance,
738                                  struct scsi_cmnd *cmd)
739 {
740         struct NCR5380_hostdata *hostdata = shost_priv(instance);
741         struct scsi_cmnd *tmp;
742         unsigned long flags;
743
744 #if (NDEBUG & NDEBUG_NO_WRITE)
745         switch (cmd->cmnd[0]) {
746         case WRITE_6:
747         case WRITE_10:
748                 shost_printk(KERN_DEBUG, instance, "WRITE attempted with NDEBUG_NO_WRITE set\n");
749                 cmd->result = (DID_ERROR << 16);
750                 cmd->scsi_done(cmd);
751                 return 0;
752         }
753 #endif                          /* (NDEBUG & NDEBUG_NO_WRITE) */
754
755         /* 
756          * We use the host_scribble field as a pointer to the next command  
757          * in a queue 
758          */
759
760         cmd->host_scribble = NULL;
761         cmd->result = 0;
762
763         spin_lock_irqsave(&hostdata->lock, flags);
764
765         /* 
766          * Insert the cmd into the issue queue. Note that REQUEST SENSE 
767          * commands are added to the head of the queue since any command will
768          * clear the contingent allegiance condition that exists and the 
769          * sense data is only guaranteed to be valid while the condition exists.
770          */
771
772         if (!(hostdata->issue_queue) || (cmd->cmnd[0] == REQUEST_SENSE)) {
773                 cmd->host_scribble = (unsigned char *) hostdata->issue_queue;
774                 hostdata->issue_queue = cmd;
775         } else {
776                 for (tmp = (struct scsi_cmnd *) hostdata->issue_queue; tmp->host_scribble; tmp = (struct scsi_cmnd *) tmp->host_scribble);
777                 tmp->host_scribble = (unsigned char *) cmd;
778         }
779         spin_unlock_irqrestore(&hostdata->lock, flags);
780
781         dsprintk(NDEBUG_QUEUES, instance, "command %p added to %s of queue\n",
782                  cmd, (cmd->cmnd[0] == REQUEST_SENSE) ? "head" : "tail");
783
784         /* Kick off command processing */
785         queue_work(hostdata->work_q, &hostdata->main_task);
786         return 0;
787 }
788
789 /**
790  *      NCR5380_main    -       NCR state machines
791  *
792  *      NCR5380_main is a coroutine that runs as long as more work can 
793  *      be done on the NCR5380 host adapters in a system.  Both 
794  *      NCR5380_queue_command() and NCR5380_intr() will try to start it 
795  *      in case it is not running.
796  * 
797  *      Locks: called as its own thread with no locks held. Takes the
798  *      host lock and called routines may take the isa dma lock.
799  */
800
801 static void NCR5380_main(struct work_struct *work)
802 {
803         struct NCR5380_hostdata *hostdata =
804                 container_of(work, struct NCR5380_hostdata, main_task);
805         struct Scsi_Host *instance = hostdata->host;
806         struct scsi_cmnd *tmp, *prev;
807         int done;
808         
809         spin_lock_irq(&hostdata->lock);
810         do {
811                 done = 1;
812
813                 if (!hostdata->connected) {
814                         dprintk(NDEBUG_MAIN, "scsi%d : not connected\n", instance->host_no);
815                         /*
816                          * Search through the issue_queue for a command destined
817                          * for a target that's not busy.
818                          */
819                         for (tmp = (struct scsi_cmnd *) hostdata->issue_queue, prev = NULL; tmp; prev = tmp, tmp = (struct scsi_cmnd *) tmp->host_scribble)
820                         {
821                                 dsprintk(NDEBUG_QUEUES, instance, "main: tmp=%p target=%d busy=%d lun=%llu\n",
822                                          tmp, scmd_id(tmp), hostdata->busy[scmd_id(tmp)],
823                                          tmp->device->lun);
824                                 /*  When we find one, remove it from the issue queue. */
825                                 if (!(hostdata->busy[tmp->device->id] &
826                                       (1 << (u8)(tmp->device->lun & 0xff)))) {
827                                         if (prev) {
828                                                 prev->host_scribble = tmp->host_scribble;
829                                         } else {
830                                                 hostdata->issue_queue = (struct scsi_cmnd *) tmp->host_scribble;
831                                         }
832                                         tmp->host_scribble = NULL;
833                                         dsprintk(NDEBUG_MAIN | NDEBUG_QUEUES,
834                                                  instance, "main: removed %p from issue queue %p\n",
835                                                  tmp, prev);
836
837                                         /* 
838                                          * Attempt to establish an I_T_L nexus here. 
839                                          * On success, instance->hostdata->connected is set.
840                                          * On failure, we must add the command back to the
841                                          *   issue queue so we can keep trying. 
842                                          */
843                                         /*
844                                          * REQUEST SENSE commands are issued without tagged
845                                          * queueing, even on SCSI-II devices because the
846                                          * contingent allegiance condition exists for the
847                                          * entire unit.
848                                          */
849
850                                         if (!NCR5380_select(instance, tmp)) {
851                                                 /* OK or bad target */
852                                         } else {
853                                                 /* Need to retry */
854                                                 tmp->host_scribble = (unsigned char *) hostdata->issue_queue;
855                                                 hostdata->issue_queue = tmp;
856                                                 dsprintk(NDEBUG_MAIN | NDEBUG_QUEUES,
857                                                          instance, "main: select() failed, %p returned to issue queue\n",
858                                                          tmp);
859                                                 done = 0;
860                                         }
861                                         if (hostdata->connected)
862                                                 break;
863                                 }       /* if target/lun is not busy */
864                         }       /* for */
865                 }       /* if (!hostdata->connected) */
866
867                 if (hostdata->connected
868 #ifdef REAL_DMA
869                     && !hostdata->dmalen
870 #endif
871                     ) {
872                         dprintk(NDEBUG_MAIN, "scsi%d : main() : performing information transfer\n", instance->host_no);
873                         NCR5380_information_transfer(instance);
874                         dprintk(NDEBUG_MAIN, "scsi%d : main() : done set false\n", instance->host_no);
875                         done = 0;
876                 }
877         } while (!done);
878         spin_unlock_irq(&hostdata->lock);
879 }
880
881 #ifndef DONT_USE_INTR
882
883 /**
884  * NCR5380_intr - generic NCR5380 irq handler
885  * @irq: interrupt number
886  * @dev_id: device info
887  *
888  * Handle interrupts, reestablishing I_T_L or I_T_L_Q nexuses
889  * from the disconnected queue, and restarting NCR5380_main()
890  * as required.
891  *
892  * The chip can assert IRQ in any of six different conditions. The IRQ flag
893  * is then cleared by reading the Reset Parity/Interrupt Register (RPIR).
894  * Three of these six conditions are latched in the Bus and Status Register:
895  * - End of DMA (cleared by ending DMA Mode)
896  * - Parity error (cleared by reading RPIR)
897  * - Loss of BSY (cleared by reading RPIR)
898  * Two conditions have flag bits that are not latched:
899  * - Bus phase mismatch (non-maskable in DMA Mode, cleared by ending DMA Mode)
900  * - Bus reset (non-maskable)
901  * The remaining condition has no flag bit at all:
902  * - Selection/reselection
903  *
904  * Hence, establishing the cause(s) of any interrupt is partly guesswork.
905  * In "The DP8490 and DP5380 Comparison Guide", National Semiconductor
906  * claimed that "the design of the [DP8490] interrupt logic ensures
907  * interrupts will not be lost (they can be on the DP5380)."
908  * The L5380/53C80 datasheet from LOGIC Devices has more details.
909  *
910  * Checking for bus reset by reading RST is futile because of interrupt
911  * latency, but a bus reset will reset chip logic. Checking for parity error
912  * is unnecessary because that interrupt is never enabled. A Loss of BSY
913  * condition will clear DMA Mode. We can tell when this occurs because the
914  * the Busy Monitor interrupt is enabled together with DMA Mode.
915  */
916
917 static irqreturn_t NCR5380_intr(int irq, void *dev_id)
918 {
919         struct Scsi_Host *instance = dev_id;
920         struct NCR5380_hostdata *hostdata = shost_priv(instance);
921         int handled = 0;
922         unsigned char basr;
923         unsigned long flags;
924
925         spin_lock_irqsave(&hostdata->lock, flags);
926
927         basr = NCR5380_read(BUS_AND_STATUS_REG);
928         if (basr & BASR_IRQ) {
929                 unsigned char mr = NCR5380_read(MODE_REG);
930                 unsigned char sr = NCR5380_read(STATUS_REG);
931
932                 dprintk(NDEBUG_INTR, "scsi%d: IRQ %d, BASR 0x%02x, SR 0x%02x, MR 0x%02x\n",
933                         instance->host_no, irq, basr, sr, mr);
934
935 #if defined(REAL_DMA)
936                 if ((mr & MR_DMA_MODE) || (mr & MR_MONITOR_BSY)) {
937                         /* Probably End of DMA, Phase Mismatch or Loss of BSY.
938                          * We ack IRQ after clearing Mode Register. Workarounds
939                          * for End of DMA errata need to happen in DMA Mode.
940                          */
941
942                         dprintk(NDEBUG_INTR, "scsi%d: interrupt in DMA mode\n", intance->host_no);
943
944                         int transferred;
945
946                         if (!hostdata->connected)
947                                 panic("scsi%d : DMA interrupt with no connected cmd\n",
948                                       instance->hostno);
949
950                         transferred = hostdata->dmalen - NCR5380_dma_residual(instance);
951                         hostdata->connected->SCp.this_residual -= transferred;
952                         hostdata->connected->SCp.ptr += transferred;
953                         hostdata->dmalen = 0;
954
955                         /* FIXME: we need to poll briefly then defer a workqueue task ! */
956                         NCR5380_poll_politely(hostdata, BUS_AND_STATUS_REG, BASR_ACK, 0, 2 * HZ);
957
958                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
959                         NCR5380_write(MODE_REG, MR_BASE);
960                         NCR5380_read(RESET_PARITY_INTERRUPT_REG);
961                 } else
962 #endif /* REAL_DMA */
963                 if ((NCR5380_read(CURRENT_SCSI_DATA_REG) & hostdata->id_mask) &&
964                     (sr & (SR_SEL | SR_IO | SR_BSY | SR_RST)) == (SR_SEL | SR_IO)) {
965                         /* Probably reselected */
966                         NCR5380_write(SELECT_ENABLE_REG, 0);
967                         NCR5380_read(RESET_PARITY_INTERRUPT_REG);
968
969                         dprintk(NDEBUG_INTR, "scsi%d: interrupt with SEL and IO\n",
970                                 instance->host_no);
971
972                         if (!hostdata->connected) {
973                                 NCR5380_reselect(instance);
974                                 queue_work(hostdata->work_q, &hostdata->main_task);
975                         }
976                         if (!hostdata->connected)
977                                 NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
978                 } else {
979                         /* Probably Bus Reset */
980                         NCR5380_read(RESET_PARITY_INTERRUPT_REG);
981
982                         dprintk(NDEBUG_INTR, "scsi%d: unknown interrupt\n", instance->host_no);
983                 }
984                 handled = 1;
985         } else {
986                 shost_printk(KERN_NOTICE, instance, "interrupt without IRQ bit\n");
987         }
988
989         spin_unlock_irqrestore(&hostdata->lock, flags);
990
991         return IRQ_RETVAL(handled);
992 }
993
994 #endif 
995
996 /* 
997  * Function : int NCR5380_select(struct Scsi_Host *instance,
998  *                               struct scsi_cmnd *cmd)
999  *
1000  * Purpose : establishes I_T_L or I_T_L_Q nexus for new or existing command,
1001  *      including ARBITRATION, SELECTION, and initial message out for 
1002  *      IDENTIFY and queue messages. 
1003  *
1004  * Inputs : instance - instantiation of the 5380 driver on which this 
1005  *      target lives, cmd - SCSI command to execute.
1006  * 
1007  * Returns : -1 if selection failed but should be retried.
1008  *      0 if selection failed and should not be retried.
1009  *      0 if selection succeeded completely (hostdata->connected == cmd).
1010  *
1011  * Side effects : 
1012  *      If bus busy, arbitration failed, etc, NCR5380_select() will exit 
1013  *              with registers as they should have been on entry - ie
1014  *              SELECT_ENABLE will be set appropriately, the NCR5380
1015  *              will cease to drive any SCSI bus signals.
1016  *
1017  *      If successful : I_T_L or I_T_L_Q nexus will be established, 
1018  *              instance->connected will be set to cmd.  
1019  *              SELECT interrupt will be disabled.
1020  *
1021  *      If failed (no target) : cmd->scsi_done() will be called, and the 
1022  *              cmd->result host byte set to DID_BAD_TARGET.
1023  *
1024  *      Locks: caller holds hostdata lock in IRQ mode
1025  */
1026  
1027 static int NCR5380_select(struct Scsi_Host *instance, struct scsi_cmnd *cmd)
1028 {
1029         struct NCR5380_hostdata *hostdata = shost_priv(instance);
1030         unsigned char tmp[3], phase;
1031         unsigned char *data;
1032         int len;
1033         int err;
1034
1035         NCR5380_dprint(NDEBUG_ARBITRATION, instance);
1036         dprintk(NDEBUG_ARBITRATION, "scsi%d : starting arbitration, id = %d\n", instance->host_no, instance->this_id);
1037
1038         /* 
1039          * Set the phase bits to 0, otherwise the NCR5380 won't drive the 
1040          * data bus during SELECTION.
1041          */
1042
1043         NCR5380_write(TARGET_COMMAND_REG, 0);
1044
1045         /* 
1046          * Start arbitration.
1047          */
1048
1049         NCR5380_write(OUTPUT_DATA_REG, hostdata->id_mask);
1050         NCR5380_write(MODE_REG, MR_ARBITRATE);
1051
1052         /* The chip now waits for BUS FREE phase. Then after the 800 ns
1053          * Bus Free Delay, arbitration will begin.
1054          */
1055
1056         spin_unlock_irq(&hostdata->lock);
1057         err = NCR5380_poll_politely2(instance, MODE_REG, MR_ARBITRATE, 0,
1058                         INITIATOR_COMMAND_REG, ICR_ARBITRATION_PROGRESS,
1059                                                ICR_ARBITRATION_PROGRESS, HZ);
1060         spin_lock_irq(&hostdata->lock);
1061         if (!(NCR5380_read(MODE_REG) & MR_ARBITRATE)) {
1062                 /* Reselection interrupt */
1063                 return -1;
1064         }
1065         if (err < 0) {
1066                 NCR5380_write(MODE_REG, MR_BASE);
1067                 shost_printk(KERN_ERR, instance,
1068                              "select: arbitration timeout\n");
1069                 return -1;
1070         }
1071         spin_unlock_irq(&hostdata->lock);
1072
1073         /* The SCSI-2 arbitration delay is 2.4 us */
1074         udelay(3);
1075
1076         /* Check for lost arbitration */
1077         if ((NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST) || (NCR5380_read(CURRENT_SCSI_DATA_REG) & hostdata->id_higher_mask) || (NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST)) {
1078                 NCR5380_write(MODE_REG, MR_BASE);
1079                 dprintk(NDEBUG_ARBITRATION, "scsi%d : lost arbitration, deasserting MR_ARBITRATE\n", instance->host_no);
1080                 spin_lock_irq(&hostdata->lock);
1081                 return -1;
1082         }
1083
1084         /* After/during arbitration, BSY should be asserted.
1085          * IBM DPES-31080 Version S31Q works now
1086          * Tnx to Thomas_Roesch@m2.maus.de for finding this! (Roman)
1087          */
1088         NCR5380_write(INITIATOR_COMMAND_REG,
1089                       ICR_BASE | ICR_ASSERT_SEL | ICR_ASSERT_BSY);
1090
1091         /* 
1092          * Again, bus clear + bus settle time is 1.2us, however, this is 
1093          * a minimum so we'll udelay ceil(1.2)
1094          */
1095
1096         if (hostdata->flags & FLAG_TOSHIBA_DELAY)
1097                 udelay(15);
1098         else
1099                 udelay(2);
1100
1101         spin_lock_irq(&hostdata->lock);
1102
1103         /* NCR5380_reselect() clears MODE_REG after a reselection interrupt */
1104         if (!(NCR5380_read(MODE_REG) & MR_ARBITRATE))
1105                 return -1;
1106
1107         dprintk(NDEBUG_ARBITRATION, "scsi%d : won arbitration\n", instance->host_no);
1108
1109         /* 
1110          * Now that we have won arbitration, start Selection process, asserting 
1111          * the host and target ID's on the SCSI bus.
1112          */
1113
1114         NCR5380_write(OUTPUT_DATA_REG, (hostdata->id_mask | (1 << scmd_id(cmd))));
1115
1116         /* 
1117          * Raise ATN while SEL is true before BSY goes false from arbitration,
1118          * since this is the only way to guarantee that we'll get a MESSAGE OUT
1119          * phase immediately after selection.
1120          */
1121
1122         NCR5380_write(INITIATOR_COMMAND_REG, (ICR_BASE | ICR_ASSERT_BSY | ICR_ASSERT_DATA | ICR_ASSERT_ATN | ICR_ASSERT_SEL));
1123         NCR5380_write(MODE_REG, MR_BASE);
1124
1125         /* 
1126          * Reselect interrupts must be turned off prior to the dropping of BSY,
1127          * otherwise we will trigger an interrupt.
1128          */
1129         NCR5380_write(SELECT_ENABLE_REG, 0);
1130
1131         spin_unlock_irq(&hostdata->lock);
1132
1133         /*
1134          * The initiator shall then wait at least two deskew delays and release 
1135          * the BSY signal.
1136          */
1137         udelay(1);              /* wingel -- wait two bus deskew delay >2*45ns */
1138
1139         /* Reset BSY */
1140         NCR5380_write(INITIATOR_COMMAND_REG, (ICR_BASE | ICR_ASSERT_DATA | ICR_ASSERT_ATN | ICR_ASSERT_SEL));
1141
1142         /* 
1143          * Something weird happens when we cease to drive BSY - looks
1144          * like the board/chip is letting us do another read before the 
1145          * appropriate propagation delay has expired, and we're confusing
1146          * a BSY signal from ourselves as the target's response to SELECTION.
1147          *
1148          * A small delay (the 'C++' frontend breaks the pipeline with an
1149          * unnecessary jump, making it work on my 386-33/Trantor T128, the
1150          * tighter 'C' code breaks and requires this) solves the problem - 
1151          * the 1 us delay is arbitrary, and only used because this delay will 
1152          * be the same on other platforms and since it works here, it should 
1153          * work there.
1154          *
1155          * wingel suggests that this could be due to failing to wait
1156          * one deskew delay.
1157          */
1158
1159         udelay(1);
1160
1161         dprintk(NDEBUG_SELECTION, "scsi%d : selecting target %d\n", instance->host_no, scmd_id(cmd));
1162
1163         /* 
1164          * The SCSI specification calls for a 250 ms timeout for the actual 
1165          * selection.
1166          */
1167
1168         err = NCR5380_poll_politely(instance, STATUS_REG, SR_BSY, SR_BSY,
1169                                     msecs_to_jiffies(250));
1170
1171         if ((NCR5380_read(STATUS_REG) & (SR_SEL | SR_IO)) == (SR_SEL | SR_IO)) {
1172                 spin_lock_irq(&hostdata->lock);
1173                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1174                 NCR5380_reselect(instance);
1175                 if (!hostdata->connected)
1176                         NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1177                 printk("scsi%d : reselection after won arbitration?\n", instance->host_no);
1178                 return -1;
1179         }
1180
1181         if (err < 0) {
1182                 spin_lock_irq(&hostdata->lock);
1183                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1184                 cmd->result = DID_BAD_TARGET << 16;
1185                 cmd->scsi_done(cmd);
1186                 NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1187                 dprintk(NDEBUG_SELECTION, "scsi%d : target did not respond within 250ms\n",
1188                         instance->host_no);
1189                 return 0;
1190         }
1191
1192         /* 
1193          * No less than two deskew delays after the initiator detects the 
1194          * BSY signal is true, it shall release the SEL signal and may 
1195          * change the DATA BUS.                                     -wingel
1196          */
1197
1198         udelay(1);
1199
1200         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1201
1202         /*
1203          * Since we followed the SCSI spec, and raised ATN while SEL 
1204          * was true but before BSY was false during selection, the information
1205          * transfer phase should be a MESSAGE OUT phase so that we can send the
1206          * IDENTIFY message.
1207          * 
1208          * If SCSI-II tagged queuing is enabled, we also send a SIMPLE_QUEUE_TAG
1209          * message (2 bytes) with a tag ID that we increment with every command
1210          * until it wraps back to 0.
1211          *
1212          * XXX - it turns out that there are some broken SCSI-II devices,
1213          *       which claim to support tagged queuing but fail when more than
1214          *       some number of commands are issued at once.
1215          */
1216
1217         /* Wait for start of REQ/ACK handshake */
1218
1219         err = NCR5380_poll_politely(instance, STATUS_REG, SR_REQ, SR_REQ, HZ);
1220         spin_lock_irq(&hostdata->lock);
1221         if (err < 0) {
1222                 shost_printk(KERN_ERR, instance, "select: REQ timeout\n");
1223                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1224                 NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1225                 return -1;
1226         }
1227
1228         dprintk(NDEBUG_SELECTION, "scsi%d : target %d selected, going into MESSAGE OUT phase.\n", instance->host_no, cmd->device->id);
1229         tmp[0] = IDENTIFY(((instance->irq == NO_IRQ) ? 0 : 1), cmd->device->lun);
1230
1231         len = 1;
1232         cmd->tag = 0;
1233
1234         /* Send message(s) */
1235         data = tmp;
1236         phase = PHASE_MSGOUT;
1237         NCR5380_transfer_pio(instance, &phase, &len, &data);
1238         dprintk(NDEBUG_SELECTION, "scsi%d : nexus established.\n", instance->host_no);
1239         /* XXX need to handle errors here */
1240
1241         hostdata->connected = cmd;
1242         hostdata->busy[cmd->device->id] |= (1 << (cmd->device->lun & 0xFF));
1243
1244         initialize_SCp(cmd);
1245
1246         return 0;
1247 }
1248
1249 /* 
1250  * Function : int NCR5380_transfer_pio (struct Scsi_Host *instance, 
1251  *      unsigned char *phase, int *count, unsigned char **data)
1252  *
1253  * Purpose : transfers data in given phase using polled I/O
1254  *
1255  * Inputs : instance - instance of driver, *phase - pointer to 
1256  *      what phase is expected, *count - pointer to number of 
1257  *      bytes to transfer, **data - pointer to data pointer.
1258  * 
1259  * Returns : -1 when different phase is entered without transferring
1260  *      maximum number of bytes, 0 if all bytes or transferred or exit
1261  *      is in same phase.
1262  *
1263  *      Also, *phase, *count, *data are modified in place.
1264  *
1265  * XXX Note : handling for bus free may be useful.
1266  */
1267
1268 /*
1269  * Note : this code is not as quick as it could be, however it 
1270  * IS 100% reliable, and for the actual data transfer where speed
1271  * counts, we will always do a pseudo DMA or DMA transfer.
1272  */
1273
1274 static int NCR5380_transfer_pio(struct Scsi_Host *instance, unsigned char *phase, int *count, unsigned char **data) {
1275         unsigned char p = *phase, tmp;
1276         int c = *count;
1277         unsigned char *d = *data;
1278
1279         if (!(p & SR_IO))
1280                 dprintk(NDEBUG_PIO, "scsi%d : pio write %d bytes\n", instance->host_no, c);
1281         else
1282                 dprintk(NDEBUG_PIO, "scsi%d : pio read %d bytes\n", instance->host_no, c);
1283
1284         /* 
1285          * The NCR5380 chip will only drive the SCSI bus when the 
1286          * phase specified in the appropriate bits of the TARGET COMMAND
1287          * REGISTER match the STATUS REGISTER
1288          */
1289
1290          NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(p));
1291
1292         do {
1293                 /* 
1294                  * Wait for assertion of REQ, after which the phase bits will be 
1295                  * valid 
1296                  */
1297
1298                 if (NCR5380_poll_politely(instance, STATUS_REG, SR_REQ, SR_REQ, HZ) < 0)
1299                         break;
1300
1301                 dprintk(NDEBUG_HANDSHAKE, "scsi%d : REQ detected\n", instance->host_no);
1302
1303                 /* Check for phase mismatch */
1304                 if ((NCR5380_read(STATUS_REG) & PHASE_MASK) != p) {
1305                         dprintk(NDEBUG_HANDSHAKE, "scsi%d : phase mismatch\n", instance->host_no);
1306                         NCR5380_dprint_phase(NDEBUG_HANDSHAKE, instance);
1307                         break;
1308                 }
1309                 /* Do actual transfer from SCSI bus to / from memory */
1310                 if (!(p & SR_IO))
1311                         NCR5380_write(OUTPUT_DATA_REG, *d);
1312                 else
1313                         *d = NCR5380_read(CURRENT_SCSI_DATA_REG);
1314
1315                 ++d;
1316
1317                 /* 
1318                  * The SCSI standard suggests that in MSGOUT phase, the initiator
1319                  * should drop ATN on the last byte of the message phase
1320                  * after REQ has been asserted for the handshake but before
1321                  * the initiator raises ACK.
1322                  */
1323
1324                 if (!(p & SR_IO)) {
1325                         if (!((p & SR_MSG) && c > 1)) {
1326                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA);
1327                                 NCR5380_dprint(NDEBUG_PIO, instance);
1328                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA | ICR_ASSERT_ACK);
1329                         } else {
1330                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA | ICR_ASSERT_ATN);
1331                                 NCR5380_dprint(NDEBUG_PIO, instance);
1332                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA | ICR_ASSERT_ATN | ICR_ASSERT_ACK);
1333                         }
1334                 } else {
1335                         NCR5380_dprint(NDEBUG_PIO, instance);
1336                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ACK);
1337                 }
1338
1339                 if (NCR5380_poll_politely(instance,
1340                                           STATUS_REG, SR_REQ, 0, 5 * HZ) < 0)
1341                         break;
1342
1343                 dprintk(NDEBUG_HANDSHAKE, "scsi%d : req false, handshake complete\n", instance->host_no);
1344
1345 /*
1346  * We have several special cases to consider during REQ/ACK handshaking : 
1347  * 1.  We were in MSGOUT phase, and we are on the last byte of the 
1348  *      message.  ATN must be dropped as ACK is dropped.
1349  *
1350  * 2.  We are in a MSGIN phase, and we are on the last byte of the  
1351  *      message.  We must exit with ACK asserted, so that the calling
1352  *      code may raise ATN before dropping ACK to reject the message.
1353  *
1354  * 3.  ACK and ATN are clear and the target may proceed as normal.
1355  */
1356                 if (!(p == PHASE_MSGIN && c == 1)) {
1357                         if (p == PHASE_MSGOUT && c > 1)
1358                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1359                         else
1360                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1361                 }
1362         } while (--c);
1363
1364         dprintk(NDEBUG_PIO, "scsi%d : residual %d\n", instance->host_no, c);
1365
1366         *count = c;
1367         *data = d;
1368         tmp = NCR5380_read(STATUS_REG);
1369         /* The phase read from the bus is valid if either REQ is (already)
1370          * asserted or if ACK hasn't been released yet. The latter applies if
1371          * we're in MSG IN, DATA IN or STATUS and all bytes have been received.
1372          */
1373         if ((tmp & SR_REQ) || ((tmp & SR_IO) && c == 0))
1374                 *phase = tmp & PHASE_MASK;
1375         else
1376                 *phase = PHASE_UNKNOWN;
1377
1378         if (!c || (*phase == p))
1379                 return 0;
1380         else
1381                 return -1;
1382 }
1383
1384 /**
1385  * do_reset - issue a reset command
1386  * @instance: adapter to reset
1387  *
1388  * Issue a reset sequence to the NCR5380 and try and get the bus
1389  * back into sane shape.
1390  *
1391  * This clears the reset interrupt flag because there may be no handler for
1392  * it. When the driver is initialized, the NCR5380_intr() handler has not yet
1393  * been installed. And when in EH we may have released the ST DMA interrupt.
1394  */
1395  
1396 static void do_reset(struct Scsi_Host *instance)
1397 {
1398         unsigned long flags;
1399
1400         local_irq_save(flags);
1401         NCR5380_write(TARGET_COMMAND_REG,
1402                       PHASE_SR_TO_TCR(NCR5380_read(STATUS_REG) & PHASE_MASK));
1403         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_RST);
1404         udelay(50);
1405         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1406         (void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1407         local_irq_restore(flags);
1408 }
1409
1410 /**
1411  * do_abort - abort the currently established nexus by going to
1412  * MESSAGE OUT phase and sending an ABORT message.
1413  * @instance: relevant scsi host instance
1414  *
1415  * Returns 0 on success, -1 on failure.
1416  */
1417
1418 static int do_abort(struct Scsi_Host *instance)
1419 {
1420         unsigned char *msgptr, phase, tmp;
1421         int len;
1422         int rc;
1423
1424         /* Request message out phase */
1425         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1426
1427         /* 
1428          * Wait for the target to indicate a valid phase by asserting 
1429          * REQ.  Once this happens, we'll have either a MSGOUT phase 
1430          * and can immediately send the ABORT message, or we'll have some 
1431          * other phase and will have to source/sink data.
1432          * 
1433          * We really don't care what value was on the bus or what value
1434          * the target sees, so we just handshake.
1435          */
1436
1437         rc = NCR5380_poll_politely(instance, STATUS_REG, SR_REQ, SR_REQ, 10 * HZ);
1438         if (rc < 0)
1439                 goto timeout;
1440
1441         tmp = NCR5380_read(STATUS_REG) & PHASE_MASK;
1442         
1443         NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(tmp));
1444
1445         if (tmp != PHASE_MSGOUT) {
1446                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN | ICR_ASSERT_ACK);
1447                 rc = NCR5380_poll_politely(instance, STATUS_REG, SR_REQ, 0, 3 * HZ);
1448                 if (rc < 0)
1449                         goto timeout;
1450                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1451         }
1452         tmp = ABORT;
1453         msgptr = &tmp;
1454         len = 1;
1455         phase = PHASE_MSGOUT;
1456         NCR5380_transfer_pio(instance, &phase, &len, &msgptr);
1457
1458         /*
1459          * If we got here, and the command completed successfully,
1460          * we're about to go into bus free state.
1461          */
1462
1463         return len ? -1 : 0;
1464
1465 timeout:
1466         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1467         return -1;
1468 }
1469
1470 #if defined(REAL_DMA) || defined(PSEUDO_DMA) || defined (REAL_DMA_POLL)
1471 /* 
1472  * Function : int NCR5380_transfer_dma (struct Scsi_Host *instance, 
1473  *      unsigned char *phase, int *count, unsigned char **data)
1474  *
1475  * Purpose : transfers data in given phase using either real
1476  *      or pseudo DMA.
1477  *
1478  * Inputs : instance - instance of driver, *phase - pointer to 
1479  *      what phase is expected, *count - pointer to number of 
1480  *      bytes to transfer, **data - pointer to data pointer.
1481  * 
1482  * Returns : -1 when different phase is entered without transferring
1483  *      maximum number of bytes, 0 if all bytes or transferred or exit
1484  *      is in same phase.
1485  *
1486  *      Also, *phase, *count, *data are modified in place.
1487  *
1488  *      Locks: io_request lock held by caller
1489  */
1490
1491
1492 static int NCR5380_transfer_dma(struct Scsi_Host *instance, unsigned char *phase, int *count, unsigned char **data) {
1493         register int c = *count;
1494         register unsigned char p = *phase;
1495         register unsigned char *d = *data;
1496         unsigned char tmp;
1497         int foo;
1498 #if defined(REAL_DMA_POLL)
1499         int cnt, toPIO;
1500         unsigned char saved_data = 0, overrun = 0, residue;
1501 #endif
1502
1503         struct NCR5380_hostdata *hostdata = shost_priv(instance);
1504
1505         if ((tmp = (NCR5380_read(STATUS_REG) & PHASE_MASK)) != p) {
1506                 *phase = tmp;
1507                 return -1;
1508         }
1509 #if defined(REAL_DMA) || defined(REAL_DMA_POLL)
1510         if (p & SR_IO) {
1511                 if (!(hostdata->flags & FLAG_NO_DMA_FIXUPS))
1512                         c -= 2;
1513         }
1514         dprintk(NDEBUG_DMA, "scsi%d : initializing DMA channel %d for %s, %d bytes %s %0x\n", instance->host_no, instance->dma_channel, (p & SR_IO) ? "reading" : "writing", c, (p & SR_IO) ? "to" : "from", (unsigned) d);
1515         hostdata->dma_len = (p & SR_IO) ? NCR5380_dma_read_setup(instance, d, c) : NCR5380_dma_write_setup(instance, d, c);
1516 #endif
1517
1518         NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(p));
1519
1520 #ifdef REAL_DMA
1521         NCR5380_write(MODE_REG, MR_BASE | MR_DMA_MODE | MR_MONITOR_BSY |
1522                                 MR_ENABLE_EOP_INTR);
1523 #elif defined(REAL_DMA_POLL)
1524         NCR5380_write(MODE_REG, MR_BASE | MR_DMA_MODE | MR_MONITOR_BSY);
1525 #else
1526         /*
1527          * Note : on my sample board, watch-dog timeouts occurred when interrupts
1528          * were not disabled for the duration of a single DMA transfer, from 
1529          * before the setting of DMA mode to after transfer of the last byte.
1530          */
1531
1532         if (hostdata->flags & FLAG_NO_DMA_FIXUP)
1533                 NCR5380_write(MODE_REG, MR_BASE | MR_DMA_MODE | MR_MONITOR_BSY |
1534                                         MR_ENABLE_EOP_INTR);
1535         else
1536                 NCR5380_write(MODE_REG, MR_BASE | MR_DMA_MODE | MR_MONITOR_BSY);
1537 #endif                          /* def REAL_DMA */
1538
1539         dprintk(NDEBUG_DMA, "scsi%d : mode reg = 0x%X\n", instance->host_no, NCR5380_read(MODE_REG));
1540
1541         /* 
1542          *      On the PAS16 at least I/O recovery delays are not needed here.
1543          *      Everyone else seems to want them.
1544          */
1545
1546         if (p & SR_IO) {
1547                 io_recovery_delay(1);
1548                 NCR5380_write(START_DMA_INITIATOR_RECEIVE_REG, 0);
1549         } else {
1550                 io_recovery_delay(1);
1551                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA);
1552                 io_recovery_delay(1);
1553                 NCR5380_write(START_DMA_SEND_REG, 0);
1554                 io_recovery_delay(1);
1555         }
1556
1557 #if defined(REAL_DMA_POLL)
1558         do {
1559                 tmp = NCR5380_read(BUS_AND_STATUS_REG);
1560         } while ((tmp & BASR_PHASE_MATCH) && !(tmp & (BASR_BUSY_ERROR | BASR_END_DMA_TRANSFER)));
1561
1562 /*
1563    At this point, either we've completed DMA, or we have a phase mismatch,
1564    or we've unexpectedly lost BUSY (which is a real error).
1565
1566    For write DMAs, we want to wait until the last byte has been
1567    transferred out over the bus before we turn off DMA mode.  Alas, there
1568    seems to be no terribly good way of doing this on a 5380 under all
1569    conditions.  For non-scatter-gather operations, we can wait until REQ
1570    and ACK both go false, or until a phase mismatch occurs.  Gather-writes
1571    are nastier, since the device will be expecting more data than we
1572    are prepared to send it, and REQ will remain asserted.  On a 53C8[01] we
1573    could test LAST BIT SENT to assure transfer (I imagine this is precisely
1574    why this signal was added to the newer chips) but on the older 538[01]
1575    this signal does not exist.  The workaround for this lack is a watchdog;
1576    we bail out of the wait-loop after a modest amount of wait-time if
1577    the usual exit conditions are not met.  Not a terribly clean or
1578    correct solution :-%
1579
1580    Reads are equally tricky due to a nasty characteristic of the NCR5380.
1581    If the chip is in DMA mode for an READ, it will respond to a target's
1582    REQ by latching the SCSI data into the INPUT DATA register and asserting
1583    ACK, even if it has _already_ been notified by the DMA controller that
1584    the current DMA transfer has completed!  If the NCR5380 is then taken
1585    out of DMA mode, this already-acknowledged byte is lost.
1586
1587    This is not a problem for "one DMA transfer per command" reads, because
1588    the situation will never arise... either all of the data is DMA'ed
1589    properly, or the target switches to MESSAGE IN phase to signal a
1590    disconnection (either operation bringing the DMA to a clean halt).
1591    However, in order to handle scatter-reads, we must work around the
1592    problem.  The chosen fix is to DMA N-2 bytes, then check for the
1593    condition before taking the NCR5380 out of DMA mode.  One or two extra
1594    bytes are transferred via PIO as necessary to fill out the original
1595    request.
1596  */
1597
1598         if (p & SR_IO) {
1599                 if (!(hostdata->flags & FLAG_NO_DMA_FIXUPS)) {
1600                         udelay(10);
1601                         if ((NCR5380_read(BUS_AND_STATUS_REG) & (BASR_PHASE_MATCH | BASR_ACK)) ==
1602                             (BASR_PHASE_MATCH | BASR_ACK)) {
1603                                 saved_data = NCR5380_read(INPUT_DATA_REGISTER);
1604                                 overrun = 1;
1605                         }
1606                 }
1607         } else {
1608                 int limit = 100;
1609                 while (((tmp = NCR5380_read(BUS_AND_STATUS_REG)) & BASR_ACK) || (NCR5380_read(STATUS_REG) & SR_REQ)) {
1610                         if (!(tmp & BASR_PHASE_MATCH))
1611                                 break;
1612                         if (--limit < 0)
1613                                 break;
1614                 }
1615         }
1616
1617         dprintk(NDEBUG_DMA, "scsi%d : polled DMA transfer complete, basr 0x%X, sr 0x%X\n", instance->host_no, tmp, NCR5380_read(STATUS_REG));
1618
1619         NCR5380_write(MODE_REG, MR_BASE);
1620         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1621
1622         residue = NCR5380_dma_residual(instance);
1623         c -= residue;
1624         *count -= c;
1625         *data += c;
1626         *phase = NCR5380_read(STATUS_REG) & PHASE_MASK;
1627
1628         if (!(hostdata->flags & FLAG_NO_DMA_FIXUPS) &&
1629             *phase == p && (p & SR_IO) && residue == 0) {
1630                 if (overrun) {
1631                         dprintk(NDEBUG_DMA, "Got an input overrun, using saved byte\n");
1632                         **data = saved_data;
1633                         *data += 1;
1634                         *count -= 1;
1635                         cnt = toPIO = 1;
1636                 } else {
1637                         printk("No overrun??\n");
1638                         cnt = toPIO = 2;
1639                 }
1640                 dprintk(NDEBUG_DMA, "Doing %d-byte PIO to 0x%X\n", cnt, *data);
1641                 NCR5380_transfer_pio(instance, phase, &cnt, data);
1642                 *count -= toPIO - cnt;
1643         }
1644
1645         dprintk(NDEBUG_DMA, "Return with data ptr = 0x%X, count %d, last 0x%X, next 0x%X\n", *data, *count, *(*data + *count - 1), *(*data + *count));
1646         return 0;
1647
1648 #elif defined(REAL_DMA)
1649         return 0;
1650 #else                           /* defined(REAL_DMA_POLL) */
1651         if (p & SR_IO) {
1652                 foo = NCR5380_pread(instance, d,
1653                         hostdata->flags & FLAG_NO_DMA_FIXUP ? c : c - 1);
1654                 if (!foo && !(hostdata->flags & FLAG_NO_DMA_FIXUP)) {
1655                         /*
1656                          * We can't disable DMA mode after successfully transferring 
1657                          * what we plan to be the last byte, since that would open up
1658                          * a race condition where if the target asserted REQ before 
1659                          * we got the DMA mode reset, the NCR5380 would have latched
1660                          * an additional byte into the INPUT DATA register and we'd
1661                          * have dropped it.
1662                          * 
1663                          * The workaround was to transfer one fewer bytes than we 
1664                          * intended to with the pseudo-DMA read function, wait for 
1665                          * the chip to latch the last byte, read it, and then disable
1666                          * pseudo-DMA mode.
1667                          * 
1668                          * After REQ is asserted, the NCR5380 asserts DRQ and ACK.
1669                          * REQ is deasserted when ACK is asserted, and not reasserted
1670                          * until ACK goes false.  Since the NCR5380 won't lower ACK
1671                          * until DACK is asserted, which won't happen unless we twiddle
1672                          * the DMA port or we take the NCR5380 out of DMA mode, we 
1673                          * can guarantee that we won't handshake another extra 
1674                          * byte.
1675                          */
1676
1677                         if (NCR5380_poll_politely(instance, BUS_AND_STATUS_REG,
1678                                                   BASR_DRQ, BASR_DRQ, HZ) < 0) {
1679                                 foo = -1;
1680                                 shost_printk(KERN_ERR, instance, "PDMA read: DRQ timeout\n");
1681                         }
1682                         if (NCR5380_poll_politely(instance, STATUS_REG,
1683                                                   SR_REQ, 0, HZ) < 0) {
1684                                 foo = -1;
1685                                 shost_printk(KERN_ERR, instance, "PDMA read: !REQ timeout\n");
1686                         }
1687                         d[c - 1] = NCR5380_read(INPUT_DATA_REG);
1688                 }
1689         } else {
1690                 foo = NCR5380_pwrite(instance, d, c);
1691                 if (!foo && !(hostdata->flags & FLAG_NO_DMA_FIXUP)) {
1692                         /*
1693                          * Wait for the last byte to be sent.  If REQ is being asserted for 
1694                          * the byte we're interested, we'll ACK it and it will go false.  
1695                          */
1696                         if (NCR5380_poll_politely2(instance,
1697                              BUS_AND_STATUS_REG, BASR_DRQ, BASR_DRQ,
1698                              BUS_AND_STATUS_REG, BASR_PHASE_MATCH, 0, HZ) < 0) {
1699                                 foo = -1;
1700                                 shost_printk(KERN_ERR, instance, "PDMA write: DRQ and phase timeout\n");
1701                         }
1702                 }
1703         }
1704         NCR5380_write(MODE_REG, MR_BASE);
1705         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1706         NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1707         *data = d + c;
1708         *count = 0;
1709         *phase = NCR5380_read(STATUS_REG) & PHASE_MASK;
1710         return foo;
1711 #endif                          /* def REAL_DMA */
1712 }
1713 #endif                          /* defined(REAL_DMA) | defined(PSEUDO_DMA) */
1714
1715 /*
1716  * Function : NCR5380_information_transfer (struct Scsi_Host *instance)
1717  *
1718  * Purpose : run through the various SCSI phases and do as the target 
1719  *      directs us to.  Operates on the currently connected command, 
1720  *      instance->connected.
1721  *
1722  * Inputs : instance, instance for which we are doing commands
1723  *
1724  * Side effects : SCSI things happen, the disconnected queue will be 
1725  *      modified if a command disconnects, *instance->connected will
1726  *      change.
1727  *
1728  * XXX Note : we need to watch for bus free or a reset condition here 
1729  *      to recover from an unexpected bus free condition.
1730  *
1731  * Locks: io_request_lock held by caller in IRQ mode
1732  */
1733
1734 static void NCR5380_information_transfer(struct Scsi_Host *instance) {
1735         struct NCR5380_hostdata *hostdata = shost_priv(instance);
1736         unsigned char msgout = NOP;
1737         int sink = 0;
1738         int len;
1739 #if defined(PSEUDO_DMA) || defined(REAL_DMA_POLL)
1740         int transfersize;
1741 #endif
1742         unsigned char *data;
1743         unsigned char phase, tmp, extended_msg[10], old_phase = 0xff;
1744         struct scsi_cmnd *cmd;
1745
1746         while ((cmd = hostdata->connected)) {
1747                 tmp = NCR5380_read(STATUS_REG);
1748                 /* We only have a valid SCSI phase when REQ is asserted */
1749                 if (tmp & SR_REQ) {
1750                         phase = (tmp & PHASE_MASK);
1751                         if (phase != old_phase) {
1752                                 old_phase = phase;
1753                                 NCR5380_dprint_phase(NDEBUG_INFORMATION, instance);
1754                         }
1755                         if (sink && (phase != PHASE_MSGOUT)) {
1756                                 NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(tmp));
1757
1758                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN | ICR_ASSERT_ACK);
1759                                 while (NCR5380_read(STATUS_REG) & SR_REQ);
1760                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1761                                 sink = 0;
1762                                 continue;
1763                         }
1764                         switch (phase) {
1765                         case PHASE_DATAOUT:
1766 #if (NDEBUG & NDEBUG_NO_DATAOUT)
1767                                 printk("scsi%d : NDEBUG_NO_DATAOUT set, attempted DATAOUT aborted\n", instance->host_no);
1768                                 sink = 1;
1769                                 do_abort(instance);
1770                                 cmd->result = DID_ERROR << 16;
1771                                 cmd->scsi_done(cmd);
1772                                 return;
1773 #endif
1774                         case PHASE_DATAIN:
1775                                 /* 
1776                                  * If there is no room left in the current buffer in the
1777                                  * scatter-gather list, move onto the next one.
1778                                  */
1779
1780                                 if (!cmd->SCp.this_residual && cmd->SCp.buffers_residual) {
1781                                         ++cmd->SCp.buffer;
1782                                         --cmd->SCp.buffers_residual;
1783                                         cmd->SCp.this_residual = cmd->SCp.buffer->length;
1784                                         cmd->SCp.ptr = sg_virt(cmd->SCp.buffer);
1785                                         dprintk(NDEBUG_INFORMATION, "scsi%d : %d bytes and %d buffers left\n", instance->host_no, cmd->SCp.this_residual, cmd->SCp.buffers_residual);
1786                                 }
1787                                 /*
1788                                  * The preferred transfer method is going to be 
1789                                  * PSEUDO-DMA for systems that are strictly PIO,
1790                                  * since we can let the hardware do the handshaking.
1791                                  *
1792                                  * For this to work, we need to know the transfersize
1793                                  * ahead of time, since the pseudo-DMA code will sit
1794                                  * in an unconditional loop.
1795                                  */
1796
1797 #if defined(PSEUDO_DMA) || defined(REAL_DMA_POLL)
1798                                 transfersize = 0;
1799                                 if (!cmd->device->borken &&
1800                                     !(hostdata->flags & FLAG_NO_PSEUDO_DMA))
1801                                         transfersize = NCR5380_dma_xfer_len(instance, cmd, phase);
1802
1803                                 if (transfersize) {
1804                                         len = transfersize;
1805                                         if (NCR5380_transfer_dma(instance, &phase, &len, (unsigned char **) &cmd->SCp.ptr)) {
1806                                                 /*
1807                                                  * If the watchdog timer fires, all future accesses to this
1808                                                  * device will use the polled-IO.
1809                                                  */
1810                                                 scmd_printk(KERN_INFO, cmd,
1811                                                             "switching to slow handshake\n");
1812                                                 cmd->device->borken = 1;
1813                                                 sink = 1;
1814                                                 do_abort(instance);
1815                                                 cmd->result = DID_ERROR << 16;
1816                                                 cmd->scsi_done(cmd);
1817                                                 /* XXX - need to source or sink data here, as appropriate */
1818                                         } else
1819                                                 cmd->SCp.this_residual -= transfersize - len;
1820                                 } else
1821 #endif                          /* defined(PSEUDO_DMA) || defined(REAL_DMA_POLL) */
1822                                 {
1823                                         spin_unlock_irq(&hostdata->lock);
1824                                         NCR5380_transfer_pio(instance, &phase, (int *) &cmd->SCp.this_residual, (unsigned char **)
1825                                                              &cmd->SCp.ptr);
1826                                         spin_lock_irq(&hostdata->lock);
1827                                 }
1828                                 break;
1829                         case PHASE_MSGIN:
1830                                 len = 1;
1831                                 data = &tmp;
1832                                 NCR5380_transfer_pio(instance, &phase, &len, &data);
1833                                 cmd->SCp.Message = tmp;
1834
1835                                 switch (tmp) {
1836                                 case ABORT:
1837                                 case COMMAND_COMPLETE:
1838                                         /* Accept message by clearing ACK */
1839                                         sink = 1;
1840                                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1841                                         dsprintk(NDEBUG_QUEUES, instance,
1842                                                  "COMMAND COMPLETE %p target %d lun %llu\n",
1843                                                  cmd, scmd_id(cmd), cmd->device->lun);
1844
1845                                         hostdata->connected = NULL;
1846                                         hostdata->busy[cmd->device->id] &= ~(1 << (cmd->device->lun & 0xFF));
1847
1848                                         /* 
1849                                          * I'm not sure what the correct thing to do here is : 
1850                                          * 
1851                                          * If the command that just executed is NOT a request 
1852                                          * sense, the obvious thing to do is to set the result
1853                                          * code to the values of the stored parameters.
1854                                          * 
1855                                          * If it was a REQUEST SENSE command, we need some way 
1856                                          * to differentiate between the failure code of the original
1857                                          * and the failure code of the REQUEST sense - the obvious
1858                                          * case is success, where we fall through and leave the result
1859                                          * code unchanged.
1860                                          * 
1861                                          * The non-obvious place is where the REQUEST SENSE failed 
1862                                          */
1863
1864                                         if (cmd->cmnd[0] != REQUEST_SENSE)
1865                                                 cmd->result = cmd->SCp.Status | (cmd->SCp.Message << 8);
1866                                         else if (status_byte(cmd->SCp.Status) != GOOD)
1867                                                 cmd->result = (cmd->result & 0x00ffff) | (DID_ERROR << 16);
1868
1869                                         if ((cmd->cmnd[0] == REQUEST_SENSE) &&
1870                                                 hostdata->ses.cmd_len) {
1871                                                 scsi_eh_restore_cmnd(cmd, &hostdata->ses);
1872                                                 hostdata->ses.cmd_len = 0 ;
1873                                         }
1874
1875                                         if ((cmd->cmnd[0] != REQUEST_SENSE) && (status_byte(cmd->SCp.Status) == CHECK_CONDITION)) {
1876                                                 scsi_eh_prep_cmnd(cmd, &hostdata->ses, NULL, 0, ~0);
1877
1878                                                 cmd->host_scribble = (unsigned char *)
1879                                                     hostdata->issue_queue;
1880                                                 hostdata->issue_queue = (struct scsi_cmnd *) cmd;
1881                                                 dsprintk(NDEBUG_AUTOSENSE | NDEBUG_QUEUES,
1882                                                          instance, "REQUEST SENSE cmd %p added to head of issue queue\n",
1883                                                          cmd);
1884                                         } else {
1885                                                 cmd->scsi_done(cmd);
1886                                         }
1887
1888                                         /* 
1889                                          * Restore phase bits to 0 so an interrupted selection, 
1890                                          * arbitration can resume.
1891                                          */
1892                                         NCR5380_write(TARGET_COMMAND_REG, 0);
1893
1894                                         /* Enable reselect interrupts */
1895                                         NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1896                                         return;
1897                                 case MESSAGE_REJECT:
1898                                         /* Accept message by clearing ACK */
1899                                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1900                                         switch (hostdata->last_message) {
1901                                         case HEAD_OF_QUEUE_TAG:
1902                                         case ORDERED_QUEUE_TAG:
1903                                         case SIMPLE_QUEUE_TAG:
1904                                                 cmd->device->simple_tags = 0;
1905                                                 hostdata->busy[cmd->device->id] |= (1 << (cmd->device->lun & 0xFF));
1906                                                 break;
1907                                         default:
1908                                                 break;
1909                                         }
1910                                         break;
1911                                 case DISCONNECT:{
1912                                                 /* Accept message by clearing ACK */
1913                                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1914                                                 cmd->host_scribble = (unsigned char *)
1915                                                     hostdata->disconnected_queue;
1916                                                 hostdata->connected = NULL;
1917                                                 hostdata->disconnected_queue = cmd;
1918                                                 dsprintk(NDEBUG_INFORMATION | NDEBUG_QUEUES,
1919                                                          instance, "connected command %p for target %d lun %llu moved to disconnected queue\n",
1920                                                          cmd, scmd_id(cmd), cmd->device->lun);
1921
1922                                                 /* 
1923                                                  * Restore phase bits to 0 so an interrupted selection, 
1924                                                  * arbitration can resume.
1925                                                  */
1926                                                 NCR5380_write(TARGET_COMMAND_REG, 0);
1927
1928                                                 /* Enable reselect interrupts */
1929                                                 NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1930                                                 return;
1931                                         }
1932                                         /* 
1933                                          * The SCSI data pointer is *IMPLICITLY* saved on a disconnect
1934                                          * operation, in violation of the SCSI spec so we can safely 
1935                                          * ignore SAVE/RESTORE pointers calls.
1936                                          *
1937                                          * Unfortunately, some disks violate the SCSI spec and 
1938                                          * don't issue the required SAVE_POINTERS message before
1939                                          * disconnecting, and we have to break spec to remain 
1940                                          * compatible.
1941                                          */
1942                                 case SAVE_POINTERS:
1943                                 case RESTORE_POINTERS:
1944                                         /* Accept message by clearing ACK */
1945                                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1946                                         break;
1947                                 case EXTENDED_MESSAGE:
1948 /* 
1949  * Extended messages are sent in the following format :
1950  * Byte         
1951  * 0            EXTENDED_MESSAGE == 1
1952  * 1            length (includes one byte for code, doesn't 
1953  *              include first two bytes)
1954  * 2            code
1955  * 3..length+1  arguments
1956  *
1957  * Start the extended message buffer with the EXTENDED_MESSAGE
1958  * byte, since spi_print_msg() wants the whole thing.  
1959  */
1960                                         extended_msg[0] = EXTENDED_MESSAGE;
1961                                         /* Accept first byte by clearing ACK */
1962                                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1963
1964                                         spin_unlock_irq(&hostdata->lock);
1965
1966                                         dprintk(NDEBUG_EXTENDED, "scsi%d : receiving extended message\n", instance->host_no);
1967
1968                                         len = 2;
1969                                         data = extended_msg + 1;
1970                                         phase = PHASE_MSGIN;
1971                                         NCR5380_transfer_pio(instance, &phase, &len, &data);
1972
1973                                         dprintk(NDEBUG_EXTENDED, "scsi%d : length=%d, code=0x%02x\n", instance->host_no, (int) extended_msg[1], (int) extended_msg[2]);
1974
1975                                         if (!len && extended_msg[1] > 0 &&
1976                                             extended_msg[1] <= sizeof(extended_msg) - 2) {
1977                                                 /* Accept third byte by clearing ACK */
1978                                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1979                                                 len = extended_msg[1] - 1;
1980                                                 data = extended_msg + 3;
1981                                                 phase = PHASE_MSGIN;
1982
1983                                                 NCR5380_transfer_pio(instance, &phase, &len, &data);
1984                                                 dprintk(NDEBUG_EXTENDED, "scsi%d : message received, residual %d\n", instance->host_no, len);
1985
1986                                                 switch (extended_msg[2]) {
1987                                                 case EXTENDED_SDTR:
1988                                                 case EXTENDED_WDTR:
1989                                                 case EXTENDED_MODIFY_DATA_POINTER:
1990                                                 case EXTENDED_EXTENDED_IDENTIFY:
1991                                                         tmp = 0;
1992                                                 }
1993                                         } else if (len) {
1994                                                 printk("scsi%d: error receiving extended message\n", instance->host_no);
1995                                                 tmp = 0;
1996                                         } else {
1997                                                 printk("scsi%d: extended message code %02x length %d is too long\n", instance->host_no, extended_msg[2], extended_msg[1]);
1998                                                 tmp = 0;
1999                                         }
2000
2001                                         spin_lock_irq(&hostdata->lock);
2002                                         if (!hostdata->connected)
2003                                                 return;
2004
2005                                         /* Fall through to reject message */
2006
2007                                         /* 
2008                                          * If we get something weird that we aren't expecting, 
2009                                          * reject it.
2010                                          */
2011                                 default:
2012                                         if (!tmp) {
2013                                                 printk("scsi%d: rejecting message ", instance->host_no);
2014                                                 spi_print_msg(extended_msg);
2015                                                 printk("\n");
2016                                         } else if (tmp != EXTENDED_MESSAGE)
2017                                                 scmd_printk(KERN_INFO, cmd,
2018                                                         "rejecting unknown message %02x\n",tmp);
2019                                         else
2020                                                 scmd_printk(KERN_INFO, cmd,
2021                                                         "rejecting unknown extended message code %02x, length %d\n", extended_msg[1], extended_msg[0]);
2022
2023                                         msgout = MESSAGE_REJECT;
2024                                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
2025                                         break;
2026                                 }       /* switch (tmp) */
2027                                 break;
2028                         case PHASE_MSGOUT:
2029                                 len = 1;
2030                                 data = &msgout;
2031                                 hostdata->last_message = msgout;
2032                                 NCR5380_transfer_pio(instance, &phase, &len, &data);
2033                                 if (msgout == ABORT) {
2034                                         hostdata->busy[cmd->device->id] &= ~(1 << (cmd->device->lun & 0xFF));
2035                                         hostdata->connected = NULL;
2036                                         cmd->result = DID_ERROR << 16;
2037                                         cmd->scsi_done(cmd);
2038                                         NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
2039                                         return;
2040                                 }
2041                                 msgout = NOP;
2042                                 break;
2043                         case PHASE_CMDOUT:
2044                                 len = cmd->cmd_len;
2045                                 data = cmd->cmnd;
2046                                 /* 
2047                                  * XXX for performance reasons, on machines with a 
2048                                  * PSEUDO-DMA architecture we should probably 
2049                                  * use the dma transfer function.  
2050                                  */
2051                                 NCR5380_transfer_pio(instance, &phase, &len, &data);
2052                                 break;
2053                         case PHASE_STATIN:
2054                                 len = 1;
2055                                 data = &tmp;
2056                                 NCR5380_transfer_pio(instance, &phase, &len, &data);
2057                                 cmd->SCp.Status = tmp;
2058                                 break;
2059                         default:
2060                                 printk("scsi%d : unknown phase\n", instance->host_no);
2061                                 NCR5380_dprint(NDEBUG_ANY, instance);
2062                         }       /* switch(phase) */
2063                 } else {
2064                         spin_unlock_irq(&hostdata->lock);
2065                         NCR5380_poll_politely(instance, STATUS_REG, SR_REQ, SR_REQ, HZ);
2066                         spin_lock_irq(&hostdata->lock);
2067                 }
2068         }
2069 }
2070
2071 /*
2072  * Function : void NCR5380_reselect (struct Scsi_Host *instance)
2073  *
2074  * Purpose : does reselection, initializing the instance->connected 
2075  *      field to point to the scsi_cmnd for which the I_T_L or I_T_L_Q
2076  *      nexus has been reestablished,
2077  *      
2078  * Inputs : instance - this instance of the NCR5380.
2079  *
2080  * Locks: io_request_lock held by caller if IRQ driven
2081  */
2082
2083 static void NCR5380_reselect(struct Scsi_Host *instance) {
2084         struct NCR5380_hostdata *hostdata = shost_priv(instance);
2085         unsigned char target_mask;
2086         unsigned char lun, phase;
2087         int len;
2088         unsigned char msg[3];
2089         unsigned char *data;
2090         struct scsi_cmnd *tmp = NULL, *prev;
2091
2092         /*
2093          * Disable arbitration, etc. since the host adapter obviously
2094          * lost, and tell an interrupted NCR5380_select() to restart.
2095          */
2096
2097         NCR5380_write(MODE_REG, MR_BASE);
2098
2099         target_mask = NCR5380_read(CURRENT_SCSI_DATA_REG) & ~(hostdata->id_mask);
2100         dprintk(NDEBUG_RESELECTION, "scsi%d : reselect\n", instance->host_no);
2101
2102         /* 
2103          * At this point, we have detected that our SCSI ID is on the bus,
2104          * SEL is true and BSY was false for at least one bus settle delay
2105          * (400 ns).
2106          *
2107          * We must assert BSY ourselves, until the target drops the SEL
2108          * signal.
2109          */
2110
2111         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_BSY);
2112         if (NCR5380_poll_politely(instance,
2113                                   STATUS_REG, SR_SEL, 0, 2 * HZ) < 0) {
2114                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2115                 return;
2116         }
2117         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2118
2119         /*
2120          * Wait for target to go into MSGIN.
2121          */
2122
2123         if (NCR5380_poll_politely(instance,
2124                                   STATUS_REG, SR_REQ, SR_REQ, 2 * HZ) < 0) {
2125                 do_abort(instance);
2126                 return;
2127         }
2128
2129         len = 1;
2130         data = msg;
2131         phase = PHASE_MSGIN;
2132         NCR5380_transfer_pio(instance, &phase, &len, &data);
2133
2134         if (len) {
2135                 do_abort(instance);
2136                 return;
2137         }
2138
2139         if (!(msg[0] & 0x80)) {
2140                 shost_printk(KERN_ERR, instance, "expecting IDENTIFY message, got ");
2141                 spi_print_msg(msg);
2142                 printk("\n");
2143                 do_abort(instance);
2144                 return;
2145         }
2146         lun = msg[0] & 0x07;
2147
2148         /*
2149          * We need to add code for SCSI-II to track which devices have
2150          * I_T_L_Q nexuses established, and which have simple I_T_L
2151          * nexuses so we can chose to do additional data transfer.
2152          */
2153
2154         /*
2155          * Find the command corresponding to the I_T_L or I_T_L_Q  nexus we
2156          * just reestablished, and remove it from the disconnected queue.
2157          */
2158
2159         for (tmp = (struct scsi_cmnd *) hostdata->disconnected_queue, prev = NULL;
2160              tmp; prev = tmp, tmp = (struct scsi_cmnd *) tmp->host_scribble) {
2161                 if ((target_mask == (1 << tmp->device->id)) && (lun == (u8)tmp->device->lun)) {
2162                         if (prev) {
2163                                 prev->host_scribble = tmp->host_scribble;
2164                         } else {
2165                                 hostdata->disconnected_queue =
2166                                         (struct scsi_cmnd *) tmp->host_scribble;
2167                         }
2168                         tmp->host_scribble = NULL;
2169                         break;
2170                 }
2171         }
2172
2173         if (tmp) {
2174                 dsprintk(NDEBUG_RESELECTION | NDEBUG_QUEUES, instance,
2175                          "reselect: removed %p from disconnected queue\n", tmp);
2176         } else {
2177                 shost_printk(KERN_ERR, instance, "target bitmask 0x%02x lun %d not in disconnected queue.\n",
2178                              target_mask, lun);
2179                 /*
2180                  * Since we have an established nexus that we can't do anything with,
2181                  * we must abort it.
2182                  */
2183                 do_abort(instance);
2184                 return;
2185         }
2186
2187         /* Accept message by clearing ACK */
2188         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2189
2190         hostdata->connected = tmp;
2191         dprintk(NDEBUG_RESELECTION, "scsi%d : nexus established, target = %d, lun = %llu, tag = %d\n",
2192                 instance->host_no, tmp->device->id, tmp->device->lun, tmp->tag);
2193 }
2194
2195 /*
2196  * Function : void NCR5380_dma_complete (struct Scsi_Host *instance)
2197  *
2198  * Purpose : called by interrupt handler when DMA finishes or a phase
2199  *      mismatch occurs (which would finish the DMA transfer).  
2200  *
2201  * Inputs : instance - this instance of the NCR5380.
2202  *
2203  * Returns : pointer to the scsi_cmnd structure for which the I_T_L
2204  *      nexus has been reestablished, on failure NULL is returned.
2205  */
2206
2207 #ifdef REAL_DMA
2208 static void NCR5380_dma_complete(NCR5380_instance * instance) {
2209         struct NCR5380_hostdata *hostdata = shost_priv(instance);
2210         int transferred;
2211
2212         /*
2213          * XXX this might not be right.
2214          *
2215          * Wait for final byte to transfer, ie wait for ACK to go false.
2216          *
2217          * We should use the Last Byte Sent bit, unfortunately this is 
2218          * not available on the 5380/5381 (only the various CMOS chips)
2219          *
2220          * FIXME: timeout, and need to handle long timeout/irq case
2221          */
2222
2223         NCR5380_poll_politely(instance, BUS_AND_STATUS_REG, BASR_ACK, 0, 5*HZ);
2224
2225         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2226
2227         /*
2228          * The only places we should see a phase mismatch and have to send
2229          * data from the same set of pointers will be the data transfer
2230          * phases.  So, residual, requested length are only important here.
2231          */
2232
2233         if (!(hostdata->connected->SCp.phase & SR_CD)) {
2234                 transferred = instance->dmalen - NCR5380_dma_residual();
2235                 hostdata->connected->SCp.this_residual -= transferred;
2236                 hostdata->connected->SCp.ptr += transferred;
2237         }
2238 }
2239 #endif                          /* def REAL_DMA */
2240
2241 /*
2242  * Function : int NCR5380_abort (struct scsi_cmnd *cmd)
2243  *
2244  * Purpose : abort a command
2245  *
2246  * Inputs : cmd - the scsi_cmnd to abort, code - code to set the
2247  *      host byte of the result field to, if zero DID_ABORTED is
2248  *      used.
2249  *
2250  * Returns : SUCCESS - success, FAILED on failure.
2251  *
2252  *      XXX - there is no way to abort the command that is currently
2253  *      connected, you have to wait for it to complete.  If this is
2254  *      a problem, we could implement longjmp() / setjmp(), setjmp()
2255  *      called where the loop started in NCR5380_main().
2256  *
2257  * Locks: host lock taken by caller
2258  */
2259
2260 static int NCR5380_abort(struct scsi_cmnd *cmd)
2261 {
2262         struct Scsi_Host *instance = cmd->device->host;
2263         struct NCR5380_hostdata *hostdata = shost_priv(instance);
2264         struct scsi_cmnd *tmp, **prev;
2265         unsigned long flags;
2266
2267         scmd_printk(KERN_WARNING, cmd, "aborting command\n");
2268
2269         spin_lock_irqsave(&hostdata->lock, flags);
2270
2271         NCR5380_dprint(NDEBUG_ANY, instance);
2272         NCR5380_dprint_phase(NDEBUG_ANY, instance);
2273
2274         dprintk(NDEBUG_ABORT, "scsi%d : abort called\n", instance->host_no);
2275         dprintk(NDEBUG_ABORT, "        basr 0x%X, sr 0x%X\n", NCR5380_read(BUS_AND_STATUS_REG), NCR5380_read(STATUS_REG));
2276
2277 #if 0
2278 /*
2279  * Case 1 : If the command is the currently executing command, 
2280  * we'll set the aborted flag and return control so that 
2281  * information transfer routine can exit cleanly.
2282  */
2283
2284         if (hostdata->connected == cmd) {
2285                 dprintk(NDEBUG_ABORT, "scsi%d : aborting connected command\n", instance->host_no);
2286 /*
2287  * We should perform BSY checking, and make sure we haven't slipped
2288  * into BUS FREE.
2289  */
2290
2291                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_ASSERT_ATN);
2292 /* 
2293  * Since we can't change phases until we've completed the current 
2294  * handshake, we have to source or sink a byte of data if the current
2295  * phase is not MSGOUT.
2296  */
2297
2298 /* 
2299  * Return control to the executing NCR drive so we can clear the
2300  * aborted flag and get back into our main loop.
2301  */
2302
2303                 return SUCCESS;
2304         }
2305 #endif
2306
2307 /* 
2308  * Case 2 : If the command hasn't been issued yet, we simply remove it 
2309  *          from the issue queue.
2310  */
2311  
2312         dprintk(NDEBUG_ABORT, "scsi%d : abort going into loop.\n", instance->host_no);
2313         for (prev = (struct scsi_cmnd **) &(hostdata->issue_queue), tmp = (struct scsi_cmnd *) hostdata->issue_queue; tmp; prev = (struct scsi_cmnd **) &(tmp->host_scribble), tmp = (struct scsi_cmnd *) tmp->host_scribble)
2314                 if (cmd == tmp) {
2315                         (*prev) = (struct scsi_cmnd *) tmp->host_scribble;
2316                         tmp->host_scribble = NULL;
2317                         spin_unlock_irqrestore(&hostdata->lock, flags);
2318                         tmp->result = DID_ABORT << 16;
2319                         dprintk(NDEBUG_ABORT, "scsi%d : abort removed command from issue queue.\n", instance->host_no);
2320                         tmp->scsi_done(tmp);
2321                         return SUCCESS;
2322                 }
2323 #if (NDEBUG  & NDEBUG_ABORT)
2324         /* KLL */
2325                 else if (prev == tmp)
2326                         printk(KERN_ERR "scsi%d : LOOP\n", instance->host_no);
2327 #endif
2328
2329 /* 
2330  * Case 3 : If any commands are connected, we're going to fail the abort
2331  *          and let the high level SCSI driver retry at a later time or 
2332  *          issue a reset.
2333  *
2334  *          Timeouts, and therefore aborted commands, will be highly unlikely
2335  *          and handling them cleanly in this situation would make the common
2336  *          case of noresets less efficient, and would pollute our code.  So,
2337  *          we fail.
2338  */
2339
2340         if (hostdata->connected) {
2341                 spin_unlock_irqrestore(&hostdata->lock, flags);
2342                 dprintk(NDEBUG_ABORT, "scsi%d : abort failed, command connected.\n", instance->host_no);
2343                 return FAILED;
2344         }
2345 /*
2346  * Case 4: If the command is currently disconnected from the bus, and 
2347  *      there are no connected commands, we reconnect the I_T_L or 
2348  *      I_T_L_Q nexus associated with it, go into message out, and send 
2349  *      an abort message.
2350  *
2351  * This case is especially ugly. In order to reestablish the nexus, we
2352  * need to call NCR5380_select().  The easiest way to implement this 
2353  * function was to abort if the bus was busy, and let the interrupt
2354  * handler triggered on the SEL for reselect take care of lost arbitrations
2355  * where necessary, meaning interrupts need to be enabled.
2356  *
2357  * When interrupts are enabled, the queues may change - so we 
2358  * can't remove it from the disconnected queue before selecting it
2359  * because that could cause a failure in hashing the nexus if that 
2360  * device reselected.
2361  * 
2362  * Since the queues may change, we can't use the pointers from when we
2363  * first locate it.
2364  *
2365  * So, we must first locate the command, and if NCR5380_select()
2366  * succeeds, then issue the abort, relocate the command and remove
2367  * it from the disconnected queue.
2368  */
2369
2370         for (tmp = (struct scsi_cmnd *) hostdata->disconnected_queue; tmp; tmp = (struct scsi_cmnd *) tmp->host_scribble)
2371                 if (cmd == tmp) {
2372                         dprintk(NDEBUG_ABORT, "scsi%d : aborting disconnected command.\n", instance->host_no);
2373
2374                         if (NCR5380_select(instance, cmd)) {
2375                                 spin_unlock_irq(&hostdata->lock);
2376                                 return FAILED;
2377                         }
2378                         dprintk(NDEBUG_ABORT, "scsi%d : nexus reestablished.\n", instance->host_no);
2379
2380                         do_abort(instance);
2381
2382                         for (prev = (struct scsi_cmnd **) &(hostdata->disconnected_queue), tmp = (struct scsi_cmnd *) hostdata->disconnected_queue; tmp; prev = (struct scsi_cmnd **) &(tmp->host_scribble), tmp = (struct scsi_cmnd *) tmp->host_scribble)
2383                                 if (cmd == tmp) {
2384                                         *prev = (struct scsi_cmnd *) tmp->host_scribble;
2385                                         tmp->host_scribble = NULL;
2386                                         spin_unlock_irqrestore(&hostdata->lock, flags);
2387                                         tmp->result = DID_ABORT << 16;
2388                                         tmp->scsi_done(tmp);
2389                                         return SUCCESS;
2390                                 }
2391                 }
2392 /*
2393  * Case 5 : If we reached this point, the command was not found in any of 
2394  *          the queues.
2395  *
2396  * We probably reached this point because of an unlikely race condition
2397  * between the command completing successfully and the abortion code,
2398  * so we won't panic, but we will notify the user in case something really
2399  * broke.
2400  */
2401         spin_unlock_irqrestore(&hostdata->lock, flags);
2402         printk(KERN_WARNING "scsi%d : warning : SCSI command probably completed successfully\n"
2403                         "         before abortion\n", instance->host_no);
2404         return FAILED;
2405 }
2406
2407
2408 /**
2409  * NCR5380_bus_reset - reset the SCSI bus
2410  * @cmd: SCSI command undergoing EH
2411  *
2412  * Returns SUCCESS
2413  */
2414
2415 static int NCR5380_bus_reset(struct scsi_cmnd *cmd)
2416 {
2417         struct Scsi_Host *instance = cmd->device->host;
2418         struct NCR5380_hostdata *hostdata = shost_priv(instance);
2419         unsigned long flags;
2420
2421         spin_lock_irqsave(&hostdata->lock, flags);
2422
2423 #if (NDEBUG & NDEBUG_ANY)
2424         scmd_printk(KERN_INFO, cmd, "performing bus reset\n");
2425 #endif
2426         NCR5380_dprint(NDEBUG_ANY, instance);
2427         NCR5380_dprint_phase(NDEBUG_ANY, instance);
2428
2429         do_reset(instance);
2430
2431         spin_unlock_irqrestore(&hostdata->lock, flags);
2432
2433         return SUCCESS;
2434 }