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