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