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